1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | import * as bip32 from 'bip32';
|
15 | import * as utxolib from '@bitgo/utxo-lib';
|
16 | import * as Bluebird from 'bluebird';
|
17 | import * as _ from 'lodash';
|
18 |
|
19 | import * as common from './common';
|
20 | import { getNetwork, makeRandomKey } from './bitcoin';
|
21 | import { sanitizeLegacyPath } from './bip32path';
|
22 | import { getSharedSecret } from './ecdh';
|
23 |
|
24 | interface DecryptReceivedTravelRuleOptions {
|
25 | tx?: {
|
26 | receivedTravelInfo?: {
|
27 | toPubKeyPath: string;
|
28 | fromPubKey: string;
|
29 | encryptedTravelInfo: string;
|
30 | travelInfo: string;
|
31 | transactionId: string;
|
32 | outputIndex: number;
|
33 | }[];
|
34 | };
|
35 | keychain?: {
|
36 | xprv?: string;
|
37 | };
|
38 | hdnode?: bip32.BIP32Interface;
|
39 | }
|
40 |
|
41 | interface Recipient {
|
42 | enterprise: string;
|
43 | pubKey: string;
|
44 | outputIndex: string;
|
45 | }
|
46 |
|
47 |
|
48 |
|
49 |
|
50 | const TravelRule = function (bitgo) {
|
51 | this.bitgo = bitgo;
|
52 | };
|
53 |
|
54 | TravelRule.prototype.url = function (extra) {
|
55 | extra = extra || '';
|
56 | return this.bitgo.url('/travel/' + extra);
|
57 | };
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 | TravelRule.prototype.getRecipients = function (params, callback) {
|
68 | params = params || {};
|
69 | params.txid = params.txid || params.hash;
|
70 | common.validateParams(params, ['txid'], [], callback);
|
71 |
|
72 | const url = this.url(params.txid + '/recipients');
|
73 | return Bluebird.resolve(
|
74 | this.bitgo.get(url).result('recipients')
|
75 | ).nodeify(callback);
|
76 | };
|
77 |
|
78 | TravelRule.prototype.validateTravelInfo = function (info) {
|
79 | const fields = {
|
80 | amount: { type: 'number' },
|
81 | toAddress: { type: 'string' },
|
82 | toEnterprise: { type: 'string' },
|
83 | fromUserName: { type: 'string' },
|
84 | fromUserAccount: { type: 'string' },
|
85 | fromUserAddress: { type: 'string' },
|
86 | toUserName: { type: 'string' },
|
87 | toUserAccount: { type: 'string' },
|
88 | toUserAddress: { type: 'string' },
|
89 | extra: { type: 'object' },
|
90 | };
|
91 |
|
92 | _.forEach(fields, function (field: any, fieldName) {
|
93 |
|
94 | if (field.required) {
|
95 | if (info[fieldName] === undefined) {
|
96 | throw new Error('missing required field ' + fieldName + ' in travel info');
|
97 | }
|
98 | }
|
99 | if (info[fieldName] && typeof(info[fieldName]) !== field.type) {
|
100 | throw new Error('incorrect type for field ' + fieldName + ' in travel info, expected ' + field.type);
|
101 | }
|
102 | });
|
103 |
|
104 |
|
105 | const result = _.pick(info, _.keys(fields));
|
106 | if (_.isEmpty(result)) {
|
107 | throw new Error('empty travel data');
|
108 | }
|
109 | return result;
|
110 | };
|
111 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 |
|
122 | TravelRule.prototype.decryptReceivedTravelInfo = function (params: DecryptReceivedTravelRuleOptions = {}) {
|
123 | const tx = params.tx;
|
124 | if (!_.isObject(tx)) {
|
125 | throw new Error('expecting tx param to be object');
|
126 | }
|
127 |
|
128 | if (!tx.receivedTravelInfo || !tx.receivedTravelInfo.length) {
|
129 | return tx;
|
130 | }
|
131 |
|
132 | const keychain = params.keychain;
|
133 | if (!_.isObject(keychain) || !_.isString(keychain.xprv)) {
|
134 | throw new Error('expecting keychain param with xprv');
|
135 | }
|
136 | const hdNode = bip32.fromBase58(keychain.xprv);
|
137 |
|
138 | tx.receivedTravelInfo.forEach((info) => {
|
139 | const key = hdNode.derivePath(sanitizeLegacyPath(info.toPubKeyPath));
|
140 | const secret = getSharedSecret(key, Buffer.from(info.fromPubKey, 'hex')).toString('hex');
|
141 | try {
|
142 | const decrypted = this.bitgo.decrypt({
|
143 | input: info.encryptedTravelInfo,
|
144 | password: secret,
|
145 | });
|
146 | info.travelInfo = JSON.parse(decrypted);
|
147 | } catch (err) {
|
148 | console.error('failed to decrypt or parse travel info for ', info.transactionId + ':' + info.outputIndex);
|
149 | }
|
150 | });
|
151 |
|
152 | return tx;
|
153 | };
|
154 |
|
155 | TravelRule.prototype.prepareParams = function (params) {
|
156 | params = params || {};
|
157 | params.txid = params.txid || params.hash;
|
158 | common.validateParams(params, ['txid'], ['fromPrivateInfo']);
|
159 | const txid = params.txid;
|
160 | const recipient: Recipient | undefined = params.recipient;
|
161 | let travelInfo = params.travelInfo;
|
162 | if (!recipient || !_.isObject(recipient)) {
|
163 | throw new Error('invalid or missing recipient');
|
164 | }
|
165 | if (!travelInfo || !_.isObject(travelInfo)) {
|
166 | throw new Error('invalid or missing travelInfo');
|
167 | }
|
168 | if (!params.noValidate) {
|
169 | travelInfo = this.validateTravelInfo(travelInfo);
|
170 | }
|
171 |
|
172 |
|
173 | if (!travelInfo.toEnterprise && recipient.enterprise) {
|
174 | travelInfo.toEnterprise = recipient.enterprise;
|
175 | }
|
176 |
|
177 |
|
178 | let fromKey = params.fromKey && utxolib.ECPair.fromWIF(params.fromKey, getNetwork() as utxolib.BitcoinJSNetwork);
|
179 | if (!fromKey) {
|
180 | fromKey = makeRandomKey();
|
181 | }
|
182 |
|
183 |
|
184 | const sharedSecret = getSharedSecret(fromKey, Buffer.from(recipient.pubKey, 'hex')).toString('hex');
|
185 |
|
186 |
|
187 | const travelInfoJSON = JSON.stringify(travelInfo);
|
188 | const encryptedTravelInfo = this.bitgo.encrypt({
|
189 | input: travelInfoJSON,
|
190 | password: sharedSecret,
|
191 | });
|
192 |
|
193 | const result = {
|
194 | txid: txid,
|
195 | outputIndex: recipient.outputIndex,
|
196 | toPubKey: recipient.pubKey,
|
197 | fromPubKey: fromKey.publicKey.toString('hex'),
|
198 | encryptedTravelInfo: encryptedTravelInfo,
|
199 | fromPrivateInfo: undefined,
|
200 | };
|
201 |
|
202 | if (params.fromPrivateInfo) {
|
203 | result.fromPrivateInfo = params.fromPrivateInfo;
|
204 | }
|
205 |
|
206 | return result;
|
207 | };
|
208 |
|
209 |
|
210 |
|
211 |
|
212 | TravelRule.prototype.send = function (params, callback) {
|
213 | params = params || {};
|
214 | params.txid = params.txid || params.hash;
|
215 | common.validateParams(params, ['txid', 'toPubKey', 'encryptedTravelInfo'], ['fromPubKey', 'fromPrivateInfo'], callback);
|
216 |
|
217 | if (!_.isNumber(params.outputIndex)) {
|
218 | throw new Error('invalid outputIndex');
|
219 | }
|
220 |
|
221 | return Bluebird.resolve(
|
222 | this.bitgo.post(this.url(params.txid + '/' + params.outputIndex)).send(params).result()
|
223 | ).nodeify(callback);
|
224 | };
|
225 |
|
226 |
|
227 |
|
228 |
|
229 |
|
230 |
|
231 |
|
232 |
|
233 |
|
234 |
|
235 |
|
236 |
|
237 |
|
238 |
|
239 |
|
240 |
|
241 |
|
242 |
|
243 |
|
244 |
|
245 |
|
246 |
|
247 | TravelRule.prototype.sendMany = function (params, callback) {
|
248 | params = params || {};
|
249 | params.txid = params.txid || params.hash;
|
250 | common.validateParams(params, ['txid'], callback);
|
251 |
|
252 | const travelInfos = params.travelInfos;
|
253 | if (!_.isArray(travelInfos)) {
|
254 | throw new Error('expected parameter travelInfos to be array');
|
255 | }
|
256 |
|
257 | const self = this;
|
258 | const travelInfoMap = _(travelInfos)
|
259 | .keyBy('outputIndex')
|
260 | .mapValues(function (travelInfo) {
|
261 | return self.validateTravelInfo(travelInfo);
|
262 | })
|
263 | .value();
|
264 |
|
265 | return self.getRecipients({ txid: params.txid })
|
266 | .then(function (recipients) {
|
267 |
|
268 |
|
269 | const sendParamsList: any[] = [];
|
270 |
|
271 | const fromKey = params.fromKey || makeRandomKey().toWIF();
|
272 |
|
273 | recipients.forEach(function (recipient) {
|
274 | const outputIndex = recipient.outputIndex;
|
275 | const info = travelInfoMap[outputIndex];
|
276 | if (info) {
|
277 | if (info.amount && info.amount !== recipient.amount) {
|
278 | throw new Error('amount did not match for output index ' + outputIndex);
|
279 | }
|
280 | const sendParams = self.prepareParams({
|
281 | txid: params.txid,
|
282 | recipient: recipient,
|
283 | travelInfo: info,
|
284 | fromKey: fromKey,
|
285 | noValidate: true,
|
286 | });
|
287 | sendParamsList.push(sendParams);
|
288 | }
|
289 | });
|
290 |
|
291 | const result: {
|
292 | matched: number;
|
293 | results: {
|
294 | result?: any;
|
295 | error?: string;
|
296 | }[];
|
297 | } = {
|
298 | matched: sendParamsList.length,
|
299 | results: [],
|
300 | };
|
301 |
|
302 | const sendSerial = function () {
|
303 | const sendParams = sendParamsList.shift();
|
304 | if (!sendParams) {
|
305 | return result;
|
306 | }
|
307 | return self.send(sendParams)
|
308 | .then(function (res) {
|
309 | result.results.push({ result: res });
|
310 | return sendSerial();
|
311 | })
|
312 | .catch(function (err) {
|
313 | result.results.push({ error: err.toString() });
|
314 | return sendSerial();
|
315 | });
|
316 | };
|
317 |
|
318 | return sendSerial();
|
319 | });
|
320 | };
|
321 |
|
322 | module.exports = TravelRule;
|