// Copyright (c) 2012-2015, The CryptoNote developers, The Bytecoin developers // // This file is part of Bytecoin. // // Bytecoin is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Bytecoin is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with Bytecoin. If not, see . #include "cryptonote_core/account.h" #include "cryptonote_core/cryptonote_format_utils.h" #include "WalletTransactionSender.h" #include "WalletUtils.h" #include "cryptonote_core/cryptonote_basic_impl.h" #include #include namespace { using namespace CryptoNote; uint64_t countNeededMoney(uint64_t fee, const std::vector& transfers) { uint64_t needed_money = fee; for (auto& transfer: transfers) { CryptoNote::throwIf(transfer.amount == 0, CryptoNote::error::ZERO_DESTINATION); CryptoNote::throwIf(transfer.amount < 0, CryptoNote::error::WRONG_AMOUNT); needed_money += transfer.amount; CryptoNote::throwIf(static_cast(needed_money) < transfer.amount, CryptoNote::error::SUM_OVERFLOW); } return needed_money; } void createChangeDestinations(const CryptoNote::AccountPublicAddress& address, uint64_t neededMoney, uint64_t foundMoney, CryptoNote::tx_destination_entry& changeDts) { if (neededMoney < foundMoney) { changeDts.addr = address; changeDts.amount = foundMoney - neededMoney; } } void constructTx(const CryptoNote::account_keys keys, const std::vector& sources, const std::vector& splittedDests, const std::string& extra, uint64_t unlockTimestamp, uint64_t sizeLimit, CryptoNote::Transaction& tx) { std::vector extraVec; extraVec.reserve(extra.size()); std::for_each(extra.begin(), extra.end(), [&extraVec] (const char el) { extraVec.push_back(el);}); Logging::LoggerGroup nullLog; bool r = CryptoNote::construct_tx(keys, sources, splittedDests, extraVec, tx, unlockTimestamp, nullLog); CryptoNote::throwIf(!r, CryptoNote::error::INTERNAL_WALLET_ERROR); CryptoNote::throwIf(CryptoNote::get_object_blobsize(tx) >= sizeLimit, CryptoNote::error::TRANSACTION_SIZE_TOO_BIG); } void fillTransactionHash(const CryptoNote::Transaction& tx, CryptoNote::TransactionHash& hash) { crypto::hash h = CryptoNote::get_transaction_hash(tx); memcpy(hash.data(), reinterpret_cast(&h), hash.size()); } std::shared_ptr makeCompleteEvent(WalletUserTransactionsCache& transactionCache, size_t transactionId, std::error_code ec) { transactionCache.updateTransactionSendingState(transactionId, ec); return std::make_shared(transactionId, ec); } } //namespace namespace CryptoNote { WalletTransactionSender::WalletTransactionSender(const CryptoNote::Currency& currency, WalletUserTransactionsCache& transactionsCache, CryptoNote::account_keys keys, ITransfersContainer& transfersContainer) : m_currency(currency), m_transactionsCache(transactionsCache), m_isStoping(false), m_keys(keys), m_transferDetails(transfersContainer), m_upperTransactionSizeLimit(m_currency.blockGrantedFullRewardZone() * 125 / 100 - m_currency.minerTxBlobReservedSize()) {} void WalletTransactionSender::stop() { m_isStoping = true; } bool WalletTransactionSender::validateDestinationAddress(const std::string& address) { CryptoNote::AccountPublicAddress ignore; return m_currency.parseAccountAddressString(address, ignore); } void WalletTransactionSender::validateTransfersAddresses(const std::vector& transfers) { for (const Transfer& tr: transfers) { if (!validateDestinationAddress(tr.address)) { throw std::system_error(make_error_code(CryptoNote::error::BAD_ADDRESS)); } } } std::shared_ptr WalletTransactionSender::makeSendRequest(TransactionId& transactionId, std::deque >& events, const std::vector& transfers, uint64_t fee, const std::string& extra, uint64_t mixIn, uint64_t unlockTimestamp) { using namespace CryptoNote; throwIf(transfers.empty(), CryptoNote::error::ZERO_DESTINATION); validateTransfersAddresses(transfers); uint64_t neededMoney = countNeededMoney(fee, transfers); std::shared_ptr context = std::make_shared(); context->foundMoney = selectTransfersToSend(neededMoney, 0 == mixIn, context->dustPolicy.dustThreshold, context->selectedTransfers); throwIf(context->foundMoney < neededMoney, CryptoNote::error::WRONG_AMOUNT); transactionId = m_transactionsCache.addNewTransaction(neededMoney, fee, extra, transfers, unlockTimestamp); context->transactionId = transactionId; context->mixIn = mixIn; if(context->mixIn) { std::shared_ptr request = makeGetRandomOutsRequest(context); return request; } return doSendTransaction(context, events); } std::shared_ptr WalletTransactionSender::makeGetRandomOutsRequest(std::shared_ptr context) { uint64_t outsCount = context->mixIn + 1;// add one to make possible (if need) to skip real output key std::vector amounts; for (const auto& td : context->selectedTransfers) { amounts.push_back(td.amount); } return std::make_shared(amounts, outsCount, context, std::bind(&WalletTransactionSender::sendTransactionRandomOutsByAmount, this, context, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); } void WalletTransactionSender::sendTransactionRandomOutsByAmount(std::shared_ptr context, std::deque >& events, boost::optional >& nextRequest, std::error_code ec) { if (m_isStoping) { ec = make_error_code(CryptoNote::error::TX_CANCELLED); } if (ec) { events.push_back(makeCompleteEvent(m_transactionsCache, context->transactionId, ec)); return; } auto scanty_it = std::find_if(context->outs.begin(), context->outs.end(), [&] (CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount& out) {return out.outs.size() < context->mixIn;}); if (scanty_it != context->outs.end()) { events.push_back(makeCompleteEvent(m_transactionsCache, context->transactionId, make_error_code(CryptoNote::error::MIXIN_COUNT_TOO_BIG))); return; } std::shared_ptr req = doSendTransaction(context, events); if (req) nextRequest = req; } std::shared_ptr WalletTransactionSender::doSendTransaction(std::shared_ptr context, std::deque >& events) { if (m_isStoping) { events.push_back(makeCompleteEvent(m_transactionsCache, context->transactionId, make_error_code(CryptoNote::error::TX_CANCELLED))); return std::shared_ptr(); } try { TransactionInfo& transaction = m_transactionsCache.getTransaction(context->transactionId); std::vector sources; prepareInputs(context->selectedTransfers, context->outs, sources, context->mixIn); CryptoNote::tx_destination_entry changeDts; changeDts.amount = 0; uint64_t totalAmount = -transaction.totalAmount; createChangeDestinations(m_keys.m_account_address, totalAmount, context->foundMoney, changeDts); std::vector splittedDests; splitDestinations(transaction.firstTransferId, transaction.transferCount, changeDts, context->dustPolicy, splittedDests); CryptoNote::Transaction tx; constructTx(m_keys, sources, splittedDests, transaction.extra, transaction.unlockTime, m_upperTransactionSizeLimit, tx); fillTransactionHash(tx, transaction.hash); m_transactionsCache.updateTransaction(context->transactionId, tx, totalAmount, context->selectedTransfers); notifyBalanceChanged(events); return std::make_shared(tx, std::bind(&WalletTransactionSender::relayTransactionCallback, this, context, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); } catch(std::system_error& ec) { events.push_back(makeCompleteEvent(m_transactionsCache, context->transactionId, ec.code())); } catch(std::exception&) { events.push_back(makeCompleteEvent(m_transactionsCache, context->transactionId, make_error_code(CryptoNote::error::INTERNAL_WALLET_ERROR))); } return std::shared_ptr(); } void WalletTransactionSender::relayTransactionCallback(std::shared_ptr context, std::deque >& events, boost::optional >& nextRequest, std::error_code ec) { if (m_isStoping) { return; } events.push_back(makeCompleteEvent(m_transactionsCache, context->transactionId, ec)); } void WalletTransactionSender::splitDestinations(TransferId firstTransferId, size_t transfersCount, const CryptoNote::tx_destination_entry& changeDts, const TxDustPolicy& dustPolicy, std::vector& splittedDests) { uint64_t dust = 0; digitSplitStrategy(firstTransferId, transfersCount, changeDts, dustPolicy.dustThreshold, splittedDests, dust); throwIf(dustPolicy.dustThreshold < dust, CryptoNote::error::INTERNAL_WALLET_ERROR); if (0 != dust && !dustPolicy.addToFee) { splittedDests.push_back(CryptoNote::tx_destination_entry(dust, dustPolicy.addrForDust)); } } void WalletTransactionSender::digitSplitStrategy(TransferId firstTransferId, size_t transfersCount, const CryptoNote::tx_destination_entry& change_dst, uint64_t dust_threshold, std::vector& splitted_dsts, uint64_t& dust) { splitted_dsts.clear(); dust = 0; for (TransferId idx = firstTransferId; idx < firstTransferId + transfersCount; ++idx) { Transfer& de = m_transactionsCache.getTransfer(idx); CryptoNote::AccountPublicAddress addr; if (!m_currency.parseAccountAddressString(de.address, addr)) { throw std::system_error(make_error_code(CryptoNote::error::BAD_ADDRESS)); } CryptoNote::decompose_amount_into_digits(de.amount, dust_threshold, [&](uint64_t chunk) { splitted_dsts.push_back(CryptoNote::tx_destination_entry(chunk, addr)); }, [&](uint64_t a_dust) { splitted_dsts.push_back(CryptoNote::tx_destination_entry(a_dust, addr)); } ); } CryptoNote::decompose_amount_into_digits(change_dst.amount, dust_threshold, [&](uint64_t chunk) { splitted_dsts.push_back(CryptoNote::tx_destination_entry(chunk, change_dst.addr)); }, [&](uint64_t a_dust) { dust = a_dust; } ); } void WalletTransactionSender::prepareInputs( const std::list& selectedTransfers, std::vector& outs, std::vector& sources, uint64_t mixIn) { size_t i = 0; for (const auto& td: selectedTransfers) { sources.resize(sources.size()+1); CryptoNote::tx_source_entry& src = sources.back(); src.amount = td.amount; //paste mixin transaction if(outs.size()) { outs[i].outs.sort([](const CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry& a, const CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry& b){return a.global_amount_index < b.global_amount_index;}); for (auto& daemon_oe: outs[i].outs) { if(td.globalOutputIndex == daemon_oe.global_amount_index) continue; CryptoNote::tx_source_entry::output_entry oe; oe.first = daemon_oe.global_amount_index; oe.second = daemon_oe.out_key; src.outputs.push_back(oe); if(src.outputs.size() >= mixIn) break; } } //paste real transaction to the random index auto it_to_insert = std::find_if(src.outputs.begin(), src.outputs.end(), [&](const CryptoNote::tx_source_entry::output_entry& a) { return a.first >= td.globalOutputIndex; }); CryptoNote::tx_source_entry::output_entry real_oe; real_oe.first = td.globalOutputIndex; real_oe.second = reinterpret_cast(td.outputKey); auto interted_it = src.outputs.insert(it_to_insert, real_oe); src.real_out_tx_key = reinterpret_cast(td.transactionPublicKey); src.real_output = interted_it - src.outputs.begin(); src.real_output_in_tx_index = td.outputInTransaction; ++i; } } void WalletTransactionSender::notifyBalanceChanged(std::deque >& events) { uint64_t unconfirmedOutsAmount = m_transactionsCache.unconfrimedOutsAmount(); uint64_t change = unconfirmedOutsAmount - m_transactionsCache.unconfirmedTransactionsAmount(); uint64_t actualBalance = m_transferDetails.balance(ITransfersContainer::IncludeKeyUnlocked) - unconfirmedOutsAmount; uint64_t pendingBalance = m_transferDetails.balance(ITransfersContainer::IncludeKeyNotUnlocked) + change; events.push_back(std::make_shared(actualBalance)); events.push_back(std::make_shared(pendingBalance)); } namespace { template T popRandomValue(URNG& randomGenerator, std::vector& vec) { CHECK_AND_ASSERT_MES(!vec.empty(), T(), "Vector must be non-empty"); std::uniform_int_distribution distribution(0, vec.size() - 1); size_t idx = distribution(randomGenerator); T res = vec[idx]; if (idx + 1 != vec.size()) { vec[idx] = vec.back(); } vec.resize(vec.size() - 1); return res; } } uint64_t WalletTransactionSender::selectTransfersToSend(uint64_t neededMoney, bool addDust, uint64_t dust, std::list& selectedTransfers) { std::vector unusedTransfers; std::vector unusedDust; std::vector outputs; m_transferDetails.getOutputs(outputs, ITransfersContainer::IncludeKeyUnlocked); for (size_t i = 0; i < outputs.size(); ++i) { const auto& out = outputs[i]; if (!m_transactionsCache.isUsed(out)) { if (dust < out.amount) unusedTransfers.push_back(i); else unusedDust.push_back(i); } } std::default_random_engine randomGenerator(crypto::rand()); bool selectOneDust = addDust && !unusedDust.empty(); uint64_t foundMoney = 0; while (foundMoney < neededMoney && (!unusedTransfers.empty() || !unusedDust.empty())) { size_t idx; if (selectOneDust) { idx = popRandomValue(randomGenerator, unusedDust); selectOneDust = false; } else { idx = !unusedTransfers.empty() ? popRandomValue(randomGenerator, unusedTransfers) : popRandomValue(randomGenerator, unusedDust); } selectedTransfers.push_back(outputs[idx]); foundMoney += outputs[idx].amount; } return foundMoney; } } /* namespace CryptoNote */