#include "sparkwallet.h" #include "threadpool.h" #include "sparkmessage.h" #include "../wallet/wallet.h" #include "../wallet/coincontrol.h" #include "../wallet/walletexcept.h" #include "../hash.h" #include "../validation.h" #include "../policy/policy.h" #include "../script/sign.h" #include "../utilstrencodings.h" #include "state.h" #include "sparkname.h" #include "../chain.h" #include "../init.h" #include #include #include const uint32_t DEFAULT_SPARK_NCOUNT = 1; CSparkWallet::CSparkWallet(const std::string& strWalletFile) { uiInterface.InitMessage(_("Loading Spark wallet...")); CWalletDB walletdb(strWalletFile); this->strWalletFile = strWalletFile; const spark::Params* params = spark::Params::get_default(); fullViewKey = spark::FullViewKey(params); viewKey = spark::IncomingViewKey(params); bool fWalletJustUnlocked = false; // try to get incoming view key from db, if it fails, that means it is first start if (!walletdb.readFullViewKey(fullViewKey)) { if (pwalletMain->IsLocked()) { pwalletMain->RequestUnlock(); if (pwalletMain->WaitForUnlock()) { fWalletJustUnlocked = true; } else { throw std::runtime_error("Spark wallet creation FAILED, wallet could not be unlocked\n"); return; } } // Generating spark key set first time spark::SpendKey spendKey(params); try { spendKey = std::move(generateSpendKey(params)); } catch (const WalletLocked&) { throw std::runtime_error("Spark wallet creation FAILED, wallet is locked\n"); } catch (const std::exception&) { throw std::runtime_error("Spark wallet creation FAILED, unable to generate spend key\n"); } fullViewKey = generateFullViewKey(spendKey); viewKey = generateIncomingViewKey(fullViewKey); // Write incoming view key into db, it is safe to be kept in db, it is used to identify incoming coins belonging to the wallet walletdb.writeFullViewKey(fullViewKey); // generate one initial address for wallet lastDiversifier = 0; addresses[lastDiversifier] = getDefaultAddress(); // set 0 as last diversifier into db, we will update it later, in case coin comes, or user manually generates new address walletdb.writeDiversifier(lastDiversifier); } else { viewKey = generateIncomingViewKey(fullViewKey); int32_t diversifierInDB = 0; // read diversifier from db walletdb.readDiversifier(diversifierInDB); lastDiversifier = -1; // generate all used addresses while (lastDiversifier < diversifierInDB) { addresses[lastDiversifier] = generateNextAddress(); } // Load SMints only when their containing wallet transaction is a Spark spend. auto loadedMints = walletdb.ListSparkMints(); { LOCK(pwalletMain->cs_wallet); std::erase_if(loadedMints, [&](const auto& entry) { const auto& mint = entry.second; if (mint.type != spark::COIN_TYPE_SPEND) return false; const auto parent = pwalletMain->mapWallet.find(mint.txid); if (parent == pwalletMain->mapWallet.end()) { // Keep missing-parent records on disk so a rescan can recover valid mints. LogPrintf("CSparkWallet: skipping saved SMint with missing wallet transaction %s; rescan to recover\n", mint.txid.ToString()); return true; } if (parent->second.tx->IsSparkSpend()) return false; if (!walletdb.EraseSparkMint(entry.first)) throw std::runtime_error("Failed to remove unauthenticated Spark mint from wallet"); return true; }); } { LOCK(cs_spark_wallet); coinMeta = std::move(loadedMints); for (auto& mint : coinMeta) { mint.second.coin.setParams(params); mint.second.coin.setSerialContext(mint.second.serial_context); addToLookups(mint.first, mint.second); } } } // One worker so mint jobs posted before a spend of those coins run first. threadPool = new ParallelOpThreadPool(1); fCacheAudit = GetBoolArg("-sparkcacheverify", false); // The lookup indexes answer ownership and value queries from the recorded // metadata without re-running identification, so verify the records in // the background and evict the fast-path entries of any that fail. bool fHaveCachedCoins; { LOCK(cs_spark_wallet); fHaveCachedCoins = !coinMeta.empty(); } if (fHaveCachedCoins) ((ParallelOpThreadPool*)threadPool)->PostTask([this]() { verifyCachedCoins(); }); if (fWalletJustUnlocked) pwalletMain->Lock(); } CSparkWallet::~CSparkWallet() { LOCK(cs_thread_pool); delete (ParallelOpThreadPool*)threadPool; threadPool = nullptr; } void CSparkWallet::FinishTasks() { LOCK(cs_thread_pool); if (threadPool) { ((ParallelOpThreadPool*)threadPool)->Shutdown(); } } void CSparkWallet::WaitForPendingTasks() { LOCK(cs_thread_pool); if (!threadPool) return; auto* pool = (ParallelOpThreadPool*)threadPool; if (pool->IsPoolShutdown()) return; pool->PostTask([]() {}).wait(); } void CSparkWallet::resetDiversifierFromDB(CWalletDB& walletdb) { LOCK(cs_spark_wallet); walletdb.readDiversifier(lastDiversifier); } void CSparkWallet::updatetDiversifierInDB(CWalletDB& walletdb) { LOCK(cs_spark_wallet); walletdb.writeDiversifier(lastDiversifier); } CAmount CSparkWallet::getFullBalance() { return getAvailableBalance() + getUnconfirmedBalance(); } std::pair CSparkWallet::getSparkBalance() { std::pair result = {0, 0}; LOCK(cs_spark_wallet); for (auto& it : coinMeta) { CSparkMintMeta mint = it.second; if (mint.isUsed) continue; // Not confirmed if (mint.nHeight >= 1) result.first += mint.v; else result.second += mint.v; } return result; } CAmount CSparkWallet::getAvailableBalance() { CAmount result = 0; LOCK(cs_spark_wallet); for (auto& it : coinMeta) { CSparkMintMeta mint = it.second; if (mint.isUsed) continue; // Not confirmed if (mint.nHeight < 1) continue; result += mint.v; } return result; } CAmount CSparkWallet::getUnconfirmedBalance() { CAmount result = 0; LOCK(cs_spark_wallet); for (auto& it : coinMeta) { CSparkMintMeta mint = it.second; if (mint.isUsed) continue; // Continue if confirmed if (mint.nHeight >= 1) continue; result += mint.v; } return result; } CAmount CSparkWallet::getAddressFullBalance(const spark::Address& address) { return getAddressAvailableBalance(address) + getAddressUnconfirmedBalance(address); } CAmount CSparkWallet::getAddressAvailableBalance(const spark::Address& address) { CAmount result = 0; LOCK(cs_spark_wallet); for (auto& it : coinMeta) { CSparkMintMeta mint = it.second; if (mint.isUsed) continue; // Not confirmed if (mint.nHeight < 1) continue; if (address.get_d() != mint.d) continue; result += mint.v; } return result; } CAmount CSparkWallet::getAddressUnconfirmedBalance(const spark::Address& address) { CAmount result = 0; LOCK(cs_spark_wallet); for (auto& it : coinMeta) { CSparkMintMeta mint = it.second; if (mint.isUsed) continue; // Not confirmed if (mint.nHeight >= 1) continue; if (address.get_d() != mint.d) continue; result += mint.v; } return result; } spark::Address CSparkWallet::generateNextAddress() { LOCK(cs_spark_wallet); lastDiversifier++; return spark::Address(viewKey, lastDiversifier); } spark::Address CSparkWallet::generateNewAddress() { LOCK(cs_spark_wallet); lastDiversifier++; spark::Address address(viewKey, lastDiversifier); addresses[lastDiversifier] = address; CWalletDB walletdb(strWalletFile); updatetDiversifierInDB(walletdb); return address; } spark::Address CSparkWallet::getDefaultAddress() { LOCK(cs_spark_wallet); if (addresses.count(0)) return addresses[0]; lastDiversifier = 0; return spark::Address(viewKey, lastDiversifier); } spark::Address CSparkWallet::getChangeAddress() { return spark::Address(viewKey, SPARK_CHANGE_D); } spark::SpendKey CSparkWallet::generateSpendKey(const spark::Params* params) { if (pwalletMain->IsLocked()) { LogPrintf("Spark spend key generation FAILED, wallet is locked\n"); throw WalletLocked(); } CKey secret; uint32_t nCount; { LOCK(pwalletMain->cs_wallet); nCount = GetArg("-sparkncount", DEFAULT_SPARK_NCOUNT); pwalletMain->GetKeyFromKeypath(BIP44_SPARK_INDEX, nCount, secret); } std::string nCountStr = std::to_string(nCount); CHash256 hasher; std::string prefix = "r_generation"; hasher.Write(reinterpret_cast(prefix.c_str()), prefix.size()); hasher.Write(secret.begin(), secret.size()); hasher.Write(reinterpret_cast(nCountStr.c_str()), nCountStr.size()); unsigned char hash[CSHA256::OUTPUT_SIZE]; hasher.Finalize(hash); secp_primitives::Scalar r; r.memberFromSeed(hash); spark::SpendKey key(params, r); return key; } spark::FullViewKey CSparkWallet::generateFullViewKey(const spark::SpendKey& spend_key) { return spark::FullViewKey(spend_key); } spark::IncomingViewKey CSparkWallet::generateIncomingViewKey(const spark::FullViewKey& full_view_key) { viewKey = spark::IncomingViewKey(full_view_key); return viewKey; } std::unordered_map CSparkWallet::getAllAddresses() { LOCK(cs_spark_wallet); return addresses; } spark::Address CSparkWallet::getAddress(const int32_t& i) { LOCK(cs_spark_wallet); if (lastDiversifier < i || addresses.count(i) == 0) return spark::Address(viewKey, i); return addresses[i]; } bool CSparkWallet::isAddressMine(const std::string& encodedAddr) { const spark::Params* params = spark::Params::get_default(); spark::Address address(params); try { address.decode(encodedAddr); } catch (const std::exception &) { return false; } return isAddressMine(address); } bool CSparkWallet::isAddressMine(const spark::Address& address) { LOCK(cs_spark_wallet); uint64_t d; try { d = viewKey.get_diversifier(address.get_d()); } catch (const std::exception &) { return false; } spark::Address newAddr = d <= static_cast(std::numeric_limits::max()) ? getAddress(static_cast(d)) : spark::Address(viewKey, d); if (newAddr.get_Q1() == address.get_Q1() && newAddr.get_Q2() == address.get_Q2()) return true; return false; } bool CSparkWallet::isChangeAddress(const uint64_t& i) const { return i == SPARK_CHANGE_D; } std::string CSparkWallet::SignMessage(const spark::Address& address, const std::string& message) { if (!isAddressMine(address)) throw std::runtime_error("Spark address does not belong to this wallet"); const spark::Params* params = spark::Params::get_default(); spark::SpendKey spendKey(params); try { spendKey = std::move(generateSpendKey(params)); } catch (const WalletLocked&) { throw; } catch (const std::exception&) { throw std::runtime_error("Unable to generate spend key"); } spark::OwnershipProof proof; spark::FullViewKey fullViewKey(spendKey); address.prove_own(spark::MessageScalar(message), spendKey, fullViewKey, proof); CDataStream proofStream(SER_NETWORK, PROTOCOL_VERSION); proofStream << proof; return HexStr(proofStream.begin(), proofStream.end()); } std::vector CSparkWallet::ListSparkMints(bool fUnusedOnly, bool fMatureOnly) const { std::vector setMints; LOCK(cs_spark_wallet); for (auto& it : coinMeta) { CSparkMintMeta mint = it.second; if (fUnusedOnly && mint.isUsed) continue; // Not confirmed if (fMatureOnly && mint.nHeight < 1) continue; setMints.push_back(mint); } return setMints; } std::list CSparkWallet::ListSparkSpends() const { std::list result; CWalletDB walletdb(strWalletFile); walletdb.ListSparkSpends(result); return result; } std::unordered_map CSparkWallet::getMintMap() const { LOCK(cs_spark_wallet); return coinMeta; } spark::Coin CSparkWallet::getCoinFromMeta(const CSparkMintMeta& meta) const { const spark::Params* params = spark::Params::get_default(); if (meta.coin != spark::Coin()) return meta.coin; spark::Address address(viewKey, meta.i); return spark::Coin(params, meta.type, meta.k, address, meta.v, meta.memo, meta.serial_context); } spark::Coin CSparkWallet::getCoinFromLTagHash(const uint256& lTagHash) const { LOCK(cs_spark_wallet); CSparkMintMeta meta; if (coinMeta.count(lTagHash)) { meta = coinMeta.at(lTagHash); return getCoinFromMeta(meta); } return spark::Coin(); } spark::Coin CSparkWallet::getCoinFromLTag(const GroupElement& lTag) const { uint256 lTagHash = primitives::GetLTagHash(lTag); return getCoinFromLTagHash(lTagHash); } void CSparkWallet::clearAllMints(CWalletDB& walletdb) { LOCK(cs_spark_wallet); for (auto& itr : coinMeta) { walletdb.EraseSparkMint(itr.first); } coinMeta.clear(); coinLookup.clear(); nonceLookup.clear(); lastDiversifier = 0; walletdb.writeDiversifier(lastDiversifier); } void CSparkWallet::eraseMint(const uint256& hash, CWalletDB& walletdb) { LOCK(cs_spark_wallet); walletdb.EraseSparkMint(hash); auto it = coinMeta.find(hash); if (it != coinMeta.end()) { removeFromLookups(hash, it->second); coinMeta.erase(it); } } void CSparkWallet::addOrUpdateMint(const CSparkMintMeta& mint, const uint256& lTagHash, CWalletDB& walletdb) { LOCK(cs_spark_wallet); if (cmp::greater(mint.i, lastDiversifier)) { lastDiversifier = mint.i; walletdb.writeDiversifier(lastDiversifier); } auto it = coinMeta.find(lTagHash); if (it != coinMeta.end()) removeFromLookups(lTagHash, it->second); coinMeta[lTagHash] = mint; addToLookups(lTagHash, mint); walletdb.WriteSparkMint(lTagHash, mint); } void CSparkWallet::updateMint(const CSparkMintMeta& mint, CWalletDB& walletdb) { LOCK(cs_spark_wallet); for (const auto& coin : coinMeta) { if (mint == coin.second) { addOrUpdateMint(mint, coin.first, walletdb); } } } void CSparkWallet::setCoinUnused(const GroupElement& lTag) { LOCK(cs_spark_wallet); CWalletDB walletdb(strWalletFile); uint256 lTagHash = primitives::GetLTagHash(lTag); CSparkMintMeta coinMeta = getMintMeta(lTagHash); if (coinMeta != CSparkMintMeta()) { coinMeta.isUsed = false; updateMint(coinMeta, walletdb); } } void CSparkWallet::updateMintInMemory(const CSparkMintMeta& mint) { LOCK(cs_spark_wallet); for (auto& itr : coinMeta) { if (itr.second == mint) { removeFromLookups(itr.first, itr.second); coinMeta[itr.first] = mint; addToLookups(itr.first, mint); break; } } } void CSparkWallet::addToLookups(const uint256& lTagHash, const CSparkMintMeta& mint) { if (mint.coin != spark::Coin()) coinLookup[primitives::GetSparkCoinHash(mint.coin)] = lTagHash; nonceLookup[mint.GetNonceHash()] = lTagHash; } void CSparkWallet::removeFromLookups(const uint256& lTagHash, const CSparkMintMeta& mint) { // Only drop entries still owned by this mint, so a colliding entry that // points at a surviving mint is left intact. if (mint.coin != spark::Coin()) { auto coinIt = coinLookup.find(primitives::GetSparkCoinHash(mint.coin)); if (coinIt != coinLookup.end() && coinIt->second == lTagHash) coinLookup.erase(coinIt); } auto nonceIt = nonceLookup.find(mint.GetNonceHash()); if (nonceIt != nonceLookup.end() && nonceIt->second == lTagHash) nonceLookup.erase(nonceIt); } const CSparkMintMeta* CSparkWallet::findMintMeta(const spark::Coin& coin) const { auto it = coinLookup.find(primitives::GetSparkCoinHash(coin)); if (it == coinLookup.end()) return nullptr; auto metaIt = coinMeta.find(it->second); if (metaIt == coinMeta.end()) return nullptr; const CSparkMintMeta& meta = metaIt->second; // Coin equality does not cover the serial context, but identification // depends on it; require both so a hit answers exactly as identify would. if (meta.coin != coin || meta.serial_context != coin.serial_context) return nullptr; if (fCacheAudit) { // Audit mode: reject the hit unless identification confirms the record try { spark::Coin coinCopy = coin; spark::IdentifiedCoinData data = coinCopy.identify(viewKey); if (data.k != meta.k || data.v != meta.v || data.i != meta.i || data.d != meta.d) { LogPrintf("CSparkWallet::%s: audit: cached mint %s diverges from identification\n", __func__, it->second.GetHex()); return nullptr; } } catch (const std::exception&) { LogPrintf("CSparkWallet::%s: audit: cached mint %s failed identification\n", __func__, it->second.GetHex()); return nullptr; } } return &meta; } size_t CSparkWallet::verifyCachedCoins() { std::vector> snapshot; { LOCK(cs_spark_wallet); snapshot.reserve(coinMeta.size()); for (const auto& it : coinMeta) { if (it.second.coin == spark::Coin()) continue; // only records that still hold a fast-path entry need verifying auto coinIt = coinLookup.find(primitives::GetSparkCoinHash(it.second.coin)); bool fIndexed = coinIt != coinLookup.end() && coinIt->second == it.first; if (!fIndexed) { auto nonceIt = nonceLookup.find(it.second.GetNonceHash()); fIndexed = nonceIt != nonceLookup.end() && nonceIt->second == it.first; } if (fIndexed) snapshot.push_back(it); } } // records that unspent balances display are the ones to confirm first std::stable_partition(snapshot.begin(), snapshot.end(), [](const std::pair& entry) { return !entry.second.isUsed; }); size_t evicted = 0; for (const auto& entry : snapshot) { if (ShutdownRequested() || (threadPool && ((ParallelOpThreadPool*)threadPool)->IsPoolShutdown())) break; const CSparkMintMeta& meta = entry.second; bool fValid = false; try { spark::Coin coin = meta.coin; spark::IdentifiedCoinData data = coin.identify(viewKey); fValid = data.k == meta.k && data.v == meta.v && data.i == meta.i && data.d == meta.d; } catch (const std::exception&) { fValid = false; } if (!fValid) { LOCK(cs_spark_wallet); auto it = coinMeta.find(entry.first); // evict only if the record has not changed since the snapshot if (it != coinMeta.end() && it->second == meta && it->second.coin == meta.coin) { removeFromLookups(entry.first, it->second); ++evicted; LogPrintf("CSparkWallet::%s: cached mint %s failed identification, lookup entries evicted\n", __func__, entry.first.GetHex()); } } } if (evicted > 0) LogPrintf("CSparkWallet::%s: verified %d cached mints, evicted %d from lookup indexes\n", __func__, snapshot.size(), evicted); return evicted; } bool CSparkWallet::validateLookupIndexes() const { LOCK(cs_spark_wallet); for (const auto& entry : coinLookup) { auto it = coinMeta.find(entry.second); if (it == coinMeta.end()) return false; if (primitives::GetSparkCoinHash(it->second.coin) != entry.first) return false; } for (const auto& entry : nonceLookup) { auto it = coinMeta.find(entry.second); if (it == coinMeta.end()) return false; if (it->second.GetNonceHash() != entry.first) return false; } for (const auto& entry : coinMeta) { if (entry.second.coin != spark::Coin() && !coinLookup.count(primitives::GetSparkCoinHash(entry.second.coin))) return false; if (!nonceLookup.count(entry.second.GetNonceHash())) return false; } return true; } CSparkMintMeta CSparkWallet::getMintMeta(const uint256& hash) { LOCK(cs_spark_wallet); if (coinMeta.count(hash)) return coinMeta[hash]; return CSparkMintMeta(); } CSparkMintMeta CSparkWallet::getMintMeta(const secp_primitives::Scalar& nonce) { LOCK(cs_spark_wallet); auto it = nonceLookup.find(primitives::GetNonceHash(nonce)); if (it != nonceLookup.end()) { auto metaIt = coinMeta.find(it->second); if (metaIt != coinMeta.end() && metaIt->second.k == nonce) return metaIt->second; } return CSparkMintMeta(); } bool CSparkWallet::getMintMeta(spark::Coin coin, CSparkMintMeta& mintMeta) { { LOCK(cs_spark_wallet); const CSparkMintMeta* meta = findMintMeta(coin); if (meta) { mintMeta = *meta; return true; } } spark::IdentifiedCoinData identifiedCoinData; try { identifiedCoinData = coin.identify(this->viewKey); } catch (...) { return false; } mintMeta = getMintMeta(identifiedCoinData.k); if(mintMeta == CSparkMintMeta()) return false; return true; } bool CSparkWallet::getMintAmount(spark::Coin coin, CAmount& amount) { { LOCK(cs_spark_wallet); const CSparkMintMeta* meta = findMintMeta(coin); if (meta) { amount = meta->v; return true; } } spark::IdentifiedCoinData identifiedCoinData; try { identifiedCoinData = coin.identify(this->viewKey); } catch (const std::exception &) { return false; } amount = identifiedCoinData.v; return true; } void CSparkWallet::UpdateSpendState(const GroupElement& lTag, const uint256& lTagHash, const uint256& txHash, bool fUpdateMint) { LOCK(cs_spark_wallet); if (coinMeta.count(lTagHash)) { auto mintMeta = coinMeta[lTagHash]; CSparkSpendEntry spendEntry; spendEntry.lTag = lTag; spendEntry.lTagHash = lTagHash; spendEntry.hashTx = txHash; spendEntry.amount = mintMeta.v; CWalletDB walletdb(strWalletFile); walletdb.WriteSparkSpendEntry(spendEntry); if (fUpdateMint) { mintMeta.isUsed = true; addOrUpdateMint(mintMeta, lTagHash, walletdb); } // pwalletMain->NotifyZerocoinChanged( // pwalletMain, // lTagHash.GetHex(), // std::string("used (") + std::to_string((double)mintMeta.v / COIN) + "mint)", // CT_UPDATED); } } void CSparkWallet::UpdateSpendState(const GroupElement& lTag, const uint256& txHash, bool fUpdateMint) { uint256 lTagHash = primitives::GetLTagHash(lTag); UpdateSpendState(lTag, lTagHash, txHash, fUpdateMint); } void CSparkWallet::UpdateSpendStateFromMempool(const std::vector& lTags, const uint256& txHash, bool fUpdateMint) { ((ParallelOpThreadPool*)threadPool)->PostTask([=, this]() { LOCK2(cs_main, cs_spark_wallet); if (!mempool.exists(txHash) && !txpools.getStemTxPool().exists(txHash)) return; for (const auto& lTag : lTags) { uint256 lTagHash = primitives::GetLTagHash(lTag); if (coinMeta.count(lTagHash)) { UpdateSpendState(lTag, lTagHash, txHash, fUpdateMint); } } }); } void CSparkWallet::UpdateSpendStateFromBlock(const CBlock& block) { std::vector vtxCopy = block.vtx; const uint256 blockHash = block.GetHash(); ((ParallelOpThreadPool*)threadPool)->PostTask([=, this]() { LOCK2(cs_main, cs_spark_wallet); auto it = mapBlockIndex.find(blockHash); if (it == mapBlockIndex.end() || !chainActive.Contains(it->second)) return; for (const auto& tx : vtxCopy) { if (tx->IsSparkSpend()) { try { spark::SpendTransaction spend = spark::ParseSparkSpend(*tx); const auto& txLTags = spend.getUsedLTags(); for (const auto& txLTag : txLTags) { uint256 txHash = tx->GetHash(); uint256 lTagHash = primitives::GetLTagHash(txLTag); UpdateSpendState(txLTag, lTagHash, txHash); } } catch (const std::exception &) { } } } }); } bool CSparkWallet::isMine(spark::Coin coin) const { { LOCK(cs_spark_wallet); if (findMintMeta(coin)) return true; } try { spark::IdentifiedCoinData identifiedCoinData = coin.identify(this->viewKey); } catch (const std::exception &) { return false; } return true; } bool CSparkWallet::isMine(const std::vector& lTags) const { LOCK(cs_spark_wallet); for (const auto& lTag : lTags) { uint256 lTagHash = primitives::GetLTagHash(lTag); if (coinMeta.count(lTagHash)) { return true; } } return false; } CAmount CSparkWallet::getMyCoinV(spark::Coin coin) const { { LOCK(cs_spark_wallet); const CSparkMintMeta* meta = findMintMeta(coin); if (meta) return meta->v; } CAmount v(0); try { spark::IdentifiedCoinData identifiedCoinData = coin.identify(this->viewKey); v = identifiedCoinData.v; } catch (const std::runtime_error& e) { //don nothing } return v; } bool CSparkWallet::getMyCoinIsChange(spark::Coin coin) const { { LOCK(cs_spark_wallet); const CSparkMintMeta* meta = findMintMeta(coin); if (meta) return isChangeAddress(meta->i); } try { spark::IdentifiedCoinData identifiedCoinData = coin.identify(this->viewKey); return isChangeAddress(identifiedCoinData.i); } catch (const std::runtime_error& e) { return false; } } spark::Address CSparkWallet::getMyCoinAddress(spark::Coin coin) { { LOCK(cs_spark_wallet); const CSparkMintMeta* meta = findMintMeta(coin); if (meta) return getAddress(int32_t(meta->i)); } spark::Address address; try { spark::IdentifiedCoinData identifiedCoinData = coin.identify(this->viewKey); address = getAddress(int32_t(identifiedCoinData.i)); } catch (const std::runtime_error& e) { // do nothing } return address; } CAmount CSparkWallet::getMySpendAmount(const std::vector& lTags) const { CAmount result = 0; LOCK(cs_spark_wallet); for (const auto& lTag : lTags) { uint256 lTagHash = primitives::GetLTagHash(lTag); if (coinMeta.count(lTagHash)) { result += coinMeta.at(lTagHash).v; } } return result; } CSparkWallet::IdentifiedMint CSparkWallet::IdentifyMint(spark::Coin coin, const uint256& txHash) const { // These keys are initialized before the wallet worker starts and never change. const auto identified = coin.identify(viewKey); const auto recovered = coin.recover(fullViewKey, identified); IdentifiedMint mint{}; mint.meta.txid = txHash; mint.meta.i = identified.i; mint.meta.d = identified.d; mint.meta.v = identified.v; mint.meta.k = identified.k; mint.meta.memo = identified.memo; mint.meta.serial_context = coin.serial_context; mint.meta.type = coin.type; mint.meta.coin = std::move(coin); mint.lTag = recovered.T; return mint; } void CSparkWallet::RecordMint(IdentifiedMint mint, CWalletDB& walletdb) { LOCK2(cs_main, cs_spark_wallet); auto& mintMeta = mint.meta; auto* sparkState = spark::CSparkState::GetState(); const auto heightAndId = sparkState->GetMintedCoinHeightAndId(mintMeta.coin); mintMeta.nHeight = heightAndId.first; mintMeta.nId = heightAndId.second; mintMeta.isUsed = sparkState->IsUsedLTag(mint.lTag); uint256 spendTxHash; for (auto* pool : {&mempool, &txpools.getStemTxPool()}) { LOCK(pool->cs); if (pool->sparkState.HasLTag(mint.lTag)) { mintMeta.isUsed = true; spendTxHash = pool->sparkState.GetMempoolConflictingTxHash(mint.lTag); break; } } const uint256 lTagHash = primitives::GetLTagHash(mint.lTag); addOrUpdateMint(mintMeta, lTagHash, walletdb); // Preserve the confirmed spend's txid when neither pool contains it. if (!spendTxHash.IsNull()) { UpdateSpendState(mint.lTag, lTagHash, spendTxHash, false); } } void CSparkWallet::UpdateMintState(const std::vector& coins, const uint256& txHash, CWalletDB& walletdb) { for (auto coin : coins) { try { RecordMint(IdentifyMint(std::move(coin), txHash), walletdb); } catch (const std::runtime_error& e) { continue; } } } void CSparkWallet::UpdateMintStateFromMempool(const std::vector& coins, const uint256& txHash) { ((ParallelOpThreadPool*)threadPool)->PostTask([=, this]() mutable { std::vector mints; for (const auto& coin : coins) { try { mints.push_back(IdentifyMint(coin, txHash)); } catch (const std::runtime_error&) { continue; } } // Match block processing's lock order before consulting either pool. LOCK2(cs_main, cs_spark_wallet); if (!mempool.exists(txHash) && !txpools.getStemTxPool().exists(txHash)) return; CWalletDB walletdb(strWalletFile); for (auto& mint : mints) { try { RecordMint(std::move(mint), walletdb); } catch (const std::runtime_error&) { continue; } } }); } void CSparkWallet::UpdateMintStateFromBlock(const CBlock& block) { const uint256 blockHash = block.GetHash(); { LOCK2(cs_main, cs_spark_wallet); auto it = mapBlockIndex.find(blockHash); if (it == mapBlockIndex.end() || !chainActive.Contains(it->second)) return; // Confirm known mints before block notifications reach balance/spend callers. // Unknown outputs are still identified by the worker below. CWalletDB walletdb(strWalletFile); for (const auto& tx : block.vtx) { for (const auto& coin : spark::GetSparkMintCoins(*tx)) { const auto* known = findMintMeta(coin); if (!known) continue; auto mint = *known; std::tie(mint.nHeight, mint.nId) = spark::CSparkState::GetState()->GetMintedCoinHeightAndId(coin); const uint256 lTagHash = coinLookup.at(primitives::GetSparkCoinHash(coin)); addOrUpdateMint(mint, lTagHash, walletdb); } } } std::vector vtxCopy = block.vtx; ((ParallelOpThreadPool*)threadPool)->PostTask([=, this]() mutable { std::vector mints; for (const auto& tx : vtxCopy) { if (tx->IsSparkTransaction()) { auto coins = spark::GetSparkMintCoins(*tx); for (auto& coin : coins) { try { mints.push_back(IdentifyMint(std::move(coin), tx->GetHash())); } catch (const std::runtime_error&) { // Most outputs belong to other wallets. } } } } if (mints.empty()) return; // Identification can overlap a reorg. Only record mints still on the active chain. LOCK(cs_main); auto it = mapBlockIndex.find(blockHash); if (it == mapBlockIndex.end() || !chainActive.Contains(it->second)) return; std::set updatedTransactions; { LOCK(cs_spark_wallet); CWalletDB walletdb(strWalletFile); for (auto& mint : mints) { try { const uint256 txid = mint.meta.txid; RecordMint(std::move(mint), walletdb); updatedTransactions.insert(txid); } catch (const std::runtime_error&) { continue; } } } // Balance polling may have consumed the block notification during identification. // NotifyTransactionChanged requires cs_wallet; acquire it after releasing Spark's lock. LOCK(pwalletMain->cs_wallet); for (const auto& txid : updatedTransactions) pwalletMain->NotifyTransactionChanged(pwalletMain, txid, CT_UPDATED); }); } void CSparkWallet::RemoveSparkMints(const std::vector& mints) { LOCK(cs_spark_wallet); for (auto coin : mints) { try { spark::IdentifiedCoinData identifiedCoinData = coin.identify(this->viewKey); spark::RecoveredCoinData recoveredCoinData = coin.recover(this->fullViewKey, identifiedCoinData); CWalletDB walletdb(strWalletFile); uint256 lTagHash = primitives::GetLTagHash(recoveredCoinData.T); eraseMint(lTagHash, walletdb); } catch (const std::runtime_error &e) { continue; } } } void CSparkWallet::RemoveSparkSpends(const std::vector& lTags) { LOCK(cs_spark_wallet); CWalletDB walletdb(strWalletFile); for (const auto& lTag : lTags) { uint256 lTagHash = primitives::GetLTagHash(lTag); auto it = coinMeta.find(lTagHash); if (it != coinMeta.end()) { auto mintMeta = it->second; mintMeta.isUsed = false; addOrUpdateMint(mintMeta, lTagHash, walletdb); walletdb.EraseSparkSpendEntry(lTag); } } } void CSparkWallet::AbandonSparkMints(const std::vector& mints) { RemoveSparkMints(mints); } void CSparkWallet::AbandonSpends(const std::vector& spends) { RemoveSparkSpends(spends); } std::vector CSparkWallet::listAddressCoins(const int32_t& i, bool fUnusedOnly) { std::vector listMints; LOCK(cs_spark_wallet); for (auto& itr : coinMeta) { if (cmp::equal(itr.second.i, i)) { if (fUnusedOnly && itr.second.isUsed) continue; listMints.push_back(itr.second); } } return listMints; } std::vector CSparkWallet::CreateSparkMintRecipients( const std::vector& outputs, const std::vector& serial_context, bool generate) { const spark::Params* params = spark::Params::get_default(); // create spark mints, if generate is false, skip actual math operations spark::MintTransaction sparkMint(params, outputs, serial_context, generate); // verify if the mint is valid if (generate && !sparkMint.verify()) { throw std::runtime_error("Unable to validate spark mint."); } // get serialized coins, also a schnorr proof with first coin, std::vector serializedCoins = sparkMint.getMintedCoinsSerialized(); if (outputs.size() != serializedCoins.size()) throw std::runtime_error("Spark mint output number should be equal to required number."); std::vector results; results.reserve(outputs.size()); // serialize coins and put into scripts for (size_t i = 0; i < outputs.size(); i++) { // Create script for a coin CScript script; // opcode is inserted as 1 byte according to file script/script.h script << OP_SPARKMINT; script.insert(script.end(), serializedCoins[i].begin(), serializedCoins[i].end()); unsigned char network = spark::GetNetworkType(); std::string addr = outputs[i].address.encode(network); std::string memo = outputs[i].memo; const std::size_t max_memo_size = outputs[i].address.get_params()->get_memo_bytes(); if (memo.length() > max_memo_size) { throw std::runtime_error(strprintf("Memo exceeds maximum length of %d bytes", max_memo_size)); } CRecipient recipient = {script, CAmount(outputs[i].v), false, addr, memo}; results.emplace_back(recipient); } return results; } bool CSparkWallet::CreateSparkMintTransactions( const std::vector& outputs, std::vector>& wtxAndFee, CAmount& nAllFeeRet, std::list& reservekeys, int& nChangePosInOut, bool subtractFeeFromAmount, std::string& strFailReason, bool fSplit, const CCoinControl *coinControl, bool autoMintAll, const std::vector* transparentRecipients) { int nChangePosRequest = nChangePosInOut; // Create transaction template CWalletTx wtxNew; wtxNew.fTimeReceivedIsTxTime = true; wtxNew.BindWallet(pwalletMain); CMutableTransaction txNew; int nHeight = 0; { LOCK(cs_main); nHeight = chainActive.Height(); } txNew.nLockTime = nHeight; assert(txNew.nLockTime <= static_cast(nHeight)); assert(txNew.nLockTime < LOCKTIME_THRESHOLD); std::vector outputs_ = outputs; std::vector sendOutputs = transparentRecipients ? *transparentRecipients : std::vector{}; CAmount valueToMint = 0; CAmount valueToSend = 0; for (const auto& output : outputs_) { if (output.v > static_cast(MAX_MONEY - valueToMint)) { strFailReason = _("Spark mint amount out of range"); return false; } valueToMint += static_cast(output.v); } bool canAttachOpReturn = false; for (const CRecipient& recipient : sendOutputs) { if (recipient.nAmount < 0 || (recipient.nAmount == 0 && !recipient.scriptPubKey.IsUnspendable()) || !MoneyRange(recipient.nAmount) || valueToSend > MAX_MONEY - recipient.nAmount) { strFailReason = _("Transparent recipient amount out of range"); return false; } if (recipient.nAmount == 0) { if (!canAttachOpReturn) { strFailReason = _("Transparent metadata must follow a payment output"); return false; } canAttachOpReturn = false; } else { canAttachOpReturn = true; } valueToSend += recipient.nAmount; } if (valueToMint > MAX_MONEY - valueToSend) { strFailReason = _("Spark mint amount out of range"); return false; } CAmount totalValue = valueToMint + valueToSend; { LOCK2(cs_main, pwalletMain->cs_wallet); // CFeeRate::GetFee multiplies by transaction size before dividing by 1000. const CFeeRate maxSafeFeeRate(std::numeric_limits::max() / MAX_NEW_TX_WEIGHT); if (payTxFee < CFeeRate(0) || payTxFee > maxSafeFeeRate || (coinControl && coinControl->fOverrideFeeRate && (coinControl->nFeeRate < CFeeRate(0) || coinControl->nFeeRate > maxSafeFeeRate))) { strFailReason = _("Spark mint fee out of range"); return false; } { std::list cacheWtxs; // vector pairs for each transparent address std::vector>> valueAndUTXO; if (fSplit) { pwalletMain->AvailableCoinsForLMint(valueAndUTXO, coinControl); Shuffle(valueAndUTXO.begin(), valueAndUTXO.end(), FastRandomContext()); } else { std::vector vAvailableCoins; pwalletMain->AvailableCoins(vAvailableCoins, true, coinControl); CAmount balance = 0; for (auto& coin : vAvailableCoins) balance += coin.tx->tx->vout[coin.i].nValue; valueAndUTXO.emplace_back(std::make_pair(balance, vAvailableCoins)); } while (!valueAndUTXO.empty()) { // initialize CWalletTx wtx = wtxNew; CMutableTransaction tx = txNew; reservekeys.emplace_back(pwalletMain); auto &reservekey = reservekeys.back(); if (GetRandInt(10) == 0) tx.nLockTime = std::max(0, (int) tx.nLockTime - GetRandInt(100)); CAmount nFeeRet = 0; LogPrintf("nFeeRet=%d\n", nFeeRet); auto itr = valueAndUTXO.begin(); // CAmount valueToMintInTx = std::min( // ::Params().GetConsensus().nMaxValueLelantusMint, itr->first); CAmount valueToMintInTx = itr->first; if (!autoMintAll) { valueToMintInTx = std::min(valueToMintInTx, totalValue); } CAmount nValueToSelect, mintedValue; std::set> setCoins; bool skipCoin = false; CAmount sendValueInTx = 0; // Start with no fee and loop until there is enough fee while (true) { mintedValue = valueToMintInTx; if (subtractFeeFromAmount) nValueToSelect = mintedValue; else { if (nFeeRet > 0 && mintedValue > std::numeric_limits::max() - nFeeRet) { strFailReason = _("Spark mint fee out of range"); return false; } nValueToSelect = mintedValue + nFeeRet; } // if no enough coins in this group then subtract fee from mint if (nValueToSelect > itr->first && !subtractFeeFromAmount) { nValueToSelect = mintedValue; mintedValue -= nFeeRet; } if (!MoneyRange(mintedValue) || mintedValue == 0) { valueAndUTXO.erase(itr); skipCoin = true; break; } nChangePosInOut = nChangePosRequest; tx.vin.clear(); tx.vout.clear(); wtx.fFromMe = true; wtx.changes.clear(); setCoins.clear(); std::vector remainingOutputs = outputs_; std::vector singleTxOutputs; std::vector remainingSendOutputs = sendOutputs; std::vector singleTxSendOutputs; CAmount remainingRecipientValue = mintedValue; sendValueInTx = 0; if (autoMintAll) { spark::MintedCoinData mintedCoinData; mintedCoinData.v = mintedValue; mintedCoinData.memo = ""; mintedCoinData.address = getDefaultAddress(); singleTxOutputs.push_back(mintedCoinData); } else { uint64_t remainingMintValue = std::min( remainingRecipientValue, valueToMint); while (remainingMintValue > 0 && !remainingOutputs.empty()) { // Create the mint data and push into vector uint64_t singleMintValue = std::min(remainingMintValue, remainingOutputs.begin()->v); spark::MintedCoinData mintedCoinData; mintedCoinData.v = singleMintValue; mintedCoinData.address = remainingOutputs.begin()->address; mintedCoinData.memo = remainingOutputs.begin()->memo; singleTxOutputs.push_back(mintedCoinData); // subtract minted amount from remaining value remainingMintValue -= singleMintValue; remainingRecipientValue -= static_cast(singleMintValue); remainingOutputs.begin()->v -= singleMintValue; if (remainingOutputs.begin()->v == 0) remainingOutputs.erase(remainingOutputs.begin()); } while (remainingRecipientValue > 0 && !remainingSendOutputs.empty()) { if (remainingSendOutputs.begin()->nAmount == 0) { strFailReason = _("Transparent metadata lost its payment output"); return false; } const CAmount singleSendValue = remainingSendOutputs.begin()->nAmount; if (singleSendValue > remainingRecipientValue) break; CRecipient sendRecipient = remainingSendOutputs.front(); singleTxSendOutputs.push_back(std::move(sendRecipient)); remainingRecipientValue -= singleSendValue; sendValueInTx += singleSendValue; remainingSendOutputs.erase( remainingSendOutputs.begin()); while (!remainingSendOutputs.empty() && remainingSendOutputs.front().nAmount == 0) { singleTxSendOutputs.push_back( remainingSendOutputs.front()); remainingSendOutputs.erase( remainingSendOutputs.begin()); } } if (remainingRecipientValue > 0) { mintedValue -= remainingRecipientValue; remainingRecipientValue = 0; } if (mintedValue <= 0) { valueAndUTXO.erase(itr); skipCoin = true; break; } if (subtractFeeFromAmount) { nValueToSelect = mintedValue; } else { if (nFeeRet > 0 && mintedValue > std::numeric_limits::max() - nFeeRet) { strFailReason = _("Spark mint fee out of range"); return false; } nValueToSelect = mintedValue + nFeeRet; } } if (subtractFeeFromAmount) { const size_t outputCount = singleTxOutputs.size() + std::count_if( singleTxSendOutputs.begin(), singleTxSendOutputs.end(), [](const CRecipient& recipient) { return recipient.nAmount > 0; }); if (outputCount == 0) { strFailReason = _("Transaction amount too small"); return false; } const CAmount singleFee = nFeeRet / static_cast(outputCount); CAmount remainder = nFeeRet % static_cast(outputCount); for (size_t i = 0; i < singleTxOutputs.size(); ++i) { CAmount feeToSubtract = singleFee; if (i == 0 && remainder > 0) { feeToSubtract += remainder; remainder = 0; } if (cmp::less_equal(singleTxOutputs[i].v, feeToSubtract)) { strFailReason = _("Transaction amount too small"); return false; } singleTxOutputs[i].v -= feeToSubtract; } for (size_t i = 0; i < singleTxSendOutputs.size(); ++i) { if (singleTxSendOutputs[i].nAmount == 0) continue; CAmount feeToSubtract = singleFee; if (singleTxOutputs.empty() && remainder > 0) { feeToSubtract += remainder; remainder = 0; } if (cmp::less_equal( singleTxSendOutputs[i].nAmount, feeToSubtract)) { strFailReason = _("Transaction amount too small"); return false; } singleTxSendOutputs[i].nAmount -= feeToSubtract; } } // Generate dummy mint coins to save time std::vector serial_context; std::vector recipients; if (!singleTxOutputs.empty()) { recipients = CSparkWallet::CreateSparkMintRecipients( singleTxOutputs, serial_context, false); } recipients.insert( recipients.end(), singleTxSendOutputs.begin(), singleTxSendOutputs.end()); for (auto& recipient : recipients) { // vout to create mint CTxOut txout(recipient.nAmount, recipient.scriptPubKey); if (txout.IsDust(::minRelayTxFee)) { strFailReason = _("Transaction amount too small"); return false; } tx.vout.push_back(txout); } // Choose coins to use CAmount nValueIn = 0; if (!pwalletMain->SelectCoins(itr->second, nValueToSelect, setCoins, nValueIn, coinControl)) { if (nValueIn < nValueToSelect) { strFailReason = _("Insufficient funds"); } else { strFailReason = _("Unable to select coins for minting"); } return false; } double dPriority = 0; for (auto const &pcoin : setCoins) { CAmount nCredit = pcoin.first->tx->vout[pcoin.second].nValue; //The coin age after the next block (depth+1) is used instead of the current, //reflecting an assumption the user would accept a bit more delay for //a chance at a free transaction. //But mempool inputs might still be in the mempool, so their age stays 0 int age = pcoin.first->GetDepthInMainChain(); assert(age >= 0); if (age != 0) age += 1; dPriority += (double) nCredit * age; } CAmount nChange = nValueIn - nValueToSelect; if (nChange > 0) { // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-bitcoin-address CScript scriptChange; // coin control: send change to custom address if (coinControl && !boost::get(&coinControl->destChange)) scriptChange = GetScriptForDestination(coinControl->destChange); // send change to one of the specified change addresses else if (IsArgSet("-change") && mapMultiArgs.at("-change").size() > 0) { CBitcoinAddress address( mapMultiArgs.at("-change")[GetRandInt(mapMultiArgs.at("-change").size())]); CKeyID keyID; if (!address.GetKeyID(keyID)) { strFailReason = _("Bad change address"); return false; } scriptChange = GetScriptForDestination(keyID); } // no coin control: send change to newly generated address else { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. // Reserve a new key pair from key pool CPubKey vchPubKey; bool ret; ret = reservekey.GetReservedKey(vchPubKey); if (!ret) { strFailReason = _("Keypool ran out, please call keypoolrefill first"); return false; } scriptChange = GetScriptForDestination(vchPubKey.GetID()); } CTxOut newTxOut(nChange, scriptChange); // Never create dust outputs; if we would, just // add the dust to the fee. if (newTxOut.IsDust(::minRelayTxFee)) { nChangePosInOut = -1; nFeeRet += nChange; reservekey.ReturnKey(); } else { if (nChangePosInOut == -1) { // Insert change txn at random position: nChangePosInOut = GetRandInt(tx.vout.size() + 1); } else if ((unsigned int) nChangePosInOut > tx.vout.size()) { strFailReason = _("Change index out of range"); return false; } std::vector::iterator position = tx.vout.begin() + nChangePosInOut; tx.vout.insert(position, newTxOut); wtx.changes.insert(static_cast(nChangePosInOut)); } } else { reservekey.ReturnKey(); } // Fill vin // // Note how the sequence number is set to max()-1 so that the // nLockTime set above actually works. for (const auto &coin : setCoins) { tx.vin.push_back(CTxIn( coin.first->GetHash(), coin.second, CScript(), std::numeric_limits::max() - 1)); } // Fill in dummy signatures for fee calculation. if (!pwalletMain->DummySignTx(tx, setCoins)) { strFailReason = _("Signing transaction failed"); return false; } unsigned int nBytes = GetVirtualTransactionSize(tx); // Limit size CTransaction txConst(tx); if (GetTransactionWeight(txConst) >= MAX_NEW_TX_WEIGHT) { strFailReason = _("Transaction is too large (size limit: 250Kb). Select fewer inputs. If many inputs belong to one transparent address, use File > Consolidate outputs in the GUI or the consolidateaddress RPC, then retry after confirmation."); return false; } dPriority = txConst.ComputePriority(dPriority, nBytes); // Remove scriptSigs to eliminate the fee calculation dummy signatures for (auto &vin : tx.vin) { vin.scriptSig = CScript(); vin.scriptWitness.SetNull(); } // Can we complete this as a free transaction? if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) { // Not enough fee: enough priority? double dPriorityNeeded = mempool.estimateSmartPriority(nTxConfirmTarget); // Require at least hard-coded AllowFree. if (dPriority >= dPriorityNeeded && AllowFree(dPriority)) break; } CAmount nFeeNeeded = CWallet::GetMinimumFee(nBytes, nTxConfirmTarget, mempool); if (coinControl && nFeeNeeded > 0 && coinControl->nMinimumTotalFee > nFeeNeeded) { nFeeNeeded = coinControl->nMinimumTotalFee; } if (coinControl && coinControl->fOverrideFeeRate) nFeeNeeded = coinControl->nFeeRate.GetFee(nBytes); // If we made it here and we aren't even able to meet the relay fee on the next pass, give up // because we must be at the maximum allowed fee. if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes)) { strFailReason = _("Transaction too large for fee policy"); return false; } if (nFeeRet >= nFeeNeeded) { for (auto &usedCoin : setCoins) { for (auto coin = itr->second.begin(); coin != itr->second.end(); coin++) { if (usedCoin.first == coin->tx && cmp::equal(usedCoin.second, coin->i)) { itr->first -= coin->tx->tx->vout[coin->i].nValue; itr->second.erase(coin); break; } } } if (itr->second.empty()) { valueAndUTXO.erase(itr); } // Generate real mint coins CDataStream serialContextStream(SER_NETWORK, PROTOCOL_VERSION); for (auto& input : tx.vin) { serialContextStream << input; } recipients = CSparkWallet::CreateSparkMintRecipients(singleTxOutputs, std::vector(serialContextStream.begin(), serialContextStream.end()), true); size_t i = 0; for (auto& recipient : recipients) { CTxOut txout(recipient.nAmount, recipient.scriptPubKey); LogPrintf("txout: %s\n", txout.ToString()); while (i < tx.vout.size()) { if (tx.vout[i].scriptPubKey.IsSparkMint()) { tx.vout[i] = txout; CSparkOutputTx output; output.address = recipient.address; output.amount = recipient.nAmount; output.memo = recipient.memo; wtx.pendingSparkOutputRecords.emplace_back( recipient.scriptPubKey, std::move(output)); break; } ++i; } ++i; } //remove output from outputs_ vector if it got all requested value outputs_ = remainingOutputs; sendOutputs = remainingSendOutputs; break; // Done, enough fee included. } // Include more fee and try again. nFeeRet = nFeeNeeded; continue; } if (skipCoin) { reservekey.ReturnKey(); reservekeys.pop_back(); continue; } if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) { // Lastly, ensure this tx will pass the mempool's chain limits LockPoints lp; CTxMemPoolEntry entry(MakeTransactionRef(tx), 0, 0, 0, 0, false, 0, lp); CTxMemPool::setEntries setAncestors; size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000; size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT); size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000; std::string errString; if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) { strFailReason = _("Transaction has too long of a mempool chain"); return false; } } // Sign int nIn = 0; CTransaction txNewConst(tx); for (const auto &coin : setCoins) { bool signSuccess = false; const CScript &scriptPubKey = coin.first->tx->vout[coin.second].scriptPubKey; SignatureData sigdata; signSuccess = ProduceSignature(TransactionSignatureCreator(pwalletMain, &txNewConst, nIn, coin.first->tx->vout[coin.second].nValue, SIGHASH_ALL), scriptPubKey, sigdata); if (!signSuccess) { strFailReason = _("Signing transaction failed"); return false; } else { UpdateTransaction(tx, nIn, sigdata); } nIn++; } { CValidationState state; if (!mempool.IsTransactionAllowed(*wtx.tx, state)) { strFailReason = _("Transaction not allowed in mempool"); return false; } } wtx.SetTx(MakeTransactionRef(std::move(tx))); wtxAndFee.push_back(std::make_pair(wtx, nFeeRet)); if (nChangePosInOut >= 0) { // Cache wtx to somewhere because COutput use pointer of it. cacheWtxs.push_back(wtx); auto &wtx = cacheWtxs.back(); COutput out(&wtx, nChangePosInOut, wtx.GetDepthInMainChain(false), true, true); auto val = wtx.tx->vout[nChangePosInOut].nValue; bool added = false; for (auto &utxos : valueAndUTXO) { if (utxos.second.empty()) continue; auto const &o = utxos.second.front(); if (o.tx->tx->vout[o.i].scriptPubKey == wtx.tx->vout[nChangePosInOut].scriptPubKey) { utxos.first += val; utxos.second.push_back(out); added = true; break; } } if (!added) { valueAndUTXO.push_back({val, {out}}); } } nAllFeeRet += nFeeRet; if (!autoMintAll) { valueToMint -= mintedValue - sendValueInTx; valueToSend -= sendValueInTx; totalValue -= mintedValue; if (totalValue == 0) break; } } } } if (!autoMintAll && (valueToMint > 0 || valueToSend > 0)) { if (valueToSend > 0) { strFailReason = _( "Unable to fund all transparent recipients without splitting an output. " "Consolidate transparent funds or reduce the payment amounts"); } else { strFailReason = _( "Unable to mint full amount; only partial minting was possible"); } return false; } return true; } bool getIndex(const spark::Coin& coin, const std::vector& anonymity_set, size_t& index) { for (std::size_t j = 0; j < anonymity_set.size(); ++j) { if (anonymity_set[j] == coin){ index = j; return true; } } return false; } CWalletTx CSparkWallet::CreateSparkSpendTransaction( const std::vector& recipients, const std::vector>& privateRecipients, CAmount &fee, const CCoinControl *coinControl, size_t additionalTxSize, const uint256& extensionCommitment, int expectedNextBlockHeight, std::vector* recipientAmounts) { if (recipients.empty() && privateRecipients.empty()) { throw std::runtime_error(_("Either recipients or newMints has to be nonempty.")); } const auto &consensusParams = Params().GetConsensus(); if (privateRecipients.size() >= (consensusParams.nMaxSparkOutLimitPerTx - 1)) throw std::runtime_error(_("Spark shielded output limit exceeded.")); // calculate total value to spend CAmount vOut = 0; CAmount mintVOut = 0; unsigned recipientsToSubtractFee = 0; for (size_t i = 0; i < recipients.size(); i++) { auto& recipient = recipients[i]; if (recipient.scriptPubKey.IsPayToExchangeAddress()) { throw std::runtime_error("Exchange addresses cannot receive private funds. Please transfer your funds to a transparent address first before sending to an Exchange address"); } if (!MoneyRange(recipient.nAmount) || recipient.nAmount > MAX_MONEY - vOut) { throw std::runtime_error(boost::str( boost::format(_("Recipient %1% has invalid amount")) % i)); } vOut += recipient.nAmount; if (recipient.fSubtractFeeFromAmount) { recipientsToSubtractFee++; } } for (const auto& privRecipient : privateRecipients) { if (privRecipient.first.v > static_cast(MAX_MONEY) || static_cast(privRecipient.first.v) > MAX_MONEY - mintVOut) { throw std::runtime_error(_( "Private recipient has invalid amount")); } mintVOut += static_cast(privRecipient.first.v); if (privRecipient.second) { recipientsToSubtractFee++; } } if (mintVOut > MAX_MONEY - vOut) { throw std::runtime_error(_( "Spark spend output amount is out of range")); } std::vector result; CWalletTx wtxNew; CMutableTransaction tx; wtxNew.fTimeReceivedIsTxTime = true; wtxNew.BindWallet(pwalletMain); const spark::Params* params = spark::Params::get_default(); spark::SpendKey spendKey(params); spark::FullViewKey fullViewKeySnapshot; int nHeight = 0; uint256 expectedTipHash; bool useChaumV2 = false; bool enforceBoundCoverSetHash = false; uint64_t transparentOut = 0; std::vector selectedCoins; std::vector privOutputs; std::vector inputs; std::map idAndBlockHashes; std::unordered_map cover_set_data; std::unordered_map> cover_sets; std::vector finalRecipients = recipients; std::vector> finalPrivateRecipients = privateRecipients; std::vector finalRecipientAmounts; { LOCK2(cs_main, pwalletMain->cs_wallet); nHeight = chainActive.Height(); expectedTipHash = chainActive.Tip() ? chainActive.Tip()->GetBlockHash() : uint256(); if (expectedNextBlockHeight >= 0 && expectedNextBlockHeight != nHeight + 1) { throw std::runtime_error(_( "Chain height changed during Spark transaction construction; retry")); } useChaumV2 = nHeight + 1 >= consensusParams.nSparkChaumV2StartBlock; enforceBoundCoverSetHash = nHeight + 1 >= consensusParams.nSparkChaumV2StartBlock - 10; fullViewKeySnapshot = fullViewKey; if (vOut > consensusParams.GetMaxValueSparkSpendPerTransaction(nHeight + 1)) throw std::runtime_error(_("Spend to transparent address limit exceeded.")); // Discourage fee sniping. // // For a large miner the value of the transactions in the best block and // the mempool can exceed the cost of deliberately attempting to mine two // blocks to orphan the current best block. By setting nLockTime such that // only the next block can include the transaction, we discourage this // practice as the height restricted and limited blocksize gives miners // considering fee sniping fewer options for pulling off this attack. // // A simple way to think about this is from the wallet's point of view we // always want the blockchain to move forward. By setting nLockTime this // way we're basically making the statement that we only want this // transaction to appear in the next block; we don't want to potentially // encourage reorgs by allowing transactions to appear at lower heights // than the next block in forks of the best chain. // // Of course, the subsidy is high enough, and transaction volume low // enough, that fee sniping isn't a problem yet, but by implementing a fix // now we ensure code won't be written that makes assumptions about // nLockTime that preclude a fix later. tx.nLockTime = nHeight; // Secondly occasionally randomly pick a nLockTime even further back, so // that transactions that are delayed after signing for whatever reason, // e.g. high-latency mix networks and some CoinJoin implementations, have // better privacy. if (GetRandInt(10) == 0) { tx.nLockTime = std::max(0, static_cast(tx.nLockTime) - GetRandInt(100)); } assert(tx.nLockTime <= static_cast(nHeight)); assert(tx.nLockTime < LOCKTIME_THRESHOLD); { std::list coins = GetAvailableSparkCoins(coinControl); std::pair> estimated; try { estimated = SelectSparkCoins( vOut + mintVOut, recipientsToSubtractFee, coins, privateRecipients.size(), recipients.size(), coinControl, useChaumV2, additionalTxSize); } catch (const InsufficientFunds& error) { if (error.GetRequiredFee() > 0) { fee = error.GetRequiredFee(); } throw; } selectedCoins = std::move(estimated.second); // V1 construction retains the single-input selection rule. if (!useChaumV2 && selectedCoins.size() != 1) { throw InsufficientFunds(_( "Spark multi-input spends are temporarily disabled. " "No single available Spark coin can fund this transaction.")); } bool remainderSubtracted = false; fee = estimated.first; const CAmount feePerRecipient = recipientsToSubtractFee > 0 ? fee / recipientsToSubtractFee : 0; const CAmount feeRemainder = recipientsToSubtractFee > 0 ? fee % recipientsToSubtractFee : 0; for (size_t i = 0; i < finalRecipients.size(); i++) { auto &recipient = finalRecipients[i]; if (recipient.fSubtractFeeFromAmount) { CAmount feeToSubtract = feePerRecipient; if (!remainderSubtracted) { // First receiver pays the remainder not divisible by output count. feeToSubtract += feeRemainder; } if (cmp::less_equal(recipient.nAmount, feeToSubtract)) { throw std::runtime_error(boost::str( boost::format(_("Amount for recipient %1% is too small to send after the fee has been deducted")) % i)); } // Subtract fee equally from each selected recipient. recipient.nAmount -= feeToSubtract; remainderSubtracted = true; } } for (size_t i = 0; i < finalPrivateRecipients.size(); i++) { auto &privateRecipient = finalPrivateRecipients[i]; if (privateRecipient.second) { CAmount feeToSubtract = feePerRecipient; if (!remainderSubtracted) { // First receiver pays the remainder not divisible by output count. feeToSubtract += feeRemainder; } if (cmp::less_equal(privateRecipient.first.v, feeToSubtract)) { throw std::runtime_error(boost::str( boost::format(_("Amount for private recipient %1% is too small to send after the fee has been deducted")) % i)); } // Subtract fee equally from each selected recipient. privateRecipient.first.v -= feeToSubtract; remainderSubtracted = true; } } spark::CSparkState *sparkState = spark::CSparkState::GetState(); try { spendKey = std::move(generateSpendKey(params)); } catch (const WalletLocked&) { throw std::runtime_error(_("Unable to generate spend key, wallet is locked.")); } catch (const std::exception&) { throw std::runtime_error(_("Unable to generate spend key.")); } tx.vin.clear(); tx.vout.clear(); wtxNew.fFromMe = true; wtxNew.changes.clear(); CAmount spendInCurrentTx = 0; for (auto& spendCoin : selectedCoins) spendInCurrentTx += spendCoin.v; spendInCurrentTx -= fee; transparentOut = 0; // fill outputs for (size_t i = 0; i < finalRecipients.size(); i++) { auto& recipient = finalRecipients[i]; if (recipient.nAmount == 0) continue; CTxOut vout(recipient.nAmount, recipient.scriptPubKey); if (vout.IsDust(minRelayTxFee)) { std::string err; if (recipient.fSubtractFeeFromAmount && fee > 0) { if (vout.nValue < 0) { err = boost::str(boost::format(_("Amount for recipient %1% is too small to pay the fee")) % i); } else { err = boost::str(boost::format(_("Amount for recipient %1% is too small to send after the fee has been deducted")) % i); } } else { err = boost::str(boost::format(_("Amount for recipient %1% is too small")) % i); } throw std::runtime_error(err); } transparentOut += vout.nValue; tx.vout.push_back(vout); } spendInCurrentTx -= transparentOut; privOutputs.clear(); // fill outputs for (size_t i = 0; i < finalPrivateRecipients.size(); i++) { auto& recipient = finalPrivateRecipients[i]; if (recipient.first.v == 0) continue; CAmount recipientAmount = recipient.first.v; spendInCurrentTx -= recipientAmount; spark::OutputCoinData output = recipient.first; output.v = recipientAmount; privOutputs.push_back(output); } if (spendInCurrentTx < 0) throw std::invalid_argument(_("Unable to create spend transaction.")); if (!privOutputs.size() || spendInCurrentTx > 0) { spark::OutputCoinData output; output.address = getChangeAddress(); output.memo = ""; if (spendInCurrentTx > 0) output.v = spendInCurrentTx; else output.v = 0; wtxNew.changes.insert(static_cast(tx.vout.size() + privOutputs.size())); privOutputs.push_back(output); } // fill inputs uint32_t sequence = CTxIn::SEQUENCE_FINAL; CScript script; script << OP_SPARKSPEND; tx.vin.emplace_back(COutPoint(), script, sequence); // clear vExtraPayload to calculate metadata hash correctly tx.vExtraPayload.clear(); // set correct type of transaction (this affects metadata hash) tx.nVersion = 3; tx.nType = useChaumV2 ? TRANSACTION_SPARK_V2 : TRANSACTION_SPARK; // now every field is populated then we can sign transaction // We will write this into cover set representation, with anonymity set hash uint256 sig = tx.GetHash(); inputs.clear(); idAndBlockHashes.clear(); cover_set_data.clear(); cover_sets.clear(); for (auto& coin : selectedCoins) { spark::CSparkState::SparkCoinGroupInfo nextCoinGroupInfo; uint64_t groupId = coin.nId; if (cmp::greater(sparkState->GetLatestCoinID(), groupId) && sparkState->GetCoinGroupInfo(groupId + 1, nextCoinGroupInfo)) { if (nextCoinGroupInfo.firstBlock->nHeight <= coin.nHeight) groupId += 1; } if (cover_set_data.count(groupId) == 0) { std::vector set; uint256 blockHash; std::vector setHash; if (sparkState->GetCoinSetForSpend( &chainActive, chainActive.Height() - (ZC_MINT_CONFIRMATIONS - 1), // required 1 confirmation for mint to spend groupId, blockHash, set, setHash) < 2) throw std::runtime_error( _("Has to have at least two mint coins with at least 1 confirmation in order to spend a coin")); if (enforceBoundCoverSetHash && setHash.size() != CSHA256::OUTPUT_SIZE) { throw std::runtime_error(_( "Selected Spark cover set is not yet bound to a canonical state hash")); } spark::CoverSetData coverSetData; coverSetData.cover_set_size = set.size(); coverSetData.cover_set_representation = setHash; coverSetData.cover_set_representation.insert(coverSetData.cover_set_representation.end(), sig.begin(), sig.end()); cover_set_data[groupId] = coverSetData; cover_sets[groupId] = set; idAndBlockHashes[groupId] = blockHash; } spark::InputCoinData inputCoinData; inputCoinData.cover_set_id = groupId; std::size_t index = 0; if (!getIndex(coin.coin, cover_sets[groupId], index)) throw std::runtime_error( _("No such coin in set")); inputCoinData.index = index; inputCoinData.v = coin.v; inputCoinData.k = coin.k; spark::IdentifiedCoinData identifiedCoinData; identifiedCoinData.i = coin.i; identifiedCoinData.d = coin.d; identifiedCoinData.v = coin.v; identifiedCoinData.k = coin.k; identifiedCoinData.memo = coin.memo; spark::RecoveredCoinData recoveredCoinData = coin.coin.recover(fullViewKeySnapshot, identifiedCoinData); inputCoinData.T = recoveredCoinData.T; inputCoinData.s = recoveredCoinData.s; inputs.push_back(inputCoinData); } } } if (recipientAmounts) { finalRecipientAmounts.reserve( finalRecipients.size() + finalPrivateRecipients.size()); for (const CRecipient& recipient : finalRecipients) { finalRecipientAmounts.push_back(recipient.nAmount); } for (const auto& recipient : finalPrivateRecipients) { finalRecipientAmounts.push_back( static_cast(recipient.first.v)); } } // Proof construction can be expensive for large input sets. All inputs and // their cover-set context above were captured from one tip while holding the // chain and wallet locks; validate the snapshot again before recording the // completed transaction below. spark::SpendTransaction spendTransaction( params, fullViewKeySnapshot, spendKey, inputs, cover_set_data, cover_sets, fee, transparentOut, privOutputs, useChaumV2 ? spark::SpendTransactionVersion::V2 : spark::SpendTransactionVersion::V1, useChaumV2 ? extensionCommitment : uint256(), idAndBlockHashes); CDataStream serialized(SER_NETWORK, PROTOCOL_VERSION); serialized << spendTransaction; tx.vExtraPayload.assign(serialized.begin(), serialized.end()); std::vector> outputRecords; size_t i = 0; const std::vector& outCoins = spendTransaction.getOutCoins(); unsigned char network = spark::GetNetworkType(); for (auto& outCoin : outCoins) { CDataStream serializedCoin(SER_NETWORK, PROTOCOL_VERSION); serializedCoin << outCoin; CScript script; script << OP_SPARKSMINT; script.insert( script.end(), serializedCoin.begin(), serializedCoin.end()); CSparkOutputTx output; output.address = privOutputs[i].address.encode(network); output.amount = privOutputs[i].v; output.memo = privOutputs[i].memo; outputRecords.emplace_back(script, output); tx.vout.push_back(CTxOut(0, script)); ++i; } if (GetTransactionWeight(tx) >= MAX_NEW_TX_WEIGHT) { throw std::runtime_error(_("Transaction is too large (size limit: 250Kb). Select less inputs or consolidate your UTXOs")); } { LOCK2(cs_main, pwalletMain->cs_wallet); const uint256 currentTipHash = chainActive.Tip() ? chainActive.Tip()->GetBlockHash() : uint256(); if (chainActive.Height() != nHeight || currentTipHash != expectedTipHash) { throw std::runtime_error(_( "Chain tip changed during Spark transaction construction; retry")); } const std::list availableCoins = GetAvailableSparkCoins(nullptr); for (const auto& selectedCoin : selectedCoins) { const bool stillAvailable = std::any_of( availableCoins.begin(), availableCoins.end(), [&selectedCoin](const CSparkMintMeta& availableCoin) { return availableCoin == selectedCoin; }); if (!stillAvailable) { throw std::runtime_error(_( "Spark coin selection changed during transaction construction; retry")); } } const unsigned size = GetVirtualTransactionSize(tx); const CAmount feeNeeded = CWallet::GetMinimumFee(size, coinControl, mempool); if (feeNeeded < minRelayTxFee.GetFee(size)) { throw std::invalid_argument(_("Transaction too large for fee policy")); } if (fee < feeNeeded) { throw std::invalid_argument(_("Not enough fee estimated")); } wtxNew.pendingSparkOutputRecords = std::move(outputRecords); wtxNew.SetTx(MakeTransactionRef(std::move(tx))); result.push_back(wtxNew); } if (extensionCommitment.IsNull()) { CValidationState state; for (CWalletTx& wtx : result) { if (!mempool.IsTransactionAllowed(*wtx.tx, state)) throw std::invalid_argument(_("Spark transactions are disabled at the moment")); } } if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) { // Lastly, ensure this tx will pass the mempool's chain limits size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000; size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT); size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000; std::string errString; for (CWalletTx& wtx : result) { LockPoints lp; CTxMemPoolEntry entry(wtx.tx, 0, 0, 0, 0, false, 0, lp); CTxMemPool::setEntries setAncestors; if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) { throw std::runtime_error(_("Transaction has too long of a mempool chain")); } } } if (recipientAmounts) { *recipientAmounts = std::move(finalRecipientAmounts); } return wtxNew; } CWalletTx CSparkWallet::CreateSparkNameTransaction( CSparkNameTxData &nameData, CAmount sparkNameFee, CAmount &txFee, const CCoinControl *coinConrol, int expectedNextBlockHeight) { CSparkNameManager *sparkNameManager = CSparkNameManager::GetInstance(); const auto &consensusParams = Params().GetConsensus(); // Use the next-block height: this transaction will be validated at chainActive.Height() + 1, // so all height-gated decisions (fee script, inputsHash) must match that height to avoid // building a transaction the mempool immediately rejects on the activation boundary. int nHeight; uint256 expectedTipHash; { LOCK(cs_main); nHeight = chainActive.Height() + 1; if (expectedNextBlockHeight >= 0 && expectedNextBlockHeight != nHeight) { throw std::runtime_error(_( "Chain height changed during Spark name construction; retry")); } if (!chainActive.Tip()) { throw std::runtime_error(_( "Chain tip is unavailable during Spark name construction")); } expectedTipHash = chainActive.Tip()->GetBlockHash(); // Spark Name state is updated on connect/disconnect under cs_main. // Prepare from the same immutable chain snapshot used for format and // fee selection so reconnect cannot race the name lookup. sparkNameManager->PrepareSparkNameTxData(nameData, nHeight); } std::string payoutAddress = nHeight >= consensusParams.stage41StartBlockDevFundAddressChange ? consensusParams.stage3CommunityFundAddress : consensusParams.stage3DevelopmentFundAddress; CRecipient devPayout; devPayout.nAmount = sparkNameFee; devPayout.scriptPubKey = CSparkNameManager::GetSparkNameFeeScript(payoutAddress, nameData.name, nameData.sparkAddress); devPayout.fSubtractFeeFromAmount = false; const bool useChaumV2 = nHeight >= consensusParams.nSparkChaumV2StartBlock; const uint256 extensionCommitment = useChaumV2 ? CSparkNameManager::GetSparkNameCommitment(nameData) : uint256(); const spark::Params* params = spark::Params::get_default(); spark::SpendKey spendKey(params); try { spendKey = std::move(generateSpendKey(params)); } catch (const WalletLocked&) { throw std::runtime_error(_("Unable to generate spend key, wallet is locked.")); } catch (const std::exception&) { throw std::runtime_error(_("Unable to generate spend key.")); } spark::Address address(spark::Params::get_default()); try { address.decode(nameData.sparkAddress); } catch (std::exception& e) { throw std::runtime_error(_("Invalid spark address")); } if (!isAddressMine(address)) throw std::runtime_error(_("Spark address doesn't belong to the wallet")); size_t additionalTxSize = sparkNameManager->GetSparkNameTxDataSize(nameData) + 20; for (unsigned int attempt = 0; attempt < 8; ++attempt) { CWalletTx wtxSparkSpend = CreateSparkSpendTransaction( {devPayout}, {}, txFee, coinConrol, additionalTxSize, extensionCommitment, nHeight); CMutableTransaction tx(*wtxSparkSpend.tx); sparkNameManager->AppendSparkNameTxData( tx, nameData, spendKey, viewKey, nHeight); const unsigned int finalSize = GetVirtualTransactionSize(tx); const CAmount finalFeeNeeded = CWallet::GetMinimumFee(finalSize, coinConrol, mempool); if (finalFeeNeeded < minRelayTxFee.GetFee(finalSize)) { throw std::invalid_argument(_( "Transaction too large for fee policy")); } if (txFee < finalFeeNeeded) { // The ownership proof is appended after the Spark spend commits // to its fee. Rebuild with more payload headroom so the proof and // selected fee agree on the final serialized size. if (additionalTxSize > std::numeric_limits::max() - 64) { throw std::invalid_argument(_( "Spark name transaction size is out of range")); } additionalTxSize += 64; continue; } wtxSparkSpend.tx = MakeTransactionRef(std::move(tx)); { LOCK(cs_main); if (!chainActive.Tip() || chainActive.Height() + 1 != nHeight || chainActive.Tip()->GetBlockHash() != expectedTipHash) { throw std::runtime_error(_( "Chain tip changed during Spark name construction; retry")); } } CValidationState state; if (!mempool.IsTransactionAllowed(*wtxSparkSpend.tx, state)) { throw std::invalid_argument(_( "Unable to create a valid Spark name transaction")); } return wtxSparkSpend; } throw std::invalid_argument(_( "Unable to estimate the final Spark name transaction fee")); } template static CAmount CalculateBalance(Iterator begin, Iterator end) { CAmount balance(0); for (auto itr = begin; itr != end; itr++) { balance += itr->v; } return balance; } bool GetCoinsToSpend( CAmount required, std::vector& coinsToSpend_out, std::list coins, int64_t& changeToMint, const CCoinControl *coinControl) { CAmount availableBalance = CalculateBalance(coins.begin(), coins.end()); if (required > availableBalance) { throw InsufficientFunds(); } // sort by biggest amount. if it is same amount we will prefer the older block auto comparer = [](const CSparkMintMeta& a, const CSparkMintMeta& b) -> bool { return a.v != b.v ? a.v > b.v : a.nHeight < b.nHeight; }; coins.sort(comparer); CAmount spend_val(0); std::list coinsToSpend; // If coinControl, want to use all inputs bool coinControlUsed = false; if (coinControl != NULL) { if (coinControl->HasSelected()) { auto coinIt = coins.rbegin(); for (; coinIt != coins.rend(); coinIt++) { spend_val += coinIt->v; } coinControlUsed = true; coinsToSpend.insert(coinsToSpend.begin(), coins.begin(), coins.end()); } } if (!coinControlUsed) { while (spend_val < required) { if (coins.empty()) break; CSparkMintMeta choosen; CAmount need = required - spend_val; auto itr = coins.begin(); if (cmp::greater_equal(need, itr->v)) { choosen = *itr; coins.erase(itr); } else { for (auto coinIt = coins.rbegin(); coinIt != coins.rend(); coinIt++) { auto nextItr = coinIt; nextItr++; if (cmp::greater_equal(coinIt->v, need) && (nextItr == coins.rend() || nextItr->v != coinIt->v)) { choosen = *coinIt; coins.erase(std::next(coinIt).base()); break; } } } spend_val += choosen.v; coinsToSpend.push_back(choosen); } } // sort by group id ay ascending order. it is mandatory for creting proper joinsplit auto idComparer = [](const CSparkMintMeta& a, const CSparkMintMeta& b) -> bool { return a.nId < b.nId; }; coinsToSpend.sort(idComparer); changeToMint = spend_val - required; coinsToSpend_out.insert(coinsToSpend_out.begin(), coinsToSpend.begin(), coinsToSpend.end()); return true; } std::pair> CSparkWallet::SelectSparkCoins( CAmount required, bool subtractFeeFromAmount, std::list coins, std::size_t mintNum, std::size_t utxoNum, const CCoinControl *coinControl, bool useChaumV2, size_t additionalTxSize) { CAmount fee; int64_t changeToMint = 0; // this value can be negative, that means we need to spend remaining part of required value with another transaction (nMaxInputPerTransaction exceeded) if (!MoneyRange(required)) { throw std::invalid_argument(_( "Spark spend amount is out of range")); } std::vector spendCoins; for (fee = 0;;) { CAmount currentRequired = required; if (!MoneyRange(fee)) { throw std::invalid_argument(_( "Spark spend fee is out of range")); } if (!subtractFeeFromAmount) { if (fee > MAX_MONEY - currentRequired) { throw std::invalid_argument(_( "Spark spend amount plus fee is out of range")); } currentRequired += fee; } spendCoins.clear(); try { if (!GetCoinsToSpend(currentRequired, spendCoins, coins, changeToMint, coinControl)) { throw std::invalid_argument(_("Unable to select cons for spend")); } } catch (const InsufficientFunds&) { // GetCoinsToSpend throws before the caller can record the fee that // made selection fail. Re-throw with that fee so the UI can report // AmountWithFeeExceedsBalance instead of AmountExceedsBalance. if (fee > 0) { throw InsufficientFunds(fee); } throw; } if (useChaumV2 && spendCoins.size() > spark::MAX_CHAUM_V2_INPUTS) { throw std::invalid_argument(boost::str( boost::format(_("Spark V2 spends are limited to %1% inputs")) % spark::MAX_CHAUM_V2_INPUTS)); } // 1803 is for each Grootle proof/auxiliary input, 322 for // each private output (including change), 34 for each transparent // output, and 924 for the fitted constant transaction parts. uint64_t estimatedSize = 924; const auto addEstimatedSize = [&estimatedSize]( uint64_t bytesPerItem, std::size_t itemCount) { if (itemCount > (std::numeric_limits::max() - estimatedSize) / bytesPerItem) { throw std::invalid_argument( _("Spark spend size estimate is out of range")); } estimatedSize += bytesPerItem*itemCount; }; addEstimatedSize(1803, spendCoins.size()); addEstimatedSize(322, mintNum); addEstimatedSize(322, 1); addEstimatedSize(34, utxoNum); addEstimatedSize(1, additionalTxSize); if (useChaumV2) { // V2 adds a fixed extension commitment. Each additional input // also carries its own A1, t2 and t3 (34 + 32 + 32 bytes). addEstimatedSize(32, 1); if (spendCoins.size() > 1) { addEstimatedSize(98, spendCoins.size() - 1); } } const unsigned int size = static_cast(estimatedSize); CAmount feeNeeded = CWallet::GetMinimumFee(size, coinControl, mempool); if (fee >= feeNeeded) { break; } fee = feeNeeded; if (subtractFeeFromAmount) break; } if (changeToMint < 0) throw std::invalid_argument(_("Unable to select cons for spend")); return std::make_pair(fee, spendCoins); } std::list CSparkWallet::GetAvailableSparkCoins(const CCoinControl *coinControl) const { std::list coins; // get all unsued coins from spark wallet std::vector vecMints = this->ListSparkMints(true, true); for (const auto& mint : vecMints) { if (mint.v == 0) // ignore 0 mints which where created to increase privacy continue; coins.push_back(mint); } std::set lockedCoins = pwalletMain->setLockedCoins; // Filter out coins that have not been selected from CoinControl should that be used coins.remove_if([lockedCoins, coinControl](const CSparkMintMeta& coin) { COutPoint outPoint; // ignore if the coin is not actually on chain if (!spark::GetOutPoint(outPoint, coin.coin)) { return true; } // if we are using coincontrol, filter out unselected coins if (coinControl != NULL){ if (coinControl->HasSelected()){ if (!coinControl->IsSelected(outPoint)){ return true; } } } // ignore if coin is locked if (lockedCoins.count(outPoint) > 0){ return true; } return false; }); return coins; }