// Verify importwallet RPC starts rescan at earliest block with timestamp // greater or equal than key birthday. Previously there was a bug where // importwallet RPC would start the scan at the latest block with timestamp less // than or equal to key birthday. BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) { g_address_type = OUTPUT_TYPE_DEFAULT; g_change_type = OUTPUT_TYPE_DEFAULT; // Create two blocks with same timestamp to verify that importwallet rescan // will pick up both blocks, not just the first. const int64_t BLOCK_TIME = chainActive.Tip()->GetBlockTimeMax() + 5; SetMockTime(BLOCK_TIME); coinbaseTxns.emplace_back(*CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); coinbaseTxns.emplace_back(*CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); // Set key birthday to block time increased by the timestamp window, so // rescan will start at the block time. const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW; SetMockTime(KEY_TIME); coinbaseTxns.emplace_back(*CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); LOCK(cs_main); // Import key into wallet and call dumpwallet to create backup file. { CWallet wallet("dummy", CWalletDBWrapper::CreateDummy()); LOCK(wallet.cs_wallet); wallet.mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME; wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()); JSONRPCRequest request; request.params.setArray(); request.params.push_back((pathTemp / "wallet.backup").string()); vpwallets.insert(vpwallets.begin(), &wallet); ::dumpwallet(request); } // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME // were scanned, and no prior blocks were scanned. { CWallet wallet("dummy", CWalletDBWrapper::CreateDummy()); JSONRPCRequest request; request.params.setArray(); request.params.push_back((pathTemp / "wallet.backup").string()); vpwallets[0] = &wallet; ::importwallet(request); LOCK(wallet.cs_wallet); BOOST_CHECK_EQUAL(wallet.mapWallet.size(), 3); BOOST_CHECK_EQUAL(coinbaseTxns.size(), 103); for (size_t i = 0; i < coinbaseTxns.size(); ++i) { bool found = wallet.GetWalletTx(coinbaseTxns[i].GetHash()); bool expected = i >= 100; BOOST_CHECK_EQUAL(found, expected); } } SetMockTime(0); vpwallets.erase(vpwallets.begin()); }
void rai::system::generate_mass_activity (uint32_t count_a, rai::node & node_a) { std::vector<rai::account> accounts; wallet (0)->insert_adhoc (rai::test_genesis_key.prv); accounts.push_back (rai::test_genesis_key.pub); auto previous (std::chrono::steady_clock::now ()); for (uint32_t i (0); i < count_a; ++i) { if ((i & 0xff) == 0) { auto now (std::chrono::steady_clock::now ()); auto us (std::chrono::duration_cast<std::chrono::microseconds> (now - previous).count ()); uint64_t count (0); uint64_t state (0); { rai::transaction transaction (node_a.store.environment, nullptr, false); auto block_counts (node_a.store.block_count (transaction)); count = block_counts.sum (); state = block_counts.state; } std::cerr << boost::str (boost::format ("Mass activity iteration %1% us %2% us/t %3% state: %4% old: %5%\n") % i % us % (us / 256) % state % (count - state)); previous = now; } generate_activity (node_a, accounts); } }
TEST(TestGetBalance, SpendAmountBalance) { GetBalance balance; // Create Wallet just with initial amount DoCreateWallet wallet("main\\tst\\WalletBalance","+200.55"); wallet.CreateWalletFile(); //add income std::string amountt = "100"; std::string choise = "spend"; std::string category1 = "donation"; std::string wallet6 = ""; DoCreateWallet wallet1("main\\tst\\WalletBalance",amountt); wallet1.AddLineInWalletFile(amountt, choise, category1, wallet6); //add income amountt = "700"; choise = "spend"; category1 = "food"; DoCreateWallet wallet2("main\\tst\\WalletBalance",amountt); wallet2.AddLineInWalletFile(amountt, choise, category1, wallet6); //convert file content to string std::string walletFile = ReturnWalletString(wallet); //std :: cout<<walletFile; EXPECT_EQ("-599.45",balance.PrintBalance(walletFile,"")); }
TEST(TestGetBalanceCategory, IncomeSpendSameCategory) { GetBalance balance; // Create Wallet just with initial amount DoCreateWallet wallet("main\\tst\\WalletBalanceCategory","+200.55"); wallet.CreateWalletFile(); //add spend std::string amount = "10"; std::string choice = "spend"; std::string category1 = "bcategory"; std::string wallet7 = ""; DoCreateWallet wallet1("main\\tst\\WalletBalanceCategory",amount); wallet1.AddLineInWalletFile(amount, choice, category1, wallet7); //add income amount = "9"; choice = "income"; category1 = "bcategory"; DoCreateWallet wallet2("main\\tst\\WalletBalanceCategory",amount); wallet2.AddLineInWalletFile(amount, choice, category1, wallet7); //convert file content to string std::string walletFile = ReturnWalletString77(wallet); //std :: cout<<walletFile; EXPECT_EQ("-1",balance.PrintBalance(walletFile,"bcategory")); }
void rai::system::generate_send_existing (rai::node & node_a, std::vector<rai::account> & accounts_a) { rai::uint128_t amount; rai::account destination; rai::account source; { rai::account account; random_pool.GenerateBlock (account.bytes.data (), sizeof (account.bytes)); rai::transaction transaction (node_a.store.environment, nullptr, false); rai::store_iterator entry (node_a.store.latest_begin (transaction, account)); if (entry == node_a.store.latest_end ()) { entry = node_a.store.latest_begin (transaction); } assert (entry != node_a.store.latest_end ()); destination = rai::account (entry->first.uint256 ()); source = get_random_account (accounts_a); amount = get_random_amount (transaction, node_a, source); } if (!amount.is_zero ()) { auto hash (wallet (0)->send_sync (source, destination, amount)); assert (!hash.is_zero ()); } }
TEST(TestGetBalance, IncomeAmountBalance) { GetBalance balance; // Create Wallet just with initial amount DoCreateWallet wallet("main\\tst\\WalletBalance","+200.55"); wallet.CreateWalletFile(); //add income std::string amountt = "+100"; std::string choise = "income"; std::string category1 = "salary"; std::string wallet5 = ""; DoCreateWallet wallet1("main\\tst\\WalletBalance",amountt); wallet1.AddLineInWalletFile(amountt, choise, category1, wallet5); //add income amountt = "+700"; choise = "income"; category1 = "bonus"; DoCreateWallet wallet2("main\\tst\\WalletBalance",amountt); wallet2.AddLineInWalletFile(amountt, choise, category1, wallet5); //convert file content to string std::string walletFile = ReturnWalletString(wallet); //std :: cout<<walletFile; EXPECT_EQ("+1000.55",balance.PrintBalance(walletFile,"")); }
std::vector<fc::ecc::private_key> import_electrum_wallet( const fc::path& wallet_dat, const std::string& passphrase ) { try { std::vector<fc::ecc::private_key> keys; electrumwallet wallet( wallet_dat.to_native_ansi_path()); if( !wallet.ok() ) FC_THROW_EXCEPTION( fc::invalid_arg_exception, "invalid electrum wallet"); wallet.derivekeys( passphrase ); return wallet.keys(); } FC_RETHROW_EXCEPTIONS( warn, "" ) }
void rai::system::generate_change_known (rai::node & node_a, std::vector<rai::account> & accounts_a) { rai::account source (get_random_account (accounts_a)); if (!node_a.latest (source).is_zero ()) { rai::account destination (get_random_account (accounts_a)); auto change_error (wallet (0)->change_sync (source, destination)); assert (!change_error); } }
LoginWindow::LoginWindow(OnlineDocument::DocumentType type, QWidget *parent) : QDialog(parent), m_type(type), m_authDialog(new Ui_Dialog), m_wallet(0) { m_authDialog->setupUi(this); QStringList onlineServices; onlineServices << "Google Documents"; // Add services here m_authDialog->comboBox->addItems(onlineServices); connect(m_authDialog->loginButton, SIGNAL(clicked()), this, SLOT(loginService())); connect(m_authDialog->comboBox, SIGNAL(activated(int)), this, SLOT(serviceSelected(int))); const QString settingsGroup = "Google-Documents"; KConfigGroup interface = KoGlobal::calligraConfig()->group(settingsGroup); if (interface.exists()) { QString userName = interface.readEntry("userEmailId", ""); if (!userName.isEmpty()) { m_authDialog->userEdit->setText(userName); QString password; if (wallet()) { wallet()->readPassword(QString("%1-%2").arg(settingsGroup).arg(userName), password); } if (!password.isEmpty()) { m_authDialog->passwordEdit->setText(password); } } } m_authDialog->userEdit->setFocus(); showProgressIndicator(false); setWindowTitle("Online Document Services"); show(); }
TEST(TestGetBalance, PosAmountBalance) { GetBalance balance; // Create Wallet just with initial amount DoCreateWallet wallet("main\\tst\\WalletBalance","+200.55"); wallet.CreateWalletFile(); //convert file content to string std::string walletFile = ReturnWalletString(wallet); EXPECT_EQ("+200.55",balance.PrintBalance(walletFile,"")); }
// Check that GetImmatureCredit() returns a newly calculated value instead of // the cached value after a MarkDirty() call. // // This is a regression test written to verify a bugfix for the immature credit // function. Similar tests probably should be written for the other credit and // debit functions. BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup) { CWallet wallet(WalletLocation(), WalletDatabase::CreateDummy()); CWalletTx wtx(&wallet, m_coinbase_txns.back()); LOCK2(cs_main, wallet.cs_wallet); wtx.hashBlock = chainActive.Tip()->GetBlockHash(); wtx.nIndex = 0; // Call GetImmatureCredit() once before adding the key to the wallet to // cache the current immature credit amount, which is 0. BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), 0); // Invalidate the cached value, add the key, and make sure a new immature // credit amount is calculated. wtx.MarkDirty(); wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()); BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), 50*COIN); }
void rai::system::generate_send_new (rai::node & node_a, std::vector<rai::account> & accounts_a) { assert (node_a.wallets.items.size () == 1); rai::uint128_t amount; rai::account source; { rai::transaction transaction (node_a.store.environment, nullptr, false); source = get_random_account (accounts_a); amount = get_random_amount (transaction, node_a, source); } if (!amount.is_zero ()) { auto pub (node_a.wallets.items.begin ()->second->deterministic_insert ()); accounts_a.push_back (pub); auto hash (wallet (0)->send_sync (source, pub, amount)); assert (!hash.is_zero ()); } }
void rai::system::generate_receive (rai::node & node_a) { std::shared_ptr<rai::block> send_block; { rai::transaction transaction (node_a.store.environment, nullptr, false); rai::uint256_union random_block; random_pool.GenerateBlock (random_block.bytes.data (), sizeof (random_block.bytes)); auto i (node_a.store.pending_begin (transaction, rai::pending_key (random_block, 0))); if (i != node_a.store.pending_end ()) { rai::pending_key send_hash (i->first); rai::pending_info info (i->second); send_block = node_a.store.block_get (transaction, send_hash.hash); } } if (send_block != nullptr) { auto receive_error (wallet (0)->receive_sync (send_block, rai::genesis_account, std::numeric_limits<rai::uint128_t>::max ())); (void)receive_error; } }
//! Simple qt wallet tests. // // Test widgets can be debugged interactively calling show() on them and // manually running the event loop, e.g.: // // sendCoinsDialog.show(); // QEventLoop().exec(); // // This also requires overriding the default minimal Qt platform: // // src/qt/test/test_bitcoin-qt -platform xcb # Linux // src/qt/test/test_bitcoin-qt -platform windows # Windows // src/qt/test/test_bitcoin-qt -platform cocoa # macOS void WalletTests::walletTests() { // Set up wallet and chain with 101 blocks (1 mature block for spending). TestChain100Setup test; test.CreateAndProcessBlock({}, GetScriptForRawPubKey(test.coinbaseKey.GetPubKey())); bitdb.MakeMock(); std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, "wallet_test.dat")); CWallet wallet(std::move(dbw)); bool firstRun; wallet.LoadWallet(firstRun); { LOCK(wallet.cs_wallet); wallet.SetAddressBook(test.coinbaseKey.GetPubKey().GetID(), "", "receive"); wallet.AddKeyPubKey(test.coinbaseKey, test.coinbaseKey.GetPubKey()); } wallet.ScanForWalletTransactions(chainActive.Genesis(), true); wallet.SetBroadcastTransactions(true); // Create widgets for sending coins and listing transactions. std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other")); SendCoinsDialog sendCoinsDialog(platformStyle.get()); OptionsModel optionsModel; WalletModel walletModel(platformStyle.get(), &wallet, &optionsModel); sendCoinsDialog.setModel(&walletModel); // Send two transactions, and verify they are added to transaction list. TransactionTableModel* transactionTableModel = walletModel.getTransactionTableModel(); QCOMPARE(transactionTableModel->rowCount({}), 101); uint256 txid1 = SendCoins(wallet, sendCoinsDialog, CBitcoinAddress(CKeyID()), 5 * COIN); uint256 txid2 = SendCoins(wallet, sendCoinsDialog, CBitcoinAddress(CKeyID()), 10 * COIN); QCOMPARE(transactionTableModel->rowCount({}), 103); QVERIFY(FindTx(*transactionTableModel, txid1).isValid()); QVERIFY(FindTx(*transactionTableModel, txid2).isValid()); bitdb.Flush(true); bitdb.Reset(); }
/** * This test covers methods on CWalletDB * WriteZKey() */ TEST(wallet_zkeys_tests, write_zkey_direct_to_db) { SelectParams(CBaseChainParams::TESTNET); // Get temporary and unique path for file. // Note: / operator to append paths boost::filesystem::path pathTemp = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); boost::filesystem::create_directories(pathTemp); mapArgs["-datadir"] = pathTemp.string(); bool fFirstRun; CWallet wallet("wallet.dat"); ASSERT_EQ(DB_LOAD_OK, wallet.LoadWallet(fFirstRun)); // No default CPubKey set ASSERT_TRUE(fFirstRun); // wallet should be empty std::set<libzcash::PaymentAddress> addrs; wallet.GetPaymentAddresses(addrs); ASSERT_EQ(0, addrs.size()); // Add random key to the wallet auto paymentAddress = wallet.GenerateNewZKey(); // wallet should have one key wallet.GetPaymentAddresses(addrs); ASSERT_EQ(1, addrs.size()); // create random key and add it to database directly, bypassing wallet auto sk = libzcash::SpendingKey::random(); auto addr = sk.address(); int64_t now = GetTime(); CKeyMetadata meta(now); CWalletDB db("wallet.dat"); db.WriteZKey(addr, sk, meta); // wallet should not be aware of key ASSERT_FALSE(wallet.HaveSpendingKey(addr)); // wallet sees one key wallet.GetPaymentAddresses(addrs); ASSERT_EQ(1, addrs.size()); // wallet should have default metadata for addr with null createtime CKeyMetadata m = wallet.mapZKeyMetadata[addr]; ASSERT_EQ(m.nCreateTime, 0); ASSERT_NE(m.nCreateTime, now); // load the wallet again ASSERT_EQ(DB_LOAD_OK, wallet.LoadWallet(fFirstRun)); // wallet can now see the spending key ASSERT_TRUE(wallet.HaveSpendingKey(addr)); // check key is the same libzcash::SpendingKey keyOut; wallet.GetSpendingKey(addr, keyOut); ASSERT_EQ(sk, keyOut); // wallet should have two keys wallet.GetPaymentAddresses(addrs); ASSERT_EQ(2, addrs.size()); // check metadata is now the same m = wallet.mapZKeyMetadata[addr]; ASSERT_EQ(m.nCreateTime, now); }
BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup) { auto chain = interfaces::MakeChain(); // Cap last block file size, and mine new block in a new block file. const CBlockIndex* const null_block = nullptr; CBlockIndex* oldTip = chainActive.Tip(); GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE; CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); CBlockIndex* newTip = chainActive.Tip(); auto locked_chain = chain->lock(); // Verify ScanForWalletTransactions accomodates a null start block. { CWallet wallet(*chain, WalletLocation(), WalletDatabase::CreateDummy()); AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(&wallet); reserver.reserve(); const CBlockIndex *stop_block = null_block + 1, *failed_block = null_block + 1; BOOST_CHECK_EQUAL(wallet.ScanForWalletTransactions(nullptr, nullptr, reserver, failed_block, stop_block), CWallet::ScanResult::SUCCESS); BOOST_CHECK_EQUAL(failed_block, null_block); BOOST_CHECK_EQUAL(stop_block, null_block); BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 0); } // Verify ScanForWalletTransactions picks up transactions in both the old // and new block files. { CWallet wallet(*chain, WalletLocation(), WalletDatabase::CreateDummy()); AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(&wallet); reserver.reserve(); const CBlockIndex *stop_block = null_block + 1, *failed_block = null_block + 1; BOOST_CHECK_EQUAL(wallet.ScanForWalletTransactions(oldTip, nullptr, reserver, failed_block, stop_block), CWallet::ScanResult::SUCCESS); BOOST_CHECK_EQUAL(failed_block, null_block); BOOST_CHECK_EQUAL(stop_block, newTip); BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 100 * COIN); } // Prune the older block file. PruneOneBlockFile(oldTip->GetBlockPos().nFile); UnlinkPrunedFiles({oldTip->GetBlockPos().nFile}); // Verify ScanForWalletTransactions only picks transactions in the new block // file. { CWallet wallet(*chain, WalletLocation(), WalletDatabase::CreateDummy()); AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(&wallet); reserver.reserve(); const CBlockIndex *stop_block = null_block + 1, *failed_block = null_block + 1; BOOST_CHECK_EQUAL(wallet.ScanForWalletTransactions(oldTip, nullptr, reserver, failed_block, stop_block), CWallet::ScanResult::FAILURE); BOOST_CHECK_EQUAL(failed_block, oldTip); BOOST_CHECK_EQUAL(stop_block, newTip); BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 50 * COIN); } // Prune the remaining block file. PruneOneBlockFile(newTip->GetBlockPos().nFile); UnlinkPrunedFiles({newTip->GetBlockPos().nFile}); // Verify ScanForWalletTransactions scans no blocks. { CWallet wallet(*chain, WalletLocation(), WalletDatabase::CreateDummy()); AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(&wallet); reserver.reserve(); const CBlockIndex *stop_block = null_block + 1, *failed_block = null_block + 1; BOOST_CHECK_EQUAL(wallet.ScanForWalletTransactions(oldTip, nullptr, reserver, failed_block, stop_block), CWallet::ScanResult::FAILURE); BOOST_CHECK_EQUAL(failed_block, newTip); BOOST_CHECK_EQUAL(stop_block, null_block); BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 0); } }
int main(int argc, char** argv){ // clear screen std::cout << "\033[2J\033[1;1H"; std::cout << "Drachma : Partial Reconfiguration Cache Simulator\n\n\n"; // instantiate drachma wallet wallet library = wallet(); if(argc > 1 && argv[1][0] == 0x2D && argv[1][1] != 0){ //switches present // read for switch data short int switch_count = strlen(argv[1]) - 1; char switch_choices[switch_count]; bool bad_switch = false; for(int i = 0; i < switch_count; i++) switch_choices[i] = argv[1][i + 1]; for(int i = 0; i < switch_count; i++){ bool valid_use = false; switch(switch_choices[i]){ //case 'd': { /* * add device to simulator wallet * * usage: * ./drachma -da DEVICE_FILE [DEVICE_NAME] * * remove device to simulator wallet * * usage: * ./drachma -dr DEVICE_FILE [DEVICE_NAME] */ /*if(switch_count == 2){ // require two switches if(switch_choices[1] == 'a'){ std::cout << "Adding new device '" << argv[2] << "' to the Wallet.\n\n"; valid_use = true; if(fileExists(argv[2])){ std::vector<std::string> device_params {"family", "model", "slices"}; fileHandler device_reader = fileHandler(argv[2], device_params); if(device_reader.isFileValid()){ library.addDevice(argv[2]); std::cout << "Done!\n"; }else std::cout << "ERROR: The target file '" << argv[2] << "' is not a valid Device file.\n\n"; }else std::cout << "ERROR: The target file '" << argv[2] << "' does not exist.\n\n"; }else if(switch_choices[1] == 'r'){ std::cout << "Removing device '" << argv[2] << "' from the Wallet.\n\n"; valid_use = true; if(!library.removeDevice(argv[2])) std::cout << "ERROR: Could not remove Device '" << argv[2] << "' from the Wallet." << " <Device was Not Present>\n\n"; } } if(!valid_use){ std::cout << "ERROR: Improper switch use; The operations concerning Devices are as follows:\n"; deviceHelp(); } goto exit; }*/ case 'h': { // help user /* * help user - print usage synopsis * * usage: * ./drachma -h */ displayHelp(); break; } case 'm': { /* * add memory and replacement algorithm configurations * * usage: * ./drachma -ma MEMORY_FILE [CONFIGURATION_NAME] * * remove memory and replacement algorithm configurations * * usage: * ./drachma -mr MEMORY_FILE [CONFIGURATION_NAME] */ if(switch_count == 2){ // require two switches if(switch_choices[1] == 'a'){ std::cout << "Adding new Memory Configuration '" << argv[2] << "' to the Wallet.\n\n"; valid_use = true; if(fileExists(argv[2])){ fileHandler memory_reader = fileHandler(argv[2], library.getMemoryParamRules(), library.getMemoryRegexRules()); if(memory_reader.isFileValid()){ library.addMemory(argv[2]); std::cout << "Done!\n"; }else std::cout << "ERROR: The target file '" << argv[2] << "' is not a valid Memory Configuration file.\n\n"; }else std::cout << "ERROR: The target file '" << argv[2] << "' does not exist.\n\n"; }else if(switch_choices[1] == 'r'){ std::cout << "Removing Memory Configuration '" << argv[2] << "' from the Wallet.\n\n"; valid_use = true; if(!library.removeMemory(argv[2])) std::cout << "ERROR: Could not remove Memory Configuration '" << argv[2] << "' from the Wallet." << " <Memory Configuration was Not Present>\n\n"; } } if(!valid_use){ std::cout << "ERROR: Improper switch use; The operations concerning Memory Configuration files are as follows:\n"; memoryHelp(); } goto exit; } case 'a': { /* * add application to simulator wallet * * usage: * ./drachma -aa APPLICATION_FILE [APPLICATION_NAME] * * remove application to simulator wallet * * usage: * ./drachma -ar APPLICATION_FILE [APPLICATION_NAME] */ if(switch_count == 2){ // require two switches if(switch_choices[1] == 'a'){ std::cout << "Adding new application '" << argv[2] << "' to the Wallet.\n\n"; valid_use = true; if(fileExists(argv[2])){ fileHandler application_reader = fileHandler(argv[2], library.getApplicationParamRules(), library.getApplicationRegexRules()); if(application_reader.isFileValid()){ library.addApplication(argv[2]); std::cout << "Done!\n"; }else std::cout << "ERROR: The target file '" << argv[2] << "' is not a valid Application file.\n\n"; }else std::cout << "ERROR: The target file '" << argv[2] << "' does not exist.\n\n"; }else if(switch_choices[1] == 'r'){ std::cout << "Removing application '" << argv[2] << "' from the Wallet.\n\n"; valid_use = true; if(!library.removeApplication(argv[2])) std::cout << "ERROR: Could not remove Application '" << argv[2] << "' from the Wallet." << " <Application was Not Present>\n\n"; } } if(!valid_use){ std::cout << "ERROR: Improper switch use; The operations concerning Application files are as follows:\n"; deviceHelp(); } goto exit; } case 't': { /* * add application trace to simulator wallet * * usage: * ./drachma -ta TRACE_FILE [APPLICATION_NAME] * * remove application trace from simulator wallet * * usage: * ./drachma -tr TRACE_FILE [APPLICATION_NAME] */ if(switch_count == 2){ // require two switches if(switch_choices[1] == 'a'){ std::cout << "Adding new Trace File '" << argv[2] << "' to the Wallet.\n\n"; valid_use = true; if(fileExists(argv[2])){ fileHandler trace_reader = fileHandler(argv[2], library.getTraceParamRules(), library.getTraceRegexRules()); if(trace_reader.isFileValid()){ library.addTraceFile(argv[2]); std::cout << "Done!\n"; }else std::cout << "ERROR: The target file '" << argv[2] << "' is not a valid Trace File.\n\n"; }else std::cout << "ERROR: The target file '" << argv[2] << "' does not exist.\n\n"; }else if(switch_choices[1] == 'r'){ std::cout << "Removing Trace File '" << argv[2] << "' from the Wallet.\n\n"; valid_use = true; if(!library.removeTraceFile(argv[2])) std::cout << "ERROR: Could not remove Trace File '" << argv[2] << "' from the Wallet." << " <Trace File was Not Present>\n\n"; } } if(!valid_use){ std::cout << "ERROR: Improper switch use; The operations concerning Trace files are as follows:\n"; traceHelp(); } goto exit; } case 'w': { /* * list objects contained in the simulator wallet"rcr count" * * usage: * ./drachma -w */ library.printDetails(); goto exit; } case 's': { /* * start simulation * * usage: * ./drachma -s MEMORY_ID APPLICATION_ID TRACE_ID */ if(argc == 5 || argc == 6){ // initialize the simulation device //device sim_device = library.getDevice( atoi(argv[2]) ); device sim_device = device(); // get memory hierarchy reconfigurableRegions memory = library.getMemory( atoi(argv[2]) ); // get application application* app = library.getApplication( atoi(argv[3]) ); // get application traces std::vector<std::string> traces = library.getTraceFile( atoi(argv[4]) ); // apply memory hierarchy to device sim_device.associateHierarchy(memory); // prepare device resources needed by the application if (sim_device.prepareApplicationResources(app)) { sim_device.parseTraceFile(traces); // if specified, stop the simulation after a certain mount of clock cycles if(argc == 5) sim_device.simulateApplication(); else sim_device.simulateApplication(atoi(argv[5])); } else std::cout << "ERROR: Chosen application's bitstream library is too large to fit in the selected memory hierarchy.\n"; }else{ std::cout << "ERROR: Improper switch use; The operations concerning Starting the Simulator are as follows:\n"; startHelp(); } goto exit; } default: // unrecognized switch bad_switch = true; } } }else{ // no switches - default action std::cout << ">>> No Switches Present! Have some help:" << std::endl << std::endl; displayHelp(); } exit: std::cout << std::endl; return 0; }
BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup) { // Cap last block file size, and mine new block in a new block file. CBlockIndex* const nullBlock = nullptr; CBlockIndex* oldTip = chainActive.Tip(); GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE; CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); CBlockIndex* newTip = chainActive.Tip(); LOCK(cs_main); // Verify ScanForWalletTransactions picks up transactions in both the old // and new block files. { CWallet wallet(WalletLocation(), WalletDatabase::CreateDummy()); AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(&wallet); reserver.reserve(); BOOST_CHECK_EQUAL(nullBlock, wallet.ScanForWalletTransactions(oldTip, nullptr, reserver)); BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 100 * COIN); } // Prune the older block file. PruneOneBlockFile(oldTip->GetBlockPos().nFile); UnlinkPrunedFiles({oldTip->GetBlockPos().nFile}); // Verify ScanForWalletTransactions only picks transactions in the new block // file. { CWallet wallet(WalletLocation(), WalletDatabase::CreateDummy()); AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(&wallet); reserver.reserve(); BOOST_CHECK_EQUAL(oldTip, wallet.ScanForWalletTransactions(oldTip, nullptr, reserver)); BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 50 * COIN); } // Verify importmulti RPC returns failure for a key whose creation time is // before the missing block, and success for a key whose creation time is // after. { std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(WalletLocation(), WalletDatabase::CreateDummy()); AddWallet(wallet); UniValue keys; keys.setArray(); UniValue key; key.setObject(); key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey()))); key.pushKV("timestamp", 0); key.pushKV("internal", UniValue(true)); keys.push_back(key); key.clear(); key.setObject(); CKey futureKey; futureKey.MakeNewKey(true); key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey()))); key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1); key.pushKV("internal", UniValue(true)); keys.push_back(key); JSONRPCRequest request; request.params.setArray(); request.params.push_back(keys); UniValue response = importmulti(request); BOOST_CHECK_EQUAL(response.write(), strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation " "timestamp %d. There was an error reading a block from time %d, which is after or within %d " "seconds of key creation, and could contain transactions pertaining to the key. As a result, " "transactions and coins using this key may not appear in the wallet. This error could be caused " "by pruning or data corruption (see bitcoind log for details) and could be dealt with by " "downloading and rescanning the relevant blocks (see -reindex and -rescan " "options).\"}},{\"success\":true}]", 0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW)); RemoveWallet(wallet); } }
void LXQt::Wallet::changePassWordDialog::change() { m_ui->lineEditCurrentPassWord->setEnabled(false); m_ui->lineEditNewPassWord->setEnabled(false); m_ui->lineEditNewPassWord_2->setEnabled(false); m_ui->pushButtonChange->setEnabled(false); m_ui->pushButtonCancel->setEnabled(false); m_ui->label->setEnabled(true); m_ui->label_2->setEnabled(false); m_ui->label_2->setEnabled(false); m_ui->label_3->setEnabled(false); m_ui->label_4->setEnabled(false); if (m_ui->lineEditNewPassWord->text() == m_ui->lineEditNewPassWord_2->text()) { class wallet { public: wallet() { } wallet(const QString &password, const QString &walletName, const QString &applicationName) { m_error = lxqt_wallet_open(&m_wallet, password.toLatin1().constData(), password.size(), walletName.toLatin1().constData(), applicationName.toLatin1().constData()); } operator bool() { return m_error == lxqt_wallet_no_error; } bool changePassword(const QString &newPassword) { auto q = newPassword.toLatin1(); m_error = lxqt_wallet_change_wallet_password(m_wallet, q.constData(), q.size()); return m_error == lxqt_wallet_no_error; } void close() { lxqt_wallet_close(&m_wallet); } private: lxqt_wallet_t m_wallet = 0; lxqt_wallet_error m_error; }; auto password = m_ui->lineEditCurrentPassWord->text(); Task::run<wallet>([this, password]() { return wallet(password, m_walletName, m_applicationName); }).then([this](wallet w) { if (w) { if (w.changePassword(m_ui->lineEditNewPassWord->text())) { m_walletPassWordChanged = true; this->HideUI(); } else { m_ui->pushButtonChange->setEnabled(true); m_ui->pushButtonCancel->setEnabled(true); m_ui->label->setText(tr("Wallet password could not be changed")); m_ui->pushButtonCancel->setVisible(false); m_ui->pushButtonChange->setVisible(false); m_ui->pushButtonOK->setVisible(true); m_ui->pushButtonOK->setFocus(); } } else { m_ui->pushButtonChange->setEnabled(true); m_ui->pushButtonCancel->setEnabled(true); m_ui->label->setText(tr("Wallet could not be opened with the presented key")); m_ui->pushButtonCancel->setVisible(false); m_ui->pushButtonChange->setVisible(false); m_ui->pushButtonOK->setVisible(true); m_ui->pushButtonOK->setFocus(); } w.close(); }); } else { m_ui->label->setText(tr("New passwords do not match")); m_ui->pushButtonOK->setVisible(true); m_ui->pushButtonCancel->setVisible(false); m_ui->pushButtonChange->setVisible(false); m_ui->pushButtonOK->setFocus(); } }
/** * This test covers methods on CWalletDB to load/save crypted z keys. */ TEST(wallet_zkeys_tests, write_cryptedzkey_direct_to_db) { ECC_Start(); SelectParams(CBaseChainParams::TESTNET); // Get temporary and unique path for file. // Note: / operator to append paths boost::filesystem::path pathTemp = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path(); boost::filesystem::create_directories(pathTemp); mapArgs["-datadir"] = pathTemp.string(); bool fFirstRun; CWallet wallet("wallet_crypted.dat"); ASSERT_EQ(DB_LOAD_OK, wallet.LoadWallet(fFirstRun)); // No default CPubKey set ASSERT_TRUE(fFirstRun); // wallet should be empty std::set<libzcash::PaymentAddress> addrs; wallet.GetPaymentAddresses(addrs); ASSERT_EQ(0, addrs.size()); // Add random key to the wallet auto paymentAddress = wallet.GenerateNewZKey(); // wallet should have one key wallet.GetPaymentAddresses(addrs); ASSERT_EQ(1, addrs.size()); // encrypt wallet SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = "******"; ASSERT_TRUE(wallet.EncryptWallet(strWalletPass)); // adding a new key will fail as the wallet is locked EXPECT_ANY_THROW(wallet.GenerateNewZKey()); // unlock wallet and then add wallet.Unlock(strWalletPass); auto paymentAddress2 = wallet.GenerateNewZKey(); // Create a new wallet from the existing wallet path CWallet wallet2("wallet_crypted.dat"); ASSERT_EQ(DB_LOAD_OK, wallet2.LoadWallet(fFirstRun)); // Confirm it's not the same as the other wallet ASSERT_TRUE(&wallet != &wallet2); // wallet should have two keys wallet2.GetPaymentAddresses(addrs); ASSERT_EQ(2, addrs.size()); // check we have entries for our payment addresses ASSERT_TRUE(addrs.count(paymentAddress.Get())); ASSERT_TRUE(addrs.count(paymentAddress2.Get())); // spending key is crypted, so we can't extract valid payment address libzcash::SpendingKey keyOut; wallet2.GetSpendingKey(paymentAddress.Get(), keyOut); ASSERT_FALSE(paymentAddress.Get() == keyOut.address()); // unlock wallet to get spending keys and verify payment addresses wallet2.Unlock(strWalletPass); wallet2.GetSpendingKey(paymentAddress.Get(), keyOut); ASSERT_EQ(paymentAddress.Get(), keyOut.address()); wallet2.GetSpendingKey(paymentAddress2.Get(), keyOut); ASSERT_EQ(paymentAddress2.Get(), keyOut.address()); }