1 // Copyright (c) 2013-2014 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include "wallet/wallet.h"
12 #include "test/test_bitcoin.h"
14 #include "zcash/Address.hpp"
16 #include "rpcserver.h"
17 #include "asyncrpcqueue.h"
18 #include "asyncrpcoperation.h"
19 #include "wallet/asyncrpcoperation_sendmany.h"
20 #include "rpcprotocol.h"
27 #include <unordered_set>
29 #include <boost/algorithm/string.hpp>
30 #include <boost/test/unit_test.hpp>
31 #include <boost/format.hpp>
32 #include <boost/filesystem.hpp>
38 extern UniValue createArgs(int nRequired, const char* address1 = NULL, const char* address2 = NULL);
39 extern UniValue CallRPC(string args);
41 extern CWallet* pwalletMain;
43 bool find_error(const UniValue& objError, const std::string& expected) {
44 return find_value(objError, "message").get_str().find(expected) != string::npos;
47 BOOST_FIXTURE_TEST_SUITE(rpc_wallet_tests, TestingSetup)
49 BOOST_AUTO_TEST_CASE(rpc_addmultisig)
51 LOCK(pwalletMain->cs_wallet);
53 rpcfn_type addmultisig = tableRPC["addmultisigaddress"]->actor;
56 const char address1Hex[] = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8";
58 const char address2Hex[] = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4";
61 CBitcoinAddress address;
62 BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false));
63 address.SetString(v.get_str());
64 BOOST_CHECK(address.IsValid() && address.IsScript());
66 BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false));
67 address.SetString(v.get_str());
68 BOOST_CHECK(address.IsValid() && address.IsScript());
70 BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false));
71 address.SetString(v.get_str());
72 BOOST_CHECK(address.IsValid() && address.IsScript());
74 BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error);
75 BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error);
76 BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error);
78 BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error);
79 BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error);
81 string short1(address1Hex, address1Hex + sizeof(address1Hex) - 2); // last byte missing
82 BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error);
84 string short2(address1Hex + 1, address1Hex + sizeof(address1Hex)); // first byte missing
85 BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error);
88 BOOST_AUTO_TEST_CASE(rpc_wallet)
90 // Test RPC calls for various wallet statistics
93 LOCK2(cs_main, pwalletMain->cs_wallet);
95 CPubKey demoPubkey = pwalletMain->GenerateNewKey();
96 CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID()));
98 string strAccount = "";
99 string strPurpose = "receive";
100 BOOST_CHECK_NO_THROW({ /*Initialize Wallet with an account */
101 CWalletDB walletdb(pwalletMain->strWalletFile);
103 account.vchPubKey = demoPubkey;
104 pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, strPurpose);
105 walletdb.WriteAccount(strAccount, account);
108 CPubKey setaccountDemoPubkey = pwalletMain->GenerateNewKey();
109 CBitcoinAddress setaccountDemoAddress = CBitcoinAddress(CTxDestination(setaccountDemoPubkey.GetID()));
111 /*********************************
113 *********************************/
114 BOOST_CHECK_NO_THROW(CallRPC("setaccount " + setaccountDemoAddress.ToString() + " \"\""));
115 /* Accounts are disabled */
116 BOOST_CHECK_THROW(CallRPC("setaccount " + setaccountDemoAddress.ToString() + " nullaccount"), runtime_error);
117 /* t1VtArtnn1dGPiD2WFfMXYXW5mHM3q1GpgV is not owned by the test wallet. */
118 BOOST_CHECK_THROW(CallRPC("setaccount t1VtArtnn1dGPiD2WFfMXYXW5mHM3q1GpgV nullaccount"), runtime_error);
119 BOOST_CHECK_THROW(CallRPC("setaccount"), runtime_error);
120 /* t1VtArtnn1dGPiD2WFfMXYXW5mHM3q1Gpg (34 chars) is an illegal address (should be 35 chars) */
121 BOOST_CHECK_THROW(CallRPC("setaccount t1VtArtnn1dGPiD2WFfMXYXW5mHM3q1Gpg nullaccount"), runtime_error);
124 /*********************************
126 *********************************/
127 BOOST_CHECK_NO_THROW(CallRPC("getbalance"));
128 BOOST_CHECK_THROW(CallRPC("getbalance " + demoAddress.ToString()), runtime_error);
130 /*********************************
132 *********************************/
133 BOOST_CHECK_NO_THROW(CallRPC("listunspent"));
134 BOOST_CHECK_THROW(CallRPC("listunspent string"), runtime_error);
135 BOOST_CHECK_THROW(CallRPC("listunspent 0 string"), runtime_error);
136 BOOST_CHECK_THROW(CallRPC("listunspent 0 1 not_array"), runtime_error);
137 BOOST_CHECK_THROW(CallRPC("listunspent 0 1 [] extra"), runtime_error);
138 BOOST_CHECK_NO_THROW(r = CallRPC("listunspent 0 1 []"));
139 BOOST_CHECK(r.get_array().empty());
141 /*********************************
142 * listreceivedbyaddress
143 *********************************/
144 BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress"));
145 BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0"));
146 BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress not_int"), runtime_error);
147 BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 not_bool"), runtime_error);
148 BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0 true"));
149 BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 true extra"), runtime_error);
151 /*********************************
152 * listreceivedbyaccount
153 *********************************/
154 BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount"));
155 BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0"));
156 BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount not_int"), runtime_error);
157 BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 not_bool"), runtime_error);
158 BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0 true"));
159 BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 true extra"), runtime_error);
161 /*********************************
163 *********************************/
164 BOOST_CHECK_NO_THROW(CallRPC("listsinceblock"));
166 /*********************************
168 *********************************/
169 BOOST_CHECK_NO_THROW(CallRPC("listtransactions"));
170 BOOST_CHECK_NO_THROW(CallRPC("listtransactions " + demoAddress.ToString()));
171 BOOST_CHECK_NO_THROW(CallRPC("listtransactions " + demoAddress.ToString() + " 20"));
172 BOOST_CHECK_NO_THROW(CallRPC("listtransactions " + demoAddress.ToString() + " 20 0"));
173 BOOST_CHECK_THROW(CallRPC("listtransactions " + demoAddress.ToString() + " not_int"), runtime_error);
175 /*********************************
177 *********************************/
178 BOOST_CHECK_NO_THROW(CallRPC("listlockunspent"));
180 /*********************************
182 *********************************/
183 BOOST_CHECK_NO_THROW(CallRPC("listaccounts"));
185 /*********************************
186 * listaddressgroupings
187 *********************************/
188 BOOST_CHECK_NO_THROW(CallRPC("listaddressgroupings"));
190 /*********************************
191 * getrawchangeaddress
192 *********************************/
193 BOOST_CHECK_NO_THROW(CallRPC("getrawchangeaddress"));
195 /*********************************
197 *********************************/
198 BOOST_CHECK_NO_THROW(CallRPC("getnewaddress"));
199 BOOST_CHECK_NO_THROW(CallRPC("getnewaddress \"\""));
200 /* Accounts are deprecated */
201 BOOST_CHECK_THROW(CallRPC("getnewaddress getnewaddress_demoaccount"), runtime_error);
203 /*********************************
205 *********************************/
206 BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress \"\""));
207 /* Accounts are deprecated */
208 BOOST_CHECK_THROW(CallRPC("getaccountaddress accountThatDoesntExists"), runtime_error);
209 BOOST_CHECK_NO_THROW(retValue = CallRPC("getaccountaddress " + strAccount));
210 BOOST_CHECK(CBitcoinAddress(retValue.get_str()).Get() == demoAddress.Get());
212 /*********************************
214 *********************************/
215 BOOST_CHECK_THROW(CallRPC("getaccount"), runtime_error);
216 BOOST_CHECK_NO_THROW(CallRPC("getaccount " + demoAddress.ToString()));
218 /*********************************
219 * signmessage + verifymessage
220 *********************************/
221 BOOST_CHECK_NO_THROW(retValue = CallRPC("signmessage " + demoAddress.ToString() + " mymessage"));
222 BOOST_CHECK_THROW(CallRPC("signmessage"), runtime_error);
223 /* Should throw error because this address is not loaded in the wallet */
224 BOOST_CHECK_THROW(CallRPC("signmessage t1h8SqgtM3QM5e2M8EzhhT1yL2PXXtA6oqe mymessage"), runtime_error);
226 /* missing arguments */
227 BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString()), runtime_error);
228 BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str()), runtime_error);
229 /* Illegal address */
230 BOOST_CHECK_THROW(CallRPC("verifymessage t1VtArtnn1dGPiD2WFfMXYXW5mHM3q1Gpg " + retValue.get_str() + " mymessage"), runtime_error);
232 BOOST_CHECK(CallRPC("verifymessage t1VtArtnn1dGPiD2WFfMXYXW5mHM3q1GpgV " + retValue.get_str() + " mymessage").get_bool() == false);
233 /* Correct address and signature but wrong message */
234 BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " wrongmessage").get_bool() == false);
235 /* Correct address, message and signature*/
236 BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true);
238 /*********************************
239 * getaddressesbyaccount
240 *********************************/
241 BOOST_CHECK_THROW(CallRPC("getaddressesbyaccount"), runtime_error);
242 BOOST_CHECK_NO_THROW(retValue = CallRPC("getaddressesbyaccount " + strAccount));
243 UniValue arr = retValue.get_array();
244 BOOST_CHECK_EQUAL(4, arr.size());
245 bool notFound = true;
246 for (auto a : arr.getValues()) {
247 notFound &= CBitcoinAddress(a.get_str()).Get() != demoAddress.Get();
249 BOOST_CHECK(!notFound);
254 BOOST_CHECK_THROW(CallRPC("getblocksubsidy too many args"), runtime_error);
255 BOOST_CHECK_THROW(CallRPC("getblocksubsidy -1"), runtime_error);
256 BOOST_CHECK_NO_THROW(retValue = CallRPC("getblocksubsidy 50000"));
257 UniValue obj = retValue.get_obj();
258 BOOST_CHECK_EQUAL(find_value(obj, "miner").get_real(), 10.0);
259 BOOST_CHECK_EQUAL(find_value(obj, "founders").get_real(), 2.5);
260 BOOST_CHECK_NO_THROW(retValue = CallRPC("getblocksubsidy 1000000"));
261 obj = retValue.get_obj();
262 BOOST_CHECK_EQUAL(find_value(obj, "miner").get_real(), 6.25);
263 BOOST_CHECK_EQUAL(find_value(obj, "founders").get_real(), 0.0);
264 BOOST_CHECK_NO_THROW(retValue = CallRPC("getblocksubsidy 2000000"));
265 obj = retValue.get_obj();
266 BOOST_CHECK_EQUAL(find_value(obj, "miner").get_real(), 3.125);
267 BOOST_CHECK_EQUAL(find_value(obj, "founders").get_real(), 0.0);
270 BOOST_AUTO_TEST_CASE(rpc_wallet_getbalance)
272 SelectParams(CBaseChainParams::TESTNET);
274 LOCK(pwalletMain->cs_wallet);
277 BOOST_CHECK_THROW(CallRPC("z_getbalance too many args"), runtime_error);
278 BOOST_CHECK_THROW(CallRPC("z_getbalance invalidaddress"), runtime_error);
279 BOOST_CHECK_NO_THROW(CallRPC("z_getbalance tmC6YZnCUhm19dEXxh3Jb7srdBJxDawaCab"));
280 BOOST_CHECK_THROW(CallRPC("z_getbalance tmC6YZnCUhm19dEXxh3Jb7srdBJxDawaCab -1"), runtime_error);
281 BOOST_CHECK_NO_THROW(CallRPC("z_getbalance tmC6YZnCUhm19dEXxh3Jb7srdBJxDawaCab 0"));
282 BOOST_CHECK_THROW(CallRPC("z_getbalance tnRZ8bPq2pff3xBWhTJhNkVUkm2uhzksDeW5PvEa7aFKGT9Qi3YgTALZfjaY4jU3HLVKBtHdSXxoPoLA3naMPcHBcY88FcF 1"), runtime_error);
285 BOOST_CHECK_THROW(CallRPC("z_gettotalbalance too manyargs"), runtime_error);
286 BOOST_CHECK_THROW(CallRPC("z_gettotalbalance -1"), runtime_error);
287 BOOST_CHECK_NO_THROW(CallRPC("z_gettotalbalance 0"));
290 BOOST_CHECK_THROW(CallRPC("z_listreceivedbyaddress too many args"), runtime_error);
291 // negative minconf not allowed
292 BOOST_CHECK_THROW(CallRPC("z_listreceivedbyaddress tmC6YZnCUhm19dEXxh3Jb7srdBJxDawaCab -1"), runtime_error);
293 // invalid zaddr, taddr not allowed
294 BOOST_CHECK_THROW(CallRPC("z_listreceivedbyaddress tmC6YZnCUhm19dEXxh3Jb7srdBJxDawaCab 0"), runtime_error);
295 // don't have the spending key
296 BOOST_CHECK_THROW(CallRPC("z_listreceivedbyaddress tnRZ8bPq2pff3xBWhTJhNkVUkm2uhzksDeW5PvEa7aFKGT9Qi3YgTALZfjaY4jU3HLVKBtHdSXxoPoLA3naMPcHBcY88FcF 1"), runtime_error);
300 * This test covers RPC command z_validateaddress
302 BOOST_AUTO_TEST_CASE(rpc_wallet_z_validateaddress)
304 SelectParams(CBaseChainParams::MAIN);
306 LOCK2(cs_main, pwalletMain->cs_wallet);
310 // Check number of args
311 BOOST_CHECK_THROW(CallRPC("z_validateaddress"), runtime_error);
312 BOOST_CHECK_THROW(CallRPC("z_validateaddress toomany args"), runtime_error);
314 // Wallet should be empty
315 std::set<libzcash::PaymentAddress> addrs;
316 pwalletMain->GetPaymentAddresses(addrs);
317 BOOST_CHECK(addrs.size()==0);
319 // This address is not valid, it belongs to another network
320 BOOST_CHECK_NO_THROW(retValue = CallRPC("z_validateaddress ztaaga95QAPyp1kSQ1hD2kguCpzyMHjxWZqaYDEkzbvo7uYQYAw2S8X4Kx98AvhhofMtQL8PAXKHuZsmhRcanavKRKmdCzk"));
321 UniValue resultObj = retValue.get_obj();
322 bool b = find_value(resultObj, "isvalid").get_bool();
323 BOOST_CHECK_EQUAL(b, false);
325 // This address is valid, but the spending key is not in this wallet
326 BOOST_CHECK_NO_THROW(retValue = CallRPC("z_validateaddress zcfA19SDAKRYHLoRDoShcoz4nPohqWxuHcqg8WAxsiB2jFrrs6k7oSvst3UZvMYqpMNSRBkxBsnyjjngX5L55FxMzLKach8"));
327 resultObj = retValue.get_obj();
328 b = find_value(resultObj, "isvalid").get_bool();
329 BOOST_CHECK_EQUAL(b, true);
330 b = find_value(resultObj, "ismine").get_bool();
331 BOOST_CHECK_EQUAL(b, false);
333 // Let's import a spending key to the wallet and validate its payment address
334 BOOST_CHECK_NO_THROW(CallRPC("z_importkey SKxoWv77WGwFnUJitQKNEcD636bL4X5Gd6wWmgaA4Q9x8jZBPJXT"));
335 BOOST_CHECK_NO_THROW(retValue = CallRPC("z_validateaddress zcWsmqT4X2V4jgxbgiCzyrAfRT1vi1F4sn7M5Pkh66izzw8Uk7LBGAH3DtcSMJeUb2pi3W4SQF8LMKkU2cUuVP68yAGcomL"));
336 resultObj = retValue.get_obj();
337 b = find_value(resultObj, "isvalid").get_bool();
338 BOOST_CHECK_EQUAL(b, true);
339 b = find_value(resultObj, "ismine").get_bool();
340 BOOST_CHECK_EQUAL(b, true);
341 BOOST_CHECK_EQUAL(find_value(resultObj, "payingkey").get_str(), "f5bb3c888ccc9831e3f6ba06e7528e26a312eec3acc1823be8918b6a3a5e20ad");
342 BOOST_CHECK_EQUAL(find_value(resultObj, "transmissionkey").get_str(), "7a58c7132446564e6b810cf895c20537b3528357dc00150a8e201f491efa9c1a");
346 * This test covers RPC command z_exportwallet
348 BOOST_AUTO_TEST_CASE(rpc_wallet_z_exportwallet)
350 LOCK2(cs_main, pwalletMain->cs_wallet);
352 // wallet should be empty
353 std::set<libzcash::PaymentAddress> addrs;
354 pwalletMain->GetPaymentAddresses(addrs);
355 BOOST_CHECK(addrs.size()==0);
357 // wallet should have one key
358 CZCPaymentAddress paymentAddress = pwalletMain->GenerateNewZKey();
359 pwalletMain->GetPaymentAddresses(addrs);
360 BOOST_CHECK(addrs.size()==1);
363 boost::filesystem::path tmppath = boost::filesystem::temp_directory_path();
364 boost::filesystem::path tmpfilename = boost::filesystem::unique_path("%%%%%%%%");
365 boost::filesystem::path exportfilepath = tmppath / tmpfilename;
367 // export will fail since exportdir is not set
368 BOOST_CHECK_THROW(CallRPC(string("z_exportwallet ") + tmpfilename.string()), runtime_error);
371 mapArgs["-exportdir"] = tmppath.native();
374 BOOST_CHECK_THROW(CallRPC("z_exportwallet"), runtime_error);
376 BOOST_CHECK_THROW(CallRPC("z_exportwallet toomany args"), runtime_error);
378 BOOST_CHECK_THROW(CallRPC(string("z_exportwallet invalid!*/_chars.txt")), runtime_error);
380 BOOST_CHECK_NO_THROW(CallRPC(string("z_exportwallet ") + tmpfilename.string()));
383 auto addr = paymentAddress.Get();
384 libzcash::SpendingKey key;
385 BOOST_CHECK(pwalletMain->GetSpendingKey(addr, key));
387 std::string s1 = paymentAddress.ToString();
388 std::string s2 = CZCSpendingKey(key).ToString();
390 // There's no way to really delete a private key so we will read in the
391 // exported wallet file and search for the spending key and payment address.
393 EnsureWalletIsUnlocked();
396 file.open(exportfilepath.string().c_str(), std::ios::in | std::ios::ate);
397 BOOST_CHECK(file.is_open());
398 bool fVerified = false;
399 int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());
400 file.seekg(0, file.beg);
401 while (file.good()) {
403 std::getline(file, line);
404 if (line.empty() || line[0] == '#')
406 if (line.find(s1) != std::string::npos && line.find(s2) != std::string::npos) {
411 BOOST_CHECK(fVerified);
416 * This test covers RPC command z_importwallet
418 BOOST_AUTO_TEST_CASE(rpc_wallet_z_importwallet)
420 LOCK2(cs_main, pwalletMain->cs_wallet);
423 BOOST_CHECK_THROW(CallRPC("z_importwallet"), runtime_error);
425 // error if too many args
426 BOOST_CHECK_THROW(CallRPC("z_importwallet toomany args"), runtime_error);
428 // create a random key locally
429 auto testSpendingKey = libzcash::SpendingKey::random();
430 auto testPaymentAddress = testSpendingKey.address();
431 std::string testAddr = CZCPaymentAddress(testPaymentAddress).ToString();
432 std::string testKey = CZCSpendingKey(testSpendingKey).ToString();
434 // create test data using the random key
435 std::string format_str = "# Wallet dump created by Zcash v0.11.2.0.z8-9155cc6-dirty (2016-08-11 11:37:00 -0700)\n"
436 "# * Created on 2016-08-12T21:55:36Z\n"
437 "# * Best block at time of backup was 0 (0de0a3851fef2d433b9b4f51d4342bdd24c5ddd793eb8fba57189f07e9235d52),\n"
438 "# mined on 2009-01-03T18:15:05Z\n"
442 "%s 2016-08-12T21:55:36Z # zaddr=%s\n"
446 boost::format formatobject(format_str);
447 std::string testWalletDump = (formatobject % testKey % testAddr).str();
449 // write test data to file
450 boost::filesystem::path temp = boost::filesystem::temp_directory_path() /
451 boost::filesystem::unique_path();
452 const std::string path = temp.native();
453 std::ofstream file(path);
454 file << testWalletDump;
457 // wallet should currently be empty
458 std::set<libzcash::PaymentAddress> addrs;
459 pwalletMain->GetPaymentAddresses(addrs);
460 BOOST_CHECK(addrs.size()==0);
462 // import test data from file into wallet
463 BOOST_CHECK_NO_THROW(CallRPC(string("z_importwallet ") + path));
465 // wallet should now have one zkey
466 pwalletMain->GetPaymentAddresses(addrs);
467 BOOST_CHECK(addrs.size()==1);
469 // check that we have the spending key for the address
470 CZCPaymentAddress address(testAddr);
471 auto addr = address.Get();
472 BOOST_CHECK(pwalletMain->HaveSpendingKey(addr));
474 // Verify the spending key is the same as the test data
475 libzcash::SpendingKey k;
476 BOOST_CHECK(pwalletMain->GetSpendingKey(addr, k));
477 CZCSpendingKey spendingkey(k);
478 BOOST_CHECK_EQUAL(testKey, spendingkey.ToString());
483 * This test covers RPC commands z_listaddresses, z_importkey, z_exportkey
485 BOOST_AUTO_TEST_CASE(rpc_wallet_z_importexport)
487 LOCK2(cs_main, pwalletMain->cs_wallet);
489 int n1 = 1000; // number of times to import/export
490 int n2 = 1000; // number of addresses to create and list
493 BOOST_CHECK_THROW(CallRPC("z_importkey"), runtime_error);
494 BOOST_CHECK_THROW(CallRPC("z_exportkey"), runtime_error);
496 // error if too many args
497 BOOST_CHECK_THROW(CallRPC("z_importkey too many args"), runtime_error);
498 BOOST_CHECK_THROW(CallRPC("z_exportkey toomany args"), runtime_error);
500 // wallet should currently be empty
501 std::set<libzcash::PaymentAddress> addrs;
502 pwalletMain->GetPaymentAddresses(addrs);
503 BOOST_CHECK(addrs.size()==0);
505 // verify import and export key
506 for (int i = 0; i < n1; i++) {
507 // create a random key locally
508 auto testSpendingKey = libzcash::SpendingKey::random();
509 auto testPaymentAddress = testSpendingKey.address();
510 std::string testAddr = CZCPaymentAddress(testPaymentAddress).ToString();
511 std::string testKey = CZCSpendingKey(testSpendingKey).ToString();
512 BOOST_CHECK_NO_THROW(CallRPC(string("z_importkey ") + testKey));
513 BOOST_CHECK_NO_THROW(retValue = CallRPC(string("z_exportkey ") + testAddr));
514 BOOST_CHECK_EQUAL(retValue.get_str(), testKey);
517 // Verify we can list the keys imported
518 BOOST_CHECK_NO_THROW(retValue = CallRPC("z_listaddresses"));
519 UniValue arr = retValue.get_array();
520 BOOST_CHECK(arr.size() == n1);
522 // Put addresses into a set
523 std::unordered_set<std::string> myaddrs;
524 for (UniValue element : arr.getValues()) {
525 myaddrs.insert(element.get_str());
528 // Make new addresses for the set
529 for (int i=0; i<n2; i++) {
530 myaddrs.insert((pwalletMain->GenerateNewZKey()).ToString());
533 // Verify number of addresses stored in wallet is n1+n2
534 int numAddrs = myaddrs.size();
535 BOOST_CHECK(numAddrs == n1+n2);
536 pwalletMain->GetPaymentAddresses(addrs);
537 BOOST_CHECK(addrs.size()==numAddrs);
539 // Ask wallet to list addresses
540 BOOST_CHECK_NO_THROW(retValue = CallRPC("z_listaddresses"));
541 arr = retValue.get_array();
542 BOOST_CHECK(arr.size() == numAddrs);
544 // Create a set from them
545 std::unordered_set<std::string> listaddrs;
546 for (UniValue element : arr.getValues()) {
547 listaddrs.insert(element.get_str());
550 // Verify the two sets of addresses are the same
551 BOOST_CHECK(listaddrs.size() == numAddrs);
552 BOOST_CHECK(myaddrs == listaddrs);
554 // Add one more address
555 BOOST_CHECK_NO_THROW(retValue = CallRPC("z_getnewaddress"));
556 std::string newaddress = retValue.get_str();
557 CZCPaymentAddress pa(newaddress);
558 auto newAddr = pa.Get();
559 BOOST_CHECK(pwalletMain->HaveSpendingKey(newAddr));
561 // Check if too many args
562 BOOST_CHECK_THROW(CallRPC("z_getnewaddress toomanyargs"), runtime_error);
568 * Test Async RPC operations.
569 * Tip: Create mock operations by subclassing AsyncRPCOperation.
572 class MockSleepOperation : public AsyncRPCOperation {
574 std::chrono::milliseconds naptime;
575 MockSleepOperation(int t=1000) {
576 this->naptime = std::chrono::milliseconds(t);
578 virtual ~MockSleepOperation() {
580 virtual void main() {
581 set_state(OperationStatus::EXECUTING);
582 start_execution_clock();
583 std::this_thread::sleep_for(std::chrono::milliseconds(naptime));
584 stop_execution_clock();
585 set_result(UniValue(UniValue::VSTR, "done"));
586 set_state(OperationStatus::SUCCESS);
592 * Test Aysnc RPC queue and operations.
594 BOOST_AUTO_TEST_CASE(rpc_wallet_async_operations)
596 std::shared_ptr<AsyncRPCQueue> q = std::make_shared<AsyncRPCQueue>();
597 BOOST_CHECK(q->getNumberOfWorkers() == 0);
598 std::vector<AsyncRPCOperationId> ids = q->getAllOperationIds();
599 BOOST_CHECK(ids.size()==0);
601 std::shared_ptr<AsyncRPCOperation> op1 = std::make_shared<AsyncRPCOperation>();
602 q->addOperation(op1);
603 BOOST_CHECK(q->getOperationCount() == 1);
605 OperationStatus status = op1->getState();
606 BOOST_CHECK(status == OperationStatus::READY);
608 AsyncRPCOperationId id1 = op1->getId();
609 int64_t creationTime1 = op1->getCreationTime();
612 BOOST_CHECK(q->getNumberOfWorkers() == 1);
614 // an AsyncRPCOperation doesn't do anything so will finish immediately
615 std::this_thread::sleep_for(std::chrono::seconds(1));
616 BOOST_CHECK(q->getOperationCount() == 0);
618 // operation should be a success
619 BOOST_CHECK_EQUAL(op1->isCancelled(), false);
620 BOOST_CHECK_EQUAL(op1->isExecuting(), false);
621 BOOST_CHECK_EQUAL(op1->isReady(), false);
622 BOOST_CHECK_EQUAL(op1->isFailed(), false);
623 BOOST_CHECK_EQUAL(op1->isSuccess(), true);
624 BOOST_CHECK_EQUAL(op1->getError().isNull(), true);
625 BOOST_CHECK_EQUAL(op1->getResult().isNull(), false);
626 BOOST_CHECK_EQUAL(op1->getStateAsString(), "success");
627 BOOST_CHECK_NE(op1->getStateAsString(), "executing");
629 // Create a second operation which just sleeps
630 std::shared_ptr<AsyncRPCOperation> op2(new MockSleepOperation(2500));
631 AsyncRPCOperationId id2 = op2->getId();
632 int64_t creationTime2 = op2->getCreationTime();
634 // it's different from the previous operation
635 BOOST_CHECK_NE(op1.get(), op2.get());
636 BOOST_CHECK_NE(id1, id2);
637 BOOST_CHECK_NE(creationTime1, creationTime2);
639 // Only the first operation has been added to the queue
640 std::vector<AsyncRPCOperationId> v = q->getAllOperationIds();
641 std::set<AsyncRPCOperationId> opids(v.begin(), v.end());
642 BOOST_CHECK(opids.size() == 1);
643 BOOST_CHECK(opids.count(id1)==1);
644 BOOST_CHECK(opids.count(id2)==0);
645 std::shared_ptr<AsyncRPCOperation> p1 = q->getOperationForId(id1);
646 BOOST_CHECK_EQUAL(p1.get(), op1.get());
647 std::shared_ptr<AsyncRPCOperation> p2 = q->getOperationForId(id2);
648 BOOST_CHECK(!p2); // null ptr as not added to queue yet
650 // Add operation 2 and 3 to the queue
651 q->addOperation(op2);
652 std::shared_ptr<AsyncRPCOperation> op3(new MockSleepOperation(1000));
653 q->addOperation(op3);
654 std::this_thread::sleep_for(std::chrono::milliseconds(500));
655 BOOST_CHECK_EQUAL(op2->isExecuting(), true);
656 op2->cancel(); // too late, already executing
658 std::this_thread::sleep_for(std::chrono::milliseconds(3000));
659 BOOST_CHECK_EQUAL(op2->isSuccess(), true);
660 BOOST_CHECK_EQUAL(op2->isCancelled(), false);
661 BOOST_CHECK_EQUAL(op3->isCancelled(), true);
664 v = q->getAllOperationIds();
665 std::copy( v.begin(), v.end(), std::inserter( opids, opids.end() ) );
666 BOOST_CHECK(opids.size() == 3);
667 BOOST_CHECK(opids.count(id1)==1);
668 BOOST_CHECK(opids.count(id2)==1);
669 BOOST_CHECK(opids.count(op3->getId())==1);
674 // The CountOperation will increment this global
675 std::atomic<int64_t> gCounter(0);
677 class CountOperation : public AsyncRPCOperation {
680 virtual ~CountOperation() {}
681 virtual void main() {
682 set_state(OperationStatus::EXECUTING);
684 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
685 set_state(OperationStatus::SUCCESS);
689 // This tests the queue waiting for multiple workers to finish
690 BOOST_AUTO_TEST_CASE(rpc_wallet_async_operations_parallel_wait)
694 std::shared_ptr<AsyncRPCQueue> q = std::make_shared<AsyncRPCQueue>();
699 BOOST_CHECK(q->getNumberOfWorkers() == 4);
701 int64_t numOperations = 10; // 10 * 1000ms / 4 = 2.5 secs to finish
702 for (int i=0; i<numOperations; i++) {
703 std::shared_ptr<AsyncRPCOperation> op(new CountOperation());
707 std::vector<AsyncRPCOperationId> ids = q->getAllOperationIds();
708 BOOST_CHECK(ids.size()==numOperations);
710 BOOST_CHECK_EQUAL(q->isFinishing(), true);
711 BOOST_CHECK_EQUAL(numOperations, gCounter.load());
714 // This tests the queue shutting down immediately
715 BOOST_AUTO_TEST_CASE(rpc_wallet_async_operations_parallel_cancel)
719 std::shared_ptr<AsyncRPCQueue> q = std::make_shared<AsyncRPCQueue>();
722 BOOST_CHECK(q->getNumberOfWorkers() == 2);
724 int numOperations = 10000; // 10000 seconds to complete
725 for (int i=0; i<numOperations; i++) {
726 std::shared_ptr<AsyncRPCOperation> op(new CountOperation());
729 std::vector<AsyncRPCOperationId> ids = q->getAllOperationIds();
730 BOOST_CHECK(ids.size()==numOperations);
734 int numCancelled = 0;
735 for (auto & id : ids) {
736 std::shared_ptr<AsyncRPCOperation> ptr = q->popOperationForId(id);
737 if (ptr->isCancelled()) {
739 } else if (ptr->isSuccess()) {
744 BOOST_CHECK_EQUAL(numOperations, numSuccess+numCancelled);
745 BOOST_CHECK_EQUAL(gCounter.load(), numSuccess);
746 BOOST_CHECK(q->getOperationCount() == 0);
747 ids = q->getAllOperationIds();
748 BOOST_CHECK(ids.size()==0);
751 // This tests z_getoperationstatus, z_getoperationresult, z_listoperationids
752 BOOST_AUTO_TEST_CASE(rpc_z_getoperations)
754 std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue();
755 std::shared_ptr<AsyncRPCQueue> sharedInstance = AsyncRPCQueue::sharedInstance();
756 BOOST_CHECK(q == sharedInstance);
758 BOOST_CHECK_NO_THROW(CallRPC("z_getoperationstatus"));
759 BOOST_CHECK_NO_THROW(CallRPC("z_getoperationstatus []"));
760 BOOST_CHECK_NO_THROW(CallRPC("z_getoperationstatus [\"opid-1234\"]"));
761 BOOST_CHECK_THROW(CallRPC("z_getoperationstatus [] toomanyargs"), runtime_error);
762 BOOST_CHECK_THROW(CallRPC("z_getoperationstatus not_an_array"), runtime_error);
764 BOOST_CHECK_NO_THROW(CallRPC("z_getoperationresult"));
765 BOOST_CHECK_NO_THROW(CallRPC("z_getoperationresult []"));
766 BOOST_CHECK_NO_THROW(CallRPC("z_getoperationresult [\"opid-1234\"]"));
767 BOOST_CHECK_THROW(CallRPC("z_getoperationresult [] toomanyargs"), runtime_error);
768 BOOST_CHECK_THROW(CallRPC("z_getoperationresult not_an_array"), runtime_error);
770 std::shared_ptr<AsyncRPCOperation> op1 = std::make_shared<AsyncRPCOperation>();
771 q->addOperation(op1);
772 std::shared_ptr<AsyncRPCOperation> op2 = std::make_shared<AsyncRPCOperation>();
773 q->addOperation(op2);
775 BOOST_CHECK(q->getOperationCount() == 2);
776 BOOST_CHECK(q->getNumberOfWorkers() == 0);
778 BOOST_CHECK(q->getNumberOfWorkers() == 1);
779 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
780 BOOST_CHECK(q->getOperationCount() == 0);
782 // Check if too many args
783 BOOST_CHECK_THROW(CallRPC("z_listoperationids toomany args"), runtime_error);
786 BOOST_CHECK_NO_THROW(retValue = CallRPC("z_listoperationids"));
787 BOOST_CHECK(retValue.get_array().size() == 2);
789 BOOST_CHECK_NO_THROW(retValue = CallRPC("z_getoperationstatus"));
790 UniValue array = retValue.get_array();
791 BOOST_CHECK(array.size() == 2);
794 BOOST_CHECK_NO_THROW(retValue = CallRPC("z_getoperationstatus"));
795 array = retValue.get_array();
796 BOOST_CHECK(array.size() == 2);
798 for (UniValue v : array.getValues()) {
799 UniValue obj = v.get_obj();
800 UniValue id = find_value(obj, "id");
803 // removes result from internal storage
804 BOOST_CHECK_NO_THROW(result = CallRPC("z_getoperationresult [\"" + id.get_str() + "\"]"));
805 UniValue resultArray = result.get_array();
806 BOOST_CHECK(resultArray.size() == 1);
808 UniValue resultObj = resultArray[0].get_obj();
809 UniValue resultId = find_value(resultObj, "id");
810 BOOST_CHECK_EQUAL(id.get_str(), resultId.get_str());
812 // verify the operation has been removed
813 BOOST_CHECK_NO_THROW(result = CallRPC("z_getoperationresult [\"" + id.get_str() + "\"]"));
814 resultArray = result.get_array();
815 BOOST_CHECK(resultArray.size() == 0);
818 // operations removed
819 BOOST_CHECK_NO_THROW(retValue = CallRPC("z_getoperationstatus"));
820 array = retValue.get_array();
821 BOOST_CHECK(array.size() == 0);
826 BOOST_AUTO_TEST_CASE(rpc_z_sendmany_parameters)
828 SelectParams(CBaseChainParams::TESTNET);
830 LOCK(pwalletMain->cs_wallet);
832 BOOST_CHECK_THROW(CallRPC("z_sendmany"), runtime_error);
833 BOOST_CHECK_THROW(CallRPC("z_sendmany toofewargs"), runtime_error);
834 BOOST_CHECK_THROW(CallRPC("z_sendmany just too many args here"), runtime_error);
837 BOOST_CHECK_THROW(CallRPC("z_sendmany "
838 "INVALIDtmRr6yJonqGK23UVhrKuyvTpF8qxQQjKigJ []"), runtime_error);
840 BOOST_CHECK_THROW(CallRPC("z_sendmany "
841 "tmRr6yJonqGK23UVhrKuyvTpF8qxQQjKigJ []"), runtime_error);
843 // don't have the spending key for this address
844 BOOST_CHECK_THROW(CallRPC("z_sendmany "
845 "tnpoQJVnYBZZqkFadj2bJJLThNCxbADGB5gSGeYTAGGrT5tejsxY9Zc1BtY8nnHmZkB"
846 "UkJ1oSfbhTJhm72WiZizvkZz5aH1 []"), runtime_error);
849 BOOST_CHECK_THROW(CallRPC("z_sendmany "
850 "tmRr6yJonqGK23UVhrKuyvTpF8qxQQjKigJ "
851 "[{\"address\":\"tmQP9L3s31cLsghVYf2Jb5MhKj1jRBPoeQn\", \"amount\":50.0},"
852 " {\"address\":\"tmQP9L3s31cLsghVYf2Jb5MhKj1jRBPoeQn\", \"amount\":12.0} ]"
855 // invalid fee amount, cannot be negative
856 BOOST_CHECK_THROW(CallRPC("z_sendmany "
857 "tmRr6yJonqGK23UVhrKuyvTpF8qxQQjKigJ "
858 "[{\"address\":\"tmQP9L3s31cLsghVYf2Jb5MhKj1jRBPoeQn\", \"amount\":50.0}] "
862 // invalid fee amount, bigger than MAX_MONEY
863 BOOST_CHECK_THROW(CallRPC("z_sendmany "
864 "tmRr6yJonqGK23UVhrKuyvTpF8qxQQjKigJ "
865 "[{\"address\":\"tmQP9L3s31cLsghVYf2Jb5MhKj1jRBPoeQn\", \"amount\":50.0}] "
869 // fee amount is bigger than sum of outputs
870 BOOST_CHECK_THROW(CallRPC("z_sendmany "
871 "tmRr6yJonqGK23UVhrKuyvTpF8qxQQjKigJ "
872 "[{\"address\":\"tmQP9L3s31cLsghVYf2Jb5MhKj1jRBPoeQn\", \"amount\":50.0}] "
876 // memo bigger than allowed length of ZC_MEMO_SIZE
877 std::vector<char> v (2 * (ZC_MEMO_SIZE+1)); // x2 for hexadecimal string format
878 std::fill(v.begin(),v.end(), 'A');
879 std::string badmemo(v.begin(), v.end());
880 CZCPaymentAddress pa = pwalletMain->GenerateNewZKey();
881 std::string zaddr1 = pa.ToString();
882 BOOST_CHECK_THROW(CallRPC(string("z_sendmany tmRr6yJonqGK23UVhrKuyvTpF8qxQQjKigJ ")
883 + "[{\"address\":\"" + zaddr1 + "\", \"amount\":123.456}]"), runtime_error);
885 // Test constructor of AsyncRPCOperation_sendmany
887 std::shared_ptr<AsyncRPCOperation> operation(new AsyncRPCOperation_sendmany("",{}, {}, -1));
888 } catch (const UniValue& objError) {
889 BOOST_CHECK( find_error(objError, "Minconf cannot be negative"));
893 std::shared_ptr<AsyncRPCOperation> operation(new AsyncRPCOperation_sendmany("",{}, {}, 1));
894 } catch (const UniValue& objError) {
895 BOOST_CHECK( find_error(objError, "From address parameter missing"));
899 std::shared_ptr<AsyncRPCOperation> operation( new AsyncRPCOperation_sendmany("tmRr6yJonqGK23UVhrKuyvTpF8qxQQjKigJ", {}, {}, 1) );
900 } catch (const UniValue& objError) {
901 BOOST_CHECK( find_error(objError, "No recipients"));
905 std::vector<SendManyRecipient> recipients = { SendManyRecipient("dummy",1.0, "") };
906 std::shared_ptr<AsyncRPCOperation> operation( new AsyncRPCOperation_sendmany("INVALID", recipients, {}, 1) );
907 } catch (const UniValue& objError) {
908 BOOST_CHECK( find_error(objError, "payment address is invalid"));
911 // Testnet payment addresses begin with 'zt'. This test detects an incorrect prefix.
913 std::vector<SendManyRecipient> recipients = { SendManyRecipient("dummy",1.0, "") };
914 std::shared_ptr<AsyncRPCOperation> operation( new AsyncRPCOperation_sendmany("zcMuhvq8sEkHALuSU2i4NbNQxshSAYrpCExec45ZjtivYPbuiFPwk6WHy4SvsbeZ4siy1WheuRGjtaJmoD1J8bFqNXhsG6U", recipients, {}, 1) );
915 } catch (const UniValue& objError) {
916 BOOST_CHECK( find_error(objError, "payment address is for wrong network type"));
919 // Note: The following will crash as a google test because AsyncRPCOperation_sendmany
920 // invokes a method on pwalletMain, which is undefined in the google test environment.
922 std::vector<SendManyRecipient> recipients = { SendManyRecipient("dummy",1.0, "") };
923 std::shared_ptr<AsyncRPCOperation> operation( new AsyncRPCOperation_sendmany("ztjiDe569DPNbyTE6TSdJTaSDhoXEHLGvYoUnBU1wfVNU52TEyT6berYtySkd21njAeEoh8fFJUT42kua9r8EnhBaEKqCpP", recipients, {}, 1) );
924 } catch (const UniValue& objError) {
925 BOOST_CHECK( find_error(objError, "no spending key found for zaddr"));
930 // TODO: test private methods
931 BOOST_AUTO_TEST_CASE(rpc_z_sendmany_internals)
933 SelectParams(CBaseChainParams::TESTNET);
935 LOCK(pwalletMain->cs_wallet);
940 BOOST_CHECK_NO_THROW(retValue = CallRPC("getnewaddress"));
941 std::string taddr1 = retValue.get_str();
942 CZCPaymentAddress pa = pwalletMain->GenerateNewZKey();
943 std::string zaddr1 = pa.ToString();
945 // there are no utxos to spend
947 std::vector<SendManyRecipient> recipients = { SendManyRecipient(zaddr1,100.0, "DEADBEEF") };
948 std::shared_ptr<AsyncRPCOperation> operation( new AsyncRPCOperation_sendmany(taddr1, {}, recipients, 1) );
950 BOOST_CHECK(operation->isFailed());
951 std::string msg = operation->getErrorMessage();
952 BOOST_CHECK( msg.find("Insufficient funds, no UTXOs found") != string::npos);
955 // there are no unspent notes to spend
957 std::vector<SendManyRecipient> recipients = { SendManyRecipient(taddr1,100.0, "DEADBEEF") };
958 std::shared_ptr<AsyncRPCOperation> operation( new AsyncRPCOperation_sendmany(zaddr1, recipients, {}, 1) );
960 BOOST_CHECK(operation->isFailed());
961 std::string msg = operation->getErrorMessage();
962 BOOST_CHECK( msg.find("Insufficient funds, no unspent notes") != string::npos);
965 // get_memo_from_hex_string())
967 std::vector<SendManyRecipient> recipients = { SendManyRecipient(zaddr1,100.0, "DEADBEEF") };
968 std::shared_ptr<AsyncRPCOperation> operation( new AsyncRPCOperation_sendmany(zaddr1, recipients, {}, 1) );
969 std::shared_ptr<AsyncRPCOperation_sendmany> ptr = std::dynamic_pointer_cast<AsyncRPCOperation_sendmany> (operation);
970 TEST_FRIEND_AsyncRPCOperation_sendmany proxy(ptr);
972 std::string memo = "DEADBEEF";
973 boost::array<unsigned char, ZC_MEMO_SIZE> array = proxy.get_memo_from_hex_string(memo);
974 BOOST_CHECK_EQUAL(array[0], 0xDE);
975 BOOST_CHECK_EQUAL(array[1], 0xAD);
976 BOOST_CHECK_EQUAL(array[2], 0xBE);
977 BOOST_CHECK_EQUAL(array[3], 0xEF);
978 for (int i=4; i<ZC_MEMO_SIZE; i++) {
979 BOOST_CHECK_EQUAL(array[i], 0x00); // zero padding
982 // memo is longer than allowed
983 std::vector<char> v (2 * (ZC_MEMO_SIZE+1));
984 std::fill(v.begin(),v.end(), 'A');
985 std::string bigmemo(v.begin(), v.end());
988 proxy.get_memo_from_hex_string(bigmemo);
989 } catch (const UniValue& objError) {
990 BOOST_CHECK( find_error(objError, "too big"));
993 // invalid hexadecimal string
994 std::fill(v.begin(),v.end(), '@'); // not a hex character
995 std::string badmemo(v.begin(), v.end());
998 proxy.get_memo_from_hex_string(badmemo);
999 } catch (const UniValue& objError) {
1000 BOOST_CHECK( find_error(objError, "hexadecimal format"));
1003 // odd length hexadecimal string
1004 std::fill(v.begin(),v.end(), 'A');
1005 v.resize(v.size() - 1);
1006 assert(v.size() %2 == 1); // odd length
1007 std::string oddmemo(v.begin(), v.end());
1009 proxy.get_memo_from_hex_string(oddmemo);
1010 } catch (const UniValue& objError) {
1011 BOOST_CHECK( find_error(objError, "hexadecimal format"));
1016 // add_taddr_change_output_to_tx() will append a vout to a raw transaction
1018 std::vector<SendManyRecipient> recipients = { SendManyRecipient(zaddr1,100.0, "DEADBEEF") };
1019 std::shared_ptr<AsyncRPCOperation> operation( new AsyncRPCOperation_sendmany(zaddr1, recipients, {}, 1) );
1020 std::shared_ptr<AsyncRPCOperation_sendmany> ptr = std::dynamic_pointer_cast<AsyncRPCOperation_sendmany> (operation);
1021 TEST_FRIEND_AsyncRPCOperation_sendmany proxy(ptr);
1023 CTransaction tx = proxy.getTx();
1024 BOOST_CHECK(tx.vout.size() == 0);
1026 CAmount amount = 123.456;
1027 proxy.add_taddr_change_output_to_tx(amount);
1029 BOOST_CHECK(tx.vout.size() == 1);
1030 CTxOut out = tx.vout[0];
1031 BOOST_CHECK_EQUAL(out.nValue, amount);
1034 proxy.add_taddr_change_output_to_tx(amount);
1036 BOOST_CHECK(tx.vout.size() == 2);
1038 BOOST_CHECK_EQUAL(out.nValue, amount);
1041 // add_taddr_outputs_to_tx() will append many vouts to a raw transaction
1043 std::vector<SendManyRecipient> recipients = {
1044 SendManyRecipient("tmTGScYwiLMzHe4uGZtBYmuqoW4iEoYNMXt",CAmount(1.23), ""),
1045 SendManyRecipient("tmUSbHz3vxnwLvRyNDXbwkZxjVyDodMJEhh",CAmount(4.56), ""),
1046 SendManyRecipient("tmYZAXYPCP56Xa5JQWWPZuK7o7bfUQW6kkd",CAmount(7.89), ""),
1048 std::shared_ptr<AsyncRPCOperation> operation( new AsyncRPCOperation_sendmany(zaddr1, recipients, {}, 1) );
1049 std::shared_ptr<AsyncRPCOperation_sendmany> ptr = std::dynamic_pointer_cast<AsyncRPCOperation_sendmany> (operation);
1050 TEST_FRIEND_AsyncRPCOperation_sendmany proxy(ptr);
1052 proxy.add_taddr_outputs_to_tx();
1054 CTransaction tx = proxy.getTx();
1055 BOOST_CHECK(tx.vout.size() == 3);
1056 BOOST_CHECK_EQUAL(tx.vout[0].nValue, CAmount(1.23));
1057 BOOST_CHECK_EQUAL(tx.vout[1].nValue, CAmount(4.56));
1058 BOOST_CHECK_EQUAL(tx.vout[2].nValue, CAmount(7.89));
1062 // Raw joinsplit is a zaddr->zaddr
1064 std::string raw = "020000000000000000000100000000000000001027000000000000183a0d4c46c369078705e39bcfebee59a978dbd210ce8de3efc9555a03fbabfd3cea16693d730c63850d7e48ccde79854c19adcb7e9dcd7b7d18805ee09083f6b16e1860729d2d4a90e2f2acd009cf78b5eb0f4a6ee4bdb64b1262d7ce9eb910c460b02022991e968d0c50ee44908e4ccccbc591d0053bcca154dd6d6fc400a29fa686af4682339832ccea362a62aeb9df0d5aa74f86a1e75ac0f48a8ccc41e0a940643c6c33e1d09223b0a46eaf47a1bb4407cfc12b1dcf83a29c0cef51e45c7876ca5b9e5bae86d92976eb3ef68f29cd29386a8be8451b50f82bf9da10c04651868655194da8f6ed3d241bb5b5ff93a3e2bbe44644544d88bcde5cc35978032ee92699c7a61fcbb395e7583f47e698c4d53ede54f956629400bf510fb5e22d03158cc10bdcaaf29e418ef18eb6480dd9c8b9e2a377809f9f32a556ef872febd0021d4ad013aa9f0b7255e98e408d302abefd33a71180b720271835b487ab309e160b06dfe51932120fb84a7ede16b20c53599a11071592109e10260f265ee60d48c62bfe24074020e9b586ce9e9356e68f2ad1a9538258234afe4b83a209f178f45202270eaeaeecaf2ce3100b2c5a714f75f35777a9ebff5ebf47059d2bbf6f3726190216468f2b152673b766225b093f3a2f827c86d6b48b42117fec1d0ac38dd7af700308dcfb02eba821612b16a2c164c47715b9b0c93900893b1aba2ea03765c94d87022db5be06ab338d1912e0936dfe87586d0a8ee49144a6cd2e306abdcb652faa3e0222739deb23154d778b50de75069a4a2cce1208cd1ced3cb4744c9888ce1c2fcd2e66dc31e62d3aa9e423d7275882525e9981f92e84ac85975b8660739407efbe1e34c2249420fde7e17db3096d5b22e83d051d01f0e6e7690dca7d168db338aadf0897fedac10de310db2b1bff762d322935dddbb60c2efb8b15d231fa17b84630371cb275c209f0c4c7d0c68b150ea5cd514122215e3f7fcfb351d69514788d67c2f3c8922581946e3a04bdf1f07f15696ca76eb95b10698bf1188fd882945c57657515889d042a6fc45d38cbc943540c4f0f6d1c45a1574c81f3e42d1eb8702328b729909adee8a5cfed7c79d54627d1fd389af941d878376f7927b9830ca659bf9ab18c5ca5192d52d02723008728d03701b8ab3e1c4a3109409ec0b13df334c7deec3523eeef4c97b5603e643de3a647b873f4c1b47fbfc6586ba66724f112e51fc93839648005043620aa3ce458e246d77977b19c53d98e3e812de006afc1a79744df236582943631d04cc02941ac4be500e4ed9fb9e3e7cc187b1c4050fad1d9d09d5fd70d5d01d615b439d8c0015d2eb10398bcdbf8c4b2bd559dbe4c288a186aed3f86f608da4d582e120c4a896e015e2241900d1daeccd05db968852677c71d752bec46de9962174b46f980e8cc603654daf8b98a3ee92dac066033954164a89568b70b1780c2ce2410b2f816dbeddb2cd463e0c8f21a52cf6427d9647a6fd4bafa8fb4cd4d47ac057b0160bee86c6b2fb8adce214c2bcdda277512200adf0eaa5d2114a2c077b009836a68ec254bfe56f51d147b9afe2ddd9cb917c0c2de19d81b7b8fd9f4574f51fa1207630dc13976f4d7587c962f761af267de71f3909a576e6bedaf6311633910d291ac292c467cc8331ef577aef7646a5d949322fa0367a49f20597a13def53136ee31610395e3e48d291fd8f58504374031fe9dcfba5e06086ebcf01a9106f6a4d6e16e19e4c5bb893f7da79419c94eca31a384be6fa1747284dee0fc3bbc8b1b860172c10b29c1594bb8c747d7fe05827358ff2160f49050001625ffe2e880bd7fc26cd0ffd89750745379a8e862816e08a5a2008043921ab6a4976064ac18f7ee37b6628bc0127d8d5ebd3548e41d8881a082d86f20b32e33094f15a0e6ea6074b08c6cd28142de94713451640a55985051f5577eb54572699d838cb34a79c8939e981c0c277d06a6e2ce69ccb74f8a691ff08f81d8b99e6a86223d29a2b7c8e7b041aba44ea678ae654277f7e91cbfa79158b989164a3d549d9f4feb0cc43169699c13e321fe3f4b94258c75d198ff9184269cd6986c55409e07528c93f64942c6c283ce3917b4bf4c3be2fe3173c8c38cccb35f1fbda0ca88b35a599c0678cb22aa8eabea8249dbd2e4f849fffe69803d299e435ebcd7df95854003d8eda17a74d98b4be0e62d45d7fe48c06a6f464a14f8e0570077cc631279092802a89823f031eef5e1028a6d6fdbd502869a731ee7d28b4d6c71b419462a30d31442d3ee444ffbcbd16d558c9000c97e949c2b1f9d6f6d8db7b9131ebd963620d3fc8595278d6f8fdf49084325373196d53e64142fa5a23eccd6ef908c4d80b8b3e6cc334b7f7012103a3682e4678e9b518163d262a39a2c1a69bf88514c52b7ccd7cc8dc80e71f7c2ec0701cff982573eb0c2c4daeb47fa0b586f4451c10d1da2e5d182b03dd067a5e971b3a6138ca6667aaf853d2ac03b80a1d5870905f2cfb6c78ec3c3719c02f973d638a0f973424a2b0f2b0023f136d60092fe15fba4bc180b9176bd0ff576e053f1af6939fe9ca256203ffaeb3e569f09774d2a6cbf91873e56651f4d6ff77e0b5374b0a1a201d7e523604e0247644544cc571d48c458a4f96f45580b";
1065 UniValue obj(UniValue::VOBJ);
1066 obj.push_back(Pair("rawtxn", raw));
1068 // we have the spending key for the dummy recipient zaddr1
1069 std::vector<SendManyRecipient> recipients = { SendManyRecipient(zaddr1, 0.0005, "ABCD") };
1071 std::shared_ptr<AsyncRPCOperation> operation( new AsyncRPCOperation_sendmany(zaddr1, {}, recipients, 1) );
1072 std::shared_ptr<AsyncRPCOperation_sendmany> ptr = std::dynamic_pointer_cast<AsyncRPCOperation_sendmany> (operation);
1073 TEST_FRIEND_AsyncRPCOperation_sendmany proxy(ptr);
1075 // Enable test mode so tx is not sent
1076 static_cast<AsyncRPCOperation_sendmany *>(operation.get())->testmode = true;
1078 // Pretend that the operation completed successfully
1079 proxy.set_state(OperationStatus::SUCCESS);
1081 // Verify test mode is returning output (since no input taddrs, signed and unsigned are the same).
1082 BOOST_CHECK_NO_THROW( proxy.sign_send_raw_transaction(obj) );
1083 UniValue result = operation->getResult();
1084 BOOST_CHECK(!result.isNull());
1085 UniValue resultObj = result.get_obj();
1086 std::string hex = find_value(resultObj, "hex").get_str();
1087 BOOST_CHECK_EQUAL(hex, raw);
1091 // Test the perform_joinsplit methods.
1093 // Dummy input so the operation object can be instantiated.
1094 std::vector<SendManyRecipient> recipients = { SendManyRecipient(zaddr1, 0.0005, "ABCD") };
1096 std::shared_ptr<AsyncRPCOperation> operation( new AsyncRPCOperation_sendmany(zaddr1, {}, recipients, 1) );
1097 std::shared_ptr<AsyncRPCOperation_sendmany> ptr = std::dynamic_pointer_cast<AsyncRPCOperation_sendmany> (operation);
1098 TEST_FRIEND_AsyncRPCOperation_sendmany proxy(ptr);
1100 // Enable test mode so tx is not sent and proofs are not generated
1101 static_cast<AsyncRPCOperation_sendmany *>(operation.get())->testmode = true;
1103 AsyncJoinSplitInfo info;
1104 std::vector<boost::optional < ZCIncrementalWitness>> witnesses;
1107 proxy.perform_joinsplit(info, witnesses, anchor);
1108 } catch (const std::runtime_error & e) {
1109 BOOST_CHECK( string(e.what()).find("anchor is null")!= string::npos);
1113 std::vector<JSOutPoint> v;
1114 proxy.perform_joinsplit(info, v);
1115 } catch (const std::runtime_error & e) {
1116 BOOST_CHECK( string(e.what()).find("anchor is null")!= string::npos);
1119 info.notes.push_back(Note());
1121 proxy.perform_joinsplit(info);
1122 } catch (const std::runtime_error & e) {
1123 BOOST_CHECK( string(e.what()).find("number of notes")!= string::npos);
1127 info.vjsin.push_back(JSInput());
1128 info.vjsin.push_back(JSInput());
1129 info.vjsin.push_back(JSInput());
1131 proxy.perform_joinsplit(info);
1132 } catch (const std::runtime_error & e) {
1133 BOOST_CHECK( string(e.what()).find("unsupported joinsplit input")!= string::npos);
1138 proxy.perform_joinsplit(info);
1139 } catch (const std::runtime_error & e) {
1140 BOOST_CHECK( string(e.what()).find("JoinSplit verifying key not loaded")!= string::npos);
1148 * This test covers storing encrypted zkeys in the wallet.
1150 BOOST_AUTO_TEST_CASE(rpc_wallet_encrypted_wallet_zkeys)
1152 LOCK2(cs_main, pwalletMain->cs_wallet);
1156 // wallet should currently be empty
1157 std::set<libzcash::PaymentAddress> addrs;
1158 pwalletMain->GetPaymentAddresses(addrs);
1159 BOOST_CHECK(addrs.size()==0);
1162 for (int i = 0; i < n; i++) {
1163 CallRPC("z_getnewaddress");
1166 // Verify we can list the keys imported
1167 BOOST_CHECK_NO_THROW(retValue = CallRPC("z_listaddresses"));
1168 UniValue arr = retValue.get_array();
1169 BOOST_CHECK(arr.size() == n);
1171 // Verify that the wallet encryption RPC is disabled
1172 BOOST_CHECK_THROW(CallRPC("encryptwallet passphrase"), runtime_error);
1174 // Encrypt the wallet (we can't call RPC encryptwallet as that shuts down node)
1175 SecureString strWalletPass;
1176 strWalletPass.reserve(100);
1177 strWalletPass = "hello";
1179 boost::filesystem::current_path(GetArg("-datadir","/tmp/thisshouldnothappen"));
1180 BOOST_CHECK(pwalletMain->EncryptWallet(strWalletPass));
1182 // Verify we can still list the keys imported
1183 BOOST_CHECK_NO_THROW(retValue = CallRPC("z_listaddresses"));
1184 arr = retValue.get_array();
1185 BOOST_CHECK(arr.size() == n);
1187 // Try to add a new key, but we can't as the wallet is locked
1188 BOOST_CHECK_THROW(CallRPC("z_getnewaddress"), runtime_error);
1190 // We can't call RPC walletpassphrase as that invokes RPCRunLater which breaks tests.
1191 // So we manually unlock.
1192 BOOST_CHECK(pwalletMain->Unlock(strWalletPass));
1195 BOOST_CHECK_NO_THROW(CallRPC("z_getnewaddress"));
1197 // Verify the key has been added
1198 BOOST_CHECK_NO_THROW(retValue = CallRPC("z_listaddresses"));
1199 arr = retValue.get_array();
1200 BOOST_CHECK(arr.size() == n+1);
1202 // We can't simulate over RPC the wallet closing and being reloaded
1203 // but there are tests for this in gtest.
1206 BOOST_AUTO_TEST_SUITE_END()