forked from woodser/monero-ts
-
Notifications
You must be signed in to change notification settings - Fork 10
/
TestMoneroWalletCommon.js
5439 lines (4672 loc) · 253 KB
/
TestMoneroWalletCommon.js
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
const assert = require("assert");
const StartMining = require("./utils/StartMining");
const TestUtils = require("./utils/TestUtils");
const monerojs = require("../../index");
const Filter = monerojs.Filter; // TODO: don't export filter
const LibraryUtils = monerojs.LibraryUtils;
const MoneroError = monerojs.MoneroError;
const MoneroTxPriority = monerojs.MoneroTxPriority;
const MoneroWalletRpc = monerojs.MoneroWalletRpc;
const MoneroWalletKeys = monerojs.MoneroWalletKeys;
const MoneroWallet = monerojs.MoneroWallet;
const MoneroWalletListener = monerojs.MoneroWalletListener;
const MoneroWalletConfig = monerojs.MoneroWalletConfig;
const MoneroUtils = monerojs.MoneroUtils;
const GenUtils = monerojs.GenUtils;
const MoneroSyncResult = monerojs.MoneroSyncResult;
const BigInteger = monerojs.BigInteger;
const MoneroRpcConnection = monerojs.MoneroRpcConnection;
const MoneroTxQuery = monerojs.MoneroTxQuery;
const MoneroTransfer = monerojs.MoneroTransfer;
const MoneroIncomingTransfer = monerojs.MoneroIncomingTransfer;
const MoneroTransferQuery = monerojs.MoneroTransferQuery;
const MoneroOutputQuery = monerojs.MoneroOutputQuery;
const MoneroOutputWallet = monerojs.MoneroOutputWallet;
const MoneroTxConfig = monerojs.MoneroTxConfig;
const MoneroTxWallet = monerojs.MoneroTxWallet;
const MoneroDestination = monerojs.MoneroDestination;
const MoneroSubaddress = monerojs.MoneroSubaddress;
const MoneroKeyImage = monerojs.MoneroKeyImage;
const MoneroTx = monerojs.MoneroTx;
const MoneroMessageSignatureType = monerojs.MoneroMessageSignatureType;
const MoneroMessageSignatureResult = monerojs.MoneroMessageSignatureResult;
// test constants
const SEND_DIVISOR = 10;
const SEND_MAX_DIFF = 60;
const MAX_TX_PROOFS = 25; // maximum number of transactions to check for each proof, undefined to check all
const NUM_BLOCKS_LOCKED = 10;
/**
* Test a wallet for common functionality.
*/
class TestMoneroWalletCommon {
/**
* Construct the tester.
*
* @param {object} testConfig - test configuration
*/
constructor(testConfig) {
this.testConfig = testConfig;
}
/**
* Called before all wallet tests.
*/
async beforeAll() {
console.log("Before all");
this.wallet = await this.getTestWallet();
this.daemon = await this.getTestDaemon();
TestUtils.WALLET_TX_TRACKER.reset(); // all wallets need to wait for txs to confirm to reliably sync
await LibraryUtils.loadKeysModule(); // for wasm dependents like address validation
}
/**
* Called before each wallet test.
*
@param {object} currentTest - invoked with Mocha current test
*/
async beforeEach(currentTest) {
console.log("Before test \"" + currentTest.title + "\"");
}
/**
* Called after all wallet tests.
*/
async afterAll() {
console.log("After all");
// try to stop mining
try { await this.daemon.stopMining(); }
catch (err) { }
// close wallet
await this.wallet.close(true);
}
/**
* Called after each wallet test.
*
@param {object} currentTest - invoked with Mocha current test
*/
async afterEach(currentTest) {
console.log("After test \"" + currentTest.title + "\"");
}
/**
* Get the daemon to test.
*
* @return the daemon to test
*/
async getTestDaemon() {
return TestUtils.getDaemonRpc();
}
/**
* Get the main wallet to test.
*
* @return the wallet to test
*/
async getTestWallet() {
throw new Error("Subclass must implement");
}
/**
* Open a test wallet with default configuration for each wallet type.
*
* @param config - configures the wallet to open
* @return MoneroWallet is the opened wallet
*/
async openWallet(config) {
throw new Error("Subclass must implement");
}
/**
* Create a test wallet with default configuration for each wallet type.
*
* @param config - configures the wallet to create
* @return MoneroWallet is the created wallet
*/
async createWallet(config) {
throw new Error("Subclass must implement");
}
/**
* Close a test wallet with customization for each wallet type.
*
* @param {MoneroWallet} wallet - the wallet to close
* @param {bool} save - whether or not to save the wallet
*/
async closeWallet(wallet, save) {
throw new Error("Subclass must implement");
}
/**
* Get the wallet's supported languages for the mnemonic phrase. This is an
* instance method for wallet rpc and a static utility for other wallets.
*
* @return {string[]} the wallet's supported languages
*/
async getMnemonicLanguages() {
throw new Error("Subclass must implement");
}
// ------------------------------ BEGIN TESTS -------------------------------
runCommonTests() {
let that = this;
let testConfig = this.testConfig;
describe("Common Wallet Tests" + (testConfig.liteMode ? " (lite mode)" : ""), function() {
// start tests by sending to multiple addresses
if (testConfig.testRelays)
it("Can send to multiple addresses in a single transaction", async function() {
for (let i = 0; i < 3; i++) {
await testSendToMultiple(5, 3, false);
}
});
// --------------------------- TEST NON RELAYS -------------------------
if (testConfig.testNonRelays)
it("Can create a random wallet", async function() {
let e1 = undefined;
try {
let wallet = await that.createWallet();
let path; try { path = await wallet.getPath(); } catch(e) { } // TODO: factor out keys-only tests?
let e2 = undefined;
try {
await MoneroUtils.validateAddress(await wallet.getPrimaryAddress(), TestUtils.NETWORK_TYPE);
await MoneroUtils.validatePrivateViewKey(await wallet.getPrivateViewKey());
await MoneroUtils.validatePrivateSpendKey(await wallet.getPrivateSpendKey());
await MoneroUtils.validateMnemonic(await wallet.getMnemonic());
if (!(wallet instanceof MoneroWalletRpc)) assert.equal(await wallet.getMnemonicLanguage(), MoneroWallet.DEFAULT_LANGUAGE); // TODO monero-wallet-rpc: get mnemonic language
} catch (e) {
e2 = e;
}
await that.closeWallet(wallet);
if (e2 !== undefined) throw e2;
// attempt to create wallet at same path
if (path) {
try {
await that.createWallet({path: path});
throw new Error("Should have thrown error");
} catch(e) {
assert.equal(e.message, "Wallet already exists: " + path);
}
}
// attempt to create wallet with unknown language
try {
await that.createWallet({language: "english"}); // TODO: support lowercase?
throw new Error("Should have thrown error");
} catch (e) {
assert.equal(e.message, "Unknown language: english");
}
} catch (e) {
e1 = e;
}
if (e1 !== undefined) throw e1;
});
if (testConfig.testNonRelays)
it("Can create a wallet from a mnemonic phrase.", async function() {
let e1 = undefined;
try {
// save for comparison
let primaryAddress = await that.wallet.getPrimaryAddress();
let privateViewKey = await that.wallet.getPrivateViewKey();
let privateSpendKey = await that.wallet.getPrivateSpendKey();
// recreate test wallet from mnemonic
let wallet = await that.createWallet({mnemonic: TestUtils.MNEMONIC, restoreHeight: TestUtils.FIRST_RECEIVE_HEIGHT});
let path; try { path = await wallet.getPath(); } catch(e) { } // TODO: factor out keys-only tests?
let e2 = undefined;
try {
assert.equal(await wallet.getPrimaryAddress(), primaryAddress);
assert.equal(await wallet.getPrivateViewKey(), privateViewKey);
assert.equal(await wallet.getPrivateSpendKey(), privateSpendKey);
if (!(wallet instanceof MoneroWalletRpc)) assert.equal(await wallet.getMnemonicLanguage(), MoneroWallet.DEFAULT_LANGUAGE);
} catch (e) {
e2 = e;
}
await that.closeWallet(wallet);
if (e2 !== undefined) throw e2;
// attempt to create wallet with two missing words
try {
let invalidMnemonic = "memoir desk algebra inbound innocent unplugs fully okay five inflamed giant factual ritual toyed topic snake unhappy guarded tweezers haunted inundate giant";
await that.createWallet(new MoneroWalletConfig().setMnemonic(invalidMnemonic).setRestoreHeight(TestUtils.FIRST_RECEIVE_HEIGHT));
} catch(err) {
assert.equal("Invalid mnemonic", err.message);
}
// attempt to create wallet at same path
if (path) {
try {
await that.createWallet({path: path});
throw new Error("Should have thrown error");
} catch (e) {
assert.equal(e.message, "Wallet already exists: " + path);
}
}
} catch (e) {
e1 = e;
}
if (e1 !== undefined) throw e1;
});
if (testConfig.testNonRelays)
it("Can create a wallet from a mnemonic phrase with a seed offset", async function() {
let e1 = undefined;
try {
// create test wallet with offset
let wallet = await that.createWallet({mnemonic: TestUtils.MNEMONIC, restoreHeight: TestUtils.FIRST_RECEIVE_HEIGHT, seedOffset: "my secret offset!"});
let e2 = undefined;
try {
await MoneroUtils.validateMnemonic(await wallet.getMnemonic());
assert.notEqual(await wallet.getMnemonic(), TestUtils.MNEMONIC);
await MoneroUtils.validateAddress(await wallet.getPrimaryAddress(), TestUtils.NETWORK_TYPE);
assert.notEqual(await wallet.getPrimaryAddress(), TestUtils.ADDRESS);
if (!(wallet instanceof MoneroWalletRpc)) assert.equal(await wallet.getMnemonicLanguage(), MoneroWallet.DEFAULT_LANGUAGE); // TODO monero-wallet-rpc: support
} catch (e) {
e2 = e;
}
await that.closeWallet(wallet);
if (e2 !== undefined) throw e2;
} catch (e) {
e1 = e;
}
if (e1 !== undefined) throw e1;
});
if (testConfig.testNonRelays)
it("Can create a wallet from keys", async function() {
let e1 = undefined;
try {
// save for comparison
let primaryAddress = await that.wallet.getPrimaryAddress();
let privateViewKey = await that.wallet.getPrivateViewKey();
let privateSpendKey = await that.wallet.getPrivateSpendKey();
// recreate test wallet from keys
let wallet = await that.createWallet({primaryAddress: primaryAddress, privateViewKey: privateViewKey, privateSpendKey: privateSpendKey, restoreHeight: await that.daemon.getHeight()});
let path; try { path = await wallet.getPath(); } catch(e) { } // TODO: factor out keys-only tests?
let e2 = undefined;
try {
assert.equal(await wallet.getPrimaryAddress(), primaryAddress);
assert.equal(await wallet.getPrivateViewKey(), privateViewKey);
assert.equal(await wallet.getPrivateSpendKey(), privateSpendKey);
if (!(wallet instanceof MoneroWalletKeys) && !await wallet.isConnectedToDaemon()) console.log("WARNING: wallet created from keys is not connected to authenticated daemon"); // TODO monero-project: keys wallets not connected
if (!(wallet instanceof MoneroWalletRpc)) {
assert.equal(await wallet.getMnemonic(), TestUtils.MNEMONIC); // TODO monero-wallet-rpc: cannot get mnemonic from wallet created from keys?
assert.equal(await wallet.getMnemonicLanguage(), MoneroWallet.DEFAULT_LANGUAGE);
}
} catch (e) {
e2 = e;
}
await that.closeWallet(wallet);
if (e2 !== undefined) throw e2;
// recreate test wallet from spend key
if (!(wallet instanceof MoneroWalletRpc)) { // TODO monero-wallet-rpc: cannot create wallet from spend key?
wallet = await that.createWallet({privateSpendKey: privateSpendKey, restoreHeight: await that.daemon.getHeight()});
try { path = await wallet.getPath(); } catch(e) { } // TODO: factor out keys-only tests?
e2 = undefined;
try {
assert.equal(await wallet.getPrimaryAddress(), primaryAddress);
assert.equal(await wallet.getPrivateViewKey(), privateViewKey);
assert.equal(await wallet.getPrivateSpendKey(), privateSpendKey);
if (!(wallet instanceof MoneroWalletKeys) && !await wallet.isConnectedToDaemon()) console.log("WARNING: wallet created from keys is not connected to authenticated daemon"); // TODO monero-project: keys wallets not connected
if (!(wallet instanceof MoneroWalletRpc)) {
assert.equal(await wallet.getMnemonic(), TestUtils.MNEMONIC); // TODO monero-wallet-rpc: cannot get mnemonic from wallet created from keys?
assert.equal(await wallet.getMnemonicLanguage(), MoneroWallet.DEFAULT_LANGUAGE);
}
} catch (e) {
e2 = e;
}
await that.closeWallet(wallet);
if (e2 !== undefined) throw e2;
}
// attempt to create wallet at same path
if (path) {
try {
await that.createWallet({path: path});
throw new Error("Should have thrown error");
} catch(e) {
assert.equal(e.message, "Wallet already exists: " + path);
}
}
} catch (e) {
e1 = e;
}
if (e1 !== undefined) throw e1;
});
if (testConfig.testRelays)
it("Can create wallets with subaddress lookahead", async function() {
let err;
let receiver;
try {
// create wallet with high subaddress lookahead
receiver = await that.createWallet({
accountLookahead: 1,
subaddressLookahead: 100000
});
// transfer funds to subaddress with high index
await that.wallet.createTx(new MoneroTxConfig()
.setAccountIndex(0)
.addDestination((await receiver.getSubaddress(0, 85000)).getAddress(), TestUtils.MAX_FEE)
.setRelay(true));
// observe unconfirmed funds
await GenUtils.waitFor(1000);
await receiver.sync();
assert((await receiver.getBalance()).compare(new BigInteger("0")) > 0);
} catch (e) {
err = e;
}
// close wallet and throw if error occurred
if (receiver) await that.closeWallet(receiver);
if (err) throw err;
});
if (testConfig.testNonRelays)
it("Can get the wallet's version", async function() {
let version = await that.wallet.getVersion();
assert.equal(typeof version.getNumber(), "number");
assert(version.getNumber() > 0);
assert.equal(typeof version.isRelease(), "boolean");
});
if (testConfig.testNonRelays)
it("Can get the wallet's path", async function() {
// create random wallet
let wallet = await that.createWallet();
// set a random attribute
let uuid = GenUtils.getUUID();
await wallet.setAttribute("uuid", uuid);
// record the wallet's path then save and close
let path = await wallet.getPath();
await that.closeWallet(wallet, true);
// re-open the wallet using its path
wallet = await that.openWallet({path: path});
// test the attribute
assert.equal(await wallet.getAttribute("uuid"), uuid);
await that.closeWallet(wallet);
});
if (testConfig.testNonRelays)
it("Can set the daemon connection", async function() {
let err;
let wallet;
try {
// create random wallet with default daemon connection
wallet = await that.createWallet({serverUri: ""});
if (wallet instanceof MoneroWalletRpc) {
assert.deepEqual(await wallet.getDaemonConnection(), new MoneroRpcConnection(TestUtils.DAEMON_RPC_CONFIG));
assert.equal(await wallet.isConnectedToDaemon(), true);
} else {
assert.equal(await wallet.getDaemonConnection(), undefined);
assert(!await wallet.isConnectedToDaemon());
}
// set empty server uri
await wallet.setDaemonConnection("");
assert.equal(await wallet.getDaemonConnection(), undefined);
assert.equal(await wallet.isConnectedToDaemon(), false);
// set offline server uri
await wallet.setDaemonConnection(TestUtils.OFFLINE_SERVER_URI);
assert.deepEqual(await wallet.getDaemonConnection(), new MoneroRpcConnection(TestUtils.OFFLINE_SERVER_URI));
assert.equal(await wallet.isConnectedToDaemon(), false);
// set daemon with wrong credentials
await wallet.setDaemonConnection({uri: TestUtils.DAEMON_RPC_CONFIG.uri, username: "wronguser", password: "wrongpass"});
assert.deepEqual((await wallet.getDaemonConnection()).getConfig(), new MoneroRpcConnection(TestUtils.DAEMON_RPC_CONFIG.uri, "wronguser", "wrongpass").getConfig());
if (!TestUtils.DAEMON_RPC_CONFIG.username) assert.equal(await wallet.isConnectedToDaemon(), true); // TODO: monerod without authentication works with bad credentials?
else assert.equal(await wallet.isConnectedToDaemon(), false);
// set daemon with authentication
await wallet.setDaemonConnection(TestUtils.DAEMON_RPC_CONFIG);
assert.deepEqual(await wallet.getDaemonConnection(), new MoneroRpcConnection(TestUtils.DAEMON_RPC_CONFIG.uri, TestUtils.DAEMON_RPC_CONFIG.username, TestUtils.DAEMON_RPC_CONFIG.password));
assert(await wallet.isConnectedToDaemon());
// nullify daemon connection
await wallet.setDaemonConnection(undefined);
assert.equal(await wallet.getDaemonConnection(), undefined);
await wallet.setDaemonConnection(TestUtils.DAEMON_RPC_CONFIG.uri);
assert.deepEqual((await wallet.getDaemonConnection()).getConfig(), new MoneroRpcConnection(TestUtils.DAEMON_RPC_CONFIG.uri).getConfig());
await wallet.setDaemonConnection(undefined);
assert.equal(await wallet.getDaemonConnection(), undefined);
// set daemon uri to non-daemon
await wallet.setDaemonConnection("www.getmonero.org");
assert.deepEqual((await wallet.getDaemonConnection()).getConfig(), new MoneroRpcConnection("www.getmonero.org").getConfig());
assert(!await wallet.isConnectedToDaemon());
// set daemon to invalid uri
await wallet.setDaemonConnection("abc123");
assert(!await wallet.isConnectedToDaemon());
// attempt to sync
try {
await wallet.sync();
throw new Error("Exception expected");
} catch (e1) {
assert.equal(e1.message, "Wallet is not connected to daemon");
}
} catch (e) {
err = e;
}
// close wallet and throw if error occurred
await that.closeWallet(wallet);
if (err) throw err;
});
if (testConfig.testNonRelays)
it("Can get the mnemonic phrase", async function() {
let mnemonic = await that.wallet.getMnemonic();
await MoneroUtils.validateMnemonic(mnemonic);
assert.equal(mnemonic, TestUtils.MNEMONIC);
});
if (testConfig.testNonRelays)
it("Can get the language of the mnemonic phrase", async function() {
let language = await that.wallet.getMnemonicLanguage();
assert.equal(language, "English");
});
if (testConfig.testNonRelays)
it("Can get a list of supported languages for the mnemonic phrase", async function() {
let languages = await that.getMnemonicLanguages();
assert(Array.isArray(languages));
assert(languages.length);
for (let language of languages) assert(language);
});
if (testConfig.testNonRelays)
it("Can get the private view key", async function() {
let privateViewKey = await that.wallet.getPrivateViewKey()
await MoneroUtils.validatePrivateViewKey(privateViewKey);
});
if (testConfig.testNonRelays)
it("Can get the private spend key", async function() {
let privateSpendKey = await that.wallet.getPrivateSpendKey()
await MoneroUtils.validatePrivateSpendKey(privateSpendKey);
});
if (testConfig.testNonRelays)
it("Can get the public view key", async function() {
let publicViewKey = await that.wallet.getPublicViewKey()
await MoneroUtils.validatePublicViewKey(publicViewKey);
});
if (testConfig.testNonRelays)
it("Can get the public spend key", async function() {
let publicSpendKey = await that.wallet.getPublicSpendKey()
await MoneroUtils.validatePublicSpendKey(publicSpendKey);
});
if (testConfig.testNonRelays)
it("Can get the primary address", async function() {
let primaryAddress = await that.wallet.getPrimaryAddress();
await MoneroUtils.validateAddress(primaryAddress, TestUtils.NETWORK_TYPE);
assert.equal(primaryAddress, await that.wallet.getAddress(0, 0));
});
if (testConfig.testNonRelays)
it("Can get the address of a subaddress at a specified account and subaddress index", async function() {
assert.equal((await that.wallet.getSubaddress(0, 0)).getAddress(), await that.wallet.getPrimaryAddress());
for (let account of await that.wallet.getAccounts(true)) {
for (let subaddress of account.getSubaddresses()) {
assert.equal(await that.wallet.getAddress(account.getIndex(), subaddress.getIndex()), subaddress.getAddress());
}
}
});
if (testConfig.testNonRelays)
it("Can get addresses out of range of used accounts and subaddresses", async function() {
await that._testGetSubaddressAddressOutOfRange();
});
if (testConfig.testNonRelays)
it("Can get the account and subaddress indices of an address", async function() {
// get last subaddress to test
let accounts = await that.wallet.getAccounts(true);
let accountIdx = accounts.length - 1;
let subaddressIdx = accounts[accountIdx].getSubaddresses().length - 1;
let address = await that.wallet.getAddress(accountIdx, subaddressIdx);
assert(address);
assert.equal(typeof address, "string");
// get address index
let subaddress = await that.wallet.getAddressIndex(address);
assert.equal(subaddress.getAccountIndex(), accountIdx);
assert.equal(subaddress.getIndex(), subaddressIdx);
// test valid but unfound address
let nonWalletAddress = await TestUtils.getExternalWalletAddress();
try {
subaddress = await that.wallet.getAddressIndex(nonWalletAddress);
throw new Error("fail");
} catch (e) {
assert.equal(e.message, "Address doesn't belong to the wallet");
}
// test invalid address
try {
subaddress = await that.wallet.getAddressIndex("this is definitely not an address");
throw new Error("fail");
} catch (e) {
assert.equal(e.message, "Invalid address");
}
});
if (testConfig.testNonRelays)
it("Can get an integrated address given a payment id", async function() {
// save address for later comparison
let address = await that.wallet.getPrimaryAddress();
// test valid payment id
let paymentId = "03284e41c342f036";
let integratedAddress = await that.wallet.getIntegratedAddress(undefined, paymentId);
assert.equal(integratedAddress.getStandardAddress(), address);
assert.equal(integratedAddress.getPaymentId(), paymentId);
// test undefined payment id which generates a new one
integratedAddress = await that.wallet.getIntegratedAddress();
assert.equal(integratedAddress.getStandardAddress(), address);
assert(integratedAddress.getPaymentId().length);
// test with primary address
let primaryAddress = await that.wallet.getPrimaryAddress();
integratedAddress = await that.wallet.getIntegratedAddress(primaryAddress, paymentId);
assert.equal(integratedAddress.getStandardAddress(), primaryAddress);
assert.equal(integratedAddress.getPaymentId(), paymentId);
// test with subaddress
if ((await that.wallet.getSubaddresses(0)).length < 2) await that.wallet.createSubaddress(0);
let subaddress = (await that.wallet.getSubaddress(0, 1)).getAddress();
try {
integratedAddress = await that.wallet.getIntegratedAddress(subaddress);
throw new Error("Getting integrated address from subaddress should have failed");
} catch (e) {
assert.equal(e.message, "Subaddress shouldn't be used");
}
// test invalid payment id
let invalidPaymentId = "invalid_payment_id_123456";
try {
integratedAddress = await that.wallet.getIntegratedAddress(undefined, invalidPaymentId);
throw new Error("Getting integrated address with invalid payment id " + invalidPaymentId + " should have thrown a RPC exception");
} catch (e) {
//assert.equal(e.getCode(), -5); // TODO: error codes part of rpc only?
assert.equal(e.message, "Invalid payment ID: " + invalidPaymentId);
}
});
if (testConfig.testNonRelays)
it("Can decode an integrated address", async function() {
let integratedAddress = await that.wallet.getIntegratedAddress(undefined, "03284e41c342f036");
let decodedAddress = await that.wallet.decodeIntegratedAddress(integratedAddress.toString());
assert.deepEqual(decodedAddress, integratedAddress);
// decode invalid address
try {
console.log(await that.wallet.decodeIntegratedAddress("bad address"));
throw new Error("Should have failed decoding bad address");
} catch (err) {
assert.equal(err.message, "Invalid address");
}
});
// TODO: test syncing from start height
if (testConfig.testNonRelays)
it("Can sync (without progress)", async function() {
let numBlocks = 100;
let chainHeight = await that.daemon.getHeight();
assert(chainHeight >= numBlocks);
let result = await that.wallet.sync(chainHeight - numBlocks); // sync to end of chain
assert(result instanceof MoneroSyncResult);
assert(result.getNumBlocksFetched() >= 0);
assert.equal(typeof result.getReceivedMoney(), "boolean");
});
if (testConfig.testNonRelays)
it("Can get the current height that the wallet is synchronized to", async function() {
let height = await that.wallet.getHeight();
assert(height >= 0);
});
if (testConfig.testNonRelays)
it("Can get a blockchain height by date", async function() {
// collect dates to test starting 100 days ago
const DAY_MS = 24 * 60 * 60 * 1000;
let yesterday = new Date(new Date().getTime() - DAY_MS); // TODO monero-project: today's date can throw exception as "in future" so we test up to yesterday
let dates = [];
for (let i = 99; i >= 0; i--) {
dates.push(new Date(yesterday.getTime() - DAY_MS * i)); // subtract i days
}
// test heights by date
let lastHeight = undefined;
for (let date of dates) {
let height = await that.wallet.getHeightByDate(date.getYear() + 1900, date.getMonth() + 1, date.getDate());
assert(height >= 0);
if (lastHeight != undefined) assert(height >= lastHeight);
lastHeight = height;
}
assert(lastHeight >= 0);
let height = await that.wallet.getHeight();
assert(height >= 0);
// test future date
try {
let tomorrow = new Date(yesterday.getTime() + DAY_MS * 2);
await that.wallet.getHeightByDate(tomorrow.getYear() + 1900, tomorrow.getMonth() + 1, tomorrow.getDate());
throw new Error("Expected exception on future date");
} catch (err) {
assert.equal(err.message, "specified date is in the future");
}
});
if (testConfig.testNonRelays)
it("Can get the locked and unlocked balances of the wallet, accounts, and subaddresses", async function() {
// fetch accounts with all info as reference
let accounts = await that.wallet.getAccounts(true);
// test that balances add up between accounts and wallet
let accountsBalance = new BigInteger(0);
let accountsUnlockedBalance = new BigInteger(0);
for (let account of accounts) {
accountsBalance = accountsBalance.add(account.getBalance());
accountsUnlockedBalance = accountsUnlockedBalance.add(account.getUnlockedBalance());
// test that balances add up between subaddresses and accounts
let subaddressesBalance = new BigInteger(0);
let subaddressesUnlockedBalance = new BigInteger(0);
for (let subaddress of account.getSubaddresses()) {
subaddressesBalance = subaddressesBalance.add(subaddress.getBalance());
subaddressesUnlockedBalance = subaddressesUnlockedBalance.add(subaddress.getUnlockedBalance());
// test that balances are consistent with getAccounts() call
assert.equal((await that.wallet.getBalance(subaddress.getAccountIndex(), subaddress.getIndex())).toString(), subaddress.getBalance().toString());
assert.equal((await that.wallet.getUnlockedBalance(subaddress.getAccountIndex(), subaddress.getIndex())).toString(), subaddress.getUnlockedBalance().toString());
}
assert.equal((await that.wallet.getBalance(account.getIndex())).toString(), subaddressesBalance.toString());
assert.equal((await that.wallet.getUnlockedBalance(account.getIndex())).toString(), subaddressesUnlockedBalance.toString());
}
TestUtils.testUnsignedBigInteger(accountsBalance);
TestUtils.testUnsignedBigInteger(accountsUnlockedBalance);
assert.equal((await that.wallet.getBalance()).toString(), accountsBalance.toString());
assert.equal((await that.wallet.getUnlockedBalance()).toString(), accountsUnlockedBalance.toString());
// test invalid input
try {
await that.wallet.getBalance(undefined, 0);
throw new Error("Should have failed");
} catch(e) {
assert.notEqual(e.message, "Should have failed");
}
});
if (testConfig.testNonRelays)
it("Can get accounts without subaddresses", async function() {
let accounts = await that.wallet.getAccounts();
assert(accounts.length > 0);
accounts.map(async (account) => {
await testAccount(account)
assert(account.getSubaddresses() === undefined);
});
});
if (testConfig.testNonRelays)
it("Can get accounts with subaddresses", async function() {
let accounts = await that.wallet.getAccounts(true);
assert(accounts.length > 0);
accounts.map(async (account) => {
await testAccount(account);
assert(account.getSubaddresses().length > 0);
});
});
if (testConfig.testNonRelays)
it("Can get an account at a specified index", async function() {
let accounts = await that.wallet.getAccounts();
assert(accounts.length > 0);
for (let account of accounts) {
await testAccount(account);
// test without subaddresses
let retrieved = await that.wallet.getAccount(account.getIndex());
assert(retrieved.getSubaddresses() === undefined);
// test with subaddresses
retrieved = await that.wallet.getAccount(account.getIndex(), true);
assert(retrieved.getSubaddresses().length > 0);
}
});
if (testConfig.testNonRelays)
it("Can create a new account without a label", async function() {
let accountsBefore = await that.wallet.getAccounts();
let createdAccount = await that.wallet.createAccount();
await testAccount(createdAccount);
assert.equal((await that.wallet.getAccounts()).length - 1, accountsBefore.length);
});
if (testConfig.testNonRelays)
it("Can create a new account with a label", async function() {
// create account with label
let accountsBefore = await that.wallet.getAccounts();
let label = GenUtils.getUUID();
let createdAccount = await that.wallet.createAccount(label);
await testAccount(createdAccount);
assert.equal((await that.wallet.getAccounts()).length - 1, accountsBefore.length);
assert.equal((await that.wallet.getSubaddress(createdAccount.getIndex(), 0)).getLabel(), label);
// fetch and test account
createdAccount = await that.wallet.getAccount(createdAccount.getIndex());
await testAccount(createdAccount);
// create account with same label
createdAccount = await that.wallet.createAccount(label);
await testAccount(createdAccount);
assert.equal((await that.wallet.getAccounts()).length - 2, accountsBefore.length);
assert.equal((await that.wallet.getSubaddress(createdAccount.getIndex(), 0)).getLabel(), label);
// fetch and test account
createdAccount = await that.wallet.getAccount(createdAccount.getIndex());
await testAccount(createdAccount);
});
if (testConfig.testNonRelays)
it("Can get subaddresses at a specified account index", async function() {
let accounts = await that.wallet.getAccounts();
assert(accounts.length > 0);
for (let account of accounts) {
let subaddresses = await that.wallet.getSubaddresses(account.getIndex());
assert(subaddresses.length > 0);
subaddresses.map(subaddress => {
testSubaddress(subaddress);
assert(account.getIndex() === subaddress.getAccountIndex());
});
}
});
if (testConfig.testNonRelays)
it("Can get subaddresses at specified account and subaddress indices", async function() {
let accounts = await that.wallet.getAccounts();
assert(accounts.length > 0);
for (let account of accounts) {
// get subaddresses
let subaddresses = await that.wallet.getSubaddresses(account.getIndex());
assert(subaddresses.length > 0);
// remove a subaddress for query if possible
if (subaddresses.length > 1) subaddresses.splice(0, 1);
// get subaddress indices
let subaddressIndices = subaddresses.map(subaddress => subaddress.getIndex());
assert(subaddressIndices.length > 0);
// fetch subaddresses by indices
let fetchedSubaddresses = await that.wallet.getSubaddresses(account.getIndex(), subaddressIndices);
// original subaddresses (minus one removed if applicable) is equal to fetched subaddresses
assert.deepEqual(fetchedSubaddresses, subaddresses);
}
});
if (testConfig.testNonRelays)
it("Can get a subaddress at a specified account and subaddress index", async function() {
let accounts = await that.wallet.getAccounts();
assert(accounts.length > 0);
for (let account of accounts) {
let subaddresses = await that.wallet.getSubaddresses(account.getIndex());
assert(subaddresses.length > 0);
for (let subaddress of subaddresses) {
testSubaddress(subaddress);
assert.deepEqual(await that.wallet.getSubaddress(account.getIndex(), subaddress.getIndex()), subaddress);
assert.deepEqual((await that.wallet.getSubaddresses(account.getIndex(), subaddress.getIndex()))[0], subaddress); // test plural call with single subaddr number
}
}
});
if (testConfig.testNonRelays)
it("Can create a subaddress with and without a label", async function() {
// create subaddresses across accounts
let accounts = await that.wallet.getAccounts();
if (accounts.length < 2) await that.wallet.createAccount();
accounts = await that.wallet.getAccounts();
assert(accounts.length > 1);
for (let accountIdx = 0; accountIdx < 2; accountIdx++) {
// create subaddress with no label
let subaddresses = await that.wallet.getSubaddresses(accountIdx);
let subaddress = await that.wallet.createSubaddress(accountIdx);
assert.equal(subaddress.getLabel(), undefined);
testSubaddress(subaddress);
let subaddressesNew = await that.wallet.getSubaddresses(accountIdx);
assert.equal(subaddressesNew.length - 1, subaddresses.length);
assert.deepEqual(subaddressesNew[subaddressesNew.length - 1].toString(), subaddress.toString());
// create subaddress with label
subaddresses = await that.wallet.getSubaddresses(accountIdx);
let uuid = GenUtils.getUUID();
subaddress = await that.wallet.createSubaddress(accountIdx, uuid);
assert.equal(uuid, subaddress.getLabel());
testSubaddress(subaddress);
subaddressesNew = await that.wallet.getSubaddresses(accountIdx);
assert.equal(subaddressesNew.length - 1, subaddresses.length);
assert.deepEqual(subaddressesNew[subaddressesNew.length - 1].toString(), subaddress.toString());
}
});
if (testConfig.testNonRelays)
it("Can get transactions in the wallet", async function() {
let nonDefaultIncoming = false;
let txs = await that._getAndTestTxs(that.wallet, undefined, true);
assert(txs.length > 0, "Wallet has no txs to test");
assert.equal(txs[0].getHeight(), TestUtils.FIRST_RECEIVE_HEIGHT, "First tx's restore height must match the restore height in TestUtils");
// test each tranasction
let blocksPerHeight = {};
for (let i = 0; i < txs.length; i++) {
await that._testTxWallet(txs[i], {wallet: that.wallet});
await that._testTxWallet(txs[i], {wallet: that.wallet});
assert.equal(txs[i].toString(), txs[i].toString());
// test merging equivalent txs
let copy1 = txs[i].copy();
let copy2 = txs[i].copy();
if (copy1.isConfirmed()) copy1.setBlock(txs[i].getBlock().copy().setTxs([copy1]));
if (copy2.isConfirmed()) copy2.setBlock(txs[i].getBlock().copy().setTxs([copy2]));
let merged = copy1.merge(copy2);
await that._testTxWallet(merged, {wallet: that.wallet});
// find non-default incoming
if (txs[i].getIncomingTransfers()) {
for (let transfer of txs[i].getIncomingTransfers()) {
if (transfer.getAccountIndex() !== 0 && transfer.getSubaddressIndex() !== 0) nonDefaultIncoming = true;
}
}
// ensure unique block reference per height
if (txs[i].isConfirmed()) {
let block = blocksPerHeight[txs[i].getHeight()];
if (block === undefined) blocksPerHeight[txs[i].getHeight()] = txs[i].getBlock();
else assert(block === txs[i].getBlock(), "Block references for same height must be same");
}
}
// ensure non-default account and subaddress tested
assert(nonDefaultIncoming, "No incoming transfers found to non-default account and subaddress; run send-to-multiple tests first");
});
if (testConfig.testNonRelays)
it("Can get transactions by hash", async function() {
let maxNumTxs = 10; // max number of txs to test
// fetch all txs for testing
let txs = await that.wallet.getTxs();
assert(txs.length > 1, "Test requires at least 2 txs to fetch by hash");
// randomly pick a few for fetching by hash
GenUtils.shuffle(txs);
txs = txs.slice(0, Math.min(txs.length, maxNumTxs));
// test fetching by hash
let fetchedTx = await that.wallet.getTx(txs[0].getHash());
assert.equal(fetchedTx.getHash(), txs[0].getHash());
await that._testTxWallet(fetchedTx);
// test fetching by hashes
let txId1 = txs[0].getHash();
let txId2 = txs[1].getHash();
let fetchedTxs = await that.wallet.getTxs([txId1, txId2]);
assert.equal(2, fetchedTxs.length);
// test fetching by hashes as collection
let txHashes = [];
for (let tx of txs) txHashes.push(tx.getHash());
fetchedTxs = await that.wallet.getTxs(txHashes);
assert.equal(fetchedTxs.length, txs.length);
for (let i = 0; i < txs.length; i++) {
assert.equal(fetchedTxs[i].getHash(), txs[i].getHash());
await that._testTxWallet(fetchedTxs[i]);
}
// test fetching with missing tx hashes
let missingTxHash = "d01ede9cde813b2a693069b640c4b99c5adbdb49fbbd8da2c16c8087d0c3e320";
txHashes.push(missingTxHash);
let missingTxHashes = [];
fetchedTxs = await that.wallet.getTxs(txHashes, missingTxHashes);
assert.equal(1, missingTxHashes.length);
assert.equal(missingTxHash, missingTxHashes[0]);
assert.equal(txs.length, fetchedTxs.length);
for (let i = 0; i < txs.length; i++) {
assert.equal(txs[i].getHash(), fetchedTxs[i].getHash());
await that._testTxWallet(fetchedTxs[i]);
}
});
if (testConfig.testNonRelays && !testConfig.liteMode)
it("Can get transactions with additional configuration", async function() {
// get random transactions for testing
let randomTxs = await getRandomTransactions(that.wallet, undefined, 3, 5);
for (let randomTx of randomTxs) await that._testTxWallet(randomTx);
// get transactions by hash
let txHashes = [];
for (let randomTx of randomTxs) {
txHashes.push(randomTx.getHash());
let txs = await that._getAndTestTxs(that.wallet, {hash: randomTx.getHash()}, true);
assert.equal(txs.length, 1);
let merged = txs[0].merge(randomTx.copy()); // txs change with chain so check mergeability
await that._testTxWallet(merged);
}