-
Notifications
You must be signed in to change notification settings - Fork 269
/
abstractUtxoCoin.ts
1600 lines (1370 loc) · 62.2 KB
/
abstractUtxoCoin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import BaseCoin = require('../baseCoin');
const config = require('../../config');
const bitcoin = require('bitgo-utxo-lib');
const bitcoinMessage = require('bitcoinjs-message');
const Promise = require('bluebird');
const co = Promise.coroutine;
const prova = require('prova-lib');
const crypto = require('crypto');
const request = require('superagent');
const _ = require('lodash');
const RecoveryTool = require('../recovery');
const errors = require('../../errors');
const debug = require('debug')('bitgo:v2:utxo');
const { Codes } = require('@bitgo/unspents');
class AbstractUtxoCoin extends BaseCoin {
public readonly altScriptHash;
public readonly supportAltScriptDestination;
private readonly _network;
constructor(network) {
super();
if (!_.isObject(network)) {
throw new Error('network must be an object');
}
this._network = network;
}
get network() {
return this._network;
}
static get validAddressTypes() {
const validAddressTypes = [];
_.forEach(Object.keys(Codes.UnspentTypeTcomb.meta.map), function(addressType) {
try {
Codes.forType(addressType);
validAddressTypes.push(addressType);
} catch (e) {
// Do nothing. Codes.forType will throw if the address type has no chain codes, meaning it is invalid on the
// BitGo platform and should not be added to the validAddressTypes array.
}
});
return validAddressTypes;
}
/**
* Returns the factor between the base unit and its smallest subdivison
* @return {number}
*/
getBaseFactor() {
return 1e8;
}
getCoinLibrary() {
return bitcoin;
}
isValidAddress(address, forceAltScriptSupport = false) {
const validVersions = [
this.network.pubKeyHash,
this.network.scriptHash
];
if (this.altScriptHash && (forceAltScriptSupport || this.supportAltScriptDestination)) {
validVersions.push(this.altScriptHash);
}
let addressDetails;
try {
addressDetails = this.getCoinLibrary().address.fromBase58Check(address);
} catch (e) {
if (!this.supportsP2wsh()) {
return false;
}
try {
addressDetails = bitcoin.address.fromBech32(address);
return addressDetails.prefix === this.network.bech32;
} catch (e) {
return false;
}
}
// the address version needs to be among the valid ones
return validVersions.includes(addressDetails.version);
}
/**
* Return boolean indicating whether input is valid public key for the coin.
*
* @param {String} pub the pub to be checked
* @returns {Boolean} is it valid?
*/
isValidPub(pub) {
try {
bitcoin.HDNode.fromBase58(pub);
return true;
} catch (e) {
return false;
}
}
getLatestBlockHeight(reqId, callback) {
return co(function *() {
if (reqId) {
this.bitgo._reqId = reqId;
}
const chainhead = yield this.bitgo.get(this.url('/public/block/latest')).result();
return chainhead.height;
}).call(this).asCallback(callback);
}
postProcessPrebuild(prebuild, callback) {
return co(function *() {
if (_.isUndefined(prebuild.blockHeight)) {
prebuild.blockHeight = yield this.getLatestBlockHeight();
}
const transaction = bitcoin.Transaction.fromHex(prebuild.txHex, this.network);
transaction.locktime = prebuild.blockHeight + 1;
return _.extend({}, prebuild, { txHex: transaction.toHex() });
}).call(this).asCallback(callback);
}
/**
* Find outputs that are within expected outputs but not within actual outputs, including duplicates
* @param expectedOutputs
* @param actualOutputs
* @returns {Array}
*/
static findMissingOutputs(expectedOutputs, actualOutputs) {
const keyFunc = ({ address, amount }) => `${address}:${Number(amount)}`;
const groupedOutputs = _.groupBy(expectedOutputs, keyFunc);
actualOutputs.forEach((output) => {
const group = groupedOutputs[keyFunc(output)];
if (group) {
group.pop();
}
});
return _.flatten(_.values(groupedOutputs));
}
/**
* Determine an address' type based on its witness and redeem script presence
* @param addressDetails
*/
static inferAddressType(addressDetails) {
if (_.isObject(addressDetails.coinSpecific)) {
if (_.isString(addressDetails.coinSpecific.redeemScript) && _.isString(addressDetails.coinSpecific.witnessScript)) {
return Codes.UnspentTypeTcomb('p2shP2wsh');
} else if (_.isString(addressDetails.coinSpecific.redeemScript)) {
return Codes.UnspentTypeTcomb('p2sh');
} else if (_.isString(addressDetails.coinSpecific.witnessScript)) {
return Codes.UnspentTypeTcomb('p2wsh');
}
}
return null;
}
/**
* Extract and fill transaction details such as internal/change spend, external spend (explicit vs. implicit), etc.
* @param txParams
* @param txPrebuild
* @param wallet
* @param verification
* @param callback
* @returns {*}
*/
parseTransaction({ txParams, txPrebuild, wallet, verification = {} as any, reqId }, callback) {
return co(function *() {
if (!_.isUndefined(verification.disableNetworking) && !_.isBoolean(verification.disableNetworking)) {
throw new Error('verification.disableNetworking must be a boolean');
}
const disableNetworking = !!verification.disableNetworking;
// obtain the keychains and key signatures
let keychains = verification.keychains;
if (!keychains && disableNetworking) {
throw new Error('cannot fetch keychains without networking');
} else if (!keychains) {
keychains = yield Promise.props({
user: this.keychains().get({ id: wallet._wallet.keys[0], reqId }),
backup: this.keychains().get({ id: wallet._wallet.keys[1], reqId }),
bitgo: this.keychains().get({ id: wallet._wallet.keys[2], reqId })
});
}
const keychainArray = [keychains.user, keychains.backup, keychains.bitgo];
const keySignatures = _.get(wallet, '_wallet.keySignatures');
// obtain all outputs
const explanation = this.explainTransaction({
txHex: txPrebuild.txHex,
txInfo: txPrebuild.txInfo,
keychains: keychains
});
const allOutputs = [...explanation.outputs, ...explanation.changeOutputs];
// verify that each recipient from txParams has their own output
const expectedOutputs = _.get(txParams, 'recipients', []);
const missingOutputs = this.constructor.findMissingOutputs(expectedOutputs, allOutputs);
/**
* Loop through all the outputs and classify each of them as either internal spends
* or external spends by setting the "external" property to true or false on the output object.
*/
const allOutputDetails = yield Promise.map(allOutputs, co(function *(currentOutput) {
const currentAddress = currentOutput.address;
// attempt to grab the address details from either the prebuilt tx, or the verification params.
// If both of these are empty, then we will try to get the address details from bitgo instead
const addressDetailsPrebuild = _.get(txPrebuild, `txInfo.walletAddressDetails.${currentAddress}`, {});
const addressDetailsVerification = _.get(verification, `addresses.${currentAddress}`, {});
debug('Parsing address details for %s', currentAddress);
try {
/**
* The only way to determine whether an address is known on the wallet is to initiate a network request and
* fetch it. Should the request fail and return a 404, it will throw and therefore has to be caught. For that
* reason, address wallet ownership detection is wrapped in a try/catch. Additionally, once the address
* details are fetched on the wallet, a local address validation is run, whose errors however are generated
* client-side and can therefore be analyzed with more granularity and type checking.
*/
let addressDetails = _.extend({}, addressDetailsPrebuild, addressDetailsVerification);
debug('Locally available address %s details: %O', currentAddress, addressDetails);
if (_.isEmpty(addressDetails) && !disableNetworking) {
addressDetails = yield wallet.getAddress({ address: currentAddress, reqId });
debug('Downloaded address %s details: %O', currentAddress, addressDetails);
}
// verify that the address is on the wallet. verifyAddress throws if
// it fails to correctly rederive the address, meaning it's external
const addressType = this.constructor.inferAddressType(addressDetails);
this.verifyAddress(_.extend({ addressType }, addressDetails, {
keychains: keychainArray,
address: currentAddress
}));
debug('Address %s verification passed', currentAddress);
// verify address succeeded without throwing, so the address was
// correctly rederived from the wallet keychains, making it not external
return _.extend({}, currentOutput, addressDetails, { external: false });
} catch (e) {
// verify address threw an exception
debug('Address %s verification threw an error:', currentAddress, e);
// Todo: name server-side errors to avoid message-based checking [BG-5124]
const walletAddressNotFound = e.message.includes('wallet address not found');
const unexpectedAddress = (e instanceof errors.UnexpectedAddressError);
if (walletAddressNotFound || unexpectedAddress) {
if (unexpectedAddress && !walletAddressNotFound) {
/**
* this could be a migrated SafeHD BCH wallet, and the transaction we are currently
* parsing is trying to spend change back to the v1 wallet base address.
* It does this since we don't allow new address creation for these wallets,
* and instead return the base address from the v1 wallet when a new address is requested.
* If this new address is requested for the purposes of spending change back to the wallet,
* the change will go to the v1 wallet base address. This address *is* on the wallet,
* but it will still cause an error to be thrown by verifyAddress, since the derivation path
* used for this address is non-standard. (I have seen these addresses derived using paths m/0/0 and m/101,
* whereas the v2 addresses are derived using path m/0/0/${chain}/${index}).
*
* This means we need to check for this case explicitly in this catch block, and classify
* these types of outputs as internal instead of external. Failing to do so would cause the
* transaction's implicit external outputs (ie, outputs which go to addresses not specified in
* the recipients array) to add up to more than the 150 basis point limit which we enforce on
* pay-as-you-go outputs (which should be the only implicit external outputs on our transactions).
*
* The 150 basis point limit for implicit external sends is enforced in verifyTransaction,
* which calls this function to get information on the total external/internal spend amounts
* for a transaction. The idea here is to protect from the transaction being maliciously modified
* to add more implicit external spends (eg, to an attacker-controlled wallet).
*
* See verifyTransaction for more information on how transaction prebuilds are verified before signing.
*/
if (_.isString(wallet._wallet.migratedFrom) && wallet._wallet.migratedFrom === currentAddress) {
debug('found address %s which was migrated from v1 wallet, address is not external', currentAddress);
return _.extend({}, currentOutput, { external: false });
}
debug('Address %s was found on wallet but could not be reconstructed', currentAddress);
}
// the address was found, but not on the wallet, which simply means it's external
debug('Address %s presumed external', currentAddress);
return _.extend({}, currentOutput, { external: true });
} else if (e instanceof errors.InvalidAddressDerivationPropertyError && currentAddress === txParams.changeAddress) {
// expect to see this error when passing in a custom changeAddress with no chain or index
return _.extend({}, currentOutput, { external: false });
}
debug('Address %s verification failed', currentAddress);
/**
* It might be a completely invalid address or a bad validation attempt or something else completely, in
* which case we do not proceed and rather rethrow the error, which is safer than assuming that the address
* validation failed simply because it's external to the wallet.
*/
throw e;
}
}).bind(this));
const changeOutputs = _.filter(allOutputDetails, { external: false });
// these are all the outputs that were not originally explicitly specified in recipients
const implicitOutputs = this.constructor.findMissingOutputs(allOutputDetails, expectedOutputs);
const explicitOutputs = this.constructor.findMissingOutputs(allOutputDetails, implicitOutputs);
// these are all the non-wallet outputs that had been originally explicitly specified in recipients
const explicitExternalOutputs = _.filter(explicitOutputs, { external: true });
// this is the sum of all the originally explicitly specified non-wallet output values
const explicitExternalSpendAmount = _.sumBy(explicitExternalOutputs, 'amount');
/**
* The calculation of the implicit external spend amount pertains to verifying the pay-as-you-go-fee BitGo
* automatically applies to transactions sending money out of the wallet. The logic is fairly straightforward
* in that we compare the external spend amount that was specified explicitly by the user to the portion
* that was specified implicitly. To protect customers from people tampering with the transaction outputs, we
* define a threshold for the maximum percentage of the implicit external spend in relation to the explicit
* external spend.
*/
// make sure that all the extra addresses are change addresses
// get all the additional external outputs the server added and calculate their values
const implicitExternalOutputs = _.filter(implicitOutputs, { external: true });
const implicitExternalSpendAmount = _.sumBy(implicitExternalOutputs, 'amount');
return {
keychains,
keySignatures,
outputs: allOutputDetails,
missingOutputs,
explicitExternalOutputs,
implicitExternalOutputs,
changeOutputs,
explicitExternalSpendAmount,
implicitExternalSpendAmount
};
}).call(this).asCallback(callback);
}
/**
* Verify that a transaction prebuild complies with the original intention
* @param txParams params object passed to send
* @param txPrebuild prebuild object returned by server
* @param txPrebuild.txHex prebuilt transaction's txHex form
* @param wallet Wallet object to obtain keys to verify against
* @param verification Object specifying some verification parameters
* @param verification.disableNetworking Disallow fetching any data from the internet for verification purposes
* @param verification.keychains Pass keychains manually rather than fetching them by id
* @param verification.addresses Address details to pass in for out-of-band verification
* @param callback
* @returns {boolean}
*/
verifyTransaction({ txParams, txPrebuild, wallet, verification = {} as any, reqId }, callback) {
return co(function *() {
const disableNetworking = !!verification.disableNetworking;
const parsedTransaction = yield this.parseTransaction({ txParams, txPrebuild, wallet, verification, reqId });
const keychains = parsedTransaction.keychains;
// let's verify these keychains
const keySignatures = parsedTransaction.keySignatures;
if (!_.isEmpty(keySignatures)) {
// first, let's verify the integrity of the user key, whose public key is used for subsequent verifications
const userPub = keychains.user.pub;
const userKey = bitcoin.HDNode.fromBase58(userPub);
let userPrv = keychains.user.prv;
if (_.isEmpty(userPrv)) {
const encryptedPrv = keychains.user.encryptedPrv;
if (!_.isEmpty(encryptedPrv)) {
// if the decryption fails, it will throw an error
userPrv = this.bitgo.decrypt({
input: encryptedPrv,
password: txParams.walletPassphrase
});
}
}
if (_.isEmpty(userPrv)) {
const errorMessage = 'user private key unavailable for verification';
if (disableNetworking) {
console.log(errorMessage);
} else {
throw new Error(errorMessage);
}
} else {
const userPrivateKey = bitcoin.HDNode.fromBase58(userPrv);
if (userPrivateKey.toBase58() === userPrivateKey.neutered().toBase58()) {
throw new Error('user private key is only public');
}
if (userPrivateKey.neutered().toBase58() !== userPub) {
throw new Error('user private key does not match public key');
}
}
const backupPubSignature = keySignatures.backupPub;
const bitgoPubSignature = keySignatures.bitgoPub;
// verify the signatures against the user public key
const signingAddress = userKey.keyPair.getAddress();
// BG-5703: use BTC mainnet prefix for all key signature operations
// (this means do not pass a prefix parameter, and let it use the default prefix instead)
const isValidBackupSignature = bitcoinMessage.verify(keychains.backup.pub, signingAddress, Buffer.from(backupPubSignature, 'hex'));
const isValidBitgoSignature = bitcoinMessage.verify(keychains.bitgo.pub, signingAddress, Buffer.from(bitgoPubSignature, 'hex'));
if (!isValidBackupSignature || !isValidBitgoSignature) {
throw new Error('secondary public key signatures invalid');
}
} else if (!disableNetworking) {
// these keys were obtained online and their signatures were not verified
// this could be dangerous
console.log('unsigned keys obtained online are being used for address verification');
}
const missingOutputs = parsedTransaction.missingOutputs;
if (missingOutputs.length !== 0) {
// there are some outputs in the recipients list that have not made it into the actual transaction
throw new Error('expected outputs missing in transaction prebuild');
}
const intendedExternalSpend = parsedTransaction.explicitExternalSpendAmount;
// this is a limit we impose for the total value that is amended to the transaction beyond what was originally intended
const payAsYouGoLimit = intendedExternalSpend * 0.015; // 150 basis points is the absolute permitted maximum
/*
Some explanation for why we're doing what we're doing:
Some customers will have an output to BitGo's PAYGo wallet added to their transaction, and we need to account for
it here. To protect someone tampering with the output to make it send more than it should to BitGo, we define a
threshold for the output's value above which we'll throw an error, because the paygo output should never be that
high.
*/
// make sure that all the extra addresses are change addresses
// get all the additional external outputs the server added and calculate their values
const nonChangeAmount = parsedTransaction.implicitExternalSpendAmount;
// the additional external outputs can only be BitGo's pay-as-you-go fee, but we cannot verify the wallet address
if (nonChangeAmount > payAsYouGoLimit) {
// there are some addresses that are outside the scope of intended recipients that are not change addresses
throw new Error('prebuild attempts to spend to unintended external recipients');
}
const allOutputs = parsedTransaction.outputs;
const transaction = bitcoin.Transaction.fromHex(txPrebuild.txHex, this.network);
const transactionCache = {};
const inputs = yield Promise.map(transaction.ins, co(function *(currentInput) {
const transactionId = Buffer.from(currentInput.hash).reverse().toString('hex');
const txHex = _.get(txPrebuild, `txInfo.txHexes.${transactionId}`);
if (txHex) {
const localTx = bitcoin.Transaction.fromHex(txHex, this.network);
if (localTx.getId() !== transactionId) {
throw new Error('input transaction hex does not match id');
}
const currentOutput = localTx.outs[currentInput.index];
const address = bitcoin.address.fromOutputScript(currentOutput.script, this.network);
return {
address,
value: currentOutput.value
};
} else if (!transactionCache[transactionId]) {
if (disableNetworking) {
throw new Error('attempting to retrieve transaction details externally with networking disabled');
}
if (reqId) {
this.bitgo._reqId = reqId;
}
transactionCache[transactionId] = yield this.bitgo.get(this.url(`/public/tx/${transactionId}`)).result();
}
const transactionDetails = transactionCache[transactionId];
return transactionDetails.outputs[currentInput.index];
}).bind(this));
const inputAmount = _.sumBy(inputs, 'value');
const outputAmount = _.sumBy(allOutputs, 'amount');
const fee = inputAmount - outputAmount;
if (fee < 0) {
throw new Error(`attempting to spend ${outputAmount} satoshis, which exceeds the input amount (${inputAmount} satoshis) by ${-fee}`);
}
return true;
}).call(this).asCallback(callback);
}
/**
* Make sure an address is valid and throw an error if it's not.
* @param address The address string on the network
* @param addressType
* @param keychains Keychain objects with xpubs
* @param coinSpecific Coin-specific details for the address such as a witness script
* @param chain Derivation chain
* @param index Derivation index
*/
verifyAddress({ address, addressType, keychains, coinSpecific, chain, index }) {
if (!this.isValidAddress(address)) {
throw new errors.InvalidAddressError(`invalid address: ${address}`);
}
if ((_.isUndefined(chain) && _.isUndefined(index)) || (!(_.isFinite(chain) && _.isFinite(index)))) {
throw new errors.InvalidAddressDerivationPropertyError(`address validation failure: invalid chain (${chain}) or index (${index})`);
}
if (!_.isObject(coinSpecific)) {
throw new errors.InvalidAddressVerificationObjectPropertyError('address validation failure: coinSpecific field must be an object');
}
const expectedAddress: any = this.generateAddress({
addressType,
keychains,
threshold: 2,
chain: chain,
index: index
});
if (expectedAddress.address !== address) {
throw new errors.UnexpectedAddressError(`address validation failure: expected ${expectedAddress.address} but got ${address}`);
}
}
/**
* Indicates whether coin supports a block target
* @returns {boolean}
*/
supportsBlockTarget() {
return true;
}
/**
* Indicates whether a coin supports wrapped segwit outputs
* @returns {boolean}
*/
supportsP2shP2wsh() {
return false;
}
/**
* Indicates whether a coin supports native segwit outputs
* @returns {boolean}
*/
supportsP2wsh() {
return false;
}
/**
* TODO(BG-11487): Remove addressType, segwit, and bech32 params in SDKv6
* Generate an address for a wallet based on a set of configurations
* @param addressType {string} Deprecated
* @param keychains {[object]} Array of objects with xpubs
* @param threshold {number} Minimum number of signatures
* @param chain {number} Derivation chain (see https://github.com/BitGo/unspents/blob/master/src/codes.ts for
* the corresponding address type of a given chain code)
* @param index {number} Derivation index
* @param segwit {boolean} Deprecated
* @param bech32 {boolean} Deprecated
* @returns {{chain: number, index: number, coin: number, coinSpecific: {outputScript, redeemScript}}}
*/
generateAddress({ addressType, keychains, threshold, chain, index, segwit = false, bech32 = false }) {
let derivationChain = 0;
if (_.isInteger(chain) && chain > 0) {
derivationChain = chain;
}
if (_.isUndefined(addressType)) {
addressType = Codes.UnspentTypeTcomb('p2sh');
if (_.isBoolean(segwit) && segwit) {
addressType = Codes.UnspentTypeTcomb('p2shP2wsh');
}
if (_.isBoolean(bech32) && bech32) {
addressType = Codes.UnspentTypeTcomb('p2wsh');
}
}
switch (addressType) {
case Codes.UnspentTypeTcomb('p2sh'):
if (!Codes.isP2sh(derivationChain)) {
throw new errors.AddressTypeChainMismatchError(addressType, derivationChain);
}
break;
case Codes.UnspentTypeTcomb('p2shP2wsh'):
if (!this.supportsP2shP2wsh()) {
throw new errors.P2shP2wshUnsupportedError();
}
if (!Codes.isP2shP2wsh(derivationChain)) {
throw new errors.AddressTypeChainMismatchError(addressType, derivationChain);
}
break;
case Codes.UnspentTypeTcomb('p2wsh'):
if (!this.supportsP2wsh()) {
throw new errors.P2wshUnsupportedError();
}
if (!Codes.isP2wsh(derivationChain)) {
throw new errors.AddressTypeChainMismatchError(addressType, derivationChain);
}
break;
default:
throw new errors.UnsupportedAddressTypeError();
}
let signatureThreshold = 2;
if (_.isInteger(threshold)) {
signatureThreshold = threshold;
if (signatureThreshold <= 0) {
throw new Error('threshold has to be positive');
}
if (signatureThreshold > keychains.length) {
throw new Error('threshold cannot exceed number of keys');
}
}
let derivationIndex = 0;
if (_.isInteger(index) && index > 0) {
derivationIndex = index;
}
const path = 'm/0/0/' + derivationChain + '/' + derivationIndex;
const hdNodes = keychains.map(({ pub }) => prova.HDNode.fromBase58(pub));
const derivedKeys = hdNodes.map(hdNode => hdNode.hdPath().deriveKey(path).getPublicKeyBuffer());
const inputScript = bitcoin.script.multisig.output.encode(signatureThreshold, derivedKeys);
const inputScriptHash = bitcoin.crypto.hash160(inputScript);
const addressDetails: any = {
chain: derivationChain,
index: derivationIndex,
coin: this.getChain(),
coinSpecific: {},
addressType
};
function createWitnessProgram(inputScript) {
const witnessScriptHash = bitcoin.crypto.sha256(inputScript);
return bitcoin.script.witnessScriptHash.output.encode(witnessScriptHash);
}
let outputScript;
switch (addressType) {
case Codes.UnspentTypeTcomb('p2sh'):
outputScript = bitcoin.script.scriptHash.output.encode(inputScriptHash);
addressDetails.coinSpecific.redeemScript = inputScript.toString('hex');
break;
case Codes.UnspentTypeTcomb('p2shP2wsh'):
const redeemScript = createWitnessProgram(inputScript);
const redeemScriptHash = bitcoin.crypto.hash160(redeemScript);
outputScript = bitcoin.script.scriptHash.output.encode(redeemScriptHash);
addressDetails.coinSpecific.redeemScript = redeemScript.toString('hex');
addressDetails.coinSpecific.witnessScript = inputScript.toString('hex');
break;
case Codes.UnspentTypeTcomb('p2wsh'):
outputScript = createWitnessProgram(inputScript);
addressDetails.coinSpecific.witnessScript = inputScript.toString('hex');
break;
default:
throw new Error(`unexpected addressType ${addressType}`);
}
addressDetails.coinSpecific.outputScript = outputScript.toString('hex');
addressDetails.address =
this.getCoinLibrary().address.fromOutputScript(outputScript, this.network);
return addressDetails;
}
/**
* Assemble keychain and half-sign prebuilt transaction
* @param params
* - txPrebuild
* - prv
* @param params.isLastSignature Ture if txb.build() should be called and not buildIncomplete()
* @returns {{txHex}}
*/
signTransaction(params) {
const txPrebuild = params.txPrebuild;
const userPrv = params.prv;
if (_.isUndefined(txPrebuild) || !_.isObject(txPrebuild)) {
if (!_.isUndefined(txPrebuild) && !_.isObject(txPrebuild)) {
throw new Error(`txPrebuild must be an object, got type ${typeof txPrebuild}`);
}
throw new Error('missing txPrebuild parameter');
}
let transaction = bitcoin.Transaction.fromHex(txPrebuild.txHex, this.network);
if (transaction.ins.length !== txPrebuild.txInfo.unspents.length) {
throw new Error('length of unspents array should equal to the number of transaction inputs');
}
let isLastSignature = false;
if (_.isBoolean(params.isLastSignature)) {
// if build is called instead of buildIncomplete, no signature placeholders are left in the sig script
isLastSignature = params.isLastSignature;
}
if (_.isUndefined(userPrv) || !_.isString(userPrv)) {
if (!_.isUndefined(userPrv) && !_.isString(userPrv)) {
throw new Error(`prv must be a string, got type ${typeof userPrv}`);
}
throw new Error('missing prv parameter to sign transaction');
}
const keychain = bitcoin.HDNode.fromBase58(userPrv);
const hdPath = bitcoin.hdPath(keychain);
const txb = bitcoin.TransactionBuilder.fromTransaction(transaction, this.network);
this.prepareTransactionBuilder(txb);
const signatureIssues = [];
const p2wshIndices = [];
for (let index = 0; index < transaction.ins.length; ++index) {
debug('Signing input %d of %d', index + 1, transaction.ins.length);
const currentUnspent = txPrebuild.txInfo.unspents[index];
if (this.isBitGoTaintedUnspent(currentUnspent)) {
debug('Skipping input %d of %d (unspent from replay protection address which is platform signed only)', index + 1, transaction.ins.length);
continue;
}
const path = 'm/0/0/' + currentUnspent.chain + '/' + currentUnspent.index;
const privKey = hdPath.deriveKey(path);
privKey.network = this.network;
const currentSignatureIssue: any = {
inputIndex: index,
unspent: currentUnspent,
path: path
};
debug('Input details: %O', currentSignatureIssue);
const isP2wsh = !currentUnspent.redeemScript;
const sigHashType = this.defaultSigHashType;
try {
if (isP2wsh) {
debug('Signing p2wsh input');
const witnessScript = Buffer.from(currentUnspent.witnessScript, 'hex');
const witnessScriptHash = bitcoin.crypto.sha256(witnessScript);
const prevOutScript = bitcoin.script.witnessScriptHash.output.encode(witnessScriptHash);
txb.sign(index, privKey, prevOutScript, sigHashType, currentUnspent.value, witnessScript);
} else {
const subscript = new Buffer(currentUnspent.redeemScript, 'hex');
const isP2shP2wsh = !!currentUnspent.witnessScript;
if (isP2shP2wsh) {
debug('Signing p2shP2wsh input');
const witnessScript = Buffer.from(currentUnspent.witnessScript, 'hex');
txb.sign(index, privKey, subscript, sigHashType, currentUnspent.value, witnessScript);
} else {
debug('Signing p2sh input');
txb.sign(index, privKey, subscript, sigHashType, currentUnspent.value);
}
}
} catch (e) {
debug('Failed to sign input:', e);
currentSignatureIssue.error = e;
signatureIssues.push(currentSignatureIssue);
continue;
}
if (isLastSignature) {
transaction = txb.build();
} else {
transaction = txb.buildIncomplete();
}
// after signature validation, prepare p2wsh setup
if (isP2wsh) {
transaction.setInputScript(index, Buffer.alloc(0));
p2wshIndices.push(index);
}
const isValidSignature = this.verifySignature(transaction, index, currentUnspent.value);
if (!isValidSignature) {
debug('Invalid signature');
currentSignatureIssue.error = new Error('invalid signature');
signatureIssues.push(currentSignatureIssue);
}
}
if (signatureIssues.length > 0) {
const failedIndices = signatureIssues.map(currentIssue => currentIssue.inputIndex);
const error: any = new Error(`Failed to sign inputs at indices ${failedIndices.join(', ')}`);
error.code = 'input_signature_failure';
error.signingErrors = signatureIssues;
throw error;
}
for (const p2wshIndex of p2wshIndices) {
transaction.setInputScript(p2wshIndex, Buffer.alloc(0));
}
return {
txHex: transaction.toBuffer().toString('hex')
};
}
/**
* Always false for coins other than BCH and TBCH.
* @param unspent
* @returns {boolean}
*/
isBitGoTaintedUnspent(unspent) {
return false;
}
/**
* Modify the transaction builder to comply with the specific coin's requirements such as version and branch id
* @param txBuilder
* @returns {*}
*/
prepareTransactionBuilder(txBuilder) {
return txBuilder;
}
/**
*
* @returns {number}
*/
get defaultSigHashType() {
return bitcoin.Transaction.SIGHASH_ALL;
}
/**
* Parse a transaction's signature script to obtain public keys, signatures, the sig script, and other properties
* @param transaction
* @param inputIndex
* @returns {boolean}
*/
parseSignatureScript(transaction, inputIndex) {
const currentInput = transaction.ins[inputIndex];
let signatureScript = currentInput.script;
let decompiledSigScript = bitcoin.script.decompile(signatureScript);
const isSegwitInput = currentInput.witness.length > 0;
if (isSegwitInput) {
const isNativeSegwit = signatureScript.length === 0;
decompiledSigScript = currentInput.witness;
signatureScript = bitcoin.script.compile(decompiledSigScript);
if (isNativeSegwit) {
const lastWitness = _.last(transaction.ins[inputIndex].witness);
// const inputScriptHash = bitcoin.crypto.hash160(lastWitness);
const witnessScriptHash = bitcoin.crypto.sha256(lastWitness);
const prevOutScript = bitcoin.script.witnessScriptHash.output.encode(witnessScriptHash);
// we are faking a signature script for the verification
signatureScript = bitcoin.script.compile([prevOutScript]);
}
}
const inputClassification = bitcoin.script.classifyInput(signatureScript, true);
if (inputClassification !== bitcoin.script.types.P2SH) {
if (inputClassification === bitcoin.script.types.P2PKH) {
const [signature, publicKey] = decompiledSigScript;
const publicKeys = [publicKey];
const signatures = [signature];
const pubScript = bitcoin.script.pubKeyHash.output.encode(bitcoin.crypto.hash160(publicKey));
return { signatures, publicKeys, isSegwitInput, inputClassification, pubScript: pubScript };
}
return { isSegwitInput, inputClassification };
}
// all but the last entry
const signatures = decompiledSigScript.slice(0, -1);
// the last entry
const pubScript = _.last(decompiledSigScript);
const decompiledPubScript = bitcoin.script.decompile(pubScript);
// the second through antepenultimate entries
const publicKeys = decompiledPubScript.slice(1, -2);
return { signatures, publicKeys, isSegwitInput, inputClassification, pubScript };
}
/**
* Calculate the hash to verify the signature against
* @param transaction Transaction object
* @param inputIndex
* @param pubScript
* @param amount The previous output's amount
* @param hashType
* @param isSegwitInput
* @returns {*}
*/
calculateSignatureHash(transaction, inputIndex, pubScript, amount, hashType, isSegwitInput) {
if (isSegwitInput) {
return transaction.hashForWitnessV0(inputIndex, pubScript, amount, hashType);
} else {
return transaction.hashForSignature(inputIndex, pubScript, hashType);
}
}
/**
* Verify the signature on a (half-signed) transaction
* @param transaction bitcoinjs-lib tx object
* @param inputIndex The input whererfore to check the signature
* @param amount For segwit and BCH, the input amount needs to be known for signature verification
* @param verificationSettings
* @param verificationSettings.signatureIndex The index of the signature to verify (only iterates over non-empty signatures)
* @param verificationSettings.publicKey The hex of the public key to verify (will verify all signatures)
* @returns {boolean}
*/
verifySignature(transaction, inputIndex, amount, verificationSettings = {} as any) {
const { signatures, publicKeys, isSegwitInput, inputClassification, pubScript } = this.parseSignatureScript(transaction, inputIndex);
if (![bitcoin.script.types.P2SH, bitcoin.script.types.P2PKH].includes(inputClassification)) {
return false;
}
if (isSegwitInput && !amount) {
return false;
}
// get the first non-empty signature and verify it against all public keys
const nonEmptySignatures = _.filter(signatures, s => !_.isEmpty(s));
/*
We either want to verify all signature/pubkey combinations, or do an explicit combination
If a signature index is specified, only that signature is checked. It's verified against all public keys.
If a single public key is found to be valid, the function returns true.
If a public key is specified, we iterate over all signatures. If a single one matches the public key, the function
returns true.
If neither is specified, all signatures are checked against all public keys. Each signature must have its own distinct
public key that it matches for the function to return true.
*/
let signaturesToCheck = nonEmptySignatures;
if (!_.isUndefined(verificationSettings.signatureIndex)) {
signaturesToCheck = [nonEmptySignatures[verificationSettings.signatureIndex]];
}
const publicKeyHex = verificationSettings.publicKey;
const matchedPublicKeyIndices = {};
let areAllSignaturesValid = true;
// go over all signatures
for (const signatureBuffer of signaturesToCheck) {
let isSignatureValid = false;
if (Buffer.isBuffer(signatureBuffer) && signatureBuffer.length > 0) {
// slice the last byte from the signature hash input because it's the hash type
const signature = bitcoin.ECSignature.fromDER(signatureBuffer.slice(0, -1));
const hashType = _.last(signatureBuffer);
const signatureHash = this.calculateSignatureHash(transaction, inputIndex, pubScript, amount, hashType, isSegwitInput);
for (let publicKeyIndex = 0; publicKeyIndex < publicKeys.length; publicKeyIndex++) {
const publicKeyBuffer = publicKeys[publicKeyIndex];
if (!_.isUndefined(publicKeyHex) && publicKeyBuffer.toString('hex') !== publicKeyHex) {
// we are only looking to verify one specific public key's signature (publicKeyHex)
// this particular public key is not the one whose signature we're trying to verify
continue;
}
if (matchedPublicKeyIndices[publicKeyIndex]) {
continue;
}
const publicKey = bitcoin.ECPair.fromPublicKeyBuffer(publicKeyBuffer);
if (publicKey.verify(signatureHash, signature)) {
isSignatureValid = true;
matchedPublicKeyIndices[publicKeyIndex] = true;
break;
}
}
}
if (!_.isUndefined(publicKeyHex) && isSignatureValid) {
// We were trying to see if any of the signatures was valid for the given public key. Evidently yes.
return true;
}
if (!isSignatureValid && _.isUndefined(publicKeyHex)) {
return false;
}
areAllSignaturesValid = isSignatureValid && areAllSignaturesValid;
}
return areAllSignaturesValid;
}
explainTransaction(params = {} as any) {
const { txHex, txInfo } = params;
if (!txHex || !_.isString(txHex) || !txHex.match(/^([a-f0-9]{2})+$/i)) {
throw new Error('invalid transaction hex, must be a valid hex string');
}
let transaction;
try {
transaction = bitcoin.Transaction.fromHex(txHex, this.network);
} catch (e) {