1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | import { VirtualSizes } from '@bitgo/unspents';
|
15 |
|
16 | import * as bip32 from 'bip32';
|
17 | const TransactionBuilder = require('./transactionBuilder');
|
18 | import * as utxolib from '@bitgo/utxo-lib';
|
19 | const PendingApproval = require('./pendingapproval');
|
20 |
|
21 | import { common } from '@bitgo/sdk-core';
|
22 | import * as Bluebird from 'bluebird';
|
23 | const co = Bluebird.coroutine;
|
24 | import * as _ from 'lodash';
|
25 | import { makeRandomKey, getNetwork } from './bitcoin';
|
26 | import { sanitizeLegacyPath } from '@bitgo/sdk-api';
|
27 | import { getSharedSecret } from './ecdh';
|
28 | import {
|
29 | getExternalChainCode,
|
30 | getInternalChainCode,
|
31 | isChainCode,
|
32 | scriptTypeForChain,
|
33 | } from '@bitgo/utxo-lib/dist/src/bitgo';
|
34 | const request = require('superagent');
|
35 |
|
36 |
|
37 |
|
38 |
|
39 | const Wallet = function (bitgo, wallet) {
|
40 | (this.bitgo as any) = bitgo;
|
41 | this.wallet = wallet;
|
42 | this.keychains = [];
|
43 |
|
44 | if (wallet.private) {
|
45 | this.keychains = wallet.private.keychains;
|
46 | }
|
47 | };
|
48 |
|
49 | Wallet.prototype.toJSON = function () {
|
50 | return this.wallet;
|
51 | };
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 | Wallet.prototype.id = function () {
|
58 | return this.wallet.id;
|
59 | };
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 | Wallet.prototype.label = function () {
|
66 | return this.wallet.label;
|
67 | };
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 | Wallet.prototype.balance = function () {
|
74 | return this.wallet.balance;
|
75 | };
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 | Wallet.prototype.spendableBalance = function () {
|
83 | return this.wallet.spendableBalance;
|
84 | };
|
85 |
|
86 |
|
87 |
|
88 |
|
89 |
|
90 | Wallet.prototype.confirmedBalance = function () {
|
91 | return this.wallet.confirmedBalance;
|
92 | };
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 | Wallet.prototype.canSendInstant = function () {
|
100 | return this.wallet && this.wallet.canSendInstant;
|
101 | };
|
102 |
|
103 |
|
104 |
|
105 |
|
106 |
|
107 |
|
108 | Wallet.prototype.instantBalance = function () {
|
109 | if (!this.canSendInstant()) {
|
110 | throw new Error('not an instant wallet');
|
111 | }
|
112 | return this.wallet.instantBalance;
|
113 | };
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 | Wallet.prototype.unconfirmedSends = function () {
|
120 | return this.wallet.unconfirmedSends;
|
121 | };
|
122 |
|
123 |
|
124 |
|
125 |
|
126 |
|
127 | Wallet.prototype.unconfirmedReceives = function () {
|
128 | return this.wallet.unconfirmedReceives;
|
129 | };
|
130 |
|
131 |
|
132 |
|
133 |
|
134 |
|
135 | Wallet.prototype.type = function () {
|
136 | return this.wallet.type;
|
137 | };
|
138 |
|
139 | Wallet.prototype.url = function (extra) {
|
140 | extra = extra || '';
|
141 | return this.bitgo.url('/wallet/' + this.id() + extra);
|
142 | };
|
143 |
|
144 |
|
145 |
|
146 |
|
147 |
|
148 | Wallet.prototype.pendingApprovals = function () {
|
149 | const self = this;
|
150 | return this.wallet.pendingApprovals.map(function (p) {
|
151 | return new PendingApproval(self.bitgo, p, self);
|
152 | });
|
153 | };
|
154 |
|
155 |
|
156 |
|
157 |
|
158 |
|
159 | Wallet.prototype.approvalsRequired = function () {
|
160 | return this.wallet.approvalsRequired || 1;
|
161 | };
|
162 |
|
163 |
|
164 |
|
165 |
|
166 |
|
167 | Wallet.prototype.get = function (params, callback): Bluebird<any> {
|
168 | params = params || {};
|
169 | common.validateParams(params, [], [], callback);
|
170 |
|
171 | const self = this;
|
172 |
|
173 | return Bluebird.resolve(
|
174 | this.bitgo.get(this.url())
|
175 | .result()
|
176 | .then(function (res) {
|
177 | self.wallet = res;
|
178 | return self;
|
179 | })
|
180 | ).nodeify(callback);
|
181 | };
|
182 |
|
183 |
|
184 |
|
185 |
|
186 |
|
187 |
|
188 |
|
189 | Wallet.prototype.updateApprovalsRequired = function (params, callback): Bluebird<any> {
|
190 | params = params || {};
|
191 | common.validateParams(params, [], [], callback);
|
192 | if (params.approvalsRequired === undefined ||
|
193 | !_.isInteger(params.approvalsRequired) ||
|
194 | params.approvalsRequired < 1
|
195 | ) {
|
196 | throw new Error('invalid approvalsRequired: must be a nonzero positive number');
|
197 | }
|
198 |
|
199 | const self = this;
|
200 | const currentApprovalsRequired = this.approvalsRequired();
|
201 | if (currentApprovalsRequired === params.approvalsRequired) {
|
202 |
|
203 | return Bluebird.try(function () {
|
204 | return self.wallet;
|
205 | })
|
206 | .nodeify(callback);
|
207 | }
|
208 |
|
209 | return Bluebird.resolve(
|
210 | this.bitgo.put(this.url())
|
211 | .send(params)
|
212 | .result()
|
213 | ).nodeify(callback);
|
214 | };
|
215 |
|
216 |
|
217 |
|
218 |
|
219 | Wallet.prototype.getChangeChain = function (params) {
|
220 | let useSegwitChange = !!this.bitgo.getConstants().enableSegwit;
|
221 | if (!_.isUndefined(params.segwitChange)) {
|
222 | if (!_.isBoolean(params.segwitChange)) {
|
223 | throw new Error('segwitChange must be a boolean');
|
224 | }
|
225 |
|
226 |
|
227 | useSegwitChange = this.bitgo.getConstants().enableSegwit && params.segwitChange;
|
228 | }
|
229 | return useSegwitChange ? getInternalChainCode('p2shP2wsh') : getInternalChainCode('p2sh');
|
230 | };
|
231 |
|
232 |
|
233 |
|
234 |
|
235 |
|
236 | Wallet.prototype.createAddress = function (params, callback) {
|
237 | const self = this;
|
238 | params = params || {};
|
239 | common.validateParams(params, [], [], callback);
|
240 | if (this.type() === 'safe') {
|
241 | throw new Error('You are using a legacy wallet that cannot create a new address');
|
242 | }
|
243 |
|
244 |
|
245 | const shouldValidate = params.validate !== undefined ? params.validate : this.bitgo.getValidate();
|
246 |
|
247 | const allowExisting = params.allowExisting;
|
248 | if (typeof allowExisting !== 'boolean') {
|
249 | params.allowExisting = (allowExisting === 'true');
|
250 | }
|
251 |
|
252 | const isSegwit = this.bitgo.getConstants().enableSegwit;
|
253 | const defaultChain = isSegwit ? getExternalChainCode('p2shP2wsh') : getExternalChainCode('p2sh');
|
254 |
|
255 | let chain = params.chain;
|
256 | if (chain === null || chain === undefined) {
|
257 | chain = defaultChain;
|
258 | }
|
259 | return Bluebird.resolve(
|
260 | this.bitgo.post(this.url('/address/' + chain))
|
261 | .send(params)
|
262 | .result()
|
263 | .then(function (addr) {
|
264 | if (shouldValidate) {
|
265 | self.validateAddress(addr);
|
266 | }
|
267 | return addr;
|
268 | })
|
269 | ).nodeify(callback);
|
270 | };
|
271 |
|
272 |
|
273 |
|
274 |
|
275 |
|
276 |
|
277 | Wallet.prototype.generateAddress = function ({ segwit, path, keychains, threshold }) {
|
278 | const isSegwit = !!segwit;
|
279 | let signatureThreshold = 2;
|
280 | if (_.isInteger(threshold)) {
|
281 | signatureThreshold = threshold;
|
282 | if (signatureThreshold <= 0) {
|
283 | throw new Error('threshold has to be positive');
|
284 | }
|
285 | }
|
286 |
|
287 | const pathRegex = /^\/1?[01]\/\d+$/;
|
288 | if (!path.match(pathRegex)) {
|
289 | throw new Error('unsupported path: ' + path);
|
290 | }
|
291 |
|
292 | let rootKeys = this.keychains;
|
293 | if (Array.isArray(keychains)) {
|
294 | rootKeys = keychains;
|
295 | }
|
296 |
|
297 | const network = common.Environments[this.bitgo.getEnv()].network;
|
298 |
|
299 | const derivedKeys = rootKeys.map(function (k) {
|
300 | const hdnode = bip32.fromBase58(k.xpub);
|
301 | const derivationPath = k.path + (k.walletSubPath || '') + path;
|
302 | return hdnode.derivePath(sanitizeLegacyPath(derivationPath)).publicKey;
|
303 | });
|
304 |
|
305 | const pathComponents = path.split('/');
|
306 | const normalizedPathComponents = _.map(pathComponents, (component) => {
|
307 | if (component && component.length > 0) {
|
308 | return parseInt(component, 10);
|
309 | }
|
310 | });
|
311 | const pathDetails = _.filter(normalizedPathComponents, _.isInteger);
|
312 |
|
313 | const addressDetails: any = {
|
314 | chainPath: path,
|
315 | path: path,
|
316 | chain: pathDetails[0],
|
317 | index: pathDetails[1],
|
318 | wallet: this.id(),
|
319 | };
|
320 |
|
321 | const {
|
322 | scriptPubKey: outputScript,
|
323 | redeemScript,
|
324 | witnessScript,
|
325 | } = utxolib.bitgo.outputScripts.createOutputScript2of3(derivedKeys, isSegwit ? 'p2shP2wsh' : 'p2sh');
|
326 |
|
327 | addressDetails.witnessScript = witnessScript?.toString('hex');
|
328 | addressDetails.redeemScript = redeemScript?.toString('hex');
|
329 | addressDetails.outputScript = outputScript.toString('hex');
|
330 | addressDetails.address = utxolib.address.fromOutputScript(outputScript, getNetwork(network));
|
331 |
|
332 | return addressDetails;
|
333 | };
|
334 |
|
335 |
|
336 |
|
337 |
|
338 |
|
339 | Wallet.prototype.validateAddress = function (params) {
|
340 | common.validateParams(params, ['address', 'path'], []);
|
341 | const isSegwit = !!params.witnessScript && params.witnessScript.length > 0;
|
342 |
|
343 | const generatedAddress = this.generateAddress({ path: params.path, segwit: isSegwit });
|
344 | if (generatedAddress.address !== params.address) {
|
345 | throw new Error('address validation failure: ' + params.address + ' vs. ' + generatedAddress.address);
|
346 | }
|
347 | };
|
348 |
|
349 |
|
350 |
|
351 |
|
352 |
|
353 |
|
354 |
|
355 | Wallet.prototype.addresses = function (params, callback) {
|
356 | params = params || {};
|
357 | common.validateParams(params, [], [], callback);
|
358 |
|
359 | const query: any = {};
|
360 | if (params.details) {
|
361 | query.details = 1;
|
362 | }
|
363 |
|
364 | const chain = params.chain;
|
365 | if (chain !== null && chain !== undefined) {
|
366 | if (Array.isArray(chain)) {
|
367 | query.chain = _.uniq(_.filter(chain, _.isInteger));
|
368 | } else {
|
369 | if (chain !== 0 && chain !== 1) {
|
370 | throw new Error('invalid chain argument, expecting 0 or 1');
|
371 | }
|
372 | query.chain = chain;
|
373 | }
|
374 | }
|
375 | if (params.limit) {
|
376 | if (!_.isInteger(params.limit)) {
|
377 | throw new Error('invalid limit argument, expecting number');
|
378 | }
|
379 | query.limit = params.limit;
|
380 | }
|
381 | if (params.skip) {
|
382 | if (!_.isInteger(params.skip)) {
|
383 | throw new Error('invalid skip argument, expecting number');
|
384 | }
|
385 | query.skip = params.skip;
|
386 | }
|
387 | if (params.sort) {
|
388 | if (!_.isNumber(params.sort)) {
|
389 | throw new Error('invalid sort argument, expecting number');
|
390 | }
|
391 | query.sort = params.sort;
|
392 | }
|
393 |
|
394 | const url = this.url('/addresses');
|
395 | return Bluebird.resolve(
|
396 | this.bitgo.get(url)
|
397 | .query(query)
|
398 | .result()
|
399 | ).nodeify(callback);
|
400 | };
|
401 |
|
402 | Wallet.prototype.stats = function (params, callback) {
|
403 | params = params || {};
|
404 | common.validateParams(params, [], [], callback);
|
405 | const args: string[] = [];
|
406 | if (params.limit) {
|
407 | if (!_.isInteger(params.limit)) {
|
408 | throw new Error('invalid limit argument, expecting number');
|
409 | }
|
410 | args.push('limit=' + params.limit);
|
411 | }
|
412 | let query = '';
|
413 | if (args.length) {
|
414 | query = '?' + args.join('&');
|
415 | }
|
416 |
|
417 | const url = this.url('/stats' + query);
|
418 |
|
419 | return Bluebird.resolve(
|
420 | this.bitgo.get(url).result()
|
421 | ).nodeify(callback);
|
422 | };
|
423 |
|
424 |
|
425 |
|
426 |
|
427 |
|
428 |
|
429 | Wallet.prototype.refresh = function (params, callback) {
|
430 | return co(function *() {
|
431 |
|
432 | const query = _.extend({}, _.pick(params, ['gpk']));
|
433 | const res = yield this.bitgo.get(this.url()).query(query).result();
|
434 | this.wallet = res;
|
435 | return this;
|
436 | }).call(this).asCallback(callback);
|
437 | };
|
438 |
|
439 |
|
440 |
|
441 |
|
442 |
|
443 |
|
444 |
|
445 |
|
446 | Wallet.prototype.address = function (params, callback) {
|
447 | params = params || {};
|
448 | common.validateParams(params, ['address'], [], callback);
|
449 |
|
450 | const url = this.url('/addresses/' + params.address);
|
451 |
|
452 | return this.bitgo.get(url)
|
453 | .result()
|
454 | .nodeify(callback);
|
455 | };
|
456 |
|
457 |
|
458 |
|
459 |
|
460 |
|
461 | Wallet.prototype.freeze = function (params, callback) {
|
462 | params = params || {};
|
463 | common.validateParams(params, [], [], callback);
|
464 |
|
465 | if (params.duration) {
|
466 | if (!_.isNumber(params.duration)) {
|
467 | throw new Error('invalid duration - should be number of seconds');
|
468 | }
|
469 | }
|
470 |
|
471 | return Bluebird.resolve(
|
472 | this.bitgo.post(this.url('/freeze'))
|
473 | .send(params)
|
474 | .result()
|
475 | ).nodeify(callback);
|
476 | };
|
477 |
|
478 |
|
479 |
|
480 |
|
481 |
|
482 | Wallet.prototype.delete = function (params, callback) {
|
483 | params = params || {};
|
484 | common.validateParams(params, [], [], callback);
|
485 |
|
486 | return Bluebird.resolve(
|
487 | this.bitgo.del(this.url()).result()
|
488 | ).nodeify(callback);
|
489 | };
|
490 |
|
491 |
|
492 |
|
493 |
|
494 |
|
495 | Wallet.prototype.labels = function (params, callback) {
|
496 | params = params || {};
|
497 | common.validateParams(params, [], [], callback);
|
498 |
|
499 | const url = this.bitgo.url('/labels/' + this.id());
|
500 |
|
501 | return Bluebird.resolve(
|
502 | this.bitgo.get(url).result('labels')
|
503 | ).nodeify(callback);
|
504 | };
|
505 |
|
506 |
|
507 |
|
508 |
|
509 |
|
510 |
|
511 |
|
512 |
|
513 | Wallet.prototype.setWalletName = function (params, callback) {
|
514 | params = params || {};
|
515 | common.validateParams(params, ['label'], [], callback);
|
516 |
|
517 | const url = this.bitgo.url('/wallet/' + this.id());
|
518 | return Bluebird.resolve(
|
519 | this.bitgo.put(url)
|
520 | .send({ label: params.label })
|
521 | .result()
|
522 | ).nodeify(callback);
|
523 | };
|
524 |
|
525 |
|
526 |
|
527 |
|
528 |
|
529 | Wallet.prototype.setLabel = function (params, callback) {
|
530 | params = params || {};
|
531 | common.validateParams(params, ['address', 'label'], [], callback);
|
532 |
|
533 | const self = this;
|
534 |
|
535 | if (!self.bitgo.verifyAddress({ address: params.address })) {
|
536 | throw new Error('Invalid bitcoin address: ' + params.address);
|
537 | }
|
538 |
|
539 | const url = this.bitgo.url('/labels/' + this.id() + '/' + params.address);
|
540 |
|
541 | return Bluebird.resolve(
|
542 | this.bitgo.put(url)
|
543 | .send({ label: params.label })
|
544 | .result()
|
545 | ).nodeify(callback);
|
546 | };
|
547 |
|
548 |
|
549 |
|
550 |
|
551 |
|
552 | Wallet.prototype.deleteLabel = function (params, callback) {
|
553 | params = params || {};
|
554 | common.validateParams(params, ['address'], [], callback);
|
555 |
|
556 | const self = this;
|
557 |
|
558 | if (!self.bitgo.verifyAddress({ address: params.address })) {
|
559 | throw new Error('Invalid bitcoin address: ' + params.address);
|
560 | }
|
561 |
|
562 | const url = this.bitgo.url('/labels/' + this.id() + '/' + params.address);
|
563 |
|
564 | return Bluebird.resolve(
|
565 | this.bitgo.del(url).result()
|
566 | ).nodeify(callback);
|
567 | };
|
568 |
|
569 |
|
570 |
|
571 |
|
572 |
|
573 |
|
574 |
|
575 |
|
576 |
|
577 |
|
578 |
|
579 |
|
580 | Wallet.prototype.unspents = function (params, callback) {
|
581 | params = params || {};
|
582 | common.validateParams(params, [], [], callback);
|
583 |
|
584 | const allUnspents: any[] = [];
|
585 | const self = this;
|
586 |
|
587 | const getUnspentsBatch = function (skip, limit?) {
|
588 |
|
589 | const queryObject = _.cloneDeep(params);
|
590 | if (skip > 0) {
|
591 | queryObject.skip = skip;
|
592 | }
|
593 | if (limit && limit > 0) {
|
594 | queryObject.limit = limit;
|
595 | }
|
596 |
|
597 | return self.unspentsPaged(queryObject)
|
598 | .then(function (result) {
|
599 |
|
600 |
|
601 | for (let i = 0; i < result.unspents.length; i++) {
|
602 | const unspent = result.unspents[i];
|
603 | allUnspents.push(unspent);
|
604 | }
|
605 |
|
606 |
|
607 |
|
608 | if (allUnspents.length >= params.limit) {
|
609 | return allUnspents;
|
610 | }
|
611 |
|
612 | const totalUnspentCount = result.total;
|
613 |
|
614 | if (!params.target && totalUnspentCount && totalUnspentCount > allUnspents.length) {
|
615 |
|
616 |
|
617 | const newSkip = skip + result.count;
|
618 | let newLimit: number | undefined;
|
619 | if (limit > 0) {
|
620 |
|
621 | newLimit = limit - allUnspents.length;
|
622 | }
|
623 | return getUnspentsBatch(newSkip, newLimit);
|
624 | }
|
625 |
|
626 | return allUnspents;
|
627 | });
|
628 | };
|
629 |
|
630 | return getUnspentsBatch(0, params.limit)
|
631 | .nodeify(callback);
|
632 | };
|
633 |
|
634 |
|
635 |
|
636 |
|
637 |
|
638 |
|
639 |
|
640 |
|
641 |
|
642 |
|
643 |
|
644 |
|
645 |
|
646 |
|
647 |
|
648 |
|
649 |
|
650 | Wallet.prototype.unspentsPaged = function (params, callback) {
|
651 | params = params || {};
|
652 | common.validateParams(params, [], [], callback);
|
653 |
|
654 | if (!_.isUndefined(params.limit) && !_.isInteger(params.limit)) {
|
655 | throw new Error('invalid limit - should be number');
|
656 | }
|
657 | if (!_.isUndefined(params.skip) && !_.isInteger(params.skip)) {
|
658 | throw new Error('invalid skip - should be number');
|
659 | }
|
660 | if (!_.isUndefined(params.minConfirms) && !_.isInteger(params.minConfirms)) {
|
661 | throw new Error('invalid minConfirms - should be number');
|
662 | }
|
663 | if (!_.isUndefined(params.target) && !_.isNumber(params.target)) {
|
664 | throw new Error('invalid target - should be number');
|
665 | }
|
666 | if (!_.isUndefined(params.instant) && !_.isBoolean(params.instant)) {
|
667 | throw new Error('invalid instant flag - should be boolean');
|
668 | }
|
669 | if (!_.isUndefined(params.segwit) && !_.isBoolean(params.segwit)) {
|
670 | throw new Error('invalid segwit flag - should be boolean');
|
671 | }
|
672 | if (!_.isUndefined(params.targetWalletUnspents) && !_.isInteger(params.targetWalletUnspents)) {
|
673 | throw new Error('invalid targetWalletUnspents flag - should be number');
|
674 | }
|
675 | if (!_.isUndefined(params.minSize) && !_.isNumber(params.minSize)) {
|
676 | throw new Error('invalid argument: minSize must be a number');
|
677 | }
|
678 | if (!_.isUndefined(params.instant) && !_.isUndefined(params.minConfirms)) {
|
679 | throw new Error('only one of instant and minConfirms may be defined');
|
680 | }
|
681 | if (!_.isUndefined(params.targetWalletUnspents) && _.isUndefined(params.target)) {
|
682 | throw new Error('targetWalletUnspents can only be specified in conjunction with a target');
|
683 | }
|
684 | if (!_.isUndefined(params.allowLedgerSegwit) && !_.isBoolean(params.allowLedgerSegwit)) {
|
685 | throw new Error('invalid argument: allowLedgerSegwit must be a boolean');
|
686 | }
|
687 |
|
688 | const queryObject = _.cloneDeep(params);
|
689 |
|
690 | if (!_.isUndefined(params.target)) {
|
691 |
|
692 | delete queryObject.skip;
|
693 | delete queryObject.limit;
|
694 | }
|
695 |
|
696 | queryObject.segwit = true;
|
697 | if (!_.isUndefined(params.segwit)) {
|
698 | queryObject.segwit = params.segwit;
|
699 | }
|
700 |
|
701 | if (!_.isUndefined(params.allowLedgerSegwit)) {
|
702 | queryObject.allowLedgerSegwit = params.allowLedgerSegwit;
|
703 | }
|
704 |
|
705 | return Bluebird.resolve(
|
706 | this.bitgo.get(this.url('/unspents')).query(queryObject).result()
|
707 | ).nodeify(callback);
|
708 | };
|
709 |
|
710 |
|
711 |
|
712 |
|
713 |
|
714 |
|
715 | Wallet.prototype.transactions = function (params, callback) {
|
716 | params = params || {};
|
717 | common.validateParams(params, [], [], callback);
|
718 |
|
719 | const args: string[] = [];
|
720 | if (params.limit) {
|
721 | if (!_.isInteger(params.limit)) {
|
722 | throw new Error('invalid limit argument, expecting number');
|
723 | }
|
724 | args.push('limit=' + params.limit);
|
725 | }
|
726 | if (params.skip) {
|
727 | if (!_.isInteger(params.skip)) {
|
728 | throw new Error('invalid skip argument, expecting number');
|
729 | }
|
730 | args.push('skip=' + params.skip);
|
731 | }
|
732 | if (params.minHeight) {
|
733 | if (!_.isInteger(params.minHeight)) {
|
734 | throw new Error('invalid minHeight argument, expecting number');
|
735 | }
|
736 | args.push('minHeight=' + params.minHeight);
|
737 | }
|
738 | if (params.maxHeight) {
|
739 | if (!_.isInteger(params.maxHeight) || params.maxHeight < 0) {
|
740 | throw new Error('invalid maxHeight argument, expecting positive integer');
|
741 | }
|
742 | args.push('maxHeight=' + params.maxHeight);
|
743 | }
|
744 | if (params.minConfirms) {
|
745 | if (!_.isInteger(params.minConfirms) || params.minConfirms < 0) {
|
746 | throw new Error('invalid minConfirms argument, expecting positive integer');
|
747 | }
|
748 | args.push('minConfirms=' + params.minConfirms);
|
749 | }
|
750 | if (!_.isUndefined(params.compact)) {
|
751 | if (!_.isBoolean(params.compact)) {
|
752 | throw new Error('invalid compact argument, expecting boolean');
|
753 | }
|
754 | args.push('compact=' + params.compact);
|
755 | }
|
756 | let query = '';
|
757 | if (args.length) {
|
758 | query = '?' + args.join('&');
|
759 | }
|
760 |
|
761 | const url = this.url('/tx' + query);
|
762 |
|
763 | return Bluebird.resolve(
|
764 | this.bitgo.get(url).result()
|
765 | ).nodeify(callback);
|
766 | };
|
767 |
|
768 |
|
769 |
|
770 |
|
771 | Wallet.prototype.getTransaction = function (params, callback) {
|
772 | params = params || {};
|
773 | common.validateParams(params, ['id'], [], callback);
|
774 |
|
775 | const url = this.url('/tx/' + params.id);
|
776 |
|
777 | return Bluebird.resolve(
|
778 | this.bitgo.get(url).result()
|
779 | ).nodeify(callback);
|
780 | };
|
781 |
|
782 |
|
783 |
|
784 |
|
785 |
|
786 |
|
787 |
|
788 |
|
789 | Wallet.prototype.pollForTransaction = function (params, callback) {
|
790 | const self = this;
|
791 | params = params || {};
|
792 | common.validateParams(params, ['id'], [], callback);
|
793 | if (params.delay && !_.isNumber(params.delay)) {
|
794 | throw new Error('invalid delay parameter');
|
795 | }
|
796 | if (params.timeout && !_.isNumber(params.timeout)) {
|
797 | throw new Error('invalid timeout parameter');
|
798 | }
|
799 | params.delay = params.delay || 1000;
|
800 | params.timeout = params.timeout || 10000;
|
801 |
|
802 | const start = new Date();
|
803 |
|
804 | const doNextPoll = function () {
|
805 | return self.getTransaction(params)
|
806 | .then(function (res) {
|
807 | return res;
|
808 | })
|
809 | .catch(function (err) {
|
810 | if (err.status !== 404 || new Date().valueOf() - start.valueOf() > params.timeout) {
|
811 | throw err;
|
812 | }
|
813 | return Bluebird.delay(params.delay)
|
814 | .then(function () {
|
815 | return doNextPoll();
|
816 | });
|
817 | });
|
818 | };
|
819 |
|
820 | return doNextPoll();
|
821 | };
|
822 |
|
823 |
|
824 |
|
825 |
|
826 | Wallet.prototype.getWalletTransactionBySequenceId = function (params, callback) {
|
827 | params = params || {};
|
828 | common.validateParams(params, ['sequenceId'], [], callback);
|
829 |
|
830 | const url = this.url('/tx/sequence/' + params.sequenceId);
|
831 |
|
832 | return Bluebird.resolve(
|
833 | this.bitgo.get(url).result()
|
834 | ).nodeify(callback);
|
835 | };
|
836 |
|
837 |
|
838 |
|
839 |
|
840 |
|
841 |
|
842 | Wallet.prototype.getEncryptedUserKeychain = function (params, callback) {
|
843 | return co(function *() {
|
844 | params = params || {};
|
845 | common.validateParams(params, [], [], callback);
|
846 | const self = this;
|
847 |
|
848 | const tryKeyChain = co(function *(index) {
|
849 | if (!self.keychains || index >= self.keychains.length) {
|
850 | const error: any = new Error('No encrypted keychains on this wallet.');
|
851 | error.code = 'no_encrypted_keychain_on_wallet';
|
852 | throw error;
|
853 | }
|
854 |
|
855 | const params = { xpub: self.keychains[index].xpub };
|
856 |
|
857 | const keychain = yield self.bitgo.keychains().get(params);
|
858 |
|
859 | keychain.walletSubPath = self.keychains[index].path;
|
860 | if (keychain.encryptedXprv) {
|
861 | return keychain;
|
862 | }
|
863 | return tryKeyChain(index + 1);
|
864 | });
|
865 |
|
866 | return tryKeyChain(0);
|
867 | }).call(this).asCallback(callback);
|
868 | };
|
869 |
|
870 |
|
871 |
|
872 |
|
873 |
|
874 |
|
875 |
|
876 |
|
877 |
|
878 |
|
879 |
|
880 |
|
881 |
|
882 |
|
883 |
|
884 | Wallet.prototype.createTransaction = function (params, callback) {
|
885 | params = _.extend({}, params);
|
886 | common.validateParams(params, [], [], callback);
|
887 |
|
888 | if ((!_.isNumber(params.fee) && !_.isUndefined(params.fee)) ||
|
889 | (!_.isNumber(params.feeRate) && !_.isUndefined(params.feeRate)) ||
|
890 | (!_.isNumber(params.minConfirms) && !_.isUndefined(params.minConfirms)) ||
|
891 | (!_.isBoolean(params.forceChangeAtEnd) && !_.isUndefined(params.forceChangeAtEnd)) ||
|
892 | (!_.isString(params.changeAddress) && !_.isUndefined(params.changeAddress)) ||
|
893 | (!_.isBoolean(params.validate) && !_.isUndefined(params.validate)) ||
|
894 | (!_.isBoolean(params.instant) && !_.isUndefined(params.instant))) {
|
895 | throw new Error('invalid argument');
|
896 | }
|
897 |
|
898 | if (!_.isObject(params.recipients)) {
|
899 | throw new Error('expecting recipients object');
|
900 | }
|
901 |
|
902 | params.validate = params.validate !== undefined ? params.validate : this.bitgo.getValidate();
|
903 | params.wallet = this;
|
904 |
|
905 | return TransactionBuilder.createTransaction(params)
|
906 | .nodeify(callback);
|
907 | };
|
908 |
|
909 |
|
910 |
|
911 |
|
912 |
|
913 |
|
914 |
|
915 |
|
916 |
|
917 |
|
918 |
|
919 |
|
920 |
|
921 |
|
922 |
|
923 | Wallet.prototype.signTransaction = function (params, callback) {
|
924 | params = _.extend({}, params);
|
925 | common.validateParams(params, ['transactionHex'], [], callback);
|
926 |
|
927 | if (!Array.isArray(params.unspents)) {
|
928 | throw new Error('expecting the unspents array');
|
929 | }
|
930 |
|
931 | if ((!_.isObject(params.keychain) || !params.keychain.xprv) && !_.isString(params.signingKey)) {
|
932 |
|
933 | const error: any = new Error('expecting keychain object with xprv or signingKey WIF');
|
934 | error.code = 'missing_keychain_or_signingKey';
|
935 | throw error;
|
936 | }
|
937 |
|
938 | params.validate = params.validate !== undefined ? params.validate : this.bitgo.getValidate();
|
939 | params.bitgo = this.bitgo;
|
940 | return TransactionBuilder.signTransaction(params)
|
941 | .then(function (result) {
|
942 | return {
|
943 | tx: result.transactionHex,
|
944 | };
|
945 | })
|
946 | .nodeify(callback);
|
947 | };
|
948 |
|
949 |
|
950 |
|
951 |
|
952 |
|
953 |
|
954 |
|
955 |
|
956 |
|
957 | Wallet.prototype.sendTransaction = function (params, callback) {
|
958 | params = params || {};
|
959 | common.validateParams(params, ['tx'], ['message', 'otp'], callback);
|
960 |
|
961 | return Bluebird.resolve(
|
962 | this.bitgo.post(this.bitgo.url('/tx/send')).send(params).result()
|
963 | ).then(function (body) {
|
964 | if (body.pendingApproval) {
|
965 | return _.extend(body, { status: 'pendingApproval' });
|
966 | }
|
967 |
|
968 | if (body.otp) {
|
969 | return _.extend(body, { status: 'otp' });
|
970 | }
|
971 |
|
972 | return {
|
973 | status: 'accepted',
|
974 | tx: body.transaction,
|
975 | hash: body.transactionHash,
|
976 | instant: body.instant,
|
977 | instantId: body.instantId,
|
978 | };
|
979 | })
|
980 | .nodeify(callback);
|
981 | };
|
982 |
|
983 |
|
984 |
|
985 |
|
986 |
|
987 |
|
988 |
|
989 |
|
990 | Wallet.prototype.createShare = function (params, callback) {
|
991 | params = params || {};
|
992 | common.validateParams(params, ['user', 'permissions'], [], callback);
|
993 |
|
994 | if (params.keychain && !_.isEmpty(params.keychain)) {
|
995 | if (!params.keychain.xpub || !params.keychain.encryptedXprv || !params.keychain.fromPubKey || !params.keychain.toPubKey || !params.keychain.path) {
|
996 | throw new Error('requires keychain parameters - xpub, encryptedXprv, fromPubKey, toPubKey, path');
|
997 | }
|
998 | }
|
999 |
|
1000 | return Bluebird.resolve(
|
1001 | this.bitgo.post(this.url('/share')).send(params).result()
|
1002 | ).nodeify(callback);
|
1003 | };
|
1004 |
|
1005 |
|
1006 |
|
1007 |
|
1008 |
|
1009 |
|
1010 |
|
1011 |
|
1012 |
|
1013 | Wallet.prototype.createInvite = function (params, callback) {
|
1014 | params = params || {};
|
1015 | common.validateParams(params, ['email', 'permissions'], ['message'], callback);
|
1016 |
|
1017 | const options: any = {
|
1018 | toEmail: params.email,
|
1019 | permissions: params.permissions,
|
1020 | };
|
1021 |
|
1022 | if (params.message) {
|
1023 | options.message = params.message;
|
1024 | }
|
1025 |
|
1026 | return Bluebird.resolve(
|
1027 | this.bitgo.post(this.url('/invite')).send(options).result()
|
1028 | ).nodeify(callback);
|
1029 | };
|
1030 |
|
1031 |
|
1032 |
|
1033 |
|
1034 |
|
1035 |
|
1036 |
|
1037 |
|
1038 |
|
1039 |
|
1040 | Wallet.prototype.confirmInviteAndShareWallet = function (params, callback) {
|
1041 | params = params || {};
|
1042 | common.validateParams(params, ['walletInviteId'], ['walletPassphrase'], callback);
|
1043 |
|
1044 | const self = this;
|
1045 | return this.bitgo.wallets().listInvites()
|
1046 | .then(function (invites) {
|
1047 | const outgoing = invites.outgoing;
|
1048 | const invite = _.find(outgoing, function (out) {
|
1049 | return out.id === params.walletInviteId;
|
1050 | });
|
1051 | if (!invite) {
|
1052 | throw new Error('wallet invite not found');
|
1053 | }
|
1054 |
|
1055 | const options = {
|
1056 | email: invite.toEmail,
|
1057 | permissions: invite.permissions,
|
1058 | message: invite.message,
|
1059 | walletPassphrase: params.walletPassphrase,
|
1060 | };
|
1061 |
|
1062 | return self.shareWallet(options);
|
1063 | })
|
1064 | .then(function () {
|
1065 | return this.bitgo.put(this.bitgo.url('/walletinvite/' + params.walletInviteId));
|
1066 | })
|
1067 | .nodeify(callback);
|
1068 | };
|
1069 |
|
1070 |
|
1071 |
|
1072 |
|
1073 |
|
1074 |
|
1075 |
|
1076 |
|
1077 |
|
1078 |
|
1079 |
|
1080 |
|
1081 |
|
1082 |
|
1083 |
|
1084 |
|
1085 |
|
1086 |
|
1087 |
|
1088 | Wallet.prototype.sendCoins = function (params, callback) {
|
1089 | params = params || {};
|
1090 | common.validateParams(params, ['address'], ['message'], callback);
|
1091 |
|
1092 | if (!_.isNumber(params.amount)) {
|
1093 | throw new Error('invalid argument for amount - number expected');
|
1094 | }
|
1095 |
|
1096 | params.recipients = {};
|
1097 | params.recipients[params.address] = params.amount;
|
1098 |
|
1099 | return this.sendMany(params)
|
1100 | .nodeify(callback);
|
1101 | };
|
1102 |
|
1103 |
|
1104 |
|
1105 |
|
1106 |
|
1107 |
|
1108 |
|
1109 |
|
1110 |
|
1111 |
|
1112 |
|
1113 |
|
1114 |
|
1115 |
|
1116 |
|
1117 |
|
1118 |
|
1119 | Wallet.prototype.sendMany = function (params, callback) {
|
1120 | params = params || {};
|
1121 | common.validateParams(params, [], ['message', 'otp'], callback);
|
1122 | const self = this;
|
1123 |
|
1124 | if (!_.isObject(params.recipients)) {
|
1125 | throw new Error('expecting recipients object');
|
1126 | }
|
1127 |
|
1128 | if (params.fee && !_.isNumber(params.fee)) {
|
1129 | throw new Error('invalid argument for fee - number expected');
|
1130 | }
|
1131 |
|
1132 | if (params.feeRate && !_.isNumber(params.feeRate)) {
|
1133 | throw new Error('invalid argument for feeRate - number expected');
|
1134 | }
|
1135 |
|
1136 | if (params.instant && !_.isBoolean(params.instant)) {
|
1137 | throw new Error('invalid argument for instant - boolean expected');
|
1138 | }
|
1139 |
|
1140 | let bitgoFee;
|
1141 | let travelInfos;
|
1142 | let finalResult;
|
1143 | let unspentsUsed;
|
1144 |
|
1145 | const acceptedBuildParams = [
|
1146 | 'numBlocks', 'feeRate', 'minConfirms', 'enforceMinConfirmsForChange',
|
1147 | 'targetWalletUnspents', 'message', 'minValue', 'maxValue',
|
1148 | 'noSplitChange', 'comment',
|
1149 | ];
|
1150 | const preservedBuildParams = _.pick(params, acceptedBuildParams);
|
1151 |
|
1152 |
|
1153 | const retPromise = this.createAndSignTransaction(params)
|
1154 | .then(function (transaction) {
|
1155 |
|
1156 | bitgoFee = transaction.bitgoFee;
|
1157 | travelInfos = transaction.travelInfos;
|
1158 | unspentsUsed = transaction.unspents;
|
1159 | return self.sendTransaction({
|
1160 | tx: transaction.tx,
|
1161 | message: params.message,
|
1162 | sequenceId: params.sequenceId,
|
1163 | instant: params.instant,
|
1164 | otp: params.otp,
|
1165 |
|
1166 | estimatedSize: transaction.estimatedSize,
|
1167 | buildParams: preservedBuildParams,
|
1168 | });
|
1169 | })
|
1170 | .then(function (result) {
|
1171 | const tx = utxolib.bitgo.createTransactionFromHex(result.tx, utxolib.networks.bitcoin);
|
1172 | const inputsSum = _.sumBy(unspentsUsed, 'value');
|
1173 | const outputsSum = _.sumBy(tx.outs, 'value');
|
1174 | const feeUsed = inputsSum - outputsSum;
|
1175 | if (isNaN(feeUsed)) {
|
1176 | throw new Error('invalid feeUsed');
|
1177 | }
|
1178 | result.fee = feeUsed,
|
1179 | result.feeRate = feeUsed * 1000 / tx.virtualSize();
|
1180 | result.travelInfos = travelInfos;
|
1181 | if (bitgoFee) {
|
1182 | result.bitgoFee = bitgoFee;
|
1183 | }
|
1184 | finalResult = result;
|
1185 |
|
1186 |
|
1187 |
|
1188 | if (travelInfos && travelInfos.length) {
|
1189 | try {
|
1190 | return self.pollForTransaction({ id: result.hash })
|
1191 | .then(function () {
|
1192 | return self.bitgo.travelRule().sendMany(result);
|
1193 | })
|
1194 | .then(function (res) {
|
1195 | finalResult.travelResult = res;
|
1196 | })
|
1197 | .catch(function (err) {
|
1198 |
|
1199 | finalResult.travelResult = { error: err.message };
|
1200 | });
|
1201 | } catch (err) {
|
1202 |
|
1203 | finalResult.travelResult = { error: err.message };
|
1204 | }
|
1205 | }
|
1206 | })
|
1207 | .then(function () {
|
1208 | return finalResult;
|
1209 | });
|
1210 | return Bluebird.resolve(retPromise).nodeify(callback);
|
1211 | };
|
1212 |
|
1213 |
|
1214 |
|
1215 |
|
1216 |
|
1217 |
|
1218 |
|
1219 |
|
1220 |
|
1221 |
|
1222 |
|
1223 |
|
1224 |
|
1225 |
|
1226 |
|
1227 | Wallet.prototype.accelerateTransaction = function accelerateTransaction(params, callback) {
|
1228 |
|
1229 | const self = this;
|
1230 | |
1231 |
|
1232 |
|
1233 |
|
1234 |
|
1235 |
|
1236 |
|
1237 |
|
1238 |
|
1239 |
|
1240 | const estimateTxVSize = (inputs) => {
|
1241 | const segwit = inputs.segwit || 0;
|
1242 | const P2SH = inputs.P2SH || 0;
|
1243 | const P2PKH = inputs.P2PKH || 0;
|
1244 |
|
1245 | const childFeeInfo = TransactionBuilder.calculateMinerFeeInfo({
|
1246 | nP2shInputs: P2SH,
|
1247 | nP2pkhInputs: P2PKH,
|
1248 | nP2shP2wshInputs: segwit,
|
1249 | nOutputs: 1,
|
1250 | feeRate: 1,
|
1251 | });
|
1252 |
|
1253 | return childFeeInfo.size;
|
1254 | };
|
1255 |
|
1256 | |
1257 |
|
1258 |
|
1259 |
|
1260 |
|
1261 |
|
1262 |
|
1263 |
|
1264 |
|
1265 | const estimateChildFee = ({ inputs, parentFee, parentVSize, feeRate }) => {
|
1266 |
|
1267 |
|
1268 | const additionalParentFee = _.ceil(parentVSize * feeRate / 1000) - parentFee;
|
1269 |
|
1270 |
|
1271 |
|
1272 | const childFee = estimateTxVSize(inputs) * feeRate / 1000;
|
1273 |
|
1274 | return _.ceil(childFee + additionalParentFee);
|
1275 | };
|
1276 |
|
1277 | |
1278 |
|
1279 |
|
1280 |
|
1281 |
|
1282 |
|
1283 |
|
1284 |
|
1285 |
|
1286 |
|
1287 |
|
1288 |
|
1289 |
|
1290 | const findAdditionalUnspents = ({ inputs, parentOutputValue, parentFee, parentVSize, maxUnspents }) => {
|
1291 | return co(function *coFindAdditionalUnspents() {
|
1292 |
|
1293 | const additionalUnspents: any[] = [];
|
1294 |
|
1295 |
|
1296 |
|
1297 |
|
1298 |
|
1299 | let currentChildFeeEstimate = estimateChildFee({ inputs, parentFee, parentVSize, feeRate: params.feeRate });
|
1300 | let uncoveredChildFee = currentChildFeeEstimate - parentOutputValue;
|
1301 |
|
1302 | while (uncoveredChildFee > 0 && additionalUnspents.length < maxUnspents) {
|
1303 |
|
1304 | const unspents = (yield this.unspents({
|
1305 | minConfirms: 1,
|
1306 | target: uncoveredChildFee,
|
1307 | limit: maxUnspents - additionalUnspents.length,
|
1308 | })) as any;
|
1309 |
|
1310 | if (unspents.length === 0) {
|
1311 |
|
1312 | break;
|
1313 | }
|
1314 |
|
1315 | let additionalUnspentValue = 0;
|
1316 |
|
1317 |
|
1318 |
|
1319 |
|
1320 |
|
1321 |
|
1322 | _.forEach(unspents, (unspent) => {
|
1323 |
|
1324 | const unspentChain = getChain(unspent);
|
1325 | if (isChainCode(unspentChain) && scriptTypeForChain(unspentChain) === 'p2shP2wsh') {
|
1326 | inputs.segwit++;
|
1327 | } else {
|
1328 | inputs.P2SH++;
|
1329 | }
|
1330 |
|
1331 | additionalUnspents.push(unspent);
|
1332 | additionalUnspentValue += unspent.value;
|
1333 | });
|
1334 |
|
1335 | currentChildFeeEstimate = estimateChildFee({ inputs, parentFee, parentVSize, feeRate: params.feeRate });
|
1336 | uncoveredChildFee = currentChildFeeEstimate - parentOutputValue - additionalUnspentValue;
|
1337 | }
|
1338 |
|
1339 | if (uncoveredChildFee > 0) {
|
1340 |
|
1341 | throw new Error(`Insufficient confirmed unspents available to cover the child fee`);
|
1342 | }
|
1343 |
|
1344 |
|
1345 | return {
|
1346 | additional: additionalUnspents,
|
1347 | newChildFee: currentChildFeeEstimate,
|
1348 | newInputs: inputs,
|
1349 | };
|
1350 | }).call(this);
|
1351 | };
|
1352 |
|
1353 | |
1354 |
|
1355 |
|
1356 |
|
1357 |
|
1358 |
|
1359 |
|
1360 |
|
1361 |
|
1362 |
|
1363 | async function getParentTxHex({ parentTxId }: { parentTxId: string }): Promise<string> {
|
1364 | const explorerBaseUrl = common.Environments[self.bitgo.getEnv()].btcExplorerBaseUrl;
|
1365 | const result = await request.get(`${explorerBaseUrl}/tx/${parentTxId}/hex`);
|
1366 |
|
1367 | if (!result.text || !/([a-f0-9]{2})+/.test(result.text)) {
|
1368 | throw new Error(`Did not successfully receive parent tx hex. Received '${_.truncate(result.text, { length: 100 })}' instead.`);
|
1369 | }
|
1370 |
|
1371 | return result.text;
|
1372 | }
|
1373 |
|
1374 | |
1375 |
|
1376 |
|
1377 |
|
1378 |
|
1379 |
|
1380 | const getChain = (outputOrUnspent) => {
|
1381 | if (outputOrUnspent.chain !== undefined) {
|
1382 | return outputOrUnspent.chain;
|
1383 | }
|
1384 |
|
1385 | if (outputOrUnspent.chainPath !== undefined) {
|
1386 | return _.toNumber(outputOrUnspent.chainPath.split('/')[1]);
|
1387 | }
|
1388 |
|
1389 |
|
1390 |
|
1391 |
|
1392 |
|
1393 | throw Error(`Could not get chain for output on account ${outputOrUnspent.account || outputOrUnspent.address}`);
|
1394 | };
|
1395 |
|
1396 | |
1397 |
|
1398 |
|
1399 |
|
1400 |
|
1401 |
|
1402 |
|
1403 |
|
1404 |
|
1405 |
|
1406 | const effectiveValue = (outputOrUnspent) => {
|
1407 | const chain = getChain(outputOrUnspent);
|
1408 | if (isChainCode(chain) && scriptTypeForChain(chain) === 'p2shP2wsh') {
|
1409 |
|
1410 | return outputOrUnspent.value - (VirtualSizes.txP2shP2wshInputSize * params.feeRate / 1000);
|
1411 | }
|
1412 |
|
1413 | return outputOrUnspent.value - (VirtualSizes.txP2shInputSize * params.feeRate / 1000);
|
1414 | };
|
1415 |
|
1416 | |
1417 |
|
1418 |
|
1419 |
|
1420 |
|
1421 |
|
1422 |
|
1423 |
|
1424 |
|
1425 |
|
1426 |
|
1427 |
|
1428 |
|
1429 | return co(function *coAccelerateTransaction(): any {
|
1430 | params = params || {};
|
1431 | common.validateParams(params, ['transactionID'], [], callback);
|
1432 |
|
1433 |
|
1434 | if (params.feeRate === undefined) {
|
1435 | throw new Error('Missing parameter: feeRate');
|
1436 | }
|
1437 | if (!_.isFinite(params.feeRate) || params.feeRate <= 0) {
|
1438 | throw new Error('Expecting positive finite number for parameter: feeRate');
|
1439 | }
|
1440 |
|
1441 |
|
1442 | if (params.maxAdditionalUnspents === undefined) {
|
1443 |
|
1444 | params.maxAdditionalUnspents = 100;
|
1445 | }
|
1446 |
|
1447 | if (!_.isInteger(params.maxAdditionalUnspents) || params.maxAdditionalUnspents <= 0) {
|
1448 | throw Error('Expecting positive integer for parameter: maxAdditionalUnspents');
|
1449 | }
|
1450 |
|
1451 | const parentTx = yield this.getTransaction({ id: params.transactionID });
|
1452 | if (parentTx.confirmations > 0) {
|
1453 | throw new Error(`Transaction ${params.transactionID} is already confirmed and cannot be accelerated`);
|
1454 | }
|
1455 |
|
1456 |
|
1457 | const walletOutputs = _.filter(parentTx.outputs, (output) => output.isMine);
|
1458 |
|
1459 | if (walletOutputs.length === 0) {
|
1460 | throw new Error(`Transaction ${params.transactionID} contains no outputs to this wallet, and thus cannot be accelerated`);
|
1461 | }
|
1462 |
|
1463 |
|
1464 |
|
1465 |
|
1466 |
|
1467 |
|
1468 | const sortedOutputs = _.sortBy(walletOutputs, effectiveValue);
|
1469 | let parentUnspentToUse;
|
1470 | let outputToUse;
|
1471 |
|
1472 | while (sortedOutputs.length > 0 && parentUnspentToUse === undefined) {
|
1473 | outputToUse = sortedOutputs.pop();
|
1474 |
|
1475 |
|
1476 |
|
1477 |
|
1478 | const unspentsResult = yield this.unspents({
|
1479 | minSize: outputToUse.value,
|
1480 | maxSize: outputToUse.value,
|
1481 | });
|
1482 |
|
1483 | parentUnspentToUse = _.find(unspentsResult, (unspent) => {
|
1484 |
|
1485 | if (unspent.tx_hash !== params.transactionID) {
|
1486 | return false;
|
1487 | }
|
1488 |
|
1489 | return unspent.tx_output_n === outputToUse.vout;
|
1490 | });
|
1491 | }
|
1492 |
|
1493 | if (parentUnspentToUse === undefined) {
|
1494 | throw new Error(`Could not find unspent output from parent tx to use as child input`);
|
1495 | }
|
1496 |
|
1497 |
|
1498 | const parentTxHex = yield getParentTxHex({ parentTxId: params.transactionID });
|
1499 | const decodedParent = utxolib.bitgo.createTransactionFromHex(parentTxHex, utxolib.networks.bitcoin);
|
1500 | const parentVSize = decodedParent.virtualSize();
|
1501 |
|
1502 |
|
1503 |
|
1504 |
|
1505 | if (decodedParent.getId() !== params.transactionID) {
|
1506 | throw new Error(`Decoded transaction id is ${decodedParent.getId()}, which does not match given txid ${params.transactionID}`);
|
1507 | }
|
1508 |
|
1509 |
|
1510 |
|
1511 | const parentRate = 1000 * parentTx.fee / parentVSize;
|
1512 | if (params.feeRate <= parentRate) {
|
1513 | throw new Error(`Cannot lower fee rate! (Parent tx fee rate is ${parentRate} sat/kB, and requested fee rate was ${params.feeRate} sat/kB)`);
|
1514 | }
|
1515 |
|
1516 |
|
1517 | const isParentOutputSegwit =
|
1518 | isChainCode(outputToUse.chain) && scriptTypeForChain(outputToUse.chain) === 'p2shP2wsh';
|
1519 |
|
1520 | let childInputs = {
|
1521 | segwit: isParentOutputSegwit ? 1 : 0,
|
1522 | P2SH: isParentOutputSegwit ? 0 : 1,
|
1523 | };
|
1524 |
|
1525 | let childFee = estimateChildFee({
|
1526 | inputs: childInputs,
|
1527 | parentFee: parentTx.fee,
|
1528 | feeRate: params.feeRate,
|
1529 | parentVSize,
|
1530 | });
|
1531 |
|
1532 | const unspentsToUse = [parentUnspentToUse];
|
1533 |
|
1534 |
|
1535 |
|
1536 | const minChangeSize = this.bitgo.getConstants().minChangeSize || 1e7;
|
1537 |
|
1538 | if (outputToUse.value < childFee + minChangeSize) {
|
1539 |
|
1540 |
|
1541 | const { additional, newChildFee, newInputs } = yield findAdditionalUnspents({
|
1542 | inputs: childInputs,
|
1543 | parentOutputValue: outputToUse.value,
|
1544 | parentFee: parentTx.fee,
|
1545 | maxUnspents: params.maxAdditionalUnspents,
|
1546 | parentVSize,
|
1547 | });
|
1548 | childFee = newChildFee;
|
1549 | childInputs = newInputs;
|
1550 | unspentsToUse.push(... additional);
|
1551 | }
|
1552 |
|
1553 |
|
1554 |
|
1555 |
|
1556 | const maxFeeRate = this.bitgo.getConstants().maxFeeRate;
|
1557 | const childVSize = estimateTxVSize(childInputs);
|
1558 | const combinedVSize = childVSize + parentVSize;
|
1559 | const combinedFee = parentTx.fee + childFee;
|
1560 |
|
1561 | const combinedFeeRate = 1000 * combinedFee / combinedVSize;
|
1562 |
|
1563 | if (combinedFeeRate > maxFeeRate) {
|
1564 | throw new Error(`Transaction cannot be accelerated. Combined fee rate of ${combinedFeeRate} sat/kB exceeds maximum fee rate of ${maxFeeRate} sat/kB`);
|
1565 | }
|
1566 |
|
1567 |
|
1568 |
|
1569 |
|
1570 |
|
1571 | const changeAmount = _.sumBy(unspentsToUse, (unspent) => unspent.value) - childFee;
|
1572 | const changeChain = this.getChangeChain({});
|
1573 | const changeAddress = yield this.createAddress({ chain: changeChain });
|
1574 |
|
1575 |
|
1576 | const tx = yield this.createAndSignTransaction({
|
1577 | unspents: unspentsToUse,
|
1578 | recipients: [{
|
1579 | address: changeAddress.address,
|
1580 | amount: changeAmount,
|
1581 | }],
|
1582 | fee: childFee,
|
1583 | bitgoFee: {
|
1584 | amount: 0,
|
1585 | address: '',
|
1586 | },
|
1587 | xprv: params.xprv,
|
1588 | walletPassphrase: params.walletPassphrase,
|
1589 | });
|
1590 |
|
1591 |
|
1592 |
|
1593 | const childFeeRate = 1000 * childFee / childVSize;
|
1594 | if (childFeeRate > maxFeeRate) {
|
1595 |
|
1596 |
|
1597 | tx.ignoreMaxFeeRate = true;
|
1598 | }
|
1599 |
|
1600 | return this.sendTransaction(tx);
|
1601 | }).call(this).asCallback(callback);
|
1602 | };
|
1603 |
|
1604 |
|
1605 |
|
1606 |
|
1607 |
|
1608 |
|
1609 |
|
1610 |
|
1611 |
|
1612 |
|
1613 |
|
1614 | Wallet.prototype.createAndSignTransaction = function (params, callback) {
|
1615 | return co(function *() {
|
1616 | params = params || {};
|
1617 | common.validateParams(params, [], [], callback);
|
1618 |
|
1619 | if (!_.isObject(params.recipients)) {
|
1620 | throw new Error('expecting recipients object');
|
1621 | }
|
1622 |
|
1623 | if (params.fee && !_.isNumber(params.fee)) {
|
1624 | throw new Error('invalid argument for fee - number expected');
|
1625 | }
|
1626 |
|
1627 | if (params.feeRate && !_.isNumber(params.feeRate)) {
|
1628 | throw new Error('invalid argument for feeRate - number expected');
|
1629 | }
|
1630 |
|
1631 | if (params.dynamicFeeConfirmTarget && !_.isNumber(params.dynamicFeeConfirmTarget)) {
|
1632 | throw new Error('invalid argument for confirmTarget - number expected');
|
1633 | }
|
1634 |
|
1635 | if (params.instant && !_.isBoolean(params.instant)) {
|
1636 | throw new Error('invalid argument for instant - boolean expected');
|
1637 | }
|
1638 |
|
1639 | const transaction = (yield this.createTransaction(params)) as any;
|
1640 | const fee = transaction.fee;
|
1641 | const feeRate = transaction.feeRate;
|
1642 | const estimatedSize = transaction.estimatedSize;
|
1643 | const bitgoFee = transaction.bitgoFee;
|
1644 | const travelInfos = transaction.travelInfos;
|
1645 | const unspents = transaction.unspents;
|
1646 |
|
1647 |
|
1648 | try {
|
1649 | const keychain = yield this.getAndPrepareSigningKeychain(params);
|
1650 | transaction.keychain = keychain;
|
1651 | } catch (e) {
|
1652 | if (e.code !== 'no_encrypted_keychain_on_wallet') {
|
1653 | throw e;
|
1654 | }
|
1655 |
|
1656 | yield this.refresh({ gpk: true });
|
1657 | const safeUserKey = _.get(this.wallet, 'private.userPrivKey');
|
1658 | if (_.isString(safeUserKey) && _.isString(params.walletPassphrase)) {
|
1659 | transaction.signingKey = this.bitgo.decrypt({ password: params.walletPassphrase, input: safeUserKey });
|
1660 | } else {
|
1661 | throw e;
|
1662 | }
|
1663 | }
|
1664 |
|
1665 | transaction.feeSingleKeyWIF = params.feeSingleKeyWIF;
|
1666 | const result = yield this.signTransaction(transaction);
|
1667 | return _.extend(result, {
|
1668 | fee,
|
1669 | feeRate,
|
1670 | instant: params.instant,
|
1671 | bitgoFee,
|
1672 | travelInfos,
|
1673 | estimatedSize,
|
1674 | unspents,
|
1675 | });
|
1676 | }).call(this).asCallback(callback);
|
1677 | };
|
1678 |
|
1679 |
|
1680 |
|
1681 |
|
1682 |
|
1683 |
|
1684 |
|
1685 |
|
1686 |
|
1687 |
|
1688 |
|
1689 |
|
1690 |
|
1691 |
|
1692 |
|
1693 |
|
1694 | Wallet.prototype.getAndPrepareSigningKeychain = function (params, callback) {
|
1695 | params = params || {};
|
1696 |
|
1697 |
|
1698 | if (_.isObject(params.keychain) && params.keychain.xprv) {
|
1699 | return Bluebird.resolve(params.keychain);
|
1700 | }
|
1701 |
|
1702 | common.validateParams(params, [], ['walletPassphrase', 'xprv'], callback);
|
1703 |
|
1704 | if ((params.walletPassphrase && params.xprv) || (!params.walletPassphrase && !params.xprv)) {
|
1705 | throw new Error('must provide exactly one of xprv or walletPassphrase');
|
1706 | }
|
1707 |
|
1708 | const self = this;
|
1709 |
|
1710 |
|
1711 | if (params.walletPassphrase) {
|
1712 | return self.getEncryptedUserKeychain()
|
1713 | .then(function (keychain) {
|
1714 |
|
1715 | try {
|
1716 | keychain.xprv = self.bitgo.decrypt({ password: params.walletPassphrase, input: keychain.encryptedXprv });
|
1717 | } catch (e) {
|
1718 | throw new Error('Unable to decrypt user keychain');
|
1719 | }
|
1720 | return keychain;
|
1721 | });
|
1722 | }
|
1723 |
|
1724 |
|
1725 | let xpub;
|
1726 | try {
|
1727 | xpub = bip32.fromBase58(params.xprv).neutered().toBase58();
|
1728 | } catch (e) {
|
1729 | throw new Error('Unable to parse the xprv');
|
1730 | }
|
1731 |
|
1732 | if (xpub === params.xprv) {
|
1733 | throw new Error('xprv provided was not a private key (found xpub instead)');
|
1734 | }
|
1735 |
|
1736 | const walletXpubs = _.map(self.keychains, 'xpub');
|
1737 | if (!_.includes(walletXpubs, xpub)) {
|
1738 | throw new Error('xprv provided was not a keychain on this wallet!');
|
1739 | }
|
1740 |
|
1741 |
|
1742 | return self.bitgo.keychains().get({ xpub: xpub })
|
1743 | .then(function (keychain) {
|
1744 | keychain.xprv = params.xprv;
|
1745 | return keychain;
|
1746 | });
|
1747 | };
|
1748 |
|
1749 |
|
1750 |
|
1751 |
|
1752 |
|
1753 |
|
1754 |
|
1755 |
|
1756 |
|
1757 |
|
1758 |
|
1759 | Wallet.prototype.fanOutUnspents = function (params, callback) {
|
1760 | const self = this;
|
1761 | return Bluebird.coroutine(function *() {
|
1762 |
|
1763 |
|
1764 | const MAX_FANOUT_INPUT_COUNT = 80;
|
1765 |
|
1766 | const MAX_FANOUT_OUTPUT_COUNT = 300;
|
1767 | params = params || {};
|
1768 | common.validateParams(params, [], ['walletPassphrase', 'xprv'], callback);
|
1769 | const validate = params.validate === undefined ? true : params.validate;
|
1770 |
|
1771 | const target = params.target;
|
1772 |
|
1773 | if (!_.isNumber(target) || target < 2 || (target % 1) !== 0) {
|
1774 | throw new Error('Target needs to be a positive integer');
|
1775 | }
|
1776 | if (target > MAX_FANOUT_OUTPUT_COUNT) {
|
1777 | throw new Error('Fan out target too high');
|
1778 | }
|
1779 |
|
1780 | let minConfirms = params.minConfirms;
|
1781 | if (minConfirms === undefined) {
|
1782 | minConfirms = 1;
|
1783 | }
|
1784 | if (!_.isNumber(minConfirms) || minConfirms < 0) {
|
1785 | throw new Error('minConfirms needs to be an integer >= 0');
|
1786 | }
|
1787 |
|
1788 | |
1789 |
|
1790 |
|
1791 |
|
1792 |
|
1793 |
|
1794 |
|
1795 |
|
1796 |
|
1797 | const splitNumberIntoCloseNaturalNumbers = function (total, partCount) {
|
1798 | const partSize = Math.floor(total / partCount);
|
1799 | const remainder = total - partSize * partCount;
|
1800 |
|
1801 | const almostEqualParts = new Array(partCount);
|
1802 |
|
1803 | _.fill(almostEqualParts, partSize + 1, 0, remainder);
|
1804 |
|
1805 | _.fill(almostEqualParts, partSize, remainder);
|
1806 |
|
1807 |
|
1808 | if (_(almostEqualParts).sum() !== total || _(almostEqualParts).size() !== partCount) {
|
1809 | throw new Error('part sum or part count mismatch');
|
1810 | }
|
1811 | return almostEqualParts;
|
1812 | };
|
1813 |
|
1814 |
|
1815 | const allUnspents = (yield self.unspents({ minConfirms: minConfirms })) as any;
|
1816 | if (allUnspents.length < 1) {
|
1817 | throw new Error('No unspents to branch out');
|
1818 | }
|
1819 |
|
1820 |
|
1821 | if (allUnspents.length >= target) {
|
1822 | throw new Error('Fan out target has to be bigger than current number of unspents');
|
1823 | }
|
1824 |
|
1825 |
|
1826 |
|
1827 | if (allUnspents.length > MAX_FANOUT_INPUT_COUNT) {
|
1828 | throw new Error('Too many unspents');
|
1829 | }
|
1830 |
|
1831 |
|
1832 | const grossAmount = _(allUnspents).map('value').sum();
|
1833 |
|
1834 |
|
1835 | const txParams = _.extend({}, params);
|
1836 | txParams.unspents = allUnspents;
|
1837 | txParams.recipients = {};
|
1838 |
|
1839 |
|
1840 | const newAddressPromises = _.range(target)
|
1841 | .map(() => self.createAddress({ chain: self.getChangeChain(params), validate: validate }));
|
1842 | const newAddresses = yield Bluebird.all(newAddressPromises);
|
1843 |
|
1844 | const splitAmounts = splitNumberIntoCloseNaturalNumbers(grossAmount, target);
|
1845 |
|
1846 | txParams.recipients = _.zipObject(_.map(newAddresses, 'address'), splitAmounts);
|
1847 | txParams.noSplitChange = true;
|
1848 |
|
1849 | try {
|
1850 | yield self.sendMany(txParams);
|
1851 | } catch (error) {
|
1852 |
|
1853 |
|
1854 |
|
1855 | if (!error.fee && (!error.result || !error.result.fee)) {
|
1856 |
|
1857 | const debugParams = _.omit(txParams, ['walletPassphrase', 'xprv']);
|
1858 | error.message += `\n\nTX PARAMS:\n ${JSON.stringify(debugParams, null, 4)}`;
|
1859 | throw error;
|
1860 | }
|
1861 | const baseFee = error.fee || error.result.fee;
|
1862 | let totalFee = baseFee;
|
1863 | if (error.result.bitgoFee && error.result.bitgoFee.amount) {
|
1864 | totalFee += error.result.bitgoFee.amount;
|
1865 | txParams.bitgoFee = error.result.bitgoFee;
|
1866 | }
|
1867 |
|
1868 |
|
1869 | delete txParams.fee;
|
1870 | txParams.originalFeeRate = txParams.feeRate;
|
1871 | delete txParams.feeRate;
|
1872 | delete txParams.feeTxConfirmTarget;
|
1873 | txParams.fee = baseFee;
|
1874 |
|
1875 |
|
1876 | const netAmount = error.result.available - totalFee;
|
1877 |
|
1878 | const remainingSplitAmounts = splitNumberIntoCloseNaturalNumbers(netAmount, target);
|
1879 |
|
1880 | txParams.recipients = _.zipObject(_.map(newAddresses, 'address'), remainingSplitAmounts);
|
1881 | }
|
1882 |
|
1883 |
|
1884 | let fanoutTx;
|
1885 | try {
|
1886 | fanoutTx = yield self.sendMany(txParams);
|
1887 | } catch (e) {
|
1888 | const debugParams = _.omit(txParams, ['walletPassphrase', 'xprv']);
|
1889 | e.message += `\n\nTX PARAMS:\n ${JSON.stringify(debugParams, null, 4)}`;
|
1890 | throw e;
|
1891 | }
|
1892 |
|
1893 | return Bluebird.resolve(fanoutTx).asCallback(callback);
|
1894 | })().asCallback(callback);
|
1895 | };
|
1896 |
|
1897 |
|
1898 |
|
1899 |
|
1900 |
|
1901 |
|
1902 |
|
1903 | Wallet.prototype.regroupUnspents = function (params, callback) {
|
1904 | params = params || {};
|
1905 | const target = params.target;
|
1906 | if (!_.isNumber(target) || target < 1 || (target % 1) !== 0) {
|
1907 |
|
1908 | throw new Error('Target needs to be a positive integer');
|
1909 | }
|
1910 |
|
1911 | let minConfirms = params.minConfirms;
|
1912 | if (minConfirms === undefined) {
|
1913 | minConfirms = 1;
|
1914 | }
|
1915 | if ((!_.isNumber(minConfirms) || minConfirms < 0)) {
|
1916 | throw new Error('minConfirms needs to be an integer equal to or bigger than 0');
|
1917 | }
|
1918 |
|
1919 | const self = this;
|
1920 | return self.unspents({ minConfirms: minConfirms })
|
1921 | .then(function (unspents) {
|
1922 | if (unspents.length === target) {
|
1923 | return unspents;
|
1924 | } else if (unspents.length > target) {
|
1925 | return self.consolidateUnspents(params, callback);
|
1926 | } else if (unspents.length < target) {
|
1927 | return self.fanOutUnspents(params, callback);
|
1928 | }
|
1929 | });
|
1930 | };
|
1931 |
|
1932 |
|
1933 |
|
1934 |
|
1935 |
|
1936 |
|
1937 |
|
1938 |
|
1939 |
|
1940 |
|
1941 |
|
1942 |
|
1943 |
|
1944 | Wallet.prototype.consolidateUnspents = function (params, callback) {
|
1945 | params = params || {};
|
1946 | common.validateParams(params, [], ['walletPassphrase', 'xprv'], callback);
|
1947 | const validate = params.validate === undefined ? true : params.validate;
|
1948 |
|
1949 | let target = params.target;
|
1950 | if (target === undefined) {
|
1951 | target = 1;
|
1952 | } else if (!_.isNumber(target) || target < 1 || (target % 1) !== 0) {
|
1953 |
|
1954 | throw new Error('Target needs to be a positive integer');
|
1955 | }
|
1956 |
|
1957 | if (params.maxSize && !_.isNumber(params.maxSize)) {
|
1958 | throw new Error('maxSize should be a number');
|
1959 | }
|
1960 |
|
1961 | if (params.minSize && !_.isNumber(params.minSize)) {
|
1962 | throw new Error('minSize should be a number');
|
1963 | }
|
1964 |
|
1965 |
|
1966 | const MAX_INPUT_COUNT = 200;
|
1967 | let maxInputCount = params.maxInputCountPerConsolidation;
|
1968 | if (maxInputCount === undefined) {
|
1969 | maxInputCount = MAX_INPUT_COUNT;
|
1970 | }
|
1971 | if (typeof (maxInputCount) !== 'number' || maxInputCount < 2 || (maxInputCount % 1) !== 0) {
|
1972 | throw new Error('Maximum consolidation input count needs to be an integer equal to or bigger than 2');
|
1973 | } else if (maxInputCount > MAX_INPUT_COUNT) {
|
1974 | throw new Error('Maximum consolidation input count cannot be bigger than ' + MAX_INPUT_COUNT);
|
1975 | }
|
1976 |
|
1977 | const maxIterationCount = params.maxIterationCount || -1;
|
1978 | if (params.maxIterationCount && (!_.isNumber(maxIterationCount) || maxIterationCount < 1) || (maxIterationCount % 1) !== 0) {
|
1979 | throw new Error('Maximum iteration count needs to be an integer equal to or bigger than 1');
|
1980 | }
|
1981 |
|
1982 | let minConfirms = params.minConfirms;
|
1983 | if (minConfirms === undefined) {
|
1984 | minConfirms = 1;
|
1985 | }
|
1986 | if ((!_.isNumber(minConfirms) || minConfirms < 0)) {
|
1987 | throw new Error('minConfirms needs to be an integer equal to or bigger than 0');
|
1988 | }
|
1989 |
|
1990 | let minSize = params.minSize || 0;
|
1991 | if (params.feeRate) {
|
1992 |
|
1993 | const feeBasedMinSize = Math.ceil(VirtualSizes.txP2shInputSize * params.feeRate / 1000);
|
1994 | if (params.minSize && minSize < feeBasedMinSize) {
|
1995 | throw new Error('provided minSize too low due to too high fee rate');
|
1996 | }
|
1997 | minSize = Math.max(feeBasedMinSize, minSize);
|
1998 |
|
1999 | if (!params.minSize) {
|
2000 |
|
2001 | console.log('Only consolidating unspents larger than ' + minSize + ' satoshis to avoid wasting money on fees. To consolidate smaller unspents, use a lower fee rate.');
|
2002 | }
|
2003 | }
|
2004 |
|
2005 | let iterationCount = 0;
|
2006 |
|
2007 | const self = this;
|
2008 | let consolidationIndex = 0;
|
2009 |
|
2010 | |
2011 |
|
2012 |
|
2013 |
|
2014 | const runNextConsolidation = co(function *() {
|
2015 | const consolidationTransactions: any[] = [];
|
2016 | let isFinalConsolidation = false;
|
2017 | iterationCount++;
|
2018 | |
2019 |
|
2020 |
|
2021 |
|
2022 |
|
2023 |
|
2024 |
|
2025 |
|
2026 |
|
2027 |
|
2028 |
|
2029 |
|
2030 | const queryParams: any = {
|
2031 | limit: target + maxInputCount,
|
2032 | minConfirms: minConfirms,
|
2033 | minSize: minSize,
|
2034 | };
|
2035 | if (params.maxSize) {
|
2036 | queryParams.maxSize = params.maxSize;
|
2037 | }
|
2038 | const allUnspents = (yield self.unspents(queryParams)) as any;
|
2039 |
|
2040 | if (allUnspents.length <= target) {
|
2041 | if (iterationCount <= 1) {
|
2042 |
|
2043 | throw new Error('Fewer unspents than consolidation target. Use fanOutUnspents instead.');
|
2044 | } else {
|
2045 |
|
2046 | throw new Error('Done');
|
2047 | }
|
2048 | }
|
2049 |
|
2050 | const allUnspentsCount = allUnspents.length;
|
2051 |
|
2052 |
|
2053 |
|
2054 | let targetInputCount = allUnspentsCount - target + 1;
|
2055 | targetInputCount = Math.min(targetInputCount, allUnspents.length);
|
2056 |
|
2057 |
|
2058 | const inputCount = Math.min(targetInputCount, maxInputCount);
|
2059 |
|
2060 |
|
2061 |
|
2062 | isFinalConsolidation = (inputCount === targetInputCount || iterationCount === maxIterationCount);
|
2063 |
|
2064 | const currentChunk = allUnspents.splice(0, inputCount);
|
2065 | const changeChain = self.getChangeChain(params);
|
2066 | const newAddress = (yield self.createAddress({ chain: changeChain, validate: validate })) as any;
|
2067 | const txParams = _.extend({}, params);
|
2068 | const currentAddress = newAddress;
|
2069 |
|
2070 | const grossAmount = _(currentChunk).map('value').sum();
|
2071 |
|
2072 | txParams.unspents = currentChunk;
|
2073 | txParams.recipients = {};
|
2074 | txParams.recipients[newAddress.address] = grossAmount;
|
2075 | txParams.noSplitChange = true;
|
2076 |
|
2077 | if (txParams.unspents.length <= 1) {
|
2078 | throw new Error('Done');
|
2079 | }
|
2080 |
|
2081 |
|
2082 | try {
|
2083 | yield self.sendMany(txParams);
|
2084 | } catch (error) {
|
2085 |
|
2086 |
|
2087 | if (!error.fee && (!error.result || !error.result.fee)) {
|
2088 |
|
2089 | const debugParams = _.omit(txParams, ['walletPassphrase', 'xprv']);
|
2090 | error.message += `\n\nTX PARAMS:\n ${JSON.stringify(debugParams, null, 4)}`;
|
2091 | throw error;
|
2092 | }
|
2093 | const baseFee = error.fee || error.result.fee;
|
2094 | let bitgoFee = 0;
|
2095 | let totalFee = baseFee;
|
2096 | if (error.result.bitgoFee && error.result.bitgoFee.amount) {
|
2097 | bitgoFee = error.result.bitgoFee.amount;
|
2098 | totalFee += bitgoFee;
|
2099 | txParams.bitgoFee = error.result.bitgoFee;
|
2100 | }
|
2101 |
|
2102 |
|
2103 | const netAmount = Math.max(error.result.available - totalFee, self.bitgo.getConstants().minOutputSize);
|
2104 |
|
2105 | delete txParams.fee;
|
2106 | txParams.originalFeeRate = txParams.feeRate;
|
2107 | delete txParams.feeRate;
|
2108 | delete txParams.feeTxConfirmTarget;
|
2109 |
|
2110 |
|
2111 | txParams.fee = error.result.available - netAmount - bitgoFee;
|
2112 | txParams.recipients[newAddress.address] = netAmount;
|
2113 | }
|
2114 |
|
2115 | let sentTx;
|
2116 | try {
|
2117 | sentTx = yield self.sendMany(txParams);
|
2118 | } catch (e) {
|
2119 | const debugParams = _.omit(txParams, ['walletPassphrase', 'xprv']);
|
2120 | e.message += `\n\nTX PARAMS:\n ${JSON.stringify(debugParams, null, 4)}`;
|
2121 | throw e;
|
2122 | }
|
2123 | consolidationTransactions.push(sentTx);
|
2124 | if (_.isFunction(params.progressCallback)) {
|
2125 | params.progressCallback({
|
2126 | txid: sentTx.hash,
|
2127 | destination: currentAddress,
|
2128 | amount: grossAmount,
|
2129 | fee: sentTx.fee,
|
2130 | inputCount: inputCount,
|
2131 | index: consolidationIndex,
|
2132 | });
|
2133 | }
|
2134 | consolidationIndex++;
|
2135 | if (!isFinalConsolidation) {
|
2136 |
|
2137 |
|
2138 |
|
2139 | yield Bluebird.delay(1000);
|
2140 | consolidationTransactions.push(...((yield runNextConsolidation()) as any));
|
2141 | }
|
2142 |
|
2143 | return consolidationTransactions;
|
2144 | });
|
2145 |
|
2146 | return runNextConsolidation(this, target)
|
2147 | .catch(function (err) {
|
2148 | if (err.message === 'Done') {
|
2149 | return;
|
2150 | }
|
2151 | throw err;
|
2152 | })
|
2153 | .nodeify(callback);
|
2154 | };
|
2155 |
|
2156 | Wallet.prototype.shareWallet = function (params, callback) {
|
2157 | params = params || {};
|
2158 | common.validateParams(params, ['email', 'permissions'], ['walletPassphrase', 'message'], callback);
|
2159 |
|
2160 | if (params.reshare !== undefined && !_.isBoolean(params.reshare)) {
|
2161 | throw new Error('Expected reshare to be a boolean.');
|
2162 | }
|
2163 |
|
2164 | if (params.skipKeychain !== undefined && !_.isBoolean(params.skipKeychain)) {
|
2165 | throw new Error('Expected skipKeychain to be a boolean. ');
|
2166 | }
|
2167 | const needsKeychain = !params.skipKeychain && params.permissions.indexOf('spend') !== -1;
|
2168 |
|
2169 | if (params.disableEmail !== undefined && !_.isBoolean(params.disableEmail)) {
|
2170 | throw new Error('Expected disableEmail to be a boolean.');
|
2171 | }
|
2172 |
|
2173 | const self = this;
|
2174 | let sharing;
|
2175 | let sharedKeychain;
|
2176 | return this.bitgo.getSharingKey({ email: params.email.toLowerCase() })
|
2177 | .then(function (result) {
|
2178 | sharing = result;
|
2179 |
|
2180 | if (needsKeychain) {
|
2181 | return self.getEncryptedUserKeychain({})
|
2182 | .then(function (keychain) {
|
2183 |
|
2184 | if (keychain.encryptedXprv) {
|
2185 | if (!params.walletPassphrase) {
|
2186 | throw new Error('Missing walletPassphrase argument');
|
2187 | }
|
2188 | try {
|
2189 | keychain.xprv = self.bitgo.decrypt({ password: params.walletPassphrase, input: keychain.encryptedXprv });
|
2190 | } catch (e) {
|
2191 | throw new Error('Unable to decrypt user keychain');
|
2192 | }
|
2193 |
|
2194 | const eckey = makeRandomKey();
|
2195 | const secret = getSharedSecret(eckey, Buffer.from(sharing.pubkey, 'hex')).toString('hex');
|
2196 | const newEncryptedXprv = self.bitgo.encrypt({ password: secret, input: keychain.xprv });
|
2197 |
|
2198 | sharedKeychain = {
|
2199 | xpub: keychain.xpub,
|
2200 | encryptedXprv: newEncryptedXprv,
|
2201 | fromPubKey: eckey.publicKey.toString('hex'),
|
2202 | toPubKey: sharing.pubkey,
|
2203 | path: sharing.path,
|
2204 | };
|
2205 | }
|
2206 | });
|
2207 | }
|
2208 | })
|
2209 | .then(function () {
|
2210 | interface Options {
|
2211 | user: any;
|
2212 | permissions: string;
|
2213 | reshare: boolean;
|
2214 | message: string;
|
2215 | disableEmail: any;
|
2216 | keychain?: any;
|
2217 | skipKeychain?: boolean
|
2218 | }
|
2219 |
|
2220 | const options: Options = {
|
2221 | user: sharing.userId,
|
2222 | permissions: params.permissions,
|
2223 | reshare: params.reshare,
|
2224 | message: params.message,
|
2225 | disableEmail: params.disableEmail,
|
2226 | };
|
2227 | if (sharedKeychain) {
|
2228 | options.keychain = sharedKeychain;
|
2229 | } else if (params.skipKeychain) {
|
2230 | options.keychain = {};
|
2231 | }
|
2232 |
|
2233 | return self.createShare(options);
|
2234 | })
|
2235 | .nodeify(callback);
|
2236 | };
|
2237 |
|
2238 | Wallet.prototype.removeUser = function (params, callback) {
|
2239 | params = params || {};
|
2240 | common.validateParams(params, ['user'], [], callback);
|
2241 |
|
2242 | return Bluebird.resolve(
|
2243 | this.bitgo.del(this.url('/user/' + params.user))
|
2244 | .send()
|
2245 | .result()
|
2246 | ).nodeify(callback);
|
2247 | };
|
2248 |
|
2249 | Wallet.prototype.getPolicy = function (params, callback) {
|
2250 | params = params || {};
|
2251 | common.validateParams(params, [], [], callback);
|
2252 |
|
2253 | return Bluebird.resolve(
|
2254 | this.bitgo.get(this.url('/policy'))
|
2255 | .send()
|
2256 | .result()
|
2257 | ).nodeify(callback);
|
2258 | };
|
2259 |
|
2260 | Wallet.prototype.getPolicyStatus = function (params, callback) {
|
2261 | params = params || {};
|
2262 | common.validateParams(params, [], [], callback);
|
2263 |
|
2264 | return Bluebird.resolve(
|
2265 | this.bitgo.get(this.url('/policy/status'))
|
2266 | .send()
|
2267 | .result()
|
2268 | ).nodeify(callback);
|
2269 | };
|
2270 |
|
2271 | Wallet.prototype.setPolicyRule = function (params, callback) {
|
2272 | params = params || {};
|
2273 | common.validateParams(params, ['id', 'type'], ['message'], callback);
|
2274 |
|
2275 | if (!_.isObject(params.condition)) {
|
2276 | throw new Error('missing parameter: conditions object');
|
2277 | }
|
2278 |
|
2279 | if (!_.isObject(params.action)) {
|
2280 | throw new Error('missing parameter: action object');
|
2281 | }
|
2282 |
|
2283 | return Bluebird.resolve(
|
2284 | this.bitgo.put(this.url('/policy/rule'))
|
2285 | .send(params)
|
2286 | .result()
|
2287 | ).nodeify(callback);
|
2288 | };
|
2289 |
|
2290 | Wallet.prototype.removePolicyRule = function (params, callback) {
|
2291 | params = params || {};
|
2292 | common.validateParams(params, ['id'], ['message'], callback);
|
2293 |
|
2294 | return Bluebird.resolve(
|
2295 | this.bitgo.del(this.url('/policy/rule'))
|
2296 | .send(params)
|
2297 | .result()
|
2298 | ).nodeify(callback);
|
2299 | };
|
2300 |
|
2301 | Wallet.prototype.listWebhooks = function (params, callback) {
|
2302 | params = params || {};
|
2303 | common.validateParams(params, [], [], callback);
|
2304 |
|
2305 | return Bluebird.resolve(
|
2306 | this.bitgo.get(this.url('/webhooks'))
|
2307 | .send()
|
2308 | .result()
|
2309 | ).nodeify(callback);
|
2310 | };
|
2311 |
|
2312 |
|
2313 |
|
2314 |
|
2315 |
|
2316 |
|
2317 |
|
2318 |
|
2319 |
|
2320 |
|
2321 | Wallet.prototype.simulateWebhook = function (params, callback) {
|
2322 | params = params || {};
|
2323 | common.validateParams(params, ['webhookId'], ['txHash', 'pendingApprovalId'], callback);
|
2324 |
|
2325 | const hasTxHash = !!params.txHash;
|
2326 | const hasPendingApprovalId = !!params.pendingApprovalId;
|
2327 |
|
2328 | if ((hasTxHash && hasPendingApprovalId) || (!hasTxHash && !hasPendingApprovalId)) {
|
2329 | throw new Error('must supply either txHash or pendingApprovalId, but not both');
|
2330 | }
|
2331 |
|
2332 |
|
2333 |
|
2334 |
|
2335 |
|
2336 | const filteredParams = _.pick(params, ['txHash', 'pendingApprovalId']);
|
2337 |
|
2338 | const webhookId = params.webhookId;
|
2339 | return Bluebird.resolve(
|
2340 | this.bitgo.post(this.url('/webhooks/' + webhookId + '/simulate'))
|
2341 | .send(filteredParams)
|
2342 | .result()
|
2343 | ).nodeify(callback);
|
2344 | };
|
2345 |
|
2346 | Wallet.prototype.addWebhook = function (params, callback) {
|
2347 | params = params || {};
|
2348 | common.validateParams(params, ['url', 'type'], [], callback);
|
2349 |
|
2350 | return Bluebird.resolve(
|
2351 | this.bitgo.post(this.url('/webhooks'))
|
2352 | .send(params)
|
2353 | .result()
|
2354 | ).nodeify(callback);
|
2355 | };
|
2356 |
|
2357 | Wallet.prototype.removeWebhook = function (params, callback) {
|
2358 | params = params || {};
|
2359 | common.validateParams(params, ['url', 'type'], [], callback);
|
2360 |
|
2361 | return Bluebird.resolve(
|
2362 | this.bitgo.del(this.url('/webhooks'))
|
2363 | .send(params)
|
2364 | .result()
|
2365 | ).nodeify(callback);
|
2366 | };
|
2367 |
|
2368 | Wallet.prototype.estimateFee = function (params, callback) {
|
2369 | common.validateParams(params, [], [], callback);
|
2370 |
|
2371 | if (params.amount && params.recipients) {
|
2372 | throw new Error('cannot specify both amount as well as recipients');
|
2373 | }
|
2374 | if (params.recipients && !_.isObject(params.recipients)) {
|
2375 | throw new Error('recipients must be array of { address: abc, amount: 100000 } objects');
|
2376 | }
|
2377 | if (params.amount && !_.isNumber(params.amount)) {
|
2378 | throw new Error('invalid amount argument, expecting number');
|
2379 | }
|
2380 |
|
2381 | const recipients = params.recipients || [];
|
2382 |
|
2383 | if (params.amount) {
|
2384 |
|
2385 | recipients.push({
|
2386 | address: common.Environments[this.bitgo.env].signingAddress,
|
2387 | amount: params.amount,
|
2388 | });
|
2389 | }
|
2390 |
|
2391 | const transactionParams = _.extend({}, params);
|
2392 | transactionParams.amount = undefined;
|
2393 | transactionParams.recipients = recipients;
|
2394 |
|
2395 | return this.createTransaction(transactionParams)
|
2396 | .then(function (tx) {
|
2397 | return {
|
2398 | estimatedSize: tx.estimatedSize,
|
2399 | fee: tx.fee,
|
2400 | feeRate: tx.feeRate,
|
2401 | };
|
2402 | });
|
2403 | };
|
2404 |
|
2405 |
|
2406 | Wallet.prototype.updatePolicyRule = function (params, callback) {
|
2407 | params = params || {};
|
2408 | common.validateParams(params, ['id', 'type'], [], callback);
|
2409 |
|
2410 | return Bluebird.resolve(
|
2411 | this.bitgo.put(this.url('/policy/rule'))
|
2412 | .send(params)
|
2413 | .result()
|
2414 | ).nodeify(callback);
|
2415 | };
|
2416 |
|
2417 | Wallet.prototype.deletePolicyRule = function (params, callback) {
|
2418 | params = params || {};
|
2419 | common.validateParams(params, ['id'], [], callback);
|
2420 |
|
2421 | return Bluebird.resolve(
|
2422 | this.bitgo.del(this.url('/policy/rule'))
|
2423 | .send(params)
|
2424 | .result()
|
2425 | ).nodeify(callback);
|
2426 | };
|
2427 |
|
2428 |
|
2429 |
|
2430 |
|
2431 |
|
2432 | Wallet.prototype.getBitGoFee = function (params, callback) {
|
2433 | params = params || {};
|
2434 | common.validateParams(params, [], [], callback);
|
2435 | if (!_.isNumber(params.amount)) {
|
2436 | throw new Error('invalid amount argument');
|
2437 | }
|
2438 | if (params.instant && !_.isBoolean(params.instant)) {
|
2439 | throw new Error('invalid instant argument');
|
2440 | }
|
2441 | return Bluebird.resolve(
|
2442 | this.bitgo.get(this.url('/billing/fee'))
|
2443 | .query(params)
|
2444 | .result()
|
2445 | ).nodeify(callback);
|
2446 | };
|
2447 |
|
2448 | export = Wallet;
|