-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathwallet.ts
More file actions
6536 lines (5843 loc) · 229 KB
/
wallet.ts
File metadata and controls
6536 lines (5843 loc) · 229 KB
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
//
// Tests for Wallet
//
import should = require('should');
import * as sinon from 'sinon';
import '../lib/asserts';
import nock = require('nock');
import * as _ from 'lodash';
import {
BaseTssUtils,
common,
Ecdsa,
ECDSAUtils,
EDDSAUtils,
GetUserPrvOptions,
Keychains,
KeyType,
ManageUnspentsOptions,
MessageStandardType,
MessageTypes,
PopulatedIntent,
PrebuildTransactionOptions,
PrebuildTransactionWithIntentOptions,
RequestTracer,
SendManyOptions,
SignatureShareType,
SignedMessage,
SignTypedDataVersion,
TokenType,
TssUtils,
TxRequest,
TxRequestVersion,
TypedData,
TypedMessage,
Wallet,
WalletSignMessageOptions,
WalletSignTypedDataOptions,
} from '@bitgo/sdk-core';
import { TestBitGo } from '@bitgo/sdk-test';
import { BitGo } from '../../../src';
import * as utxoLib from '@bitgo/utxo-lib';
import { randomBytes } from 'crypto';
import { Tsol } from '@bitgo/sdk-coin-sol';
import { Teth } from '@bitgo/sdk-coin-eth';
import { nftResponse, unsupportedNftResponse } from '../fixtures/nfts/nftResponses';
require('should-sinon');
nock.disableNetConnect();
type CreateTxRequestBody = {
intent: PopulatedIntent;
apiversion: TxRequestVersion;
preview?: boolean;
};
describe('V2 Wallet:', function () {
const reqId = new RequestTracer();
const bitgo = TestBitGo.decorate(BitGo, { env: 'test' });
bitgo.initializeTestVars();
const basecoin: any = bitgo.coin('tbtc');
const walletData = {
id: '5b34252f1bf349930e34020a00000000',
coin: 'tbtc',
keys: ['5b3424f91bf349930e34017500000000', '5b3424f91bf349930e34017600000000', '5b3424f91bf349930e34017700000000'],
coinSpecific: {},
multisigType: 'onchain',
type: 'hot',
};
const coldWalletData = {
id: '65774419fb4d9690847fbe4b00000000',
coin: 'tbtc',
keys: ['65774412e54b7516393c9df800000000', '6577442428664ffe791af7ea00000000', '6577442b7317a945756c2fd900000000'],
coinSpecific: {},
multisigType: 'onchain',
type: 'cold',
};
const wallet = new Wallet(bitgo, basecoin, walletData);
const coldWallet = new Wallet(bitgo, basecoin, coldWalletData);
const bgUrl = common.Environments[bitgo.getEnv()].uri;
const address1 = '0x174cfd823af8ce27ed0afee3fcf3c3ba259116be';
const address2 = '0x7e85bdc27c050e3905ebf4b8e634d9ad6edd0de6';
const tbtcHotWalletDefaultParams = {
txFormat: 'psbt',
changeAddressType: ['p2trMusig2', 'p2wsh', 'p2shP2wsh', 'p2sh', 'p2tr'],
};
afterEach(function () {
sinon.restore();
sinon.reset();
});
describe('Wallet transfers', function () {
it('should search in wallet for a transfer', async function () {
const params = { limit: 1, searchLabel: 'test' };
const scope = nock(bgUrl)
.get(`/api/v2/${wallet.coin()}/wallet/${wallet.id()}/transfer`)
.query(params)
.reply(200, {
coin: 'tbch',
transfers: [
{
wallet: wallet.id(),
comment: 'tests',
},
],
});
try {
await wallet.transfers(params);
} catch (e) {
// test is successful if nock is consumed, HMAC errors expected
}
scope.isDone().should.be.True();
});
it('should forward all valid parameters', async function () {
const params = {
limit: 1,
address: ['address1', 'address2'],
dateGte: 'dateString0',
dateLt: 'dateString1',
valueGte: 0,
valueLt: 300000000,
allTokens: true,
searchLabel: 'abc',
includeHex: true,
type: 'transfer_type',
state: 'transfer_state',
};
// The actual api request will only send strings, but the SDK function expects numbers for some values
const apiParams = _.mapValues(params, (param) => (Array.isArray(param) ? param : String(param)));
const scope = nock(bgUrl)
.get(`/api/v2/${wallet.coin()}/wallet/${wallet.id()}/transfer`)
.query(_.matches(apiParams))
.reply(200);
await wallet.transfers(params);
scope.isDone().should.be.True();
});
it('should accept a string argument for address', async function () {
const params = {
limit: 1,
address: 'stringAddress',
};
const apiParams = {
limit: '1',
address: 'stringAddress',
};
const scope = nock(bgUrl)
.get(`/api/v2/${wallet.coin()}/wallet/${wallet.id()}/transfer`)
.query(_.matches(apiParams))
.reply(200);
try {
await wallet.transfers(params);
} catch (e) {
// test is successful if nock is consumed, HMAC errors expected
}
scope.isDone().should.be.True();
});
it('should throw errors for invalid expected parameters', async function () {
await wallet
// @ts-expect-error checking type mismatch
.transfers({ address: 13375 })
.should.be.rejectedWith('invalid address argument, expecting string or array');
await wallet
// @ts-expect-error checking type mismatch
.transfers({ address: [null] })
.should.be.rejectedWith('invalid address argument, expecting array of address strings');
await wallet
// @ts-expect-error checking type mismatch
.transfers({ dateGte: 20101904 })
.should.be.rejectedWith('invalid dateGte argument, expecting string');
// @ts-expect-error checking type mismatch
await wallet.transfers({ dateLt: 20101904 }).should.be.rejectedWith('invalid dateLt argument, expecting string');
await wallet
// @ts-expect-error checking type mismatch
.transfers({ valueGte: '10230005' })
.should.be.rejectedWith('invalid valueGte argument, expecting number');
// @ts-expect-error checking type mismatch
await wallet.transfers({ valueLt: '-5e8' }).should.be.rejectedWith('invalid valueLt argument, expecting number');
await wallet
// @ts-expect-error checking type mismatch
.transfers({ includeHex: '123' })
.should.be.rejectedWith('invalid includeHex argument, expecting boolean');
await wallet
// @ts-expect-error checking type mismatch
.transfers({ state: 123 })
.should.be.rejectedWith('invalid state argument, expecting string or array');
await wallet
// @ts-expect-error checking type mismatch
.transfers({ state: [123, 456] })
.should.be.rejectedWith('invalid state argument, expecting array of state strings');
// @ts-expect-error checking type mismatch
await wallet.transfers({ type: 123 }).should.be.rejectedWith('invalid type argument, expecting string');
});
});
describe('Wallet addresses', function () {
it('should search in wallet addresses', async function () {
const params = { limit: 1, labelContains: 'test' };
const scope = nock(bgUrl)
.get(`/api/v2/${wallet.coin()}/wallet/${wallet.id()}/addresses`)
.query(params)
.reply(200, {
coin: 'tbch',
transfers: [
{
wallet: wallet.id(),
comment: 'tests',
},
],
});
try {
await wallet.addresses(params);
} catch (e) {
// test is successful if nock is consumed, HMAC errors expected
}
scope.isDone().should.be.True();
});
});
it('should verify bch cashaddr format as valid', async function () {
const coin = bitgo.coin('tbch');
const valid = coin.isValidAddress('bchtest:pzfkxv532t0q5zchck2mhmmf2y02cdejyssq5qrz7a');
valid.should.be.True();
});
it('should verify bch legacy format as valid', async function () {
const coin = bitgo.coin('tbch');
const valid = coin.isValidAddress('2N6gY9r9iuXQQzZiSyngWJeoUuL5mC1x4Ac');
valid.should.be.True();
});
describe('TETH Wallet Addresses', function () {
let ethWallet;
before(async function () {
const walletData = {
id: '598f606cd8fc24710d2ebadb1d9459bb',
coin: 'teth',
keys: [
'598f606cd8fc24710d2ebad89dce86c2',
'598f606cc8e43aef09fcb785221d9dd2',
'5935d59cf660764331bafcade1855fd7',
],
};
ethWallet = new Wallet(bitgo, bitgo.coin('teth'), walletData);
});
it('search list addresses should return success', async function () {
const params = {
includeBalances: true,
includeTokens: true,
returnBalancesForToken: 'gterc6dp',
pendingDeployment: false,
includeTotalAddressCount: true,
};
const scope = nock(bgUrl)
.get(`/api/v2/${wallet.coin()}/wallet/${wallet.id()}/addresses`)
.query(params)
.reply(200);
try {
await wallet.addresses(params);
throw '';
} catch (error) {
// test is successful if nock is consumed, HMAC errors expected
}
scope.isDone().should.be.True();
});
it('should throw errors for invalid expected parameters', async function () {
await ethWallet
.addresses({ includeBalances: true, returnBalancesForToken: 1 })
.should.be.rejectedWith('invalid returnBalancesForToken argument, expecting string');
await ethWallet
.addresses({ pendingDeployment: 1 })
.should.be.rejectedWith('invalid pendingDeployment argument, expecting boolean');
await ethWallet
.addresses({ includeBalances: 1 })
.should.be.rejectedWith('invalid includeBalances argument, expecting boolean');
await ethWallet
.addresses({ includeTokens: 1 })
.should.be.rejectedWith('invalid includeTokens argument, expecting boolean');
await ethWallet
.addresses({ includeTotalAddressCount: 1 })
.should.be.rejectedWith('invalid includeTotalAddressCount argument, expecting boolean');
});
it('get forwarder balance', async function () {
const forwarders = [
{
address: '0xbfbcc0fe2b865de877134246af09378e9bc3c91d',
balance: '200000',
},
{
address: '0xe59524ed8b47165f4cb0850c9428069a6002e5eb',
balance: '10000000000000000',
},
];
nock(bgUrl).get(`/api/v2/${ethWallet.coin()}/wallet/${ethWallet.id()}/forwarders/balances`).reply(200, {
forwarders,
});
const forwarderBalance = await ethWallet.getForwarderBalance();
forwarderBalance.forwarders[0].address.should.eql(forwarders[0].address);
forwarderBalance.forwarders[0].balance.should.eql(forwarders[0].balance);
forwarderBalance.forwarders[1].address.should.eql(forwarders[1].address);
forwarderBalance.forwarders[1].balance.should.eql(forwarders[1].balance);
});
});
describe('Get User Prv', () => {
const prv =
'xprv9s21ZrQH143K3hekyNj7TciR4XNYe1kMj68W2ipjJGNHETWP7o42AjDnSPgKhdZ4x8NBAvaL72RrXjuXNdmkMqLERZza73oYugGtbLFXG8g';
const derivedPrv =
'xprv9yoG67Td11uwjXwbV8zEmrySVXERu5FZAsLD9suBeEJbgJqANs8Yng5dEJoii7hag5JermK6PbfxgDmSzW7ewWeLmeJEkmPfmZUSLdETtHx';
it('should use the cold derivation seed to derive the proper user private key', async () => {
const userPrvOptions = {
prv,
coldDerivationSeed: '123',
};
wallet.getUserPrv(userPrvOptions).should.eql(derivedPrv);
});
it('should use the user keychain derivedFromParentWithSeed as the cold derivation seed if none is provided', async () => {
const userPrvOptions: GetUserPrvOptions = {
prv,
keychain: {
derivedFromParentWithSeed: '123',
id: '456',
pub: '789',
type: 'independent',
},
};
wallet.getUserPrv(userPrvOptions).should.eql(derivedPrv);
});
it('should prefer the explicit cold derivation seed to the user keychain derivedFromParentWithSeed', async () => {
const userPrvOptions: GetUserPrvOptions = {
prv,
coldDerivationSeed: '123',
keychain: {
derivedFromParentWithSeed: '456',
id: '789',
pub: '012',
type: 'independent',
},
};
wallet.getUserPrv(userPrvOptions).should.eql(derivedPrv);
});
it('should return the prv provided for TSS SMC', async () => {
const tssWalletData = {
id: '5b34252f1bf349930e34020a00000000',
coin: 'tsol',
keys: [
'5b3424f91bf349930e34017500000000',
'5b3424f91bf349930e34017600000000',
'5b3424f91bf349930e34017700000000',
],
coinSpecific: {},
multisigType: 'tss',
};
const tsolcoin: any = bitgo.coin('tsol');
const wallet = new Wallet(bitgo, tsolcoin, tssWalletData);
const prv = 'longstringifiedjson';
const keychain = {
derivedFromParentWithSeed: 'random seed',
id: '123',
commonKeychain: 'longstring',
type: 'tss' as KeyType,
};
const userPrvOptions = {
prv,
keychain,
};
wallet.getUserPrv(userPrvOptions).should.eql(prv);
});
});
describe('TETH Wallet Transactions', function () {
let ethWallet;
before(async function () {
const walletData = {
id: '598f606cd8fc24710d2ebadb1d9459bb',
coin: 'teth',
keys: [
'598f606cd8fc24710d2ebad89dce86c2',
'598f606cc8e43aef09fcb785221d9dd2',
'5935d59cf660764331bafcade1855fd7',
],
multisigType: 'onchain',
};
ethWallet = new Wallet(bitgo, bitgo.coin('teth'), walletData);
});
afterEach(async function () {
nock.cleanAll();
});
it('should error eip1559 and gasPrice are passed', async function () {
const params = {
gasPrice: 100,
eip1559: {
maxPriorityFeePerGas: 10,
maxFeePerGas: 10,
},
amount: 10,
address: TestBitGo.V2.TEST_WALLET1_ADDRESS,
walletPassphrase: TestBitGo.V2.TEST_WALLET1_PASSCODE,
};
await ethWallet.send(params).should.be.rejected();
});
it('should search for pending transaction correctly', async function () {
const params = { walletId: wallet.id() };
const scope = nock(bgUrl).get(`/api/v2/${wallet.coin()}/tx/pending/first`).query(params).reply(200);
try {
await wallet.getFirstPendingTransaction();
throw '';
} catch (error) {
// test is successful if nock is consumed, HMAC errors expected
}
scope.isDone().should.be.True();
});
it('should try to change the fee correctly', async function () {
const params = { txid: '0xffffffff', fee: '10000000' };
const scope = nock(bgUrl).post(`/api/v2/${wallet.coin()}/wallet/${wallet.id()}/tx/changeFee`, params).reply(200);
try {
await wallet.changeFee({ txid: '0xffffffff', fee: '10000000' });
throw '';
} catch (error) {
// test is successful if nock is consumed, HMAC errors expected
}
scope.isDone().should.be.True();
});
it('should try to change the fee correctly using eip1559', async function () {
const params = {
txid: '0xffffffff',
eip1559: {
maxPriorityFeePerGas: '1000000000',
maxFeePerGas: '25000000000',
},
};
const scope = nock(bgUrl).post(`/api/v2/${wallet.coin()}/wallet/${wallet.id()}/tx/changeFee`, params).reply(200);
try {
await wallet.changeFee(params);
throw '';
} catch (error) {
// test is successful if nock is consumed, HMAC errors expected
}
scope.isDone().should.be.True();
});
it('should pass data parameter and amount: 0 when using sendTransaction', async function () {
const path = `/api/v2/${ethWallet.coin()}/wallet/${ethWallet.id()}/tx/build`;
const recipientAddress = '0x7db562c4dd465cc895761c56f83b6af0e32689ba';
const recipients = [
{
address: recipientAddress,
amount: 0,
data: '0x00110011',
},
];
const response = nock(bgUrl)
.post(path, _.matches({ recipients })) // use _.matches to do a partial match on request body object instead of strict matching
.reply(200);
const nockKeyChain = nock(bgUrl).get(`/api/v2/${ethWallet.coin()}/key/${ethWallet.keyIds()[0]}`).reply(200, {});
try {
await ethWallet.send({
address: recipients[0].address,
data: recipients[0].data,
amount: recipients[0].amount,
});
} catch (e) {
// test is successful if nock is consumed, HMAC errors expected
}
response.isDone().should.be.true();
nockKeyChain.isDone().should.be.true();
});
it('should pass data parameter and amount: 0 when using sendMany', async function () {
const path = `/api/v2/${ethWallet.coin()}/wallet/${ethWallet.id()}/tx/build`;
const recipientAddress = '0x7db562c4dd465cc895761c56f83b6af0e32689ba';
const recipients = [
{
address: recipientAddress,
amount: 0,
data: '0x00110011',
},
];
const response = nock(bgUrl)
.post(path, _.matches({ recipients })) // use _.matches to do a partial match on request body object instead of strict matching
.reply(200);
const nockKeyChain = nock(bgUrl).get(`/api/v2/${ethWallet.coin()}/key/${ethWallet.keyIds()[0]}`).reply(200, {});
try {
await ethWallet.sendMany({ recipients });
} catch (e) {
// test is successful if nock is consumed, HMAC errors expected
}
response.isDone().should.be.true();
nockKeyChain.isDone().should.be.true();
});
it('should not pass recipients in sendMany when transaction type is fillNonce', async function () {
const recipientAddress = '0x7db562c4dd465cc895761c56f83b6af0e32689ba';
const recipients = [
{
address: recipientAddress,
amount: 0,
},
];
const sendManyParams = { recipients, type: 'fillNonce', isTss: true, nonce: '13' };
try {
await ethWallet.sendMany(sendManyParams);
} catch (e) {
e.message.should.equal('cannot provide recipients for transaction type fillNonce');
// test is successful if nock is consumed, HMAC errors expected
}
});
it('should not pass receiveAddress in sendMany when TSS transaction type is transfer or transferToken', async function () {
const recipientAddress = '0x7db562c4dd465cc895761c56f83b6af0e32689ba';
const recipients = [
{
address: recipientAddress,
amount: 0,
},
];
const errorMessage = 'cannot use receive address for TSS transactions of type transfer';
const sendManyParamsReceiveAddressError = {
receiveAddress: 'throw',
recipients,
type: 'transfer',
isTss: true,
nonce: '13',
};
const sendManyParams = { recipients, type: 'transfer', isTss: true, nonce: '13' };
try {
await ethWallet.sendMany(sendManyParamsReceiveAddressError);
} catch (e) {
e.message.should.equal(errorMessage);
}
try {
await ethWallet.sendMany(sendManyParams);
} catch (e) {
e.message.should.not.equal(errorMessage);
}
});
it('should throw error early if password is wrong', async function () {
const recipientAddress = '0x7db562c4dd465cc895761c56f83b6af0e32689ba';
const recipients = [
{
address: recipientAddress,
amount: 0,
},
];
const errorMessage = `unable to decrypt keychain with the given wallet passphrase`;
const sendManyParamsCorrectPassPhrase = {
recipients,
type: 'transfer',
isTss: true,
nonce: '13',
walletPassphrase: TestBitGo.V2.TEST_ETH_WALLET_PASSPHRASE,
};
const nockKeychain = nock(bgUrl)
.get(`/api/v2/${ethWallet.coin()}/key/${ethWallet.keyIds()[0]}`)
.times(2)
.reply(200, {
id: '598f606cd8fc24710d2ebad89dce86c2',
pub: 'xpub661MyMwAqRbcFXDcWD2vxuebcT1ZpTF4Vke6qmMW8yzddwNYpAPjvYEEL5jLfyYXW2fuxtAxY8TgjPUJLcf1C8qz9N6VgZxArKX4EwB8rH5',
ethAddress: '0x26a163ba9739529720c0914c583865dec0d37278',
source: 'user',
encryptedPrv:
'{"iv":"15FsbDVI1zG9OggD8YX+Hg==","v":1,"iter":10000,"ks":256,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"hHbNH3Sz/aU=","ct":"WoNVKz7afiRxXI2w/YkzMdMyoQg/B15u1Q8aQgi96jJZ9wk6TIaSEc6bXFH3AHzD9MdJCWJQUpRhoQc/rgytcn69scPTjKeeyVMElGCxZdFVS/psQcNE+lue3//2Zlxj+6t1NkvYO+8yAezSMRBK5OdftXEjNQI="}',
coinSpecific: {},
});
await ethWallet
.sendMany({ ...sendManyParamsCorrectPassPhrase, walletPassphrase: 'wrongPassphrase' })
.should.be.rejectedWith(errorMessage);
try {
const customSigningFunction = () => {
return 'mock';
};
// Should not validate passphrase if custom signing function is provided
await ethWallet.sendMany({
...sendManyParamsCorrectPassPhrase,
walletPassphrase: 'wrongPassphrase',
customSigningFunction,
});
} catch (e) {
e.message.should.not.equal(errorMessage);
}
try {
await ethWallet.sendMany({ ...sendManyParamsCorrectPassPhrase });
} catch (e) {
e.message.should.not.equal(errorMessage);
}
nockKeychain.isDone().should.be.true();
});
});
describe('OFC Create Address', () => {
let ofcWallet: Wallet;
let nocks;
before(async function () {
const walletDataOfc = {
id: '5b34252f1bf349930e3400b00000000',
coin: 'ofc',
keys: [
'5b3424f91bf349930e34017800000000',
'5b3424f91bf349930e34017900000000',
'5b3424f91bf349930e34018000000000',
],
coinSpecific: {},
multisigType: 'onchain',
};
ofcWallet = new Wallet(bitgo, bitgo.coin('ofc'), walletDataOfc);
});
beforeEach(async function () {
nocks = [
nock(bgUrl).get(`/api/v2/ofc/key/${ofcWallet.keyIds()[0]}`).reply(200, {
id: ofcWallet.keyIds()[0],
pub: 'xpub661MyMwAqRbcFXDcWD2vxuebcT1ZpTF4Vke6qmMW8yzddwNYpAPjvYEEL5jLfyYXW2fuxtAxY8TgjPUJLcf1C8qz9N6VgZxArKX4EwB8rH5',
source: 'user',
encryptedPrv:
'{"iv":"15FsbDVI1zG9OggD8YX+Hg==","v":1,"iter":10000,"ks":256,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"hHbNH3Sz/aU=","ct":"WoNVKz7afiRxXI2w/YkzMdMyoQg/B15u1Q8aQgi96jJZ9wk6TIaSEc6bXFH3AHzD9MdJCWJQUpRhoQc/rgytcn69scPTjKeeyVMElGCxZdFVS/psQcNE+lue3//2Zlxj+6t1NkvYO+8yAezSMRBK5OdftXEjNQI="}',
coinSpecific: {},
}),
nock(bgUrl).get(`/api/v2/ofc/key/${ofcWallet.keyIds()[1]}`).reply(200, {
id: ofcWallet.keyIds()[1],
pub: 'xpub661MyMwAqRbcGhSaXikpuTC9KU88Xx9LrjKSw1JKsvXNgabpTdgjy7LSovh9ZHhcqhAHQu7uthu7FguNGdcC4aXTKK5gqTcPe4WvLYRbCSG',
source: 'backup',
coinSpecific: {},
}),
nock(bgUrl).get(`/api/v2/ofc/key/${ofcWallet.keyIds()[2]}`).reply(200, {
id: ofcWallet.keyIds()[2],
pub: 'xpub661MyMwAqRbcFsXShW8R3hJsHNTYTUwzcejnLkY7KCtaJbDqcGkcBF99BrEJSjNZHeHveiYUrsAdwnjUMGwpgmEbiKcZWRuVA9HxnRaA3r3',
source: 'bitgo',
coinSpecific: {},
}),
];
});
afterEach(async function () {
nock.cleanAll();
nocks.forEach((scope) => scope.isDone().should.be.true());
});
it('should correctly validate arguments to create address on OFC wallet', async function () {
await ofcWallet.createAddress().should.be.rejectedWith('onToken is a mandatory parameter for OFC wallets');
// @ts-expect-error test passing invalid number argument
await ofcWallet.createAddress({ onToken: 42 }).should.be.rejectedWith('onToken has to be a string');
});
it('address creation with valid onToken argument succeeds', async function () {
const scope = nock(bgUrl)
.post(`/api/v2/ofc/wallet/${ofcWallet.id()}/address`, { onToken: 'ofctbtc' })
.reply(200, {
id: '638a48c6c3dba40007a3497fa49a080c',
address: 'generated address',
chain: 0,
index: 1,
coin: 'tbtc',
wallet: ofcWallet.id,
});
const address = await ofcWallet.createAddress({ onToken: 'ofctbtc' });
address.address.should.equal('generated address');
scope.isDone().should.be.true();
});
});
describe('TETH Create Address', () => {
let ethWallet, nocks;
const walletData = {
id: '598f606cd8fc24710d2ebadb1d9459bb',
coinSpecific: {
baseAddress: '0xdf07117705a9f8dc4c2a78de66b7f1797dba9d4e',
},
coin: 'teth',
keys: [
'598f606cd8fc24710d2ebad89dce86c2',
'598f606cc8e43aef09fcb785221d9dd2',
'5935d59cf660764331bafcade1855fd7',
],
};
beforeEach(async function () {
ethWallet = new Wallet(bitgo, bitgo.coin('teth'), walletData);
nocks = [
nock(bgUrl).get(`/api/v2/${ethWallet.coin()}/key/${ethWallet.keyIds()[0]}`).reply(200, {
id: '598f606cd8fc24710d2ebad89dce86c2',
pub: 'xpub661MyMwAqRbcFXDcWD2vxuebcT1ZpTF4Vke6qmMW8yzddwNYpAPjvYEEL5jLfyYXW2fuxtAxY8TgjPUJLcf1C8qz9N6VgZxArKX4EwB8rH5',
ethAddress: '0x26a163ba9739529720c0914c583865dec0d37278',
source: 'user',
encryptedPrv:
'{"iv":"15FsbDVI1zG9OggD8YX+Hg==","v":1,"iter":10000,"ks":256,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"hHbNH3Sz/aU=","ct":"WoNVKz7afiRxXI2w/YkzMdMyoQg/B15u1Q8aQgi96jJZ9wk6TIaSEc6bXFH3AHzD9MdJCWJQUpRhoQc/rgytcn69scPTjKeeyVMElGCxZdFVS/psQcNE+lue3//2Zlxj+6t1NkvYO+8yAezSMRBK5OdftXEjNQI="}',
coinSpecific: {},
}),
nock(bgUrl).get(`/api/v2/${ethWallet.coin()}/key/${ethWallet.keyIds()[1]}`).reply(200, {
id: '598f606cc8e43aef09fcb785221d9dd2',
pub: 'xpub661MyMwAqRbcGhSaXikpuTC9KU88Xx9LrjKSw1JKsvXNgabpTdgjy7LSovh9ZHhcqhAHQu7uthu7FguNGdcC4aXTKK5gqTcPe4WvLYRbCSG',
ethAddress: '0xa1a88a502274073b1bc4fe06ea0f5fe77e151b91',
source: 'backup',
coinSpecific: {},
}),
nock(bgUrl).get(`/api/v2/${ethWallet.coin()}/key/${ethWallet.keyIds()[2]}`).reply(200, {
id: '5935d59cf660764331bafcade1855fd7',
pub: 'xpub661MyMwAqRbcFsXShW8R3hJsHNTYTUwzcejnLkY7KCtaJbDqcGkcBF99BrEJSjNZHeHveiYUrsAdwnjUMGwpgmEbiKcZWRuVA9HxnRaA3r3',
ethAddress: '0x032821b7ea40ea5d446f47c29a0f777ee035aa10',
source: 'bitgo',
coinSpecific: {},
}),
];
});
afterEach(async function () {
nock.cleanAll();
nocks.forEach((scope) => scope.isDone().should.be.true());
});
it('should correctly validate arguments to create address', async function () {
let message = 'gasPrice has to be an integer or numeric string';
// @ts-expect-error checking type mismatch
await wallet.createAddress({ gasPrice: {} }).should.be.rejectedWith(message);
await wallet.createAddress({ gasPrice: 'abc' }).should.be.rejectedWith(message);
// @ts-expect-error checking type mismatch
await wallet.createAddress({ gasPrice: null }).should.be.rejectedWith(message);
message = 'chain has to be an integer';
// @ts-expect-error checking type mismatch
await wallet.createAddress({ chain: {} }).should.be.rejectedWith(message);
// @ts-expect-error checking type mismatch
await wallet.createAddress({ chain: 'abc' }).should.be.rejectedWith(message);
// @ts-expect-error checking type mismatch
await wallet.createAddress({ chain: null }).should.be.rejectedWith(message);
message = 'count has to be a number between 1 and 250';
// @ts-expect-error checking type mismatch
await wallet.createAddress({ count: {} }).should.be.rejectedWith(message);
// @ts-expect-error checking type mismatch
await wallet.createAddress({ count: 'abc' }).should.be.rejectedWith(message);
// @ts-expect-error checking type mismatch
await wallet.createAddress({ count: null }).should.be.rejectedWith(message);
await wallet.createAddress({ count: -1 }).should.be.rejectedWith(message);
await wallet.createAddress({ count: 0 }).should.be.rejectedWith(message);
await wallet.createAddress({ count: 251 }).should.be.rejectedWith(message);
message = 'baseAddress has to be a string';
// @ts-expect-error checking type mismatch
await wallet.createAddress({ baseAddress: {} }).should.be.rejectedWith(message);
// @ts-expect-error checking type mismatch
await wallet.createAddress({ baseAddress: 123 }).should.be.rejectedWith(message);
// @ts-expect-error checking type mismatch
await wallet.createAddress({ baseAddress: null }).should.be.rejectedWith(message);
message = 'allowSkipVerifyAddress has to be a boolean';
// @ts-expect-error checking type mismatch
await wallet.createAddress({ allowSkipVerifyAddress: {} }).should.be.rejectedWith(message);
// @ts-expect-error checking type mismatch
await wallet.createAddress({ allowSkipVerifyAddress: 123 }).should.be.rejectedWith(message);
// @ts-expect-error checking type mismatch
await wallet.createAddress({ allowSkipVerifyAddress: 'abc' }).should.be.rejectedWith(message);
// @ts-expect-error checking type mismatch
await wallet.createAddress({ allowSkipVerifyAddress: null }).should.be.rejectedWith(message);
message = 'forwarderVersion has to be an integer 0, 1, 2, 3, 4 or 5';
await wallet.createAddress({ forwarderVersion: 6 }).should.be.rejectedWith(message);
await wallet.createAddress({ forwarderVersion: -1 }).should.be.rejectedWith(message);
});
it('address creation with forwarder version 3 succeeds', async function () {
const scope = nock(bgUrl)
.post(`/api/v2/${ethWallet.coin()}/wallet/${ethWallet.id()}/address`, { chain: 0, forwarderVersion: 3 })
.reply(200, {
id: '638a48c6c3dba40007a3497fa49a080c',
address: '0x5e61b64f38f1b5f85078fb84b27394830b4c8e80',
chain: 0,
index: 1,
coin: 'tpolygon',
lastNonce: 0,
wallet: '63785f95af7c760007cfae068c2f31ae',
coinSpecific: {
nonce: -1,
updateTime: '2022-12-02T18:49:42.348Z',
txCount: 0,
pendingChainInitialization: false,
creationFailure: [],
salt: '0x1',
pendingDeployment: true,
forwarderVersion: 3,
isTss: true,
},
});
const address = await ethWallet.createAddress({ chain: 0, forwarderVersion: 3 });
address.coinSpecific.forwarderVersion.should.equal(3);
scope.isDone().should.be.true();
});
it('address creation with forwarder version 3 fails due invalid address', async function () {
const address = '0x5e61b6'; // invalid address
nock(bgUrl)
.post(`/api/v2/${ethWallet.coin()}/wallet/${ethWallet.id()}/address`, { chain: 0, forwarderVersion: 3 })
.reply(200, {
id: '638a48c6c3dba40007a3497fa49a080c',
address: address,
chain: 0,
index: 1,
coin: 'tpolygon',
lastNonce: 0,
wallet: '63785f95af7c760007cfae068c2f31ae',
coinSpecific: {
nonce: -1,
updateTime: '2022-12-02T18:49:42.348Z',
txCount: 0,
pendingChainInitialization: false,
creationFailure: [],
salt: '0x1',
pendingDeployment: true,
forwarderVersion: 3,
isTss: true,
},
});
await ethWallet
.createAddress({ chain: 0, forwarderVersion: 3 })
.should.be.rejectedWith(`invalid address: ${address}`);
});
it('address creation with forwarder version 2 succeeds', async function () {
const scope = nock(bgUrl)
.post(`/api/v2/${ethWallet.coin()}/wallet/${ethWallet.id()}/address`, { chain: 0, forwarderVersion: 2 })
.reply(200, {
id: '638a48c6c3dba40007a3497fa49a080c',
address: '0x5e61b64f38f1b5f85078fb84b27394830b4c8e80',
chain: 0,
index: 1,
coin: 'tpolygon',
lastNonce: 0,
wallet: '63785f95af7c760007cfae068c2f31ae',
coinSpecific: {
nonce: -1,
updateTime: '2022-12-02T18:49:42.348Z',
txCount: 0,
pendingChainInitialization: true,
creationFailure: [],
salt: '0x1',
pendingDeployment: true,
forwarderVersion: 2,
isTss: true,
},
});
const address = await ethWallet.createAddress({ chain: 0, forwarderVersion: 2 });
address.coinSpecific.forwarderVersion.should.equal(2);
scope.isDone().should.be.true();
});
it('verify address when pendingChainInitialization is true in case of eth v1 forwarder', async function () {
const scope = nock(bgUrl)
.post(`/api/v2/${ethWallet.coin()}/wallet/${ethWallet.id()}/address`, { chain: 0, forwarderVersion: 1 })
.reply(200, {
id: '615c643a98a2a100068e023c639c0f74',
address: '0x8c13cd0bb198858f628d5631ba4b2293fc08df49',
baseAddress: '0xdf07117705a9f8dc4c2a78de66b7f1797dba9d4e',
chain: 0,
index: 3179,
coin: 'teth',
lastNonce: 0,
wallet: '598f606cd8fc24710d2ebadb1d9459bb',
coinSpecific: {
nonce: -1,
updateTime: '2021-10-05T14:42:02.399Z',
txCount: 0,
pendingChainInitialization: true,
creationFailure: [],
salt: '0xc6b',
pendingDeployment: true,
forwarderVersion: 1,
},
});
await ethWallet
.createAddress({ chain: 0, forwarderVersion: 1 })
.should.be.rejectedWith(
'address validation failure: expected 0x32a226cda14e352a47bf4b1658648d8037736f80 but got 0x8c13cd0bb198858f628d5631ba4b2293fc08df49'
);
scope.isDone().should.be.true();
});
it('verify address when invalid baseAddress is passed', async function () {
const scope = nock(bgUrl)
.post(`/api/v2/${ethWallet.coin()}/wallet/${ethWallet.id()}/address`, { chain: 0, forwarderVersion: 1 })
.reply(200, {
id: '615c643a98a2a100068e023c639c0f74',
address: '0x32a226cda14e352a47bf4b1658648d8037736f80',
baseAddress: '0xdf07117705a9f8dc4c2a78de66b7f1797dba9d4e',
chain: 0,
index: 3179,
coin: 'teth',
lastNonce: 0,
wallet: '598f606cd8fc24710d2ebadb1d9459bb',
coinSpecific: {
nonce: -1,
updateTime: '2021-10-05T14:42:02.399Z',
txCount: 0,
pendingChainInitialization: true,
creationFailure: [],
salt: '0xc6b',
pendingDeployment: true,
forwarderVersion: 1,
},
});
await ethWallet
.createAddress({ chain: 0, forwarderVersion: 1, baseAddress: 'asgf' })
.should.be.rejectedWith('invalid base address');
scope.isDone().should.be.true();
});
it('verify address when incorrect baseAddress is passed', async function () {
const scope = nock(bgUrl)
.post(`/api/v2/${ethWallet.coin()}/wallet/${ethWallet.id()}/address`, { chain: 0, forwarderVersion: 1 })
.reply(200, {
id: '615c643a98a2a100068e023c639c0f74',
address: '0x32a226cda14e352a47bf4b1658648d8037736f80',
baseAddress: '0xdf07117705a9f8dc4c2a78de66b7f1797dba9d4e',
chain: 0,
index: 3179,
coin: 'teth',
lastNonce: 0,
wallet: '598f606cd8fc24710d2ebadb1d9459bb',
coinSpecific: {
nonce: -1,
updateTime: '2021-10-05T14:42:02.399Z',
txCount: 0,
pendingChainInitialization: true,
creationFailure: [],
salt: '0xc6b',
pendingDeployment: true,
forwarderVersion: 1,
},
});
// incorrect address is generated while validating due to incorrect baseAddress
await ethWallet
.createAddress({ chain: 0, forwarderVersion: 1, baseAddress: '0x8c13cd0bb198858f628d5631ba4b2293fc08df49' })
.should.be.rejectedWith(
'address validation failure: expected 0x36748926007790e7ee416c6485b32e00cfb177a3 but got 0x32a226cda14e352a47bf4b1658648d8037736f80'