forked from woodser/monero-java
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestUtils.java
More file actions
Latest commit
374 lines (323 loc) · 16.8 KB
/
Copy pathTestUtils.java
File metadata and controls
374 lines (323 loc) · 16.8 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
packageutils;
importstaticorg.junit.jupiter.api.Assertions.assertEquals;
importstaticorg.junit.jupiter.api.Assertions.assertNotNull;
importstaticorg.junit.jupiter.api.Assertions.assertTrue;
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.math.BigInteger;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importjava.util.UUID;
importjava.util.logging.LogManager;
importjava.util.logging.Logger;
importmonero.common.MoneroError;
importmonero.common.MoneroRpcConnection;
importmonero.common.MoneroRpcError;
importmonero.common.MoneroUtils;
importmonero.daemon.MoneroDaemonRpc;
importmonero.daemon.model.MoneroNetworkType;
importmonero.wallet.MoneroWalletFull;
importmonero.wallet.MoneroWalletRpc;
importmonero.wallet.model.MoneroTxWallet;
importmonero.wallet.model.MoneroWalletConfig;
/**
* Test utilities and constants.
*/
publicclassTestUtils {
// c++ log configuration
publicstaticbooleanCPP_LOG_ENABLED = false;
publicstaticStringCPP_LOG_PATH = "log_java_tests.txt";
publicstaticintCPP_LOG_LEVEL = 1;
publicstaticbooleanCPP_LOG_CONSOLE = true;
static {
if (CPP_LOG_ENABLED) {
MoneroUtils.loadNativeLibrary();
MoneroUtils.configureNativeLogging(CPP_LOG_PATH, CPP_LOG_CONSOLE);
MoneroUtils.setLogLevel(CPP_LOG_LEVEL);
}
}
// directory with monero binaries to test (monerod and monero-wallet-rpc)
publicstaticfinalStringMONERO_BINS_DIR = "";
// monero daemon rpc endpoint configuration (change per your configuration)
publicstaticfinalStringDAEMON_RPC_URI = "localhost:28081";
publicstaticfinalStringDAEMON_RPC_USERNAME = "";
publicstaticfinalStringDAEMON_RPC_PASSWORD = "";
publicstaticfinalStringDAEMON_LOCAL_PATH = MONERO_BINS_DIR + "/monerod";
// monero wallet rpc configuration (change per your configuration)
publicstaticfinalintWALLET_RPC_PORT_START = 28084; // test wallet executables will bind to consecutive ports after these
publicstaticfinalbooleanWALLET_RPC_ZMQ_ENABLED = false;
publicstaticfinalintWALLET_RPC_ZMQ_PORT_START = 58083;
publicstaticfinalintWALLET_RPC_ZMQ_BIND_PORT_START = 48083; // TODO: zmq bind port necessary?
publicstaticfinalbooleanWALLET_RPC_PROXY_ENABLED = false;
publicstaticfinalStringWALLET_RPC_PROXY_URI = null;
publicstaticfinalStringWALLET_RPC_USERNAME = "rpc_user";
publicstaticfinalStringWALLET_RPC_PASSWORD = "abc123";
publicstaticfinalStringWALLET_RPC_ZMQ_DOMAIN = "127.0.0.1";
publicstaticfinalStringWALLET_RPC_DOMAIN = "localhost";
publicstaticfinalStringWALLET_RPC_URI = WALLET_RPC_DOMAIN + ":" + WALLET_RPC_PORT_START;
publicstaticfinalStringWALLET_RPC_ZMQ_URI = "tcp://" + WALLET_RPC_ZMQ_DOMAIN + ":" + WALLET_RPC_ZMQ_PORT_START;
publicstaticfinalStringWALLET_RPC_LOCAL_PATH = MONERO_BINS_DIR + "/monero-wallet-rpc";
publicstaticfinalStringWALLET_RPC_LOCAL_WALLET_DIR = MONERO_BINS_DIR;
publicstaticfinalStringWALLET_RPC_ACCESS_CONTROL_ORIGINS = "http://localhost:8080"; // cors access from web browser
// test wallet config
publicstaticfinalStringWALLET_NAME = "test_wallet_1";
publicstaticfinalStringWALLET_PASSWORD = "supersecretpassword123";
publicstaticfinalStringTEST_WALLETS_DIR = "./test_wallets";
publicstaticfinalStringWALLET_FULL_PATH = TEST_WALLETS_DIR + "/" + WALLET_NAME;
// test wallet constants
publicstaticfinalBigIntegerMAX_FEE = BigInteger.valueOf(7500000).multiply(BigInteger.valueOf(10000));
publicstaticfinalMoneroNetworkTypeNETWORK_TYPE = MoneroNetworkType.TESTNET;
publicstaticfinalStringLANGUAGE = "English";
publicstaticfinalStringSEED = "silk mocked cucumber lettuce hope adrenalin aching lush roles fuel revamp baptism wrist long tender teardrop midst pastry pigment equip frying inbound pinched ravine frying";
publicstaticfinalStringADDRESS = "A1y9sbVt8nqhZAVm3me1U18rUVXcjeNKuBd1oE2cTs8biA9cozPMeyYLhe77nPv12JA3ejJN3qprmREriit2fi6tJDi99RR";
publicstaticfinallongFIRST_RECEIVE_HEIGHT = 171; // NOTE: this value must be the height of the wallet's first tx for tests
publicstaticfinallongSYNC_PERIOD_IN_MS = 5000; // period between wallet syncs in milliseconds
publicstaticfinalStringOFFLINE_SERVER_URI = "offline_server_uri"; // dummy server uri to remain offline because wallet2 connects to default if not given
publicstaticfinallongAUTO_CONNECT_TIMEOUT_MS = 3000;
// logger configuration
publicstaticfinalLoggerLOGGER = Logger.getLogger(TestUtils.class.getName());
static {
try {
InputStreamis = TestUtils.class.getClassLoader().getResourceAsStream("logger.properties");
if (is != null) LogManager.getLogManager().readConfiguration(is);
} catch (IOExceptione) {
thrownewRuntimeException(e);
}
}
// used to track wallet txs for tests
publicstaticWalletTxTrackerWALLET_TX_TRACKER = newWalletTxTracker();
/**
* Get a singleton instance of a monerod client.
*/
privatestaticMoneroDaemonRpcdaemonRpc;
publicstaticMoneroDaemonRpcgetDaemonRpc() {
if (daemonRpc == null) {
MoneroRpcConnectionrpc = newMoneroRpcConnection(DAEMON_RPC_URI, DAEMON_RPC_USERNAME, DAEMON_RPC_PASSWORD);
daemonRpc = newMoneroDaemonRpc(rpc);
}
returndaemonRpc;
}
/**
* Get a singleton instance of a monero-wallet-rpc client.
*/
privatestaticMoneroWalletRpcwalletRpc;
publicstaticMoneroWalletRpcgetWalletRpc() {
if (walletRpc == null) {
// construct wallet rpc instance with daemon connection
MoneroRpcConnectionrpc = newMoneroRpcConnection(WALLET_RPC_URI, WALLET_RPC_USERNAME, WALLET_RPC_PASSWORD, WALLET_RPC_ZMQ_ENABLED ? WALLET_RPC_ZMQ_URI : null, WALLET_RPC_PROXY_ENABLED ? WALLET_RPC_PROXY_URI : null);
walletRpc = newMoneroWalletRpc(rpc);
}
// attempt to open test wallet
try {
walletRpc.openWallet(WALLET_NAME, WALLET_PASSWORD);
} catch (MoneroRpcErrore) {
// -1 returned when wallet does not exist or fails to open e.g. it's already open by another application
if (e.getCode() == -1) {
// create wallet
walletRpc.createWallet(newMoneroWalletConfig().setPath(WALLET_NAME).setPassword(WALLET_PASSWORD).setSeed(SEED).setRestoreHeight(FIRST_RECEIVE_HEIGHT));
} else {
throwe;
}
}
// ensure we're testing the right wallet
assertEquals(TestUtils.SEED, walletRpc.getSeed());
assertEquals(TestUtils.ADDRESS, walletRpc.getPrimaryAddress());
// sync and save wallet
walletRpc.sync();
walletRpc.save();
walletRpc.startSyncing(TestUtils.SYNC_PERIOD_IN_MS);
// return cached wallet rpc
returnwalletRpc;
}
publicstaticMoneroWalletRpcopenWalletRpc(MoneroWalletConfigconfig) {
// assign defaults
if (config == null) config = newMoneroWalletConfig();
if (config.getPassword() == null) config.setPassword(TestUtils.WALLET_PASSWORD);
if (config.getServer() == null && config.getConnectionManager() == null) config.setServer(TestUtils.getDaemonRpc().getRpcConnection());
// create client connected to internal monero-wallet-rpc process
MoneroWalletRpcwallet = TestUtils.startWalletRpcProcess(config.getServerUri(), config.getServerUsername(), config.getServerPassword());
// open wallet
try {
wallet.stopSyncing();
wallet.openWallet(config);
wallet.setDaemonConnection(wallet.getDaemonConnection(), true, null); // set daemon as trusted
if (wallet.isConnectedToDaemon()) wallet.startSyncing(TestUtils.SYNC_PERIOD_IN_MS);
returnwallet;
} catch (MoneroErrore) {
try { TestUtils.stopWalletRpcProcess(wallet); } catch (Exceptione2) { thrownewRuntimeException(e2); }
throwe;
}
}
publicstaticMoneroWalletRpccreateWalletRpc(MoneroWalletConfigconfig) {
// assign defaults
if (config == null) config = newMoneroWalletConfig();
booleanrandom = config.getSeed() == null && config.getPrimaryAddress() == null;
if (config.getPath() == null) config.setPath(UUID.randomUUID().toString());
if (config.getPassword() == null) config.setPassword(TestUtils.WALLET_PASSWORD);
if (config.getRestoreHeight() == null && !random) config.setRestoreHeight(0l);
if (config.getServer() == null && config.getConnectionManager() == null) config.setServer(TestUtils.getDaemonRpc().getRpcConnection());
// create client connected to internal monero-wallet-rpc process
MoneroWalletRpcwallet = TestUtils.startWalletRpcProcess(config.getServerUri(), config.getServerUsername(), config.getServerPassword());
// create wallet
try {
wallet.stopSyncing();
wallet.createWallet(config);
wallet.setDaemonConnection(wallet.getDaemonConnection(), true, null); // set daemon as trusted
if (wallet.isConnectedToDaemon()) wallet.startSyncing(TestUtils.SYNC_PERIOD_IN_MS);
returnwallet;
} catch (MoneroErrore) {
try { TestUtils.stopWalletRpcProcess(wallet); } catch (Exceptione2) { thrownewRuntimeException(e2); }
throwe;
}
}
/**
* Start a monero-wallet-rpc process bound to the next available port.
*/
publicstaticMap<MoneroWalletRpc, Integer> WALLET_PORT_OFFSETS = newHashMap<MoneroWalletRpc, Integer>();
publicstaticMoneroWalletRpcstartWalletRpcProcess() { returnTestUtils.startWalletRpcProcess(null, null, null); }
publicstaticMoneroWalletRpcstartWalletRpcProcess(StringdaemonUri, StringdaemonUsername, StringdaemonPassword) {
// get next available offset of ports to bind to
intportOffset = 1;
while (WALLET_PORT_OFFSETS.values().contains(portOffset)) portOffset++;
// create command to start client with internal monero-wallet-rpc process
List<String> cmd = newArrayList<String>(Arrays.asList(
TestUtils.WALLET_RPC_LOCAL_PATH,
"--" + TestUtils.NETWORK_TYPE.toString().toLowerCase(),
"--rpc-bind-port", "" + (TestUtils.WALLET_RPC_PORT_START + portOffset),
"--rpc-login", TestUtils.WALLET_RPC_USERNAME + ":" + TestUtils.WALLET_RPC_PASSWORD,
"--wallet-dir", TestUtils.WALLET_RPC_LOCAL_WALLET_DIR,
"--rpc-access-control-origins", TestUtils.WALLET_RPC_ACCESS_CONTROL_ORIGINS));
booleanoffline = TestUtils.OFFLINE_SERVER_URI.equals(daemonUri);
if (offline) cmd.add("--offline");
elseif (daemonUri != null && !daemonUri.isEmpty()) {
cmd.addAll(Arrays.asList("--daemon-address", daemonUri));
if (daemonUsername != null && !daemonUsername.equals("")) cmd.addAll(Arrays.asList("--daemon-login", daemonUsername + ":" + daemonPassword));
}
// start with zmq if enabled
if (WALLET_RPC_ZMQ_ENABLED) {
cmd.addAll(Arrays.asList("--zmq-rpc-bind-port", "" + (TestUtils.WALLET_RPC_ZMQ_BIND_PORT_START + portOffset)));
cmd.addAll(Arrays.asList("--zmq-pub", "tcp://" + WALLET_RPC_ZMQ_DOMAIN + ":" + (TestUtils.WALLET_RPC_ZMQ_PORT_START + portOffset)));
} else {
//cmd.add("--no-zmq"); // TODO: enable this when zmq supported in monero-wallet-rpc
}
// register wallet with port offset
try {
MoneroWalletRpcwallet = newMoneroWalletRpc(cmd);
WALLET_PORT_OFFSETS.put(wallet, portOffset);
returnwallet;
} catch (Exceptione) {
thrownewRuntimeException(e);
}
}
/**
* Stop a monero-wallet-rpc process and release its associated port.
*
* @param walletRpc - wallet created with internal monero-wallet-rpc process
*/
publicstaticvoidstopWalletRpcProcess(MoneroWalletRpcwalletRpc) {
WALLET_PORT_OFFSETS.remove(walletRpc);
walletRpc.stopProcess();
}
/**
* Get a singleton instance of a wallet supported by JNI bindings to monero-project's wallet2.
*/
privatestaticMoneroWalletFullwalletFull;
publicstaticMoneroWalletFullgetWalletFull() {
if (walletFull == null || walletFull.isClosed()) {
// create wallet from seed if it doesn't exist
if (!MoneroWalletFull.walletExists(WALLET_FULL_PATH)) {
// create directory for test wallets if it doesn't exist
FiletestWalletsDir = newFile(TestUtils.TEST_WALLETS_DIR);
if (!testWalletsDir.exists()) testWalletsDir.mkdirs();
// create wallet with connection
MoneroRpcConnectiondaemonConnection = newMoneroRpcConnection(DAEMON_RPC_URI, DAEMON_RPC_USERNAME, DAEMON_RPC_PASSWORD);
walletFull = MoneroWalletFull.createWallet(newMoneroWalletConfig().setPath(TestUtils.WALLET_FULL_PATH).setPassword(TestUtils.WALLET_PASSWORD).setNetworkType(NETWORK_TYPE).setSeed(TestUtils.SEED).setServer(daemonConnection).setRestoreHeight(FIRST_RECEIVE_HEIGHT));
assertEquals(TestUtils.FIRST_RECEIVE_HEIGHT, walletFull.getRestoreHeight());
assertEquals(daemonConnection, walletFull.getDaemonConnection());
}
// otherwise open existing wallet and update daemon connection
else {
walletFull = MoneroWalletFull.openWallet(WALLET_FULL_PATH, WALLET_PASSWORD, TestUtils.NETWORK_TYPE);
walletFull.setDaemonConnection(TestUtils.getDaemonRpc().getRpcConnection());
}
// sync and save wallet
walletFull.sync(newWalletSyncPrinter());
walletFull.save();
walletFull.startSyncing(TestUtils.SYNC_PERIOD_IN_MS); // start background synchronizing with sync period
}
// ensure we're testing the right wallet
assertEquals(TestUtils.SEED, walletFull.getSeed());
assertEquals(TestUtils.ADDRESS, walletFull.getPrimaryAddress());
returnwalletFull;
}
/**
* Creates a new wallet considered to be "ground truth".
*
* @param networkType is the ground truth wallet's network type
* @param seed is the ground truth wallet's seed
* @param startHeight is the height to start syncing from
* @param restoreHeight is the ground truth wallet's restore height
* @return the created wallet
*/
publicstaticMoneroWalletFullcreateWalletGroundTruth(MoneroNetworkTypenetworkType, Stringseed, LongstartHeight, LongrestoreHeight) {
// create directory for test wallets if it doesn't exist
FiletestWalletsDir = newFile(TestUtils.TEST_WALLETS_DIR);
if (!testWalletsDir.exists()) testWalletsDir.mkdirs();
// create ground truth wallet
MoneroRpcConnectiondaemonConnection = newMoneroRpcConnection(DAEMON_RPC_URI, DAEMON_RPC_USERNAME, DAEMON_RPC_PASSWORD);
Stringpath = TestUtils.TEST_WALLETS_DIR + "/gt_wallet_" + System.currentTimeMillis();
MoneroWalletFullgtWallet = MoneroWalletFull.createWallet(newMoneroWalletConfig().setPath(path).setPassword(TestUtils.WALLET_PASSWORD).setNetworkType(networkType).setSeed(seed).setServer(daemonConnection).setRestoreHeight(restoreHeight));
assertEquals(restoreHeight == null ? 0 : (long) restoreHeight, gtWallet.getRestoreHeight());
gtWallet.sync(startHeight, newWalletSyncPrinter());
gtWallet.startSyncing(TestUtils.SYNC_PERIOD_IN_MS);
// close the full wallet when the runtime is shutting down to release resources
Runtime.getRuntime().addShutdownHook(newThread() {
@Override
publicvoidrun() {
gtWallet.close();
}
});
returngtWallet;
}
publicstaticvoidtestUnsignedBigInteger(BigIntegernum) {
testUnsignedBigInteger(num, null);
}
publicstaticvoidtestUnsignedBigInteger(BigIntegernum, BooleannonZero) {
assertNotNull(num);
intcomparison = num.compareTo(BigInteger.valueOf(0));
assertTrue(comparison >= 0);
if (Boolean.TRUE.equals(nonZero)) assertTrue(comparison > 0);
if (Boolean.FALSE.equals(nonZero)) assertTrue(comparison == 0);
}
// TODO: switch to local wallet (like js version) if/when it can generate addresses
publicstaticStringgetExternalWalletAddress() {
MoneroNetworkTypenetworkType = getDaemonRpc().getInfo().getNetworkType();
switch (networkType) {
caseSTAGENET:
return"78Zq71rS1qK4CnGt8utvMdWhVNMJexGVEDM2XsSkBaGV9bDSnRFFhWrQTbmCACqzevE8vth9qhWfQ9SUENXXbLnmMVnBwgW"; // subaddress
caseTESTNET:
return"BhsbVvqW4Wajf4a76QW3hA2B3easR5QdNE5L8NwkY7RWXCrfSuaUwj1DDUsk3XiRGHBqqsK3NPvsATwcmNNPUQQ4SRR2b3V"; // subaddress
caseMAINNET:
return"87a1Yf47UqyQFCrMqqtxfvhJN9se3PgbmU7KUFWqhSu5aih6YsZYoxfjgyxAM1DztNNSdoYTZYn9xa3vHeJjoZqdAybnLzN"; // subaddress
default:
thrownewRuntimeException("Invalid network type: " + networkType);
}
}
publicstaticbooleantxsMergeable(MoneroTxWallettx1, MoneroTxWallettx2) {
try {
MoneroTxWalletcopy1 = tx1.copy();
MoneroTxWalletcopy2 = tx2.copy();
if (copy1.isConfirmed()) copy1.setBlock(tx1.getBlock().copy().setTxs(Arrays.asList(copy1)));
if (copy2.isConfirmed()) copy2.setBlock(tx2.getBlock().copy().setTxs(Arrays.asList(copy2)));
copy1.merge(copy2);
returntrue;
} catch (Exception | AssertionErrore) {
e.printStackTrace();
returnfalse;
}
}
}