-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathTestMoneroWalletCommon.java
More file actions
6284 lines (5417 loc) · 274 KB
/
TestMoneroWalletCommon.java
File metadata and controls
6284 lines (5417 loc) · 274 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
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import common.types.Filter;
import common.utils.GenUtils;
import common.utils.JsonUtils;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import monero.common.MoneroConnectionManager;
import monero.common.MoneroError;
import monero.common.MoneroRpcConnection;
import monero.common.MoneroUtils;
import monero.daemon.MoneroDaemonRpc;
import monero.daemon.model.MoneroBlock;
import monero.daemon.model.MoneroBlockHeader;
import monero.daemon.model.MoneroKeyImage;
import monero.daemon.model.MoneroMiningStatus;
import monero.daemon.model.MoneroOutput;
import monero.daemon.model.MoneroSubmitTxResult;
import monero.daemon.model.MoneroTx;
import monero.daemon.model.MoneroVersion;
import monero.wallet.MoneroWallet;
import monero.wallet.MoneroWalletRpc;
import monero.wallet.model.MoneroAccount;
import monero.wallet.model.MoneroAddressBookEntry;
import monero.wallet.model.MoneroCheckReserve;
import monero.wallet.model.MoneroCheckTx;
import monero.wallet.model.MoneroDestination;
import monero.wallet.model.MoneroIncomingTransfer;
import monero.wallet.model.MoneroIntegratedAddress;
import monero.wallet.model.MoneroKeyImageImportResult;
import monero.wallet.model.MoneroMessageSignatureResult;
import monero.wallet.model.MoneroMessageSignatureType;
import monero.wallet.model.MoneroMultisigInfo;
import monero.wallet.model.MoneroMultisigInitResult;
import monero.wallet.model.MoneroMultisigSignResult;
import monero.wallet.model.MoneroOutgoingTransfer;
import monero.wallet.model.MoneroOutputQuery;
import monero.wallet.model.MoneroOutputWallet;
import monero.wallet.model.MoneroSubaddress;
import monero.wallet.model.MoneroSyncResult;
import monero.wallet.model.MoneroTransfer;
import monero.wallet.model.MoneroTransferQuery;
import monero.wallet.model.MoneroTxConfig;
import monero.wallet.model.MoneroTxPriority;
import monero.wallet.model.MoneroTxQuery;
import monero.wallet.model.MoneroTxSet;
import monero.wallet.model.MoneroTxWallet;
import monero.wallet.model.MoneroWalletConfig;
import monero.wallet.model.MoneroWalletListener;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.opentest4j.AssertionFailedError;
import utils.Pair;
import utils.StartMining;
import utils.TestUtils;
import utils.WalletEqualityUtils;
/**
* Runs common tests that every Monero wallet implementation should support.
*/
@TestInstance(Lifecycle.PER_CLASS) // so @BeforeAll and @AfterAll can be used on non-static functions
public abstract class TestMoneroWalletCommon {
// test constants
protected static final boolean LITE_MODE = false;
protected static final boolean TEST_NON_RELAYS = true;
protected static final boolean TEST_RELAYS = true;
protected static final boolean TEST_NOTIFICATIONS = true;
protected static final boolean TEST_RESETS = false;
private static final int MAX_TX_PROOFS = 25; // maximum number of transactions to check for each proof, undefined to check all
private static final int SEND_MAX_DIFF = 60;
private static final int SEND_DIVISOR = 10;
private static final int NUM_BLOCKS_LOCKED = 10;
// instance variables
protected MoneroWallet wallet; // wallet instance to test
protected MoneroDaemonRpc daemon; // daemon instance to test
public TestMoneroWalletCommon() {
}
@BeforeAll
public void beforeAll() {
wallet = getTestWallet();
daemon = getTestDaemon();
}
@BeforeEach
public void beforeEach(TestInfo testInfo) {
System.out.println("Before test " + testInfo.getDisplayName());
// stop mining
MoneroMiningStatus status = daemon.getMiningStatus();
if (status.isActive()) wallet.stopMining();
}
@AfterAll
public void afterAll() {
// try to stop mining
if (daemon != null) {
try { daemon.stopMining(); }
catch (MoneroError e) { }
}
// close wallet
if (wallet != null) wallet.close(true);
}
@AfterEach
public void afterEach(TestInfo testInfo) {
System.out.println("After test " + testInfo.getDisplayName());
if (daemon.getMiningStatus().isActive()) {
System.err.println("WARNING: mining is active after test " + testInfo.getDisplayName() + ", stopping");
daemon.stopMining();
}
}
/**
* Get the daemon to test.
*
* @return the daemon to test
*/
protected MoneroDaemonRpc getTestDaemon() {
return TestUtils.getDaemonRpc();
}
/**
* Get the main wallet to test.
*
* @return the wallet to test
*/
protected abstract MoneroWallet getTestWallet();
/**
* Open a test wallet with default configuration for each wallet type.
*
* @param config configures the wallet to open
* @return MoneroWallet is the opened wallet
*/
protected MoneroWallet openWallet(String path, String password) { return openWallet(new MoneroWalletConfig().setPath(path).setPassword(password)); }
protected abstract MoneroWallet openWallet(MoneroWalletConfig config);
/**
* Create a test wallet with default configuration for each wallet type.
*
* @param config configures the wallet to create
* @return MoneroWallet is the created wallet
*/
protected abstract MoneroWallet createWallet(MoneroWalletConfig config);
/**
* Close a test wallet with customization for each wallet type.
*
* @param wallet - the wallet to close
* @param save - whether or not to save the wallet
*/
protected void closeWallet(MoneroWallet wallet) { closeWallet(wallet, false); }
protected abstract void closeWallet(MoneroWallet wallet, boolean save);
/**
* Get the wallet's supported languages for the seed. This is an
* instance method for wallet rpc and a static utility for other wallets.
*
* @return List<String> are the wallet's supported languages
*/
protected abstract List<String> getSeedLanguages();
// ------------------------------ BEGIN TESTS -------------------------------
// Can create a random wallet
@Test
public void testCreateWalletRandom() {
assumeTrue(TEST_NON_RELAYS);
Exception e1 = null; // emulating Java "finally" but compatible with other languages
try {
// create random wallet
MoneroWallet wallet = createWallet(new MoneroWalletConfig());
String path = wallet.getPath();
Exception e2 = null;
try {
MoneroUtils.validateAddress(wallet.getPrimaryAddress(), TestUtils.NETWORK_TYPE);
MoneroUtils.validatePrivateViewKey(wallet.getPrivateViewKey());
MoneroUtils.validatePrivateSpendKey(wallet.getPrivateSpendKey());
MoneroUtils.validateMnemonic(wallet.getSeed());
if (!(wallet instanceof MoneroWalletRpc)) assertEquals(MoneroWallet.DEFAULT_LANGUAGE, wallet.getSeedLanguage()); // TODO monero-wallet-rpc: get seed language
} catch (Exception e) {
e2 = e;
}
closeWallet(wallet);
if (e2 != null) throw e2;
// attempt to create wallet at same path
try {
createWallet(new MoneroWalletConfig().setPath(path));
throw new Error("Should have thrown error");
} catch(Exception e) {
assertEquals("Wallet already exists: " + path, e.getMessage());
}
// attempt to create wallet with unknown language
try {
createWallet(new MoneroWalletConfig().setLanguage("english")); // TODO: support lowercase?
throw new Error("Should have thrown error");
} catch (Exception e) {
assertEquals("Unknown language: english", e.getMessage());
}
} catch (Exception e) {
e1 = e;
}
if (e1 != null) throw new RuntimeException(e1);
}
// Can create a wallet from a seed.
@Test
public void testCreateWalletFromSeed() {
assumeTrue(TEST_NON_RELAYS);
Exception e1 = null; // emulating Java "finally" but compatible with other languages
try {
// save for comparison
String primaryAddress = wallet.getPrimaryAddress();
String privateViewKey = wallet.getPrivateViewKey();
String privateSpendKey = wallet.getPrivateSpendKey();
// recreate test wallet from seed
MoneroWallet wallet = createWallet(new MoneroWalletConfig().setSeed(TestUtils.SEED).setRestoreHeight(TestUtils.FIRST_RECEIVE_HEIGHT));
String path = wallet.getPath();
Exception e2 = null;
try {
assertEquals(primaryAddress, wallet.getPrimaryAddress());
assertEquals(privateViewKey, wallet.getPrivateViewKey());
assertEquals(privateSpendKey, wallet.getPrivateSpendKey());
assertEquals(TestUtils.SEED, wallet.getSeed());
if (!(wallet instanceof MoneroWalletRpc)) assertEquals(MoneroWallet.DEFAULT_LANGUAGE, wallet.getSeedLanguage());
} catch (Exception e) {
e2 = e;
}
closeWallet(wallet);
if (e2 != null) throw e2;
// attempt to create wallet with two missing words
try {
String invalidMnemonic = "memoir desk algebra inbound innocent unplugs fully okay five inflamed giant factual ritual toyed topic snake unhappy guarded tweezers haunted inundate giant";
wallet = createWallet(new MoneroWalletConfig().setSeed(invalidMnemonic).setRestoreHeight(TestUtils.FIRST_RECEIVE_HEIGHT));
} catch(Exception e) {
assertEquals("Invalid mnemonic", e.getMessage());
}
// attempt to create wallet at same path
try {
createWallet(new MoneroWalletConfig().setPath(path));
throw new RuntimeException("Should have thrown error");
} catch (Exception e) {
assertEquals("Wallet already exists: " + path, e.getMessage());
}
} catch (Exception e) {
e1 = e;
}
if (e1 != null) throw new RuntimeException(e1);
}
// Can create a wallet from a seed with a seed offset
@Test
public void testCreateWalletFromSeedWithOffset() {
assumeTrue(TEST_NON_RELAYS);
Exception e1 = null; // emulating Java "finally" but compatible with other languages
try {
// create test wallet with offset
MoneroWallet wallet = createWallet(new MoneroWalletConfig().setSeed(TestUtils.SEED).setRestoreHeight(TestUtils.FIRST_RECEIVE_HEIGHT).setSeedOffset("my secret offset!"));
Exception e2 = null;
try {
MoneroUtils.validateMnemonic(wallet.getSeed());
assertNotEquals(TestUtils.SEED, wallet.getSeed());
MoneroUtils.validateAddress(wallet.getPrimaryAddress(), TestUtils.NETWORK_TYPE);
assertNotEquals(TestUtils.ADDRESS, wallet.getPrimaryAddress());
if (!(wallet instanceof MoneroWalletRpc)) assertEquals(MoneroWallet.DEFAULT_LANGUAGE, wallet.getSeedLanguage()); // TODO monero-wallet-rpc: support
} catch (Exception e) {
e2 = e;
}
closeWallet(wallet);
if (e2 != null) throw e2;
} catch (Exception e) {
e1 = e;
}
if (e1 != null) throw new RuntimeException(e1);
}
// Can create a wallet from keys
@Test
public void testCreateWalletFromKeys() {
assumeTrue(TEST_NON_RELAYS);
Exception e1 = null; // emulating Java "finally" but compatible with other languages
try {
// save for comparison
String primaryAddress = wallet.getPrimaryAddress();
String privateViewKey = wallet.getPrivateViewKey();
String privateSpendKey = wallet.getPrivateSpendKey();
// recreate test wallet from keys
MoneroWallet wallet = createWallet(new MoneroWalletConfig().setPrimaryAddress(primaryAddress).setPrivateViewKey(privateViewKey).setPrivateSpendKey(privateSpendKey).setRestoreHeight(daemon.getHeight()));
String path = wallet.getPath();
Exception e2 = null;
try {
assertEquals(primaryAddress, wallet.getPrimaryAddress());
assertEquals(privateViewKey, wallet.getPrivateViewKey());
assertEquals(privateSpendKey, wallet.getPrivateSpendKey());
if (!wallet.isConnectedToDaemon()) System.out.println("WARNING: wallet created from keys is not connected to authenticated daemon"); // TODO monero-project: keys wallets not connected
assertTrue(wallet.isConnectedToDaemon(), "Wallet created from keys is not connected to authenticated daemon");
if (!(wallet instanceof MoneroWalletRpc)) {
MoneroUtils.validateMnemonic(wallet.getSeed()); // TODO monero-wallet-rpc: cannot get seed from wallet created from keys?
assertEquals(MoneroWallet.DEFAULT_LANGUAGE, wallet.getSeedLanguage());
}
} catch (Exception e) {
e2 = e;
}
closeWallet(wallet);
if (e2 != null) throw e2;
// recreate test wallet from spend key
if (!(wallet instanceof MoneroWalletRpc)) { // TODO monero-wallet-rpc: cannot create wallet from spend key?
wallet = createWallet(new MoneroWalletConfig().setPrivateSpendKey(privateSpendKey).setRestoreHeight(daemon.getHeight()));
e2 = null;
try {
assertEquals(primaryAddress, wallet.getPrimaryAddress());
assertEquals(privateViewKey, wallet.getPrivateViewKey());
assertEquals(privateSpendKey, wallet.getPrivateSpendKey());
if (!wallet.isConnectedToDaemon()) System.out.println("WARNING: wallet created from keys is not connected to authenticated daemon"); // TODO monero-project: keys wallets not connected
assertTrue(wallet.isConnectedToDaemon(), "Wallet created from keys is not connected to authenticated daemon");
if (!(wallet instanceof MoneroWalletRpc)) {
MoneroUtils.validateMnemonic(wallet.getSeed()); // TODO monero-wallet-rpc: cannot get seed from wallet created from keys?
assertEquals(MoneroWallet.DEFAULT_LANGUAGE, wallet.getSeedLanguage());
}
} catch (Exception e) {
e2 = e;
}
closeWallet(wallet);
if (e2 != null) throw e2;
}
// attempt to create wallet at same path
try {
createWallet(new MoneroWalletConfig().setPath(path));
throw new Error("Should have thrown error");
} catch(Exception e) {
assertEquals("Wallet already exists: " + path, e.getMessage());
}
} catch (Exception e) {
e1 = e;
}
if (e1 != null) throw new RuntimeException(e1);
}
// Can create wallets with subaddress lookahead
@Test
public void testSubaddressLookahead() {
assumeTrue(TEST_NON_RELAYS);
Exception e1 = null; // emulating Java "finally" but compatible with other languages
MoneroWallet receiver = null;
try {
// create wallet with high subaddress lookahead
receiver = createWallet(new MoneroWalletConfig().setAccountLookahead(1).setSubaddressLookahead(100000));
// transfer funds to subaddress with high index
wallet.createTx(new MoneroTxConfig()
.setAccountIndex(0)
.addDestination(receiver.getSubaddress(0, 85000).getAddress(), TestUtils.MAX_FEE)
.setRelay(true));
// observe unconfirmed funds
GenUtils.waitFor(1000);
receiver.sync();
assert(receiver.getBalance().compareTo(new BigInteger("0")) > 0);
} catch (Exception e) {
e1 = e;
}
if (receiver != null) closeWallet(receiver);
if (e1 != null) throw new RuntimeException(e1);
}
// Can get the wallet's version
@Test
public void testGetVersion() {
assumeTrue(TEST_NON_RELAYS);
MoneroVersion version = wallet.getVersion();
assertNotNull(version.getNumber());
assertTrue(version.getNumber() > 0);
assertNotNull(version.getIsRelease());
}
// Can get the wallet's path
@Test
public void testGetPath() {
assumeTrue(TEST_NON_RELAYS);
// create random wallet
MoneroWallet wallet = createWallet(new MoneroWalletConfig());
// set a random attribute
String uuid = UUID.randomUUID().toString();
wallet.setAttribute("uuid", uuid);
// record the wallet's path then save and close
String path = wallet.getPath();
closeWallet(wallet, true);
// re-open the wallet using its path
wallet = openWallet(path, null);
// test the attribute
assertEquals(uuid, wallet.getAttribute("uuid"));
closeWallet(wallet);
}
// Can set the daemon connection
@Test
public void testSetDaemonConnection() {
// create random wallet with default daemon connection
MoneroWallet wallet = createWallet(new MoneroWalletConfig());
assertEquals(new MoneroRpcConnection(TestUtils.DAEMON_RPC_URI, TestUtils.DAEMON_RPC_USERNAME, TestUtils.DAEMON_RPC_PASSWORD), wallet.getDaemonConnection());
assertTrue(wallet.isConnectedToDaemon()); // uses default localhost connection
// set empty server uri
wallet.setDaemonConnection("");
assertEquals(null, wallet.getDaemonConnection());
assertFalse(wallet.isConnectedToDaemon());
// set offline server uri
wallet.setDaemonConnection(TestUtils.OFFLINE_SERVER_URI);
assertEquals(new MoneroRpcConnection(TestUtils.OFFLINE_SERVER_URI, "", ""), wallet.getDaemonConnection());
assertFalse(wallet.isConnectedToDaemon());
// set daemon with wrong credentials
wallet.setDaemonConnection(TestUtils.DAEMON_RPC_URI, "wronguser", "wrongpass");
assertEquals(new MoneroRpcConnection(TestUtils.DAEMON_RPC_URI, "wronguser", "wrongpass"), wallet.getDaemonConnection());
if ("".equals(TestUtils.DAEMON_RPC_USERNAME) || TestUtils.DAEMON_RPC_USERNAME == null) assertTrue(wallet.isConnectedToDaemon()); // TODO: monerod without authentication works with bad credentials?
else assertFalse(wallet.isConnectedToDaemon());
// set daemon with authentication
wallet.setDaemonConnection(TestUtils.DAEMON_RPC_URI, TestUtils.DAEMON_RPC_USERNAME, TestUtils.DAEMON_RPC_PASSWORD);
assertEquals(new MoneroRpcConnection(TestUtils.DAEMON_RPC_URI, TestUtils.DAEMON_RPC_USERNAME, TestUtils.DAEMON_RPC_PASSWORD), wallet.getDaemonConnection());
assertTrue(wallet.isConnectedToDaemon());
// nullify daemon connection
wallet.setDaemonConnection((String) null);
assertEquals(null, wallet.getDaemonConnection());
wallet.setDaemonConnection(TestUtils.DAEMON_RPC_URI);
assertEquals(new MoneroRpcConnection(TestUtils.DAEMON_RPC_URI), wallet.getDaemonConnection());
wallet.setDaemonConnection((MoneroRpcConnection) null);
assertEquals(null, wallet.getDaemonConnection());
// set daemon uri to non-daemon
wallet.setDaemonConnection("www.getmonero.org");
assertEquals(new MoneroRpcConnection("www.getmonero.org"), wallet.getDaemonConnection());
assertFalse(wallet.isConnectedToDaemon());
// set daemon to invalid uri
wallet.setDaemonConnection("abc123");
assertFalse(wallet.isConnectedToDaemon());
// attempt to sync
try {
wallet.sync();
fail("Exception expected");
} catch (MoneroError e) {
assertEquals("Wallet is not connected to daemon", e.getMessage());
} finally {
closeWallet(wallet);
}
}
// Can use a connection manager
@Test
public void testConnectionManager() {
// create connection manager with monerod connections
MoneroConnectionManager connectionManager = new MoneroConnectionManager();
MoneroRpcConnection connection1 = new MoneroRpcConnection(TestUtils.getDaemonRpc().getRpcConnection()).setPriority(1);
MoneroRpcConnection connection2 = new MoneroRpcConnection("localhost:48081").setPriority(2);
connectionManager.setConnection(connection1);
connectionManager.addConnection(connection2);
// create wallet with connection manager
MoneroWallet wallet = createWallet(new MoneroWalletConfig().setServerUri("").setConnectionManager(connectionManager));
assertEquals(TestUtils.getDaemonRpc().getRpcConnection(), wallet.getDaemonConnection());
assertTrue(wallet.isConnectedToDaemon());
// set manager's connection
connectionManager.setConnection(connection2);
GenUtils.waitFor(TestUtils.AUTO_CONNECT_TIMEOUT_MS);
assertEquals(connection2, wallet.getDaemonConnection());
// reopen wallet with connection manager
String path = wallet.getPath();
closeWallet(wallet);
wallet = openWallet(new MoneroWalletConfig().setServerUri("").setConnectionManager(connectionManager).setPath(path));
assertEquals(connection2, wallet.getDaemonConnection());
// disconnect
connectionManager.setConnection((String) null);
assertEquals(null, wallet.getDaemonConnection());
assertFalse(wallet.isConnectedToDaemon());
// start polling connections
connectionManager.startPolling(TestUtils.SYNC_PERIOD_IN_MS);
// test that wallet auto connects
GenUtils.waitFor(TestUtils.AUTO_CONNECT_TIMEOUT_MS);
assertEquals(connection1, wallet.getDaemonConnection());
assertTrue(wallet.isConnectedToDaemon());
// test override with bad connection
wallet.addListener(new MoneroWalletListener());
connectionManager.setAutoSwitch(false);
connectionManager.setConnection("http://foo.bar.xyz");
assertEquals("http://foo.bar.xyz", wallet.getDaemonConnection().getUri());
assertEquals(wallet.isConnectedToDaemon(), false);
GenUtils.waitFor(5000);
assertEquals(wallet.isConnectedToDaemon(), false);
// set to another connection manager
MoneroConnectionManager connectionManager2 = new MoneroConnectionManager();
connectionManager2.setConnection(connection2);
wallet.setConnectionManager(connectionManager2);
assertEquals(connection2, wallet.getDaemonConnection());
// unset connection manager
wallet.setConnectionManager(null);
assertEquals(null, wallet.getConnectionManager());
assertEquals(connection2, wallet.getDaemonConnection());
// stop polling and close
connectionManager.stopPolling();
closeWallet(wallet);
}
// Can get the seed
@Test
public void testGetSeed() {
assumeTrue(TEST_NON_RELAYS);
String seed = wallet.getSeed();
MoneroUtils.validateMnemonic(seed);
assertEquals(TestUtils.SEED, seed);
}
// Can get the language of the seed
@Test
public void testGetSeedLanguage() {
assumeTrue(TEST_NON_RELAYS);
String language = wallet.getSeedLanguage();
assertEquals(MoneroWallet.DEFAULT_LANGUAGE, language);
}
// Can get a list of supported languages for the seed
@Test
public void testGetSeedLanguages() {
assumeTrue(TEST_NON_RELAYS);
List<String> languages = getSeedLanguages();
assertFalse(languages.isEmpty());
for (String language : languages) assertFalse(language.isEmpty());
}
// Can get the private view key
@Test
public void testGetPrivateViewKey() {
assumeTrue(TEST_NON_RELAYS);
String privateViewKey = wallet.getPrivateViewKey();
MoneroUtils.validatePrivateViewKey(privateViewKey);
}
// Can get the private spend key
@Test
public void testGetPrivateSpendKey() {
assumeTrue(TEST_NON_RELAYS);
String privateSpendKey = wallet.getPrivateSpendKey();
MoneroUtils.validatePrivateSpendKey(privateSpendKey);
}
// Can get the public view key
@Test
public void testGetPublicViewKey() {
assumeTrue(TEST_NON_RELAYS);
String publicViewKey = wallet.getPublicViewKey();
MoneroUtils.validatePrivateSpendKey(publicViewKey);
}
// Can get the public view key
@Test
public void testGetPublicSpendKey() {
assumeTrue(TEST_NON_RELAYS);
String publicSpendKey = wallet.getPublicSpendKey();
MoneroUtils.validatePrivateSpendKey(publicSpendKey);
}
// Can get the primary address
@Test
public void testGetPrimaryAddress() {
assumeTrue(TEST_NON_RELAYS);
String primaryAddress = wallet.getPrimaryAddress();
MoneroUtils.validateAddress(primaryAddress, TestUtils.NETWORK_TYPE);
assertEquals(wallet.getAddress(0, 0), primaryAddress);
}
// Can get the address of a subaddress at a specified account and subaddress index
@Test
public void testGetSubaddressAddress() {
assumeTrue(TEST_NON_RELAYS);
assertEquals(wallet.getPrimaryAddress(), (wallet.getSubaddress(0, 0)).getAddress());
for (MoneroAccount account : wallet.getAccounts(true)) {
for (MoneroSubaddress subaddress : account.getSubaddresses()) {
assertEquals(subaddress.getAddress(), wallet.getAddress(account.getIndex(), subaddress.getIndex()));
}
}
}
// Can get addresses out of range of used accounts and subaddresses
@Test
public void testGetSubaddressAddressOutOfRange() {
assumeTrue(TEST_NON_RELAYS);
List<MoneroAccount> accounts = wallet.getAccounts(true);
int accountIdx = accounts.size() - 1;
int subaddressIdx = accounts.get(accountIdx).getSubaddresses().size();
String address = wallet.getAddress(accountIdx, subaddressIdx);
assertNotNull(address);
assertTrue(address.length() > 0);
}
// Can get the account and subaddress indices of an address
@Test
public void testGetAddressIndices() {
assumeTrue(TEST_NON_RELAYS);
// get last subaddress to test
List<MoneroAccount> accounts = wallet.getAccounts(true);
int accountIdx = accounts.size() - 1;
int subaddressIdx = accounts.get(accountIdx).getSubaddresses().size() - 1;
String address = wallet.getAddress(accountIdx, subaddressIdx);
assertNotNull(address);
// get address index
MoneroSubaddress subaddress = wallet.getAddressIndex(address);
assertEquals(accountIdx, (int) subaddress.getAccountIndex());
assertEquals(subaddressIdx, (int) subaddress.getIndex());
// test valid but unfound address
String nonWalletAddress = TestUtils.getExternalWalletAddress();
try {
subaddress = wallet.getAddressIndex(nonWalletAddress);
fail("Should have thrown exception");
} catch (MoneroError e) {
assertEquals("Address doesn't belong to the wallet", e.getMessage());
}
// test invalid address
try {
subaddress = wallet.getAddressIndex("this is definitely not an address");
fail("Should have thrown exception");
} catch (MoneroError e) {
assertEquals("Invalid address", e.getMessage());
}
}
// Can get an integrated address given a payment id
@Test
public void testGetIntegratedAddress() {
assumeTrue(TEST_NON_RELAYS);
// save address for later comparison
String address = wallet.getPrimaryAddress();
// test valid payment id
String paymentId = "03284e41c342f036";
MoneroIntegratedAddress integratedAddress = wallet.getIntegratedAddress(null, paymentId);
assertEquals(integratedAddress.getStandardAddress(), address);
assertEquals(integratedAddress.getPaymentId(), paymentId);
// test null payment id which generates a new one
integratedAddress = wallet.getIntegratedAddress();
assertEquals(integratedAddress.getStandardAddress(), address);
assertFalse(integratedAddress.getPaymentId().isEmpty());
// test with primary address
String primaryAddress = wallet.getPrimaryAddress();
integratedAddress = wallet.getIntegratedAddress(primaryAddress, paymentId);
assertEquals(integratedAddress.getStandardAddress(), primaryAddress);
assertEquals(integratedAddress.getPaymentId(), paymentId);
// test with subaddress
if (wallet.getSubaddresses(0).size() < 2) wallet.createSubaddress(0);
String subaddress = wallet.getSubaddress(0, 1).getAddress();
try {
integratedAddress = wallet.getIntegratedAddress(subaddress, null);
fail("Getting integrated address from subaddress should have failed");
} catch (MoneroError e) {
assertEquals("Subaddress shouldn't be used", e.getMessage());
}
// test invalid payment id
String invalidPaymentId = "invalid_payment_id_123456";
try {
integratedAddress = wallet.getIntegratedAddress(null, invalidPaymentId);
fail("Getting integrated address with invalid payment id " + invalidPaymentId + " should have thrown exception");
} catch (MoneroError e) {
assertEquals("Invalid payment ID: " + invalidPaymentId, e.getMessage());
}
}
// Can decode an integrated address
@Test
public void testDecodeIntegratedAddress() {
assumeTrue(TEST_NON_RELAYS);
MoneroIntegratedAddress integratedAddress = wallet.getIntegratedAddress(null, "03284e41c342f036");
MoneroIntegratedAddress decodedAddress = wallet.decodeIntegratedAddress(integratedAddress.toString());
assertEquals(integratedAddress, decodedAddress);
// decode invalid address
try {
wallet.decodeIntegratedAddress("bad address");
throw new Error("Should have failed decoding bad address");
} catch (MoneroError err) {
assertEquals("Invalid address", err.getMessage());
}
}
// Can sync (without progress)
// TODO: test syncing from start height
@Test
public void testSyncWithoutProgress() {
assumeTrue(TEST_NON_RELAYS);
long numBlocks = 100;
long chainHeight = daemon.getHeight();
assertTrue(chainHeight >= numBlocks);
MoneroSyncResult result = wallet.sync(chainHeight - numBlocks); // sync end of chain
assertTrue(result.getNumBlocksFetched() >= 0);
assertNotNull(result.getReceivedMoney());
}
// Is equal to a ground truth wallet according to on-chain data
@Test
public void testWalletEqualityGroundTruth() {
assumeTrue(TEST_NON_RELAYS);
TestUtils.WALLET_TX_TRACKER.waitForTxsToClearPool(wallet);
MoneroWallet walletGt = TestUtils.createWalletGroundTruth(TestUtils.NETWORK_TYPE, TestUtils.SEED, null, TestUtils.FIRST_RECEIVE_HEIGHT);
try {
WalletEqualityUtils.testWalletEqualityOnChain(walletGt, wallet);
} finally {
walletGt.close();
}
}
// Can get the current height that the wallet is synchronized to
@Test
public void testGetHeight() {
assumeTrue(TEST_NON_RELAYS);
long height = wallet.getHeight();
assertTrue(height >= 0);
}
// Can get a blockchain height by date
@SuppressWarnings("deprecation")
@Test
public void testGetHeightByDate() {
assumeTrue(TEST_NON_RELAYS);
// collect dates to test starting 100 days ago
long DAY_MS = 24 * 60 * 60 * 1000;
Date 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
List<Date> dates = new ArrayList<Date>();
for (long i = 99; i >= 0; i--) {
dates.add(new Date(yesterday.getTime() - DAY_MS * i)); // subtract i days
}
// test heights by date
Long lastHeight = null;
for (Date date : dates) {
long height = wallet.getHeightByDate(date.getYear() + 1900, date.getMonth() + 1, date.getDate());
assertTrue(height >= 0);
if (lastHeight != null) assertTrue(height >= lastHeight);
lastHeight = height;
}
assertTrue(lastHeight >= 0);
long height = wallet.getHeight();
assertTrue(height >= 0);
// test future date
try {
Date tomorrow = new Date(yesterday.getTime() + DAY_MS * 2);
wallet.getHeightByDate(tomorrow.getYear() + 1900, tomorrow.getMonth() + 1, tomorrow.getDate());
fail("Expected exception on future date");
} catch (MoneroError err) {
assertEquals("specified date is in the future", err.getMessage());
}
}
// Can get the locked and unlocked balances of the wallet, accounts, and subaddresses
@Test
public void testGetAllBalances() {
assumeTrue(TEST_NON_RELAYS);
// fetch accounts with all info as reference
List<MoneroAccount> accounts = wallet.getAccounts(true);
// test that balances add up between accounts and wallet
BigInteger accountsBalance = BigInteger.valueOf(0);
BigInteger accountsUnlockedBalance = BigInteger.valueOf(0);
for (MoneroAccount account : accounts) {
accountsBalance = accountsBalance.add(account.getBalance());
accountsUnlockedBalance = accountsUnlockedBalance.add(account.getUnlockedBalance());
// test that balances add up between subaddresses and accounts
BigInteger subaddressesBalance = BigInteger.valueOf(0);
BigInteger subaddressesUnlockedBalance = BigInteger.valueOf(0);
for (MoneroSubaddress subaddress : account.getSubaddresses()) {
subaddressesBalance = subaddressesBalance.add(subaddress.getBalance());
subaddressesUnlockedBalance = subaddressesUnlockedBalance.add(subaddress.getUnlockedBalance());
// test that balances are consistent with getAccounts() call
assertEquals((wallet.getBalance(subaddress.getAccountIndex(), subaddress.getIndex())).toString(), subaddress.getBalance().toString());
assertEquals((wallet.getUnlockedBalance(subaddress.getAccountIndex(), subaddress.getIndex())).toString(), subaddress.getUnlockedBalance().toString());
}
assertEquals((wallet.getBalance(account.getIndex())).toString(), subaddressesBalance.toString());
assertEquals((wallet.getUnlockedBalance(account.getIndex())).toString(), subaddressesUnlockedBalance.toString());
}
TestUtils.testUnsignedBigInteger(accountsBalance);
TestUtils.testUnsignedBigInteger(accountsUnlockedBalance);
assertEquals((wallet.getBalance()).toString(), accountsBalance.toString());
assertEquals((wallet.getUnlockedBalance()).toString(), accountsUnlockedBalance.toString());
}
// Can get accounts without subaddresses
@Test
public void testGetAccountsWithoutSubaddresses() {
assumeTrue(TEST_NON_RELAYS);
List<MoneroAccount> accounts = wallet.getAccounts();
assertFalse(accounts.isEmpty());
for (MoneroAccount account : accounts) {
testAccount(account);
assertNull(account.getSubaddresses());
}
}
// Can get accounts with subaddresses
@Test
public void testGetAccountsWithSubaddresses() {
assumeTrue(TEST_NON_RELAYS);
List<MoneroAccount> accounts = wallet.getAccounts(true);
assertFalse(accounts.isEmpty());
for (MoneroAccount account : accounts) {
testAccount(account);
assertFalse(account.getSubaddresses().isEmpty());
}
}
// Can get an account at a specified index
@Test
public void testGetAccount() {
assumeTrue(TEST_NON_RELAYS);
List<MoneroAccount> accounts = wallet.getAccounts();
assertFalse(accounts.isEmpty());
for (MoneroAccount account : accounts) {
testAccount(account);
// test without subaddresses
MoneroAccount retrieved = wallet.getAccount(account.getIndex());
assertNull(retrieved.getSubaddresses());
// test with subaddresses
retrieved = wallet.getAccount(account.getIndex(), true);
assertFalse(retrieved.getSubaddresses().isEmpty());
}
}
// Can create a new account without a label
@Test
public void testCreateAccountWithoutLabel() {
assumeTrue(TEST_NON_RELAYS);
List<MoneroAccount> accountsBefore = wallet.getAccounts();
MoneroAccount createdAccount = wallet.createAccount();
testAccount(createdAccount);
assertEquals(accountsBefore.size(), (wallet.getAccounts()).size() - 1);
}
// Can create a new account with a label
@Test
public void testCreateAccountWithLabel() {
assumeTrue(TEST_NON_RELAYS);
// create account with label
List<MoneroAccount> accountsBefore = wallet.getAccounts();
String label = UUID.randomUUID().toString();
MoneroAccount createdAccount = wallet.createAccount(label);
testAccount(createdAccount);
assertEquals(accountsBefore.size(), (wallet.getAccounts()).size() - 1);
assertEquals(label, wallet.getSubaddress(createdAccount.getIndex(), 0).getLabel());
// fetch and test account
createdAccount = wallet.getAccount(createdAccount.getIndex());
testAccount(createdAccount);
// create account with same label
createdAccount = wallet.createAccount(label);
testAccount(createdAccount);
assertEquals(accountsBefore.size(), (wallet.getAccounts()).size() - 2);
assertEquals(label, wallet.getSubaddress(createdAccount.getIndex(), 0).getLabel());
// fetch and test account
createdAccount = wallet.getAccount(createdAccount.getIndex());
testAccount(createdAccount);
}
// Can set account labels
@Test
public void testSetAccountLabel() {
// create account
if (wallet.getAccounts().size() < 2) wallet.createAccount();
// set account label
String label = GenUtils.getUUID();
wallet.setAccountLabel(1, label);
assertEquals(label, wallet.getSubaddress(1, 0).getLabel());
}
// Can get subaddresses at a specified account index
@Test
public void testGetSubaddresses() {
assumeTrue(TEST_NON_RELAYS);
List<MoneroAccount> accounts = wallet.getAccounts();
assertFalse(accounts.isEmpty());
for (MoneroAccount account : accounts) {
List<MoneroSubaddress> subaddresses = wallet.getSubaddresses(account.getIndex());
assertFalse(subaddresses.isEmpty());
for (MoneroSubaddress subaddress : subaddresses) {
testSubaddress(subaddress);
assertEquals(account.getIndex(), subaddress.getAccountIndex());
}
}
}
// Can get subaddresses at specified account and subaddress indices
@Test
public void testGetSubaddressesByIndices() {
assumeTrue(TEST_NON_RELAYS);
List<MoneroAccount> accounts = wallet.getAccounts();
assertFalse(accounts.isEmpty());
for (MoneroAccount account : accounts) {
// get subaddresses
List<MoneroSubaddress> subaddresses = wallet.getSubaddresses(account.getIndex());
assertTrue(subaddresses.size() > 0);
// remove a subaddress for query if possible
if (subaddresses.size() > 1) subaddresses.remove(0);
// get subaddress indices
List<Integer> subaddressIndices = new ArrayList<Integer>();
for (MoneroSubaddress subaddress : subaddresses) subaddressIndices.add(subaddress.getIndex());
assertTrue(subaddressIndices.size() > 0);