diff options
Diffstat (limited to 'src')
99 files changed, 3367 insertions, 1893 deletions
diff --git a/src/Makefile.am b/src/Makefile.am index 2603dbae56..60ecf07a59 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -274,6 +274,7 @@ libbitcoin_wallet_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) libbitcoin_wallet_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libbitcoin_wallet_a_SOURCES = \ interfaces/wallet.cpp \ + wallet/coincontrol.cpp \ wallet/crypter.cpp \ wallet/db.cpp \ wallet/feebumper.cpp \ diff --git a/src/Makefile.qt.include b/src/Makefile.qt.include index a84a11ac45..c7a1963135 100644 --- a/src/Makefile.qt.include +++ b/src/Makefile.qt.include @@ -357,7 +357,7 @@ if ENABLE_WALLET BITCOIN_QT_CPP += $(BITCOIN_QT_WALLET_CPP) endif -RES_IMAGES = +RES_IMAGES = RES_MOVIES = $(wildcard $(srcdir)/qt/res/movies/spinner-*.png) diff --git a/src/Makefile.test.include b/src/Makefile.test.include index 0c1516f4d5..02f2063504 100644 --- a/src/Makefile.test.include +++ b/src/Makefile.test.include @@ -94,6 +94,7 @@ BITCOIN_TESTS =\ if ENABLE_WALLET BITCOIN_TESTS += \ wallet/test/accounting_tests.cpp \ + wallet/test/psbt_wallet_tests.cpp \ wallet/test/wallet_tests.cpp \ wallet/test/wallet_crypto_tests.cpp \ wallet/test/coinselector_tests.cpp diff --git a/src/addrman.cpp b/src/addrman.cpp index e811dd4bea..3337ec54db 100644 --- a/src/addrman.cpp +++ b/src/addrman.cpp @@ -356,7 +356,7 @@ CAddrInfo CAddrMan::Select_(bool newOnly) // Use a 50% chance for choosing between tried and new table entries. if (!newOnly && - (nTried > 0 && (nNew == 0 || RandomInt(2) == 0))) { + (nTried > 0 && (nNew == 0 || RandomInt(2) == 0))) { // use a tried node double fChanceFactor = 1.0; while (1) { diff --git a/src/addrman.h b/src/addrman.h index a36f7ea100..dc8ef8375b 100644 --- a/src/addrman.h +++ b/src/addrman.h @@ -182,8 +182,8 @@ public: //! the maximum number of tried addr collisions to store #define ADDRMAN_SET_TRIED_COLLISION_SIZE 10 -/** - * Stochastical (IP) address manager +/** + * Stochastical (IP) address manager */ class CAddrMan { diff --git a/src/bench/coin_selection.cpp b/src/bench/coin_selection.cpp index f3180809b5..7510d53c88 100644 --- a/src/bench/coin_selection.cpp +++ b/src/bench/coin_selection.cpp @@ -8,7 +8,7 @@ #include <set> -static void addCoin(const CAmount& nValue, const CWallet& wallet, std::vector<COutput>& vCoins) +static void addCoin(const CAmount& nValue, const CWallet& wallet, std::vector<OutputGroup>& groups) { int nInput = 0; @@ -21,7 +21,7 @@ static void addCoin(const CAmount& nValue, const CWallet& wallet, std::vector<CO int nAge = 6 * 24; COutput output(wtx, nInput, nAge, true /* spendable */, true /* solvable */, true /* safe */); - vCoins.push_back(output); + groups.emplace_back(output.GetInputCoin(), 0, false, 0, 0); } // Simple benchmark for wallet coin selection. Note that it maybe be necessary @@ -37,11 +37,11 @@ static void CoinSelection(benchmark::State& state) LOCK(wallet.cs_wallet); // Add coins. - std::vector<COutput> vCoins; + std::vector<OutputGroup> groups; for (int i = 0; i < 1000; ++i) { - addCoin(1000 * COIN, wallet, vCoins); + addCoin(1000 * COIN, wallet, groups); } - addCoin(3 * COIN, wallet, vCoins); + addCoin(3 * COIN, wallet, groups); const CoinEligibilityFilter filter_standard(1, 6, 0); const CoinSelectionParams coin_selection_params(true, 34, 148, CFeeRate(0), 0); @@ -49,7 +49,7 @@ static void CoinSelection(benchmark::State& state) std::set<CInputCoin> setCoinsRet; CAmount nValueRet; bool bnb_used; - bool success = wallet.SelectCoinsMinConf(1003 * COIN, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used); + bool success = wallet.SelectCoinsMinConf(1003 * COIN, filter_standard, groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used); assert(success); assert(nValueRet == 1003 * COIN); assert(setCoinsRet.size() == 2); @@ -57,17 +57,21 @@ static void CoinSelection(benchmark::State& state) } typedef std::set<CInputCoin> CoinSet; +static const CWallet testWallet("dummy", WalletDatabase::CreateDummy()); +std::vector<std::unique_ptr<CWalletTx>> wtxn; // Copied from src/wallet/test/coinselector_tests.cpp -static void add_coin(const CAmount& nValue, int nInput, std::vector<CInputCoin>& set) +static void add_coin(const CAmount& nValue, int nInput, std::vector<OutputGroup>& set) { CMutableTransaction tx; tx.vout.resize(nInput + 1); tx.vout[nInput].nValue = nValue; - set.emplace_back(MakeTransactionRef(tx), nInput); + std::unique_ptr<CWalletTx> wtx(new CWalletTx(&testWallet, MakeTransactionRef(std::move(tx)))); + set.emplace_back(COutput(wtx.get(), nInput, 0, true, true, true).GetInputCoin(), 0, true, 0, 0); + wtxn.emplace_back(std::move(wtx)); } // Copied from src/wallet/test/coinselector_tests.cpp -static CAmount make_hard_case(int utxos, std::vector<CInputCoin>& utxo_pool) +static CAmount make_hard_case(int utxos, std::vector<OutputGroup>& utxo_pool) { utxo_pool.clear(); CAmount target = 0; @@ -82,7 +86,7 @@ static CAmount make_hard_case(int utxos, std::vector<CInputCoin>& utxo_pool) static void BnBExhaustion(benchmark::State& state) { // Setup - std::vector<CInputCoin> utxo_pool; + std::vector<OutputGroup> utxo_pool; CoinSet selection; CAmount value_ret = 0; CAmount not_input_fees = 0; diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp index b332b5e581..a77e3d49b8 100644 --- a/src/bitcoin-cli.cpp +++ b/src/bitcoin-cli.cpp @@ -35,6 +35,7 @@ static void SetupCliArgs() const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET); gArgs.AddArg("-?", "This help message", false, OptionsCategory::OPTIONS); + gArgs.AddArg("-version", "Print version and exit", false, OptionsCategory::OPTIONS); gArgs.AddArg("-conf=<file>", strprintf("Specify configuration file. Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME), false, OptionsCategory::OPTIONS); gArgs.AddArg("-datadir=<dir>", "Specify data directory", false, OptionsCategory::OPTIONS); gArgs.AddArg("-getinfo", "Get general information from the remote server. Note that unlike server-side RPC calls, the results of -getinfo is the result of multiple non-atomic requests. Some entries in the result may represent results from different states (e.g. wallet balance may be as of a different block from the chain state reported)", false, OptionsCategory::OPTIONS); diff --git a/src/bitcoind.cpp b/src/bitcoind.cpp index 494a925a79..5c711c0773 100644 --- a/src/bitcoind.cpp +++ b/src/bitcoind.cpp @@ -21,8 +21,6 @@ #include <utilstrencodings.h> #include <walletinitinterface.h> -#include <boost/thread.hpp> - #include <stdio.h> /* Introduction text for doxygen: */ @@ -31,12 +29,14 @@ * * \section intro_sec Introduction * - * This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin (https://www.bitcoin.org/), + * This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin, * which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * + * See https://github.com/bitcoin/bitcoin and https://bitcoincore.org/ for further information about the project. + * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ diff --git a/src/bloom.cpp b/src/bloom.cpp index f8e28edded..799e0eef00 100644 --- a/src/bloom.cpp +++ b/src/bloom.cpp @@ -148,7 +148,7 @@ bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx) const CTxOut& txout = tx.vout[i]; // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx // If this matches, also add the specific output that was matched. - // This means clients don't have to update the filter themselves when a new relevant tx + // This means clients don't have to update the filter themselves when a new relevant tx // is discovered in order to find spending transactions, which avoids round-tripping and race conditions. CScript::const_iterator pc = txout.scriptPubKey.begin(); std::vector<unsigned char> data; diff --git a/src/bloom.h b/src/bloom.h index 2f9d2109cd..71386f52fa 100644 --- a/src/bloom.h +++ b/src/bloom.h @@ -33,9 +33,9 @@ enum bloomflags /** * BloomFilter is a probabilistic filter which SPV clients provide * so that we can filter the transactions we send them. - * + * * This allows for significantly more efficient transaction and block downloads. - * + * * Because bloom filters are probabilistic, a SPV node can increase the false- * positive rate, making us send it transactions which aren't actually its, * allowing clients to trade more bandwidth for more privacy by obfuscating which diff --git a/src/checkqueue.h b/src/checkqueue.h index 7500bae60e..84360d0716 100644 --- a/src/checkqueue.h +++ b/src/checkqueue.h @@ -16,7 +16,7 @@ template <typename T> class CCheckQueueControl; -/** +/** * Queue for verifications that have to be performed. * The verifications are represented by a type T, which must provide an * operator(), returning a bool. @@ -163,7 +163,7 @@ public: }; -/** +/** * RAII-style controller object for a CCheckQueue that guarantees the passed * queue is finished before continuing. */ diff --git a/src/clientversion.cpp b/src/clientversion.cpp index 662fbb6e77..a3eb127ca8 100644 --- a/src/clientversion.cpp +++ b/src/clientversion.cpp @@ -81,8 +81,8 @@ std::string FormatFullVersion() return CLIENT_BUILD; } -/** - * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki) +/** + * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki) */ std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { diff --git a/src/coins.h b/src/coins.h index a73f016a31..89685ce4b2 100644 --- a/src/coins.h +++ b/src/coins.h @@ -203,7 +203,7 @@ class CCoinsViewCache : public CCoinsViewBacked protected: /** * Make mutable so that we can "fill the cache" even from Get-methods - * declared as "const". + * declared as "const". */ mutable uint256 hashBlock; mutable CCoinsMap cacheCoins; @@ -280,7 +280,7 @@ public: //! Calculate the size of the cache (in bytes) size_t DynamicMemoryUsage() const; - /** + /** * Amount of bitcoins coming in to a transaction * Note that lightweight clients may not know anything besides the hash of previous transactions, * so may not be able to calculate this. diff --git a/src/compat/byteswap.h b/src/compat/byteswap.h index c331af2b5e..bfb80bd632 100644 --- a/src/compat/byteswap.h +++ b/src/compat/byteswap.h @@ -15,7 +15,7 @@ #include <byteswap.h> #endif -#if defined(__APPLE__) +#if defined(MAC_OSX) #if !defined(bswap_16) @@ -61,6 +61,6 @@ inline uint64_t bswap_64(uint64_t x) } #endif // HAVE_DECL_BSWAP64 == 0 -#endif // defined(__APPLE__) +#endif // defined(MAC_OSX) #endif // BITCOIN_COMPAT_BYTESWAP_H diff --git a/src/consensus/tx_verify.h b/src/consensus/tx_verify.h index a4836ceda4..50db1775a3 100644 --- a/src/consensus/tx_verify.h +++ b/src/consensus/tx_verify.h @@ -41,7 +41,7 @@ unsigned int GetLegacySigOpCount(const CTransaction& tx); /** * Count ECDSA signature operations in pay-to-script-hash inputs. - * + * * @param[in] mapInputs Map of previous transactions that have outputs we're spending * @return maximum number of sigops required to validate this transaction's inputs * @see CTransaction::FetchInputs diff --git a/src/core_io.h b/src/core_io.h index 1d87d21d40..ebddcc2a04 100644 --- a/src/core_io.h +++ b/src/core_io.h @@ -14,6 +14,7 @@ class CBlock; class CScript; class CTransaction; struct CMutableTransaction; +struct PartiallySignedTransaction; class uint256; class UniValue; @@ -24,12 +25,16 @@ bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no bool DecodeHexBlk(CBlock&, const std::string& strHexBlk); uint256 ParseHashStr(const std::string&, const std::string& strName); std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName); +bool DecodePSBT(PartiallySignedTransaction& psbt, const std::string& base64_tx, std::string& error); +int ParseSighashString(const UniValue& sighash); // core_write.cpp UniValue ValueFromAmount(const CAmount& amount); std::string FormatScript(const CScript& script); std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags = 0); +std::string SighashToStr(unsigned char sighash_type); void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex); +void ScriptToUniv(const CScript& script, UniValue& out, bool include_address); void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex = true, int serialize_flags = 0); #endif // BITCOIN_CORE_IO_H diff --git a/src/core_read.cpp b/src/core_read.cpp index 4d851610ef..4337c38282 100644 --- a/src/core_read.cpp +++ b/src/core_read.cpp @@ -7,6 +7,7 @@ #include <primitives/block.h> #include <primitives/transaction.h> #include <script/script.h> +#include <script/sign.h> #include <serialize.h> #include <streams.h> #include <univalue.h> @@ -15,10 +16,11 @@ #include <version.h> #include <boost/algorithm/string/classification.hpp> -#include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/split.hpp> +#include <algorithm> + CScript ParseScript(const std::string& s) { CScript result; @@ -53,20 +55,20 @@ CScript ParseScript(const std::string& s) { // Empty string, ignore. (boost::split given '' will return one word) } - else if (all(*w, boost::algorithm::is_digit()) || - (boost::algorithm::starts_with(*w, "-") && all(std::string(w->begin()+1, w->end()), boost::algorithm::is_digit()))) + else if (std::all_of(w->begin(), w->end(), ::IsDigit) || + (w->front() == '-' && w->size() > 1 && std::all_of(w->begin()+1, w->end(), ::IsDigit))) { // Number int64_t n = atoi64(*w); result << n; } - else if (boost::algorithm::starts_with(*w, "0x") && (w->begin()+2 != w->end()) && IsHex(std::string(w->begin()+2, w->end()))) + else if (w->substr(0,2) == "0x" && w->size() > 2 && IsHex(std::string(w->begin()+2, w->end()))) { // Raw hex data, inserted NOT pushed onto stack: std::vector<unsigned char> raw = ParseHex(std::string(w->begin()+2, w->end())); result.insert(result.end(), raw.begin(), raw.end()); } - else if (w->size() >= 2 && boost::algorithm::starts_with(*w, "'") && boost::algorithm::ends_with(*w, "'")) + else if (w->size() >= 2 && w->front() == '\'' && w->back() == '\'') { // Single-quoted string, pushed as data. NOTE: this is poor-man's // parsing, spaces/tabs/newlines in single-quoted strings won't work. @@ -104,7 +106,7 @@ static bool CheckTxScriptsSanity(const CMutableTransaction& tx) return false; } } - + return true; } @@ -139,7 +141,7 @@ bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no // Fall through. } } - + return false; } @@ -160,6 +162,23 @@ bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk) return true; } +bool DecodePSBT(PartiallySignedTransaction& psbt, const std::string& base64_tx, std::string& error) +{ + std::vector<unsigned char> tx_data = DecodeBase64(base64_tx.c_str()); + CDataStream ss_data(tx_data, SER_NETWORK, PROTOCOL_VERSION); + try { + ss_data >> psbt; + if (!ss_data.empty()) { + error = "extra data after PSBT"; + return false; + } + } catch (const std::exception& e) { + error = e.what(); + return false; + } + return true; +} + uint256 ParseHashStr(const std::string& strHex, const std::string& strName) { if (!IsHex(strHex)) // Note: IsHex("") is false @@ -179,3 +198,26 @@ std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strN throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')"); return ParseHex(strHex); } + +int ParseSighashString(const UniValue& sighash) +{ + int hash_type = SIGHASH_ALL; + if (!sighash.isNull()) { + static std::map<std::string, int> map_sighash_values = { + {std::string("ALL"), int(SIGHASH_ALL)}, + {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)}, + {std::string("NONE"), int(SIGHASH_NONE)}, + {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)}, + {std::string("SINGLE"), int(SIGHASH_SINGLE)}, + {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)}, + }; + std::string strHashType = sighash.get_str(); + const auto& it = map_sighash_values.find(strHashType); + if (it != map_sighash_values.end()) { + hash_type = it->second; + } else { + throw std::runtime_error(strHashType + " is not a valid sighash parameter."); + } + } + return hash_type; +} diff --git a/src/core_write.cpp b/src/core_write.cpp index ee6737201b..1272266235 100644 --- a/src/core_write.cpp +++ b/src/core_write.cpp @@ -70,6 +70,13 @@ const std::map<unsigned char, std::string> mapSigHashTypes = { {static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")}, }; +std::string SighashToStr(unsigned char sighash_type) +{ + const auto& it = mapSigHashTypes.find(sighash_type); + if (it == mapSigHashTypes.end()) return ""; + return it->second; +} + /** * Create the assembly string representation of a CScript object. * @param[in] script CScript object to convert into the asm string representation. @@ -128,6 +135,22 @@ std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags) return HexStr(ssTx.begin(), ssTx.end()); } +void ScriptToUniv(const CScript& script, UniValue& out, bool include_address) +{ + out.pushKV("asm", ScriptToAsmStr(script)); + out.pushKV("hex", HexStr(script.begin(), script.end())); + + std::vector<std::vector<unsigned char>> solns; + txnouttype type; + Solver(script, type, solns); + out.pushKV("type", GetTxnOutputType(type)); + + CTxDestination address; + if (include_address && ExtractDestination(script, address)) { + out.pushKV("address", EncodeDestination(address)); + } +} + void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex) { diff --git a/src/httprpc.cpp b/src/httprpc.cpp index 97b152b11b..0e5b497960 100644 --- a/src/httprpc.cpp +++ b/src/httprpc.cpp @@ -86,7 +86,7 @@ static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const Uni //This function checks username and password against -rpcauth //entries from config file. static bool multiUserAuthorized(std::string strUserPass) -{ +{ if (strUserPass.find(':') == std::string::npos) { return false; } diff --git a/src/interfaces/wallet.cpp b/src/interfaces/wallet.cpp index b42c9b63df..28081c7c2c 100644 --- a/src/interfaces/wallet.cpp +++ b/src/interfaces/wallet.cpp @@ -426,6 +426,7 @@ public: } unsigned int getConfirmTarget() override { return m_wallet.m_confirm_target; } bool hdEnabled() override { return m_wallet.IsHDEnabled(); } + bool IsWalletFlagSet(uint64_t flag) override { return m_wallet.IsWalletFlagSet(flag); } OutputType getDefaultAddressType() override { return m_wallet.m_default_address_type; } OutputType getDefaultChangeType() override { return m_wallet.m_default_change_type; } std::unique_ptr<Handler> handleUnload(UnloadFn fn) override diff --git a/src/interfaces/wallet.h b/src/interfaces/wallet.h index 96e742eaca..ae54d42442 100644 --- a/src/interfaces/wallet.h +++ b/src/interfaces/wallet.h @@ -236,6 +236,9 @@ public: // Return whether HD enabled. virtual bool hdEnabled() = 0; + // check if a certain wallet flag is set. + virtual bool IsWalletFlagSet(uint64_t flag) = 0; + // Get default address type. virtual OutputType getDefaultAddressType() = 0; diff --git a/src/limitedmap.h b/src/limitedmap.h index d5f00f1fee..22dde5ec36 100644 --- a/src/limitedmap.h +++ b/src/limitedmap.h @@ -70,7 +70,7 @@ public: // since it is a constant time operation in C++11. For more details, see // https://stackoverflow.com/questions/765148/how-to-remove-constness-of-const-iterator iterator itTarget = map.erase(itIn, itIn); - + if (itTarget == map.end()) return; std::pair<rmap_iterator, rmap_iterator> itPair = rmap.equal_range(itTarget->second); diff --git a/src/net.cpp b/src/net.cpp index e44aa1fdb4..67a73fa9fc 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -1163,6 +1163,17 @@ void CConnman::ThreadSocketHandler() // { LOCK(cs_vNodes); + + if (!fNetworkActive) { + // Disconnect any connected nodes + for (CNode* pnode : vNodes) { + if (!pnode->fDisconnect) { + LogPrint(BCLog::NET, "Network not active, dropping peer=%d\n", pnode->GetId()); + pnode->fDisconnect = true; + } + } + } + // Disconnect unused nodes std::vector<CNode*> vNodesCopy = vNodes; for (CNode* pnode : vNodesCopy) @@ -2198,14 +2209,6 @@ void CConnman::SetNetworkActive(bool active) fNetworkActive = active; - if (!fNetworkActive) { - LOCK(cs_vNodes); - // Close sockets to all nodes - for (CNode* pnode : vNodes) { - pnode->CloseSocketDisconnect(); - } - } - uiInterface.NotifyNetworkActiveChanged(fNetworkActive); } @@ -2254,7 +2257,8 @@ bool CConnman::InitBinds(const std::vector<CService>& binds, const std::vector<C if (binds.empty() && whiteBinds.empty()) { struct in_addr inaddr_any; inaddr_any.s_addr = INADDR_ANY; - fBound |= Bind(CService((in6_addr)IN6ADDR_ANY_INIT, GetListenPort()), BF_NONE); + struct in6_addr inaddr6_any = IN6ADDR_ANY_INIT; + fBound |= Bind(CService(inaddr6_any, GetListenPort()), BF_NONE); fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE); } return fBound; diff --git a/src/net_processing.cpp b/src/net_processing.cpp index a0136675f3..5267f96f70 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -1665,17 +1665,6 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr return false; } - if (nServices & ((1 << 7) | (1 << 5))) { - if (GetTime() < 1533096000) { - // Immediately disconnect peers that use service bits 6 or 8 until August 1st, 2018 - // These bits have been used as a flag to indicate that a node is running incompatible - // consensus rules instead of changing the network magic, so we're stuck disconnecting - // based on these service bits, at least for a while. - pfrom->fDisconnect = true; - return false; - } - } - if (nVersion < MIN_PEER_PROTO_VERSION) { // disconnect from peers older than this proto version diff --git a/src/netbase.cpp b/src/netbase.cpp index 4ce63cb0ec..607eb89573 100644 --- a/src/netbase.cpp +++ b/src/netbase.cpp @@ -20,7 +20,6 @@ #endif #include <boost/algorithm/string/case_conv.hpp> // for to_lower() -#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith() #if !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 @@ -121,8 +120,7 @@ bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nM std::string strHost(pszName); if (strHost.empty()) return false; - if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]")) - { + if (strHost.front() == '[' && strHost.back() == ']') { strHost = strHost.substr(1, strHost.size() - 2); } diff --git a/src/pubkey.cpp b/src/pubkey.cpp index 6e601a6f13..1eb126434b 100644 --- a/src/pubkey.cpp +++ b/src/pubkey.cpp @@ -171,7 +171,7 @@ bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchS return false; secp256k1_pubkey pubkey; secp256k1_ecdsa_signature sig; - if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, &(*this)[0], size())) { + if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch, size())) { return false; } if (!ecdsa_signature_parse_der_lax(secp256k1_context_verify, &sig, vchSig.data(), vchSig.size())) { @@ -207,14 +207,14 @@ bool CPubKey::IsFullyValid() const { if (!IsValid()) return false; secp256k1_pubkey pubkey; - return secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, &(*this)[0], size()); + return secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch, size()); } bool CPubKey::Decompress() { if (!IsValid()) return false; secp256k1_pubkey pubkey; - if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, &(*this)[0], size())) { + if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch, size())) { return false; } unsigned char pub[PUBLIC_KEY_SIZE]; @@ -232,7 +232,7 @@ bool CPubKey::Derive(CPubKey& pubkeyChild, ChainCode &ccChild, unsigned int nChi BIP32Hash(cc, nChild, *begin(), begin()+1, out); memcpy(ccChild.begin(), out+32, 32); secp256k1_pubkey pubkey; - if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, &(*this)[0], size())) { + if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch, size())) { return false; } if (!secp256k1_ec_pubkey_tweak_add(secp256k1_context_verify, &pubkey, out)) { diff --git a/src/pubkey.h b/src/pubkey.h index bb254547c8..0985273f34 100644 --- a/src/pubkey.h +++ b/src/pubkey.h @@ -107,6 +107,7 @@ public: //! Simple read-only vector-like interface to the pubkey data. unsigned int size() const { return GetLen(vch[0]); } + const unsigned char* data() const { return vch; } const unsigned char* begin() const { return vch; } const unsigned char* end() const { return vch + size(); } const unsigned char& operator[](unsigned int pos) const { return vch[pos]; } diff --git a/src/qt/bitcoin.cpp b/src/qt/bitcoin.cpp index 3454d3421e..5d0e384cf8 100644 --- a/src/qt/bitcoin.cpp +++ b/src/qt/bitcoin.cpp @@ -614,7 +614,6 @@ int main(int argc, char *argv[]) QApplication::setOrganizationName(QAPP_ORG_NAME); QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN); QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT); - GUIUtil::SubstituteFonts(GetLangTerritory()); /// 4. Initialization of translations, so that intro dialog is in user's language // Now that QSettings are accessible, initialize translations diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp index 2438361a58..c8f8b9c7d3 100644 --- a/src/qt/bitcoingui.cpp +++ b/src/qt/bitcoingui.cpp @@ -470,13 +470,13 @@ void BitcoinGUI::setClientModel(ClientModel *_clientModel) } #endif // ENABLE_WALLET unitDisplayControl->setOptionsModel(_clientModel->getOptionsModel()); - + OptionsModel* optionsModel = _clientModel->getOptionsModel(); if(optionsModel) { // be aware of the tray icon disable state change reported by the OptionsModel object. connect(optionsModel,SIGNAL(hideTrayIconChanged(bool)),this,SLOT(setTrayIconVisible(bool))); - + // initialize the disable state of the tray icon with the current value in the model. setTrayIconVisible(optionsModel->getHideTrayIcon()); } @@ -1057,7 +1057,7 @@ void BitcoinGUI::setHDStatus(int hdEnabled) labelWalletHDStatusIcon->setPixmap(platformStyle->SingleColorIcon(hdEnabled ? ":/icons/hd_enabled" : ":/icons/hd_disabled").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelWalletHDStatusIcon->setToolTip(hdEnabled ? tr("HD key generation is <b>enabled</b>") : tr("HD key generation is <b>disabled</b>")); - // eventually disable the QLabel to set its opacity to 50% + // eventually disable the QLabel to set its opacity to 50% labelWalletHDStatusIcon->setEnabled(hdEnabled); } diff --git a/src/qt/bitcoingui.h b/src/qt/bitcoingui.h index 4deeb325b3..d7ca8081d1 100644 --- a/src/qt/bitcoingui.h +++ b/src/qt/bitcoingui.h @@ -262,7 +262,7 @@ private Q_SLOTS: /** Show progress dialog e.g. for verifychain */ void showProgress(const QString &title, int nProgress); - + /** When hideTrayIcon setting is changed in OptionsModel hide or show the icon accordingly. */ void setTrayIconVisible(bool); diff --git a/src/qt/bitcoinstrings.cpp b/src/qt/bitcoinstrings.cpp index adf001c968..ab7e56a9da 100644 --- a/src/qt/bitcoinstrings.cpp +++ b/src/qt/bitcoinstrings.cpp @@ -12,128 +12,37 @@ static const char UNUSED *bitcoin_strings[] = { QT_TRANSLATE_NOOP("bitcoin-core", "Bitcoin Core"), QT_TRANSLATE_NOOP("bitcoin-core", "The %s developers"), QT_TRANSLATE_NOOP("bitcoin-core", "" -"(1 = keep tx meta data e.g. account owner and payment request information, 2 " -"= drop tx meta data)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" "-maxtxfee is set very high! Fees this large could be paid on a single " "transaction."), QT_TRANSLATE_NOOP("bitcoin-core", "" -"A fee rate (in %s/kB) that will be used when fee estimation has insufficient " -"data (default: %s)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Accept relayed transactions received from whitelisted peers even when not " -"relaying transactions (default: %d)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Add a node to connect to and attempt to keep the connection open (see the " -"`addnode` RPC command help for more info)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Allow JSON-RPC connections from specified source. Valid for <ip> are a " -"single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or " -"a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Bind to given address and always listen on it. Use [host]:port notation for " -"IPv6"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Bind to given address and whitelist peers connecting to it. Use [host]:port " -"notation for IPv6"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Bind to given address to listen for JSON-RPC connections. This option is " -"ignored unless -rpcallowip is also passed. Port is optional and overrides -" -"rpcport. Use [host]:port notation for IPv6. This option can be specified " -"multiple times (default: 127.0.0.1 and ::1 i.e., localhost, or if -" -"rpcallowip has been specified, 0.0.0.0 and :: i.e., all addresses)"), +"Can't generate a change-address key. Private keys are disabled for this " +"wallet."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Cannot obtain a lock on data directory %s. %s is probably already running."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Cannot provide specific connections and have addrman find outgoing " "connections at the same."), QT_TRANSLATE_NOOP("bitcoin-core", "" -"Connect only to the specified node(s); -connect=0 disables automatic " -"connections (the rules for this peer are the same as for -addnode)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Create new files with system default permissions, instead of umask 077 (only " -"effective with disabled wallet functionality)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Delete all wallet transactions and only recover those parts of the " -"blockchain through -rescan on startup"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Discover own IP addresses (default: 1 when listening and no -externalip or -" -"proxy)"), +"Cannot upgrade a non HD split wallet without upgrading to support pre split " +"keypool. Please use -upgradewallet=169900 or -upgradewallet with no version " +"specified."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Distributed under the MIT software license, see the accompanying file %s or " "%s"), QT_TRANSLATE_NOOP("bitcoin-core", "" -"Do not keep transactions in the mempool longer than <n> hours (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" "Error loading %s: You can't enable HD on an already existing non-HD wallet"), QT_TRANSLATE_NOOP("bitcoin-core", "" -"Error loading wallet %s. -wallet parameter must only specify a filename (not " -"a path)."), -QT_TRANSLATE_NOOP("bitcoin-core", "" "Error reading %s! All keys read correctly, but transaction data or address " "book entries might be missing or incorrect."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: Listening for incoming connections failed (listen returned error %s)"), QT_TRANSLATE_NOOP("bitcoin-core", "" -"Exclude debugging information for a category. Can be used in conjunction " -"with -debug=1 to output debug logs for all categories except one or more " -"specified categories."), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Execute command when a relevant alert is received or we see a really long " -"fork (%s in cmd is replaced by message)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Execute command when a wallet transaction changes (%s in cmd is replaced by " -"TxID)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Execute command when the best block changes (%s in cmd is replaced by block " -"hash)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Extra transactions to keep in memory for compact block reconstructions " -"(default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Fees (in %s/kB) smaller than this are considered zero fee for relaying, " -"mining and transaction creation (default: %s)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Fees (in %s/kB) smaller than this are considered zero fee for transaction " -"creation (default: %s)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Force relay of transactions from whitelisted peers even if they violate " -"local relay policy (default: %d)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"How thorough the block verification of -checkblocks is (0-4, default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"If <category> is not supplied or if <category> = 1, output all debugging " -"information."), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"If paytxfee is not set, include enough fee so transactions begin " -"confirmation on average within n blocks (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"If this block is in the chain assume that it and its ancestors are valid and " -"potentially skip their script verification (0 to verify all, default: %s, " -"testnet: %s)"), +"Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -" +"fallbackfee."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay " "fee of %s to prevent stuck transactions)"), QT_TRANSLATE_NOOP("bitcoin-core", "" -"Maintain a full transaction index, used by the getrawtransaction rpc call " -"(default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Maximum allowed median peer time offset adjustment. Local perspective of " -"time may be influenced by peers forward or backward by this amount. " -"(default: %u seconds)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Maximum size of data in data carrier transactions we relay and mine " -"(default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Maximum total fees (in %s) to use in a single wallet transaction or raw " -"transaction; setting this too low may abort large transactions (default: %s)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Output debugging information (default: %u, supplying <category> is optional)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" "Please check that your computer's date and time are correct! If your clock " "is wrong, %s will not work properly."), QT_TRANSLATE_NOOP("bitcoin-core", "" @@ -145,53 +54,14 @@ QT_TRANSLATE_NOOP("bitcoin-core", "" "Prune: last wallet synchronisation goes beyond pruned data. You need to -" "reindex (download the whole blockchain again in case of pruned node)"), QT_TRANSLATE_NOOP("bitcoin-core", "" -"Query for peer addresses via DNS lookup, if low on addresses (default: 1 " -"unless -connect used)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Randomize credentials for every proxy connection. This enables Tor stream " -"isolation (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Reduce storage requirements by enabling pruning (deleting) of old blocks. " -"This allows the pruneblockchain RPC to be called to delete specific blocks, " -"and enables automatic pruning of old blocks if a target size in MiB is " -"provided. This mode is incompatible with -txindex and -rescan. Warning: " -"Reverting this setting requires re-downloading the entire blockchain. " -"(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >%u " -"= automatically prune block files to stay under the specified target size in " -"MiB)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" "Rescans are not possible in pruned mode. You will need to use -reindex which " "will download the whole blockchain again."), QT_TRANSLATE_NOOP("bitcoin-core", "" -"Set lowest fee rate (in %s/kB) for transactions to be included in block " -"creation. (default: %s)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Set maximum BIP141 block weight to this * 4. Deprecated, use blockmaxweight"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Set the number of script verification threads (%u to %d, 0 = auto, <0 = " -"leave that many cores free, default: %d)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Sets the serialization of raw transaction or block hex returned in non-" -"verbose mode, non-segwit(0) or segwit(1) (default: %d)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Specify directory to hold wallets (default: <datadir>/wallets if it exists, " -"otherwise <datadir>)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Specify location of debug log file: this can be an absolute path or a path " -"relative to the data directory (default: %s)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Support filtering of blocks and transaction with bloom filters (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" "The block database contains a block which appears to be from the future. " "This may be due to your computer's date and time being set incorrectly. Only " "rebuild the block database if you are sure that your computer's date and " "time are correct"), QT_TRANSLATE_NOOP("bitcoin-core", "" -"The fee rate (in %s/kB) that indicates your tolerance for discarding change " -"by adding it to the fee (default: %s). Note: An output is discarded if it is " -"dust at this rate, but we will always discard up to the dust relay fee and a " -"discard fee above that is limited by the fee estimate for the longest target"), -QT_TRANSLATE_NOOP("bitcoin-core", "" "The transaction amount is too small to send after the fee has been deducted"), QT_TRANSLATE_NOOP("bitcoin-core", "" "This is a pre-release test build - use at your own risk - do not use for " @@ -209,9 +79,6 @@ QT_TRANSLATE_NOOP("bitcoin-core", "" "Total length of network version string (%i) exceeds maximum length (%i). " "Reduce the number or size of uacomments."), QT_TRANSLATE_NOOP("bitcoin-core", "" -"Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = " -"no limit (default: %d)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" "Unable to replay blocks. You will need to rebuild the database using -" "reindex-chainstate."), QT_TRANSLATE_NOOP("bitcoin-core", "" @@ -224,19 +91,7 @@ QT_TRANSLATE_NOOP("bitcoin-core", "" "Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/" "or -whitelistforcerelay."), QT_TRANSLATE_NOOP("bitcoin-core", "" -"Use UPnP to map the listening port (default: 1 when listening and no -proxy)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: " -"%s)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Username and hashed password for JSON-RPC connections. The field <userpw> " -"comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is " -"included in share/rpcuser. The client then connects normally using the " -"rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can " -"be specified multiple times"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Wallet will not create transactions that violate mempool chain limits " -"(default: %u)"), +"Warning: Private keys detected in wallet {%s} with disabled private keys"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: The network does not appear to fully agree! Some miners appear to " "be experiencing issues."), @@ -251,61 +106,30 @@ QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: We do not appear to fully agree with our peers! You may need to " "upgrade, or other nodes may need to upgrade."), QT_TRANSLATE_NOOP("bitcoin-core", "" -"Whether to save the mempool on shutdown and load on restart (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or CIDR " -"notated network (e.g. 1.2.3.0/24). Can be specified multiple times."), -QT_TRANSLATE_NOOP("bitcoin-core", "" -"Whitelisted peers cannot be DoS banned and their transactions are always " -"relayed, even if they are already in the mempool, useful e.g. for a gateway"), -QT_TRANSLATE_NOOP("bitcoin-core", "" "You need to rebuild the database using -reindex to go back to unpruned " "mode. This will redownload the entire blockchain"), QT_TRANSLATE_NOOP("bitcoin-core", "%d of last 100 blocks have unexpected version"), QT_TRANSLATE_NOOP("bitcoin-core", "%s corrupt, salvage failed"), QT_TRANSLATE_NOOP("bitcoin-core", "%s is set very high!"), -QT_TRANSLATE_NOOP("bitcoin-core", "(default: %s)"), -QT_TRANSLATE_NOOP("bitcoin-core", "(default: %u)"), QT_TRANSLATE_NOOP("bitcoin-core", "-maxmempool must be at least %d MB"), -QT_TRANSLATE_NOOP("bitcoin-core", "<category> can be:"), -QT_TRANSLATE_NOOP("bitcoin-core", "Accept command line and JSON-RPC commands"), -QT_TRANSLATE_NOOP("bitcoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Accept public REST requests (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"), -QT_TRANSLATE_NOOP("bitcoin-core", "Always query for peer addresses via DNS lookup (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Append comment to the user agent string"), -QT_TRANSLATE_NOOP("bitcoin-core", "Attempt to recover private keys from a corrupt wallet on startup"), -QT_TRANSLATE_NOOP("bitcoin-core", "Automatically create Tor hidden service (default: %d)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Block creation options:"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot downgrade wallet"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -%s address: '%s'"), -QT_TRANSLATE_NOOP("bitcoin-core", "Chain selection options:"), +QT_TRANSLATE_NOOP("bitcoin-core", "Cannot write to data directory '%s'; check permissions."), QT_TRANSLATE_NOOP("bitcoin-core", "Change index out of range"), -QT_TRANSLATE_NOOP("bitcoin-core", "Connect through SOCKS5 proxy"), -QT_TRANSLATE_NOOP("bitcoin-core", "Connect to a node to retrieve peer addresses, and disconnect"), -QT_TRANSLATE_NOOP("bitcoin-core", "Connection options:"), QT_TRANSLATE_NOOP("bitcoin-core", "Copyright (C) %i-%i"), QT_TRANSLATE_NOOP("bitcoin-core", "Corrupted block database detected"), -QT_TRANSLATE_NOOP("bitcoin-core", "Debugging/Testing options:"), -QT_TRANSLATE_NOOP("bitcoin-core", "Do not load the wallet and disable wallet RPC calls"), QT_TRANSLATE_NOOP("bitcoin-core", "Do you want to rebuild the block database now?"), QT_TRANSLATE_NOOP("bitcoin-core", "Done loading"), -QT_TRANSLATE_NOOP("bitcoin-core", "Enable publish hash block in <address>"), -QT_TRANSLATE_NOOP("bitcoin-core", "Enable publish hash transaction in <address>"), -QT_TRANSLATE_NOOP("bitcoin-core", "Enable publish raw block in <address>"), -QT_TRANSLATE_NOOP("bitcoin-core", "Enable publish raw transaction in <address>"), -QT_TRANSLATE_NOOP("bitcoin-core", "Enable transaction replacement in the memory pool (default: %u)"), QT_TRANSLATE_NOOP("bitcoin-core", "Error creating %s: You can't create non-HD wallets with this version."), QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing block database"), QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing wallet database environment %s!"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading %s"), +QT_TRANSLATE_NOOP("bitcoin-core", "Error loading %s: Private keys can only be disabled during creation"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading %s: Wallet corrupted"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading %s: Wallet requires newer version of %s"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading %s: You can't disable HD on an already existing HD wallet"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading block database"), -QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet %s. -wallet filename must be a regular file."), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet %s. Duplicate -wallet filename specified."), -QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet %s. Invalid characters in -wallet filename."), QT_TRANSLATE_NOOP("bitcoin-core", "Error opening block database"), QT_TRANSLATE_NOOP("bitcoin-core", "Error reading from database, shutting down."), QT_TRANSLATE_NOOP("bitcoin-core", "Error upgrading chainstate database"), @@ -314,11 +138,7 @@ QT_TRANSLATE_NOOP("bitcoin-core", "Error: A fatal internal error occurred, see d QT_TRANSLATE_NOOP("bitcoin-core", "Error: Disk space is low!"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to listen on any port. Use -listen=0 if you want this."), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to rescan the wallet during initialization"), -QT_TRANSLATE_NOOP("bitcoin-core", "Fee (in %s/kB) to add to transactions you send (default: %s)"), -QT_TRANSLATE_NOOP("bitcoin-core", "How many blocks to check at startup (default: %u, 0 = all)"), QT_TRANSLATE_NOOP("bitcoin-core", "Importing..."), -QT_TRANSLATE_NOOP("bitcoin-core", "Imports blocks from external blk000??.dat file on startup"), -QT_TRANSLATE_NOOP("bitcoin-core", "Include IP addresses in debug output (default: %u)"), QT_TRANSLATE_NOOP("bitcoin-core", "Incorrect or no genesis block found. Wrong datadir for network?"), QT_TRANSLATE_NOOP("bitcoin-core", "Information"), QT_TRANSLATE_NOOP("bitcoin-core", "Initialization sanity check failed. %s is shutting down."), @@ -330,62 +150,25 @@ QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -discardfee=<amount>: '%s' QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -fallbackfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid netmask specified in -whitelist: '%s'"), -QT_TRANSLATE_NOOP("bitcoin-core", "Keep at most <n> unconnectable transactions in memory (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Keep the transaction memory pool below <n> megabytes (default: %u)"), QT_TRANSLATE_NOOP("bitcoin-core", "Keypool ran out, please call keypoolrefill first"), -QT_TRANSLATE_NOOP("bitcoin-core", "Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Listen for connections on <port> (default: %u or testnet: %u)"), QT_TRANSLATE_NOOP("bitcoin-core", "Loading P2P addresses..."), QT_TRANSLATE_NOOP("bitcoin-core", "Loading banlist..."), QT_TRANSLATE_NOOP("bitcoin-core", "Loading block index..."), QT_TRANSLATE_NOOP("bitcoin-core", "Loading wallet..."), -QT_TRANSLATE_NOOP("bitcoin-core", "Location of the auth cookie (default: data dir)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Maintain at most <n> connections to peers (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Make the wallet broadcast transactions"), -QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), QT_TRANSLATE_NOOP("bitcoin-core", "Need to specify a port with -whitebind: '%s'"), -QT_TRANSLATE_NOOP("bitcoin-core", "Node relay options:"), QT_TRANSLATE_NOOP("bitcoin-core", "Not enough file descriptors available."), -QT_TRANSLATE_NOOP("bitcoin-core", "Only connect to nodes in network <net> (ipv4, ipv6 or onion)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Options:"), -QT_TRANSLATE_NOOP("bitcoin-core", "Password for JSON-RPC connections"), -QT_TRANSLATE_NOOP("bitcoin-core", "Prepend debug output with timestamp (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Print this help message and exit"), -QT_TRANSLATE_NOOP("bitcoin-core", "Print version and exit"), QT_TRANSLATE_NOOP("bitcoin-core", "Prune cannot be configured with a negative value."), QT_TRANSLATE_NOOP("bitcoin-core", "Prune mode is incompatible with -txindex."), QT_TRANSLATE_NOOP("bitcoin-core", "Pruning blockstore..."), -QT_TRANSLATE_NOOP("bitcoin-core", "RPC server options:"), -QT_TRANSLATE_NOOP("bitcoin-core", "Rebuild chain state and block index from the blk*.dat files on disk"), -QT_TRANSLATE_NOOP("bitcoin-core", "Rebuild chain state from the currently indexed blocks"), QT_TRANSLATE_NOOP("bitcoin-core", "Reducing -maxconnections from %d to %d, because of system limitations."), -QT_TRANSLATE_NOOP("bitcoin-core", "Relay and mine data carrier transactions (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Relay non-P2SH multisig (default: %u)"), QT_TRANSLATE_NOOP("bitcoin-core", "Replaying blocks..."), -QT_TRANSLATE_NOOP("bitcoin-core", "Rescan the block chain for missing wallet transactions on startup"), QT_TRANSLATE_NOOP("bitcoin-core", "Rescanning..."), QT_TRANSLATE_NOOP("bitcoin-core", "Rewinding blocks..."), -QT_TRANSLATE_NOOP("bitcoin-core", "Run in the background as a daemon and accept commands"), -QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to console instead of debug.log file"), -QT_TRANSLATE_NOOP("bitcoin-core", "Send transactions with full-RBF opt-in enabled (RPC only, default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Set database cache size in megabytes (%d to %d, default: %d)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Set key pool size to <n> (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Set maximum BIP141 block weight (default: %d)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Set the number of threads to service RPC calls (default: %d)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Show all debugging options (usage: --help -help-debug)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"), QT_TRANSLATE_NOOP("bitcoin-core", "Signing transaction failed"), QT_TRANSLATE_NOOP("bitcoin-core", "Specified -walletdir \"%s\" does not exist"), QT_TRANSLATE_NOOP("bitcoin-core", "Specified -walletdir \"%s\" is a relative path"), QT_TRANSLATE_NOOP("bitcoin-core", "Specified -walletdir \"%s\" is not a directory"), -QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: %s)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Specify connection timeout in milliseconds (minimum: 1, default: %d)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Specify data directory"), -QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: %s)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Specify wallet file (within data directory)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Specify your own public address"), -QT_TRANSLATE_NOOP("bitcoin-core", "Spend unconfirmed change when sending transactions (default: %u)"), +QT_TRANSLATE_NOOP("bitcoin-core", "Specified blocks directory \"%s\" does not exist.\n"), QT_TRANSLATE_NOOP("bitcoin-core", "Starting network threads..."), QT_TRANSLATE_NOOP("bitcoin-core", "The source code is available from %s."), QT_TRANSLATE_NOOP("bitcoin-core", "The transaction amount is too small to pay the fee"), @@ -393,9 +176,6 @@ QT_TRANSLATE_NOOP("bitcoin-core", "The wallet will avoid paying less than the mi QT_TRANSLATE_NOOP("bitcoin-core", "This is experimental software."), QT_TRANSLATE_NOOP("bitcoin-core", "This is the minimum transaction fee you pay on every transaction."), QT_TRANSLATE_NOOP("bitcoin-core", "This is the transaction fee you will pay if you send a transaction."), -QT_TRANSLATE_NOOP("bitcoin-core", "Threshold for disconnecting misbehaving peers (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Tor control port password (default: empty)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Tor control port to use if onion listening enabled (default: %s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Transaction amount too small"), QT_TRANSLATE_NOOP("bitcoin-core", "Transaction amounts must not be negative"), QT_TRANSLATE_NOOP("bitcoin-core", "Transaction fee and change calculation failed"), @@ -406,28 +186,21 @@ QT_TRANSLATE_NOOP("bitcoin-core", "Transaction too large"), QT_TRANSLATE_NOOP("bitcoin-core", "Unable to bind to %s on this computer (bind returned error %s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Unable to bind to %s on this computer. %s is probably already running."), QT_TRANSLATE_NOOP("bitcoin-core", "Unable to generate initial keys"), +QT_TRANSLATE_NOOP("bitcoin-core", "Unable to generate keys"), QT_TRANSLATE_NOOP("bitcoin-core", "Unable to start HTTP server. See debug log for details."), QT_TRANSLATE_NOOP("bitcoin-core", "Unknown network specified in -onlynet: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Unsupported argument -benchmark ignored, use -debug=bench."), QT_TRANSLATE_NOOP("bitcoin-core", "Unsupported argument -debugnet ignored, use -debug=net."), QT_TRANSLATE_NOOP("bitcoin-core", "Unsupported argument -tor found, use -onion."), QT_TRANSLATE_NOOP("bitcoin-core", "Unsupported logging category %s=%s."), -QT_TRANSLATE_NOOP("bitcoin-core", "Upgrade wallet to latest format on startup"), QT_TRANSLATE_NOOP("bitcoin-core", "Upgrading UTXO database"), -QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Use the test chain"), +QT_TRANSLATE_NOOP("bitcoin-core", "Upgrading txindex database"), QT_TRANSLATE_NOOP("bitcoin-core", "User Agent comment (%s) contains unsafe characters."), -QT_TRANSLATE_NOOP("bitcoin-core", "Username for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Verifying blocks..."), QT_TRANSLATE_NOOP("bitcoin-core", "Verifying wallet(s)..."), QT_TRANSLATE_NOOP("bitcoin-core", "Wallet %s resides outside wallet directory %s"), -QT_TRANSLATE_NOOP("bitcoin-core", "Wallet debugging/testing options:"), QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart %s to complete"), -QT_TRANSLATE_NOOP("bitcoin-core", "Wallet options:"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning: unknown new rules activated (versionbit %i)"), -QT_TRANSLATE_NOOP("bitcoin-core", "Whether to operate in a blocks only mode (default: %u)"), -QT_TRANSLATE_NOOP("bitcoin-core", "You need to rebuild the database using -reindex to change -txindex"), QT_TRANSLATE_NOOP("bitcoin-core", "Zapping all transactions from wallet..."), -QT_TRANSLATE_NOOP("bitcoin-core", "ZeroMQ notification options:"), }; diff --git a/src/qt/clientmodel.cpp b/src/qt/clientmodel.cpp index a623771aa0..8a4a2955f6 100644 --- a/src/qt/clientmodel.cpp +++ b/src/qt/clientmodel.cpp @@ -28,8 +28,6 @@ #include <QDebug> #include <QTimer> -class CBlockIndex; - static int64_t nLastHeaderTipUpdateNotification = 0; static int64_t nLastBlockTipUpdateNotification = 0; diff --git a/src/qt/guiutil.cpp b/src/qt/guiutil.cpp index acd9f7b35c..9dde2c392c 100644 --- a/src/qt/guiutil.cpp +++ b/src/qt/guiutil.cpp @@ -63,16 +63,6 @@ static fs::detail::utf8_codecvt_facet utf8; -#if defined(Q_OS_MAC) -extern double NSAppKitVersionNumber; -#if !defined(NSAppKitVersionNumber10_8) -#define NSAppKitVersionNumber10_8 1187 -#endif -#if !defined(NSAppKitVersionNumber10_9) -#define NSAppKitVersionNumber10_9 1265 -#endif -#endif - namespace GUIUtil { QString dateTimeStr(const QDateTime &date) @@ -381,52 +371,16 @@ bool openBitcoinConf() /* Create the file */ boost::filesystem::ofstream configFile(pathConfig, std::ios_base::app); - + if (!configFile.good()) return false; - + configFile.close(); - + /* Open bitcoin.conf with the associated application */ return QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig))); } -void SubstituteFonts(const QString& language) -{ -#if defined(Q_OS_MAC) -// Background: -// OSX's default font changed in 10.9 and Qt is unable to find it with its -// usual fallback methods when building against the 10.7 sdk or lower. -// The 10.8 SDK added a function to let it find the correct fallback font. -// If this fallback is not properly loaded, some characters may fail to -// render correctly. -// -// The same thing happened with 10.10. .Helvetica Neue DeskInterface is now default. -// -// Solution: If building with the 10.7 SDK or lower and the user's platform -// is 10.9 or higher at runtime, substitute the correct font. This needs to -// happen before the QApplication is created. -#if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8 - if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8) - { - if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9) - /* On a 10.9 - 10.9.x system */ - QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande"); - else - { - /* 10.10 or later system */ - if (language == "zh_CN" || language == "zh_TW" || language == "zh_HK") // traditional or simplified Chinese - QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Heiti SC"); - else if (language == "ja") // Japanese - QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Songti SC"); - else - QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Lucida Grande"); - } - } -#endif -#endif -} - ToolTipToRichTextFilter::ToolTipToRichTextFilter(int _size_threshold, QObject *parent) : QObject(parent), size_threshold(_size_threshold) @@ -741,7 +695,7 @@ LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef if (listSnapshot == nullptr) { return nullptr; } - + // loop through the list of startup items and try to find the bitcoin app for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) { LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i); @@ -769,7 +723,7 @@ LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef CFRelease(currentItemURL); } } - + CFRelease(listSnapshot); return nullptr; } @@ -780,7 +734,7 @@ bool GetStartOnSystemStartup() if (bitcoinAppUrl == nullptr) { return false; } - + LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); @@ -794,7 +748,7 @@ bool SetStartOnSystemStartup(bool fAutoStart) if (bitcoinAppUrl == nullptr) { return false; } - + LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); @@ -806,7 +760,7 @@ bool SetStartOnSystemStartup(bool fAutoStart) // remove item LSSharedFileListItemRemove(loginItems, foundItem); } - + CFRelease(bitcoinAppUrl); return true; } @@ -967,7 +921,7 @@ void ClickableLabel::mouseReleaseEvent(QMouseEvent *event) { Q_EMIT clicked(event->pos()); } - + void ClickableProgressBar::mouseReleaseEvent(QMouseEvent *event) { Q_EMIT clicked(event->pos()); diff --git a/src/qt/guiutil.h b/src/qt/guiutil.h index e965a91d18..6aa65369fa 100644 --- a/src/qt/guiutil.h +++ b/src/qt/guiutil.h @@ -120,9 +120,6 @@ namespace GUIUtil // Open the config file bool openBitcoinConf(); - // Replace invalid default fonts with known good ones - void SubstituteFonts(const QString& language); - /** Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text representation if needed. This assures that Qt can word-wrap long tooltip messages. Tooltips longer than the provided size threshold (in characters) are wrapped. @@ -219,11 +216,11 @@ namespace GUIUtil protected: void mouseReleaseEvent(QMouseEvent *event); }; - + class ClickableProgressBar : public QProgressBar { Q_OBJECT - + Q_SIGNALS: /** Emitted when the progressbar is clicked. The relative mouse coordinates of the click are * passed to the signal. @@ -233,19 +230,7 @@ namespace GUIUtil void mouseReleaseEvent(QMouseEvent *event); }; -#if defined(Q_OS_MAC) - // workaround for Qt OSX Bug: - // https://bugreports.qt-project.org/browse/QTBUG-15631 - // QProgressBar uses around 10% CPU even when app is in background - class ProgressBar : public ClickableProgressBar - { - bool event(QEvent *e) { - return (e->type() != QEvent::StyleAnimationUpdate) ? QProgressBar::event(e) : false; - } - }; -#else typedef ClickableProgressBar ProgressBar; -#endif } // namespace GUIUtil diff --git a/src/qt/locale/bitcoin_en.ts b/src/qt/locale/bitcoin_en.ts index 2b712b4317..1b51699b31 100644 --- a/src/qt/locale/bitcoin_en.ts +++ b/src/qt/locale/bitcoin_en.ts @@ -4,7 +4,7 @@ <context> <name>AddressBookPage</name> <message> - <location filename="../forms/addressbookpage.ui" line="+30"/> + <location filename="../forms/addressbookpage.ui" line="+37"/> <source>Right-click to edit address or label</source> <translation type="unfinished"></translation> </message> @@ -39,7 +39,12 @@ <translation>Delete the currently selected address from the list</translation> </message> <message> - <location line="+30"/> + <location line="-71"/> + <source>Enter address or label to search</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+101"/> <source>Export the data in the current tab to a file</source> <translation>Export the data in the current tab to a file</translation> </message> @@ -54,7 +59,7 @@ <translation>&Delete</translation> </message> <message> - <location filename="../addressbookpage.cpp" line="+50"/> + <location filename="../addressbookpage.cpp" line="+85"/> <source>Choose the address to send coins to</source> <translation type="unfinished"></translation> </message> @@ -84,12 +89,12 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+4"/> + <location line="+5"/> <source>These are your Bitcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+6"/> + <location line="+7"/> <source>&Copy Address</source> <translation type="unfinished"></translation> </message> @@ -104,7 +109,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+193"/> + <location line="+177"/> <source>Export Address List</source> <translation type="unfinished"></translation> </message> @@ -127,7 +132,7 @@ <context> <name>AddressTableModel</name> <message> - <location filename="../addresstablemodel.cpp" line="+169"/> + <location filename="../addresstablemodel.cpp" line="+164"/> <source>Label</source> <translation type="unfinished"></translation> </message> @@ -291,7 +296,7 @@ <context> <name>BanTableModel</name> <message> - <location filename="../bantablemodel.cpp" line="+89"/> + <location filename="../bantablemodel.cpp" line="+88"/> <source>IP/Netmask</source> <translation type="unfinished"></translation> </message> @@ -304,27 +309,27 @@ <context> <name>BitcoinGUI</name> <message> - <location filename="../bitcoingui.cpp" line="+358"/> + <location filename="../bitcoingui.cpp" line="+307"/> <source>Sign &message...</source> <translation>Sign &message...</translation> </message> <message> - <location line="+430"/> + <location line="+483"/> <source>Synchronizing with network...</source> <translation>Synchronizing with network...</translation> </message> <message> - <location line="-508"/> + <location line="-561"/> <source>&Overview</source> <translation>&Overview</translation> </message> <message> - <location line="-144"/> + <location line="-140"/> <source>Node</source> <translation type="unfinished"></translation> </message> <message> - <location line="+145"/> + <location line="+141"/> <source>Show general overview of wallet</source> <translation>Show general overview of wallet</translation> </message> @@ -409,7 +414,17 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+360"/> + <location line="+104"/> + <source>Wallet:</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+83"/> + <source>default wallet</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+226"/> <source>Click to disable network activity.</source> <translation type="unfinished"></translation> </message> @@ -434,7 +449,12 @@ <translation>Reindexing blocks on disk...</translation> </message> <message> - <location line="-511"/> + <location line="+316"/> + <source>Proxy is <b>enabled</b>: %1</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="-880"/> <source>Send coins to a Bitcoin address</source> <translation>Send coins to a Bitcoin address</translation> </message> @@ -464,17 +484,17 @@ <translation>&Verify message...</translation> </message> <message> - <location line="+517"/> + <location line="+570"/> <source>Bitcoin</source> <translation>Bitcoin</translation> </message> <message> - <location line="-743"/> + <location line="-792"/> <source>Wallet</source> <translation>Wallet</translation> </message> <message> - <location line="+153"/> + <location line="+149"/> <source>&Send</source> <translation>&Send</translation> </message> @@ -554,7 +574,7 @@ <translation type="unfinished"></translation> </message> <message numerus="yes"> - <location line="+357"/> + <location line="+410"/> <source>%n active connection(s) to Bitcoin network</source> <translation> <numerusform>%n active connection to Bitcoin network</numerusform> @@ -615,12 +635,12 @@ <translation>Up to date</translation> </message> <message> - <location line="-441"/> + <location line="-494"/> <source>Show the %1 help message to get a list with possible Bitcoin command-line options</source> <translation type="unfinished"></translation> </message> <message> - <location line="+200"/> + <location line="+253"/> <source>%1 client</source> <translation type="unfinished"></translation> </message> @@ -635,7 +655,7 @@ <translation>Catching up...</translation> </message> <message> - <location line="+145"/> + <location line="+151"/> <source>Date: %1 </source> <translation type="unfinished"></translation> @@ -647,7 +667,13 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> + <location line="+2"/> + <source>Wallet: %1 +</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+2"/> <source>Type: %1 </source> <translation type="unfinished"></translation> @@ -695,7 +721,7 @@ <translation>Wallet is <b>encrypted</b> and currently <b>locked</b></translation> </message> <message> - <location filename="../bitcoin.cpp" line="+534"/> + <location filename="../bitcoin.cpp" line="+529"/> <source>A fatal error occurred. Bitcoin can no longer continue safely and will quit.</source> <translation type="unfinished"></translation> </message> @@ -849,7 +875,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+325"/> + <location line="+315"/> <source>(%1 locked)</source> <translation type="unfinished"></translation> </message> @@ -874,8 +900,8 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+42"/> - <location line="+52"/> + <location line="+45"/> + <location line="+54"/> <source>(no label)</source> <translation type="unfinished"></translation> </message> @@ -918,12 +944,7 @@ <translation>&Address</translation> </message> <message> - <location filename="../editaddressdialog.cpp" line="+30"/> - <source>New receiving address</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+4"/> + <location filename="../editaddressdialog.cpp" line="+29"/> <source>New sending address</source> <translation type="unfinished"></translation> </message> @@ -938,17 +959,22 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+72"/> + <location line="+71"/> <source>The entered address "%1" is not a valid Bitcoin address.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+5"/> - <source>The entered address "%1" is already in the address book.</source> + <location line="+33"/> + <source>Address "%1" already exists as a receiving address with label "%2" and so cannot be added as a sending address.</source> <translation type="unfinished"></translation> </message> <message> <location line="+5"/> + <source>The entered address "%1" is already in the address book with label "%2".</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="-28"/> <source>Could not unlock wallet.</source> <translation type="unfinished"></translation> </message> @@ -961,7 +987,7 @@ <context> <name>FreespaceChecker</name> <message> - <location filename="../intro.cpp" line="+76"/> + <location filename="../intro.cpp" line="+77"/> <source>A new data directory will be created.</source> <translation>A new data directory will be created.</translation> </message> @@ -989,7 +1015,7 @@ <context> <name>HelpMessageDialog</name> <message> - <location filename="../utilitydialog.cpp" line="+40"/> + <location filename="../utilitydialog.cpp" line="+41"/> <source>version</source> <translation type="unfinished">version</translation> </message> @@ -1009,51 +1035,6 @@ <source>Command-line options</source> <translation type="unfinished"></translation> </message> - <message> - <location line="+1"/> - <source>Usage:</source> - <translation type="unfinished">Usage:</translation> - </message> - <message> - <location line="+1"/> - <source>command-line options</source> - <translation type="unfinished">command-line options</translation> - </message> - <message> - <location line="+9"/> - <source>UI Options:</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+4"/> - <source>Choose data directory on startup (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Set language, for example "de_DE" (default: system locale)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Start minimized</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Set SSL root certificates for payment request (default: -system-)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Show splash screen on startup (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Reset all settings changed in the GUI</source> - <translation type="unfinished"></translation> - </message> </context> <context> <name>Intro</name> @@ -1128,7 +1109,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+26"/> + <location line="+27"/> <source>Error</source> <translation>Error</translation> </message> @@ -1238,7 +1219,7 @@ <translation type="unfinished"></translation> </message> <message> - <location filename="../openuridialog.cpp" line="+47"/> + <location filename="../openuridialog.cpp" line="+45"/> <source>Select payment request file to open</source> <translation type="unfinished"></translation> </message> @@ -1266,7 +1247,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+9"/> + <location line="+72"/> <source>Size of &database cache</source> <translation type="unfinished"></translation> </message> @@ -1350,7 +1331,27 @@ <translation>&Network</translation> </message> <message> - <location line="-85"/> + <location line="-191"/> + <source>Disables some advanced features but all blocks will still be fully validated. Reverting this setting requires re-downloading the entire blockchain. Actual disk usage may be somewhat higher.</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+3"/> + <source>Prune &block storage to</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+10"/> + <source>GB</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+25"/> + <source>Reverting this setting requires re-downloading the entire blockchain.</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+68"/> <source>(0 = auto, <0 = leave that many cores free)</source> <translation type="unfinished"></translation> </message> @@ -1518,28 +1519,28 @@ <translation>&Cancel</translation> </message> <message> - <location filename="../optionsdialog.cpp" line="+82"/> + <location filename="../optionsdialog.cpp" line="+92"/> <source>default</source> <translation>default</translation> </message> <message> - <location line="+64"/> + <location line="+52"/> <source>none</source> <translation type="unfinished"></translation> </message> <message> - <location line="+72"/> + <location line="+77"/> <source>Confirm options reset</source> <translation>Confirm options reset</translation> </message> <message> <location line="+1"/> - <location line="+55"/> + <location line="+60"/> <source>Client restart required to activate changes.</source> <translation type="unfinished"></translation> </message> <message> - <location line="-55"/> + <location line="-60"/> <source>Client will be shut down. Do you want to proceed?</source> <translation type="unfinished"></translation> </message> @@ -1564,7 +1565,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+38"/> + <location line="+43"/> <source>This change would require a client restart.</source> <translation type="unfinished"></translation> </message> @@ -1671,10 +1672,10 @@ <context> <name>PaymentServer</name> <message> - <location filename="../paymentserver.cpp" line="+326"/> - <location line="+214"/> + <location filename="../paymentserver.cpp" line="+317"/> + <location line="+215"/> <location line="+42"/> - <location line="+111"/> + <location line="+110"/> <location line="+14"/> <location line="+18"/> <source>Payment request error</source> @@ -1686,14 +1687,20 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+102"/> + <location line="+82"/> + <location line="+21"/> <location line="+13"/> <location line="+7"/> <source>URI handling</source> <translation type="unfinished"></translation> </message> <message> - <location line="-19"/> + <location line="-41"/> + <source>'bitcoin://' is not a valid URI. Use 'bitcoin:' instead.</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+22"/> <source>Payment request fetch URL is invalid: %1</source> <translation type="unfinished"></translation> </message> @@ -1723,12 +1730,12 @@ <location line="+31"/> <location line="+10"/> <location line="+17"/> - <location line="+86"/> + <location line="+85"/> <source>Payment request rejected</source> <translation type="unfinished"></translation> </message> <message> - <location line="-153"/> + <location line="-152"/> <source>Payment request network doesn't match client network.</source> <translation type="unfinished"></translation> </message> @@ -1759,12 +1766,12 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+55"/> + <location line="+65"/> <source>Refund from %1</source> <translation type="unfinished"></translation> </message> <message> - <location line="+42"/> + <location line="+31"/> <source>Payment request %1 is too large (%2 bytes, allowed %3 bytes).</source> <translation type="unfinished"></translation> </message> @@ -1797,7 +1804,7 @@ <context> <name>PeerTableModel</name> <message> - <location filename="../peertablemodel.cpp" line="+121"/> + <location filename="../peertablemodel.cpp" line="+109"/> <source>User Agent</source> <translation type="unfinished"></translation> </message> @@ -1830,17 +1837,17 @@ <context> <name>QObject</name> <message> - <location filename="../bitcoinunits.cpp" line="+185"/> + <location filename="../bitcoinunits.cpp" line="+197"/> <source>Amount</source> <translation type="unfinished">Amount</translation> </message> <message> - <location filename="../guiutil.cpp" line="+130"/> + <location filename="../guiutil.cpp" line="+124"/> <source>Enter a Bitcoin address (e.g. %1)</source> <translation type="unfinished"></translation> </message> <message> - <location line="+760"/> + <location line="+722"/> <source>%1 d</source> <translation type="unfinished"></translation> </message> @@ -1950,7 +1957,7 @@ <translation type="unfinished"></translation> </message> <message> - <location filename="../bitcoin.cpp" line="+178"/> + <location filename="../bitcoin.cpp" line="+193"/> <source>%1 didn't yet exit safely...</source> <translation type="unfinished"></translation> </message> @@ -1963,13 +1970,18 @@ <context> <name>QObject::QObject</name> <message> - <location filename="../bitcoin.cpp" line="-86"/> + <location filename="../bitcoin.cpp" line="-118"/> + <source>Error parsing command line arguments: %1.</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+39"/> <source>Error: Specified data directory "%1" does not exist.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+7"/> - <source>Error: Cannot parse configuration file: %1. Only use key=value syntax.</source> + <location line="+5"/> + <source>Error: Cannot parse configuration file: %1.</source> <translation type="unfinished"></translation> </message> <message> @@ -1981,7 +1993,7 @@ <context> <name>QRImageWidget</name> <message> - <location filename="../receiverequestdialog.cpp" line="+35"/> + <location filename="../receiverequestdialog.cpp" line="+32"/> <source>&Save Image...</source> <translation type="unfinished"></translation> </message> @@ -2015,7 +2027,7 @@ <location line="+23"/> <location line="+36"/> <location line="+23"/> - <location line="+663"/> + <location line="+679"/> <location line="+23"/> <location line="+23"/> <location line="+23"/> @@ -2037,7 +2049,7 @@ <translation>N/A</translation> </message> <message> - <location line="-1345"/> + <location line="-1361"/> <source>Client version</source> <translation>Client version</translation> </message> @@ -2112,7 +2124,17 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+324"/> + <location line="+94"/> + <source>Wallet: </source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+8"/> + <source>(none)</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+238"/> <source>&Reset</source> <translation type="unfinished"></translation> </message> @@ -2140,8 +2162,8 @@ </message> <message> <location line="+60"/> - <location filename="../rpcconsole.cpp" line="+496"/> - <location line="+718"/> + <location filename="../rpcconsole.cpp" line="+502"/> + <location line="+760"/> <source>Select a peer to view detailed information.</source> <translation type="unfinished"></translation> </message> @@ -2176,18 +2198,18 @@ <translation type="unfinished"></translation> </message> <message> - <location line="-1079"/> - <location line="+987"/> + <location line="-1095"/> + <location line="+1003"/> <source>User Agent</source> <translation type="unfinished"></translation> </message> <message> - <location line="-684"/> + <location line="-700"/> <source>Open the %1 debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+68"/> + <location line="+84"/> <source>Decrease font size</source> <translation type="unfinished"></translation> </message> @@ -2247,7 +2269,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="-1116"/> + <location line="-1132"/> <source>Last block time</source> <translation>Last block time</translation> </message> @@ -2262,7 +2284,7 @@ <translation>&Console</translation> </message> <message> - <location line="+195"/> + <location line="+211"/> <source>&Network Traffic</source> <translation type="unfinished"></translation> </message> @@ -2272,7 +2294,7 @@ <translation type="unfinished"></translation> </message> <message> - <location filename="../rpcconsole.cpp" line="-401"/> + <location filename="../rpcconsole.cpp" line="-414"/> <source>In:</source> <translation type="unfinished"></translation> </message> @@ -2282,17 +2304,17 @@ <translation type="unfinished"></translation> </message> <message> - <location filename="../forms/debugwindow.ui" line="-299"/> + <location filename="../forms/debugwindow.ui" line="-315"/> <source>Debug log file</source> <translation>Debug log file</translation> </message> <message> - <location line="+136"/> + <location line="+152"/> <source>Clear console</source> <translation>Clear console</translation> </message> <message> - <location filename="../rpcconsole.cpp" line="-225"/> + <location filename="../rpcconsole.cpp" line="-253"/> <source>1 &hour</source> <translation type="unfinished"></translation> </message> @@ -2330,7 +2352,12 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+136"/> + <location line="+54"/> + <source>default wallet</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+110"/> <source>Welcome to the %1 RPC console.</source> <translation type="unfinished"></translation> </message> @@ -2360,7 +2387,17 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+243"/> + <location line="+68"/> + <source>Executing command without any wallet</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+2"/> + <source>Executing command using "%1" wallet</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+190"/> <source>(node id: %1)</source> <translation type="unfinished"></translation> </message> @@ -2453,27 +2490,27 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+142"/> - <source>Requested payments history</source> + <location line="+78"/> + <source>Native segwit addresses (aka Bech32 or BIP-173) reduce your transaction fees later on and offer better protection against typos, but old wallets don't support them. When unchecked, an address compatible with older wallets will be created instead.</source> <translation type="unfinished"></translation> </message> <message> - <location line="-162"/> - <source>&Request payment</source> + <location line="+3"/> + <source>Generate native segwit (Bech32) address</source> <translation type="unfinished"></translation> </message> <message> - <location line="+98"/> - <source>Bech32 addresses (BIP-173) are cheaper to spend from and offer better protection against typos. When unchecked a P2SH wrapped SegWit address will be created, compatible with older wallets.</source> + <location line="+61"/> + <source>Requested payments history</source> <translation type="unfinished"></translation> </message> <message> - <location line="+3"/> - <source>Generate Bech32 address</source> + <location line="-162"/> + <source>&Request payment</source> <translation type="unfinished"></translation> </message> <message> - <location line="+86"/> + <location line="+187"/> <source>Show the selected request (does the same as double clicking an entry)</source> <translation type="unfinished"></translation> </message> @@ -2571,7 +2608,12 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+10"/> + <location line="+2"/> + <source>Wallet</source> + <translation type="unfinished">Wallet</translation> + </message> + <message> + <location line="+11"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"></translation> </message> @@ -2584,7 +2626,7 @@ <context> <name>RecentRequestsTableModel</name> <message> - <location filename="../recentrequeststablemodel.cpp" line="+28"/> + <location filename="../recentrequeststablemodel.cpp" line="+27"/> <source>Date</source> <translation type="unfinished">Date</translation> </message> @@ -2623,7 +2665,7 @@ <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> - <location filename="../sendcoinsdialog.cpp" line="+578"/> + <location filename="../sendcoinsdialog.cpp" line="+588"/> <source>Send Coins</source> <translation>Send Coins</translation> </message> @@ -2713,22 +2755,24 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+54"/> - <source>per kilobyte</source> + <location line="+51"/> + <source>Specify a custom fee per kB (1,000 bytes) of the transaction's virtual size. + +Note: Since the fee is calculated on a per-byte basis, a fee of "100 satoshis per kB" for a transaction size of 500 bytes (half of 1 kB) would ultimately yield a fee of only 50 satoshis.</source> <translation type="unfinished"></translation> </message> <message> - <location line="-3"/> - <source>If the custom fee is set to 1000 satoshis and the transaction is only 250 bytes, then "per kilobyte" only pays 250 satoshis in fee, while "total at least" pays 1000 satoshis. For transactions bigger than a kilobyte both pay by kilobyte.</source> + <location line="+5"/> + <source>per kilobyte</source> <translation type="unfinished"></translation> </message> <message> - <location line="-48"/> + <location line="-53"/> <source>Hide</source> <translation type="unfinished"></translation> </message> <message> - <location line="+78"/> + <location line="+80"/> <location line="+13"/> <source>Paying only the minimum fee is just fine as long as there is less transaction volume than space in the blocks. But be aware that this can end up in a never confirming transaction once there is more demand for bitcoin transactions than the network can process.</source> <translation type="unfinished"></translation> @@ -2769,12 +2813,12 @@ <translation type="unfinished"></translation> </message> <message> - <location line="-833"/> + <location line="-835"/> <source>Dust:</source> <translation type="unfinished"></translation> </message> <message> - <location line="+694"/> + <location line="+696"/> <source>Confirmation time target:</source> <translation type="unfinished"></translation> </message> @@ -2809,7 +2853,7 @@ <translation>S&end</translation> </message> <message> - <location filename="../sendcoinsdialog.cpp" line="-494"/> + <location filename="../sendcoinsdialog.cpp" line="-504"/> <source>Copy quantity</source> <translation type="unfinished"></translation> </message> @@ -2849,7 +2893,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+127"/> + <location line="+131"/> <location line="+5"/> <location line="+5"/> <location line="+4"/> @@ -2862,31 +2906,41 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+9"/> - <source>added as transaction fee</source> + <location line="+42"/> + <source>or</source> <translation type="unfinished"></translation> </message> <message> - <location line="+15"/> - <source>Total Amount %1</source> + <location line="-19"/> + <source>You can increase the fee later (signals Replace-By-Fee, BIP-125).</source> <translation type="unfinished"></translation> </message> <message> - <location line="+3"/> - <source>or</source> + <location line="-57"/> + <source>from wallet %1</source> <translation type="unfinished"></translation> </message> <message> - <location line="+4"/> - <source>You can increase the fee later (signals Replace-By-Fee, BIP-125).</source> + <location line="+36"/> + <source>Please, review your transaction.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+2"/> + <location line="+7"/> + <source>Transaction fee</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+16"/> <source>Not signalling Replace-By-Fee, BIP-125.</source> <translation type="unfinished"></translation> </message> <message> + <location line="+14"/> + <source>Total Amount</source> + <translation type="unfinished"></translation> + </message> + <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"></translation> @@ -2942,7 +2996,7 @@ <translation type="unfinished"></translation> </message> <message numerus="yes"> - <location line="+42"/> + <location line="+43"/> <source>Estimated to begin confirmation within %n block(s).</source> <translation> <numerusform>Estimated to begin confirmation within %n block.</numerusform> @@ -3084,7 +3138,7 @@ <translation type="unfinished"></translation> </message> <message> - <location filename="../sendcoinsentry.cpp" line="+36"/> + <location filename="../sendcoinsentry.cpp" line="+35"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"></translation> </message> @@ -3101,7 +3155,7 @@ <context> <name>ShutdownWindow</name> <message> - <location filename="../utilitydialog.cpp" line="+78"/> + <location filename="../utilitydialog.cpp" line="+84"/> <source>%1 is shutting down...</source> <translation type="unfinished"></translation> </message> @@ -3222,12 +3276,12 @@ <translation>Reset all verify message fields</translation> </message> <message> - <location filename="../signverifymessagedialog.cpp" line="+41"/> + <location filename="../signverifymessagedialog.cpp" line="+39"/> <source>Click "Sign Message" to generate signature</source> <translation type="unfinished"></translation> </message> <message> - <location line="+82"/> + <location line="+81"/> <location line="+78"/> <source>The entered address is invalid.</source> <translation type="unfinished"></translation> @@ -3304,7 +3358,7 @@ <context> <name>TrafficGraphWidget</name> <message> - <location filename="../trafficgraphwidget.cpp" line="+80"/> + <location filename="../trafficgraphwidget.cpp" line="+81"/> <source>KB/s</source> <translation type="unfinished"></translation> </message> @@ -3312,7 +3366,7 @@ <context> <name>TransactionDesc</name> <message numerus="yes"> - <location filename="../transactiondesc.cpp" line="+30"/> + <location filename="../transactiondesc.cpp" line="+31"/> <source>Open for %n more block(s)</source> <translation> <numerusform>Open for %n more block</numerusform> @@ -3331,11 +3385,6 @@ </message> <message> <location line="+2"/> - <source>%1/offline</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+2"/> <source>0/unconfirmed, %1</source> <translation type="unfinished"></translation> </message> @@ -3365,25 +3414,12 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+17"/> + <location line="+23"/> <source>Status</source> <translation type="unfinished"></translation> </message> <message> - <location line="+5"/> - <source>, has not been successfully broadcast yet</source> - <translation type="unfinished"></translation> - </message> - <message numerus="yes"> - <location line="+2"/> - <source>, broadcast through %n node(s)</source> - <translation> - <numerusform>, broadcast through %n node</numerusform> - <numerusform>, broadcast through %n nodes</numerusform> - </translation> - </message> - <message> - <location line="+4"/> + <location line="+3"/> <source>Date</source> <translation type="unfinished">Date</translation> </message> @@ -3399,7 +3435,7 @@ </message> <message> <location line="+5"/> - <location line="+12"/> + <location line="+14"/> <location line="+72"/> <source>From</source> <translation type="unfinished"></translation> @@ -3412,12 +3448,12 @@ <message> <location line="+1"/> <location line="+20"/> - <location line="+69"/> + <location line="+70"/> <source>To</source> <translation type="unfinished"></translation> </message> <message> - <location line="-87"/> + <location line="-88"/> <source>own address</source> <translation type="unfinished"></translation> </message> @@ -3433,16 +3469,16 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+34"/> + <location line="+36"/> <location line="+12"/> - <location line="+53"/> - <location line="+26"/> - <location line="+55"/> + <location line="+54"/> + <location line="+30"/> + <location line="+58"/> <source>Credit</source> <translation type="unfinished"></translation> </message> <message numerus="yes"> - <location line="-144"/> + <location line="-152"/> <source>matures in %n more block(s)</source> <translation> <numerusform>matures in %n more block</numerusform> @@ -3455,14 +3491,14 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+59"/> - <location line="+25"/> - <location line="+55"/> + <location line="+60"/> + <location line="+26"/> + <location line="+61"/> <source>Debit</source> <translation type="unfinished"></translation> </message> <message> - <location line="-70"/> + <location line="-77"/> <source>Total debit</source> <translation type="unfinished"></translation> </message> @@ -3477,18 +3513,18 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+16"/> + <location line="+22"/> <source>Net amount</source> <translation type="unfinished"></translation> </message> <message> <location line="+6"/> - <location line="+11"/> + <location line="+12"/> <source>Message</source> <translation type="unfinished"></translation> </message> <message> - <location line="-9"/> + <location line="-10"/> <source>Comment</source> <translation type="unfinished"></translation> </message> @@ -3504,6 +3540,11 @@ </message> <message> <location line="+1"/> + <source>Transaction virtual size</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+1"/> <source>Output index</source> <translation type="unfinished"></translation> </message> @@ -3533,7 +3574,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+20"/> + <location line="+21"/> <source>Amount</source> <translation type="unfinished">Amount</translation> </message> @@ -3566,7 +3607,7 @@ <context> <name>TransactionTableModel</name> <message> - <location filename="../transactiontablemodel.cpp" line="+248"/> + <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation type="unfinished">Date</translation> </message> @@ -3595,11 +3636,6 @@ </message> <message> <location line="+3"/> - <source>Offline</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"></translation> </message> @@ -3630,11 +3666,6 @@ </message> <message> <location line="+3"/> - <source>This block was not received by any other nodes and will probably not be accepted!</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"></translation> </message> @@ -3674,7 +3705,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+213"/> + <location line="+208"/> <source>(no label)</source> <translation type="unfinished"></translation> </message> @@ -3773,17 +3804,17 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+6"/> + <location line="+5"/> <source>Enter address, transaction id, or label to search</source> <translation type="unfinished"></translation> </message> <message> - <location line="+6"/> + <location line="+4"/> <source>Min amount</source> <translation type="unfinished"></translation> </message> <message> - <location line="+48"/> + <location line="+47"/> <source>Abandon transaction</source> <translation type="unfinished"></translation> </message> @@ -3833,7 +3864,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+194"/> + <location line="+193"/> <source>Export Transaction History</source> <translation type="unfinished"></translation> </message> @@ -3911,7 +3942,7 @@ <context> <name>UnitDisplayStatusBarControl</name> <message> - <location filename="../bitcoingui.cpp" line="+129"/> + <location filename="../bitcoingui.cpp" line="+159"/> <source>Unit to show amounts in. Click to select another unit.</source> <translation type="unfinished"></translation> </message> @@ -3919,7 +3950,7 @@ <context> <name>WalletFrame</name> <message> - <location filename="../walletframe.cpp" line="+28"/> + <location filename="../walletframe.cpp" line="+29"/> <source>No wallet has been loaded.</source> <translation type="unfinished"></translation> </message> @@ -3927,12 +3958,12 @@ <context> <name>WalletModel</name> <message> - <location filename="../walletmodel.cpp" line="+290"/> + <location filename="../walletmodel.cpp" line="+215"/> <source>Send Coins</source> <translation type="unfinished">Send Coins</translation> </message> <message> - <location line="+384"/> + <location line="+289"/> <location line="+39"/> <location line="+6"/> <source>Fee bump error</source> @@ -3982,7 +4013,7 @@ <context> <name>WalletView</name> <message> - <location filename="../walletview.cpp" line="+46"/> + <location filename="../walletview.cpp" line="+47"/> <source>&Export</source> <translation type="unfinished">&Export</translation> </message> @@ -3992,7 +4023,7 @@ <translation type="unfinished">Export the data in the current tab to a file</translation> </message> <message> - <location line="+201"/> + <location line="+207"/> <source>Backup Wallet</source> <translation type="unfinished"></translation> </message> @@ -4021,46 +4052,21 @@ <source>The wallet data was successfully saved to %1.</source> <translation type="unfinished"></translation> </message> + <message> + <location line="+54"/> + <source>Cancel</source> + <translation type="unfinished"></translation> + </message> </context> <context> <name>bitcoin-core</name> <message> - <location filename="../bitcoinstrings.cpp" line="+351"/> - <source>Options:</source> - <translation>Options:</translation> - </message> - <message> - <location line="+33"/> - <source>Specify data directory</source> - <translation>Specify data directory</translation> - </message> - <message> - <location line="-99"/> - <source>Connect to a node to retrieve peer addresses, and disconnect</source> - <translation>Connect to a node to retrieve peer addresses, and disconnect</translation> - </message> - <message> - <location line="+102"/> - <source>Specify your own public address</source> - <translation>Specify your own public address</translation> - </message> - <message> - <location line="-116"/> - <source>Accept command line and JSON-RPC commands</source> - <translation>Accept command line and JSON-RPC commands</translation> - </message> - <message> - <location line="-209"/> + <location filename="../bitcoinstrings.cpp" line="+29"/> <source>Distributed under the MIT software license, see the accompanying file %s or %s</source> <translation type="unfinished"></translation> </message> <message> - <location line="+44"/> - <source>If <category> is not supplied or if <category> = 1, output all debugging information.</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+36"/> + <location line="+22"/> <source>Prune configured below the minimum of %d MiB. Please use a higher number.</source> <translation type="unfinished"></translation> </message> @@ -4070,37 +4076,27 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+18"/> + <location line="+3"/> <source>Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+151"/> + <location line="+81"/> <source>Error: A fatal internal error occurred, see debug.log for details</source> <translation type="unfinished"></translation> </message> <message> - <location line="+4"/> - <source>Fee (in %s/kB) to add to transactions you send (default: %s)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+41"/> + <location line="+25"/> <source>Pruning blockstore...</source> <translation type="unfinished"></translation> </message> <message> - <location line="+11"/> - <source>Run in the background as a daemon and accept commands</source> - <translation>Run in the background as a daemon and accept commands</translation> - </message> - <message> - <location line="+40"/> + <location line="+28"/> <source>Unable to start HTTP server. See debug log for details.</source> <translation type="unfinished"></translation> </message> <message> - <location line="-397"/> + <location line="-178"/> <source>Bitcoin Core</source> <translation type="unfinished">Bitcoin Core</translation> </message> @@ -4111,26 +4107,6 @@ </message> <message> <location line="+7"/> - <source>A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> - <source>Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> - <source>Add a node to connect to and attempt to keep the connection open (see the `addnode` RPC command help for more info)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+7"/> - <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> - <translation>Bind to given address and always listen on it. Use [host]:port notation for IPv6</translation> - </message> - <message> - <location line="+12"/> <source>Cannot obtain a lock on data directory %s. %s is probably already running.</source> <translation type="unfinished"></translation> </message> @@ -4140,52 +4116,12 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+3"/> - <source>Connect only to the specified node(s); -connect=0 disables automatic connections (the rules for this peer are the same as for -addnode)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+6"/> - <source>Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+18"/> + <location line="+12"/> <source>Error reading %s! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+5"/> - <source>Exclude debugging information for a category. Can be used in conjunction with -debug=1 to output debug logs for all categories except one or more specified categories.</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+7"/> - <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> - <translation>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</translation> - </message> - <message> - <location line="+6"/> - <source>Extra transactions to keep in memory for compact block reconstructions (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+20"/> - <source>If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+10"/> - <source>Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+7"/> - <source>Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+7"/> + <location line="+11"/> <source>Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.</source> <translation type="unfinished"></translation> </message> @@ -4195,32 +4131,12 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+8"/> - <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+6"/> - <source>Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex and -rescan. Warning: Reverting this setting requires re-downloading the entire blockchain. (default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >%u = automatically prune block files to stay under the specified target size in MiB)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+12"/> - <source>Set lowest fee rate (in %s/kB) for transactions to be included in block creation. (default: %s)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+5"/> - <source>Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+14"/> + <location line="+11"/> <source>The block database contains a block which appears to be from the future. This may be due to your computer's date and time being set incorrectly. Only rebuild the block database if you are sure that your computer's date and time are correct</source> <translation type="unfinished"></translation> </message> <message> - <location line="+12"/> + <location line="+7"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"></translation> </message> @@ -4230,7 +4146,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+15"/> + <location line="+12"/> <source>Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.</source> <translation type="unfinished"></translation> </message> @@ -4240,22 +4156,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+9"/> - <source>Use UPnP to map the listening port (default: 1 when listening and no -proxy)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+5"/> - <source>Username and hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcuser. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+6"/> - <source>Wallet will not create transactions that violate mempool chain limits (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> + <location line="+11"/> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation type="unfinished"></translation> </message> @@ -4265,12 +4166,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+3"/> - <source>Whether to save the mempool on shutdown and load on restart (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+11"/> + <location line="+6"/> <source>%d of last 100 blocks have unexpected version</source> <translation type="unfinished"></translation> </message> @@ -4280,56 +4176,21 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+4"/> - <source>-maxmempool must be at least %d MB</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source><category> can be:</source> - <translation type="unfinished"></translation> - </message> - <message> <location line="+2"/> - <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+4"/> - <source>Append comment to the user agent string</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Attempt to recover private keys from a corrupt wallet on startup</source> + <source>-maxmempool must be at least %d MB</source> <translation type="unfinished"></translation> </message> <message> <location line="+2"/> - <source>Block creation options:</source> - <translation>Block creation options:</translation> - </message> - <message> - <location line="+2"/> <source>Cannot resolve -%s address: '%s'</source> <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> - <source>Chain selection options:</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> + <location line="+2"/> <source>Change index out of range</source> <translation type="unfinished"></translation> </message> <message> - <location line="+3"/> - <source>Connection options:</source> - <translation type="unfinished"></translation> - </message> - <message> <location line="+1"/> <source>Copyright (C) %i-%i</source> <translation type="unfinished"></translation> @@ -4341,46 +4202,11 @@ </message> <message> <location line="+1"/> - <source>Debugging/Testing options:</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Do not load the wallet and disable wallet RPC calls</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Do you want to rebuild the block database now?</translation> </message> <message> <location line="+2"/> - <source>Enable publish hash block in <address></source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Enable publish hash transaction in <address></source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Enable publish raw block in <address></source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Enable publish raw transaction in <address></source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Enable transaction replacement in the memory pool (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> <source>Error creating %s: You can't create non-HD wallets with this version.</source> <translation type="unfinished"></translation> </message> @@ -4401,6 +4227,11 @@ </message> <message> <location line="+1"/> + <source>Error loading %s: Private keys can only be disabled during creation</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+1"/> <source>Error loading %s: Wallet corrupted</source> <translation type="unfinished"></translation> </message> @@ -4415,7 +4246,7 @@ <translation>Error loading block database</translation> </message> <message> - <location line="+4"/> + <location line="+2"/> <source>Error opening block database</source> <translation>Error opening block database</translation> </message> @@ -4435,12 +4266,12 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+3"/> + <location line="+1"/> <source>Importing...</source> <translation type="unfinished"></translation> </message> <message> - <location line="+3"/> + <location line="+1"/> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>Incorrect or no genesis block found. Wrong datadir for network?</translation> </message> @@ -4465,12 +4296,12 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+4"/> - <source>Keep the transaction memory pool below <n> megabytes (default: %u)</source> + <location line="+47"/> + <source>Upgrading txindex database</source> <translation type="unfinished"></translation> </message> <message> - <location line="+4"/> + <location line="-43"/> <source>Loading P2P addresses...</source> <translation type="unfinished"></translation> </message> @@ -4480,32 +4311,12 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+3"/> - <source>Location of the auth cookie (default: data dir)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+7"/> + <location line="+4"/> <source>Not enough file descriptors available.</source> <translation>Not enough file descriptors available.</translation> </message> <message> <location line="+1"/> - <source>Only connect to nodes in network <net> (ipv4, ipv6 or onion)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+4"/> - <source>Print this help message and exit</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Print version and exit</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> <source>Prune cannot be configured with a negative value.</source> <translation type="unfinished"></translation> </message> @@ -4516,46 +4327,21 @@ </message> <message> <location line="+3"/> - <source>Rebuild chain state and block index from the blk*.dat files on disk</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Rebuild chain state from the currently indexed blocks</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+4"/> <source>Replaying blocks...</source> <translation type="unfinished"></translation> </message> <message> - <location line="+3"/> + <location line="+2"/> <source>Rewinding blocks...</source> <translation type="unfinished"></translation> </message> <message> - <location line="+3"/> - <source>Send transactions with full-RBF opt-in enabled (RPC only, default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Set database cache size in megabytes (%d to %d, default: %d)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+14"/> - <source>Specify wallet file (within data directory)</source> - <translation>Specify wallet file (within data directory)</translation> - </message> - <message> - <location line="+4"/> + <location line="+7"/> <source>The source code is available from %s.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+11"/> + <location line="+8"/> <source>Transaction fee and change calculation failed</source> <translation type="unfinished"></translation> </message> @@ -4565,7 +4351,12 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+4"/> + <location line="+2"/> + <source>Unable to generate keys</source> + <translation type="unfinished"></translation> + </message> + <message> + <location line="+3"/> <source>Unsupported argument -benchmark ignored, use -debug=bench.</source> <translation type="unfinished"></translation> </message> @@ -4585,142 +4376,52 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+2"/> - <source>Upgrading UTXO database</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Use UPnP to map the listening port (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> <location line="+1"/> - <source>Use the test chain</source> + <source>Upgrading UTXO database</source> <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> + <location line="+2"/> <source>User Agent comment (%s) contains unsafe characters.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+2"/> + <location line="+1"/> <source>Verifying blocks...</source> <translation>Verifying blocks...</translation> </message> <message> <location line="+3"/> - <source>Wallet debugging/testing options:</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> <source>Wallet needed to be rewritten: restart %s to complete</source> <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> - <source>Wallet options:</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="-397"/> - <source>Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+7"/> - <source>Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+17"/> - <source>Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+6"/> - <source>Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+18"/> + <location line="-165"/> <source>Error: Listening for incoming connections failed (listen returned error %s)</source> <translation type="unfinished"></translation> </message> <message> - <location line="+6"/> - <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> - <translation>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</translation> - </message> - <message> - <location line="+12"/> - <source>Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+14"/> - <source>If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+7"/> + <location line="+5"/> <source>Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)</source> <translation type="unfinished"></translation> </message> <message> - <location line="+10"/> - <source>Maximum size of data in data carrier transactions we relay and mine (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+24"/> - <source>Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+44"/> + <location line="+22"/> <source>The transaction amount is too small to send after the fee has been deducted</source> <translation type="unfinished"></translation> </message> <message> - <location line="+64"/> - <source>Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> + <location line="+44"/> <source>You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain</source> <translation type="unfinished"></translation> </message> <message> - <location line="+7"/> - <source>(default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+5"/> - <source>Accept public REST requests (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+5"/> - <source>Automatically create Tor hidden service (default: %d)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+6"/> - <source>Connect through SOCKS5 proxy</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+20"/> + <location line="+22"/> <source>Error loading %s: You can't disable HD on an already existing HD wallet</source> <translation type="unfinished"></translation> </message> <message> - <location line="+6"/> + <location line="+4"/> <source>Error reading from database, shutting down.</source> <translation type="unfinished"></translation> </message> @@ -4730,12 +4431,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+9"/> - <source>Imports blocks from external blk000??.dat file on startup</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> + <location line="+8"/> <source>Information</source> <translation>Information</translation> </message> @@ -4760,52 +4456,17 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> - <source>Keep at most <n> unconnectable transactions in memory (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+14"/> + <location line="+6"/> <source>Need to specify a port with -whitebind: '%s'</source> <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> - <source>Node relay options:</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+11"/> - <source>RPC server options:</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> + <location line="+5"/> <source>Reducing -maxconnections from %d to %d, because of system limitations.</source> <translation type="unfinished"></translation> </message> <message> <location line="+4"/> - <source>Rescan the block chain for missing wallet transactions on startup</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+4"/> - <source>Send trace/debug info to console instead of debug.log file</source> - <translation>Send trace/debug info to console instead of debug.log file</translation> - </message> - <message> - <location line="+6"/> - <source>Show all debugging options (usage: --help -help-debug)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> - <translation>Shrink debug.log file on client startup (default: 1 when no -debug)</translation> - </message> - <message> - <location line="+1"/> <source>Signing transaction failed</source> <translation>Signing transaction failed</translation> </message> @@ -4825,27 +4486,23 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+10"/> - <source>The transaction amount is too small to pay the fee</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+2"/> - <source>This is experimental software.</source> + <location line="+1"/> + <source>Specified blocks directory "%s" does not exist. +</source> <translation type="unfinished"></translation> </message> <message> - <location line="+4"/> - <source>Tor control port password (default: empty)</source> + <location line="+3"/> + <source>The transaction amount is too small to pay the fee</source> <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> - <source>Tor control port to use if onion listening enabled (default: %s)</source> + <location line="+2"/> + <source>This is experimental software.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> + <location line="+3"/> <source>Transaction amount too small</source> <translation>Transaction amount too small</translation> </message> @@ -4870,17 +4527,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+7"/> - <source>Upgrade wallet to latest format on startup</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+5"/> - <source>Username for JSON-RPC connections</source> - <translation>Username for JSON-RPC connections</translation> - </message> - <message> - <location line="+2"/> + <location line="+12"/> <source>Verifying wallet(s)...</source> <translation type="unfinished"></translation> </message> @@ -4890,7 +4537,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+4"/> + <location line="+2"/> <source>Warning</source> <translation>Warning</translation> </message> @@ -4901,136 +4548,21 @@ </message> <message> <location line="+1"/> - <source>Whether to operate in a blocks only mode (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>You need to rebuild the database using -reindex to change -txindex</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> <source>Zapping all transactions from wallet...</source> <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> - <source>ZeroMQ notification options:</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="-80"/> - <source>Password for JSON-RPC connections</source> - <translation>Password for JSON-RPC connections</translation> - </message> - <message> - <location line="-263"/> - <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> - <translation>Execute command when the best block changes (%s in cmd is replaced by block hash)</translation> - </message> - <message> - <location line="+185"/> - <source>Allow DNS lookups for -addnode, -seednode and -connect</source> - <translation>Allow DNS lookups for -addnode, -seednode and -connect</translation> - </message> - <message> - <location line="-260"/> - <source>(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> + <location line="-191"/> <source>-maxtxfee is set very high! Fees this large could be paid on a single transaction.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+22"/> - <source>Bind to given address to listen for JSON-RPC connections. This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost, or if -rpcallowip has been specified, 0.0.0.0 and :: i.e., all addresses)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+26"/> - <source>Do not keep transactions in the mempool longer than <n> hours (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+2"/> - <source>Equivalent bytes per sigop in transactions for relay and mining (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+2"/> + <location line="+18"/> <source>Error loading %s: You can't enable HD on an already existing non-HD wallet</source> <translation type="unfinished"></translation> </message> <message> - <location line="+2"/> - <source>Error loading wallet %s. -wallet parameter must only specify a filename (not a path).</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+27"/> - <source>Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> - <source>Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> - <source>How thorough the block verification of -checkblocks is (0-4, default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+15"/> - <source>Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+13"/> - <source>Number of seconds to keep misbehaving peers from reconnecting (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+2"/> - <source>Output debugging information (default: %u, supplying <category> is optional)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+34"/> - <source>Set maximum BIP141 block weight to this * 4. Deprecated, use blockmaxweight</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+5"/> - <source>Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> - <source>Specify directory to hold wallets (default: <datadir>/wallets if it exists, otherwise <datadir>)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> - <source>Specify location of debug log file: this can be an absolute path or a path relative to the data directory (default: %s)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> - <source>Support filtering of blocks and transaction with bloom filters (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+7"/> - <source>The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+13"/> + <location line="+40"/> <source>This is the transaction fee you may pay when fee estimates are not available.</source> <translation type="unfinished"></translation> </message> @@ -5045,11 +4577,6 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+3"/> - <source>Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)</source> - <translation type="unfinished"></translation> - </message> - <message> <location line="+9"/> <source>Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source> <translation type="unfinished"></translation> @@ -5060,12 +4587,7 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+5"/> - <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+15"/> + <location line="+8"/> <source>Warning: Unknown block versions being mined! It's possible unknown rules are in effect</source> <translation type="unfinished"></translation> </message> @@ -5075,187 +4597,92 @@ <translation type="unfinished"></translation> </message> <message> - <location line="+9"/> - <source>Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or CIDR notated network (e.g. 1.2.3.0/24). Can be specified multiple times.</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+11"/> + <location line="+12"/> <source>%s is set very high!</source> <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> - <source>(default: %s)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+8"/> - <source>Always query for peer addresses via DNS lookup (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+31"/> - <source>Error loading wallet %s. -wallet filename must be a regular file.</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> + <location line="+19"/> <source>Error loading wallet %s. Duplicate -wallet filename specified.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> - <source>Error loading wallet %s. Invalid characters in -wallet filename.</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+10"/> - <source>How many blocks to check at startup (default: %u, 0 = all)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+3"/> - <source>Include IP addresses in debug output (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+14"/> + <location line="+21"/> <source>Keypool ran out, please call keypoolrefill first</source> <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> - <source>Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Listen for connections on <port> (default: %u or testnet: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+6"/> - <source>Maintain at most <n> connections to peers (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Make the wallet broadcast transactions</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Maximum per-connection send buffer, <n>*1000 bytes (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+7"/> - <source>Prepend debug output with timestamp (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+10"/> - <source>Relay and mine data carrier transactions (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Relay non-P2SH multisig (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+9"/> - <source>Set key pool size to <n> (default: %u)</source> - <translation type="unfinished"></translation> - </message> - <message> - <location line="+1"/> - <source>Set maximum BIP141 block weight (default: %d)</source> + <location line="+19"/> + <source>Starting network threads...</source> <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> - <source>Set the number of threads to service RPC calls (default: %d)</source> + <location line="+3"/> + <source>The wallet will avoid paying less than the minimum relay fee.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+7"/> - <source>Specify configuration file (default: %s)</source> + <location line="+2"/> + <source>This is the minimum transaction fee you pay on every transaction.</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> - <source>Specify connection timeout in milliseconds (minimum: 1, default: %d)</source> + <source>This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"></translation> </message> <message> <location line="+2"/> - <source>Specify pid file (default: %s)</source> + <source>Transaction amounts must not be negative</source> <translation type="unfinished"></translation> </message> <message> - <location line="+3"/> - <source>Spend unconfirmed change when sending transactions (default: %u)</source> + <location line="+2"/> + <source>Transaction has too long of a mempool chain</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> - <source>Starting network threads...</source> + <source>Transaction must have at least one recipient</source> <translation type="unfinished"></translation> </message> <message> - <location line="+3"/> - <source>The wallet will avoid paying less than the minimum relay fee.</source> - <translation type="unfinished"></translation> + <location line="+8"/> + <source>Unknown network specified in -onlynet: '%s'</source> + <translation>Unknown network specified in -onlynet: '%s'</translation> </message> <message> - <location line="+2"/> - <source>This is the minimum transaction fee you pay on every transaction.</source> - <translation type="unfinished"></translation> + <location line="-46"/> + <source>Insufficient funds</source> + <translation>Insufficient funds</translation> </message> <message> - <location line="+1"/> - <source>This is the transaction fee you will pay if you send a transaction.</source> + <location line="-128"/> + <source>Can't generate a change-address key. Private keys are disabled for this wallet.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> - <source>Threshold for disconnecting misbehaving peers (default: %u)</source> + <location line="+8"/> + <source>Cannot upgrade a non HD split wallet without upgrading to support pre split keypool. Please use -upgradewallet=169900 or -upgradewallet with no version specified.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+4"/> - <source>Transaction amounts must not be negative</source> + <location line="+14"/> + <source>Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+2"/> - <source>Transaction has too long of a mempool chain</source> + <location line="+54"/> + <source>Warning: Private keys detected in wallet {%s} with disabled private keys</source> <translation type="unfinished"></translation> </message> <message> - <location line="+1"/> - <source>Transaction must have at least one recipient</source> + <location line="+24"/> + <source>Cannot write to data directory '%s'; check permissions.</source> <translation type="unfinished"></translation> </message> <message> - <location line="+7"/> - <source>Unknown network specified in -onlynet: '%s'</source> - <translation>Unknown network specified in -onlynet: '%s'</translation> - </message> - <message> - <location line="-85"/> - <source>Insufficient funds</source> - <translation>Insufficient funds</translation> - </message> - <message> - <location line="+15"/> + <location line="+39"/> <source>Loading block index...</source> <translation>Loading block index...</translation> </message> @@ -5265,22 +4692,22 @@ <translation>Loading wallet...</translation> </message> <message> - <location line="-61"/> + <location line="-42"/> <source>Cannot downgrade wallet</source> <translation>Cannot downgrade wallet</translation> </message> <message> - <location line="+87"/> + <location line="+50"/> <source>Rescanning...</source> <translation>Rescanning...</translation> </message> <message> - <location line="-75"/> + <location line="-43"/> <source>Done loading</source> <translation>Done loading</translation> </message> <message> - <location line="+20"/> + <location line="+14"/> <source>Error</source> <translation>Error</translation> </message> diff --git a/src/qt/macdockiconhandler.mm b/src/qt/macdockiconhandler.mm index a0b62ae000..b9ad191da7 100644 --- a/src/qt/macdockiconhandler.mm +++ b/src/qt/macdockiconhandler.mm @@ -19,9 +19,9 @@ static MacDockIconHandler *s_instance = nullptr; bool dockClickHandler(id self,SEL _cmd,...) { Q_UNUSED(self) Q_UNUSED(_cmd) - + s_instance->handleDockIconClickEvent(); - + // Return NO (false) to suppress the default OS X actions return false; } @@ -29,7 +29,7 @@ bool dockClickHandler(id self,SEL _cmd,...) { void setupDockClickHandler() { Class cls = objc_getClass("NSApplication"); id appInst = objc_msgSend((id)cls, sel_registerName("sharedApplication")); - + if (appInst != nullptr) { id delegate = objc_msgSend(appInst, sel_registerName("delegate")); Class delClass = (Class)objc_msgSend(delegate, sel_registerName("class")); diff --git a/src/qt/macnotificationhandler.mm b/src/qt/macnotificationhandler.mm index 1b16c5f524..0e04d50baa 100644 --- a/src/qt/macnotificationhandler.mm +++ b/src/qt/macnotificationhandler.mm @@ -64,7 +64,7 @@ MacNotificationHandler *MacNotificationHandler::instance() static MacNotificationHandler *s_instance = nullptr; if (!s_instance) { s_instance = new MacNotificationHandler(); - + Class aPossibleClass = objc_getClass("NSBundle"); if (aPossibleClass) { // change NSBundle -bundleIdentifier method to return a correct bundle identifier diff --git a/src/qt/modaloverlay.cpp b/src/qt/modaloverlay.cpp index 249418213f..e9d03c5828 100644 --- a/src/qt/modaloverlay.cpp +++ b/src/qt/modaloverlay.cpp @@ -104,7 +104,7 @@ void ModalOverlay::tipUpdate(int count, const QDateTime& blockDate, double nVeri ui->progressIncreasePerH->setText(QString::number(progressPerHour * 100, 'f', 2)+"%"); // show expected remaining time - if(remainingMSecs >= 0) { + if(remainingMSecs >= 0) { ui->expectedTimeLeft->setText(GUIUtil::formatNiceTimeOffset(remainingMSecs / 1000.0)); } else { ui->expectedTimeLeft->setText(QObject::tr("unknown")); diff --git a/src/qt/optionsdialog.h b/src/qt/optionsdialog.h index 5aad484ce7..54e1a8a9b1 100644 --- a/src/qt/optionsdialog.h +++ b/src/qt/optionsdialog.h @@ -50,7 +50,7 @@ private Q_SLOTS: void on_openBitcoinConfButton_clicked(); void on_okButton_clicked(); void on_cancelButton_clicked(); - + void on_hideTrayIcon_stateChanged(int fState); void togglePruneWarning(bool enabled); diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp index 31a85f4e23..834ff7633c 100644 --- a/src/qt/optionsmodel.cpp +++ b/src/qt/optionsmodel.cpp @@ -57,7 +57,7 @@ void OptionsModel::Init(bool resetSettings) settings.setValue("fHideTrayIcon", false); fHideTrayIcon = settings.value("fHideTrayIcon").toBool(); Q_EMIT hideTrayIconChanged(fHideTrayIcon); - + if (!settings.contains("fMinimizeToTray")) settings.setValue("fMinimizeToTray", false); fMinimizeToTray = settings.value("fMinimizeToTray").toBool() && !fHideTrayIcon; diff --git a/src/qt/qvalidatedlineedit.h b/src/qt/qvalidatedlineedit.h index 66734cc9d4..9ad9e66ae2 100644 --- a/src/qt/qvalidatedlineedit.h +++ b/src/qt/qvalidatedlineedit.h @@ -34,7 +34,7 @@ public Q_SLOTS: Q_SIGNALS: void validationDidChange(QValidatedLineEdit *validatedLineEdit); - + private Q_SLOTS: void markValid(); void checkValidity(); diff --git a/src/qt/receivecoinsdialog.cpp b/src/qt/receivecoinsdialog.cpp index e458a52856..8c430e0af1 100644 --- a/src/qt/receivecoinsdialog.cpp +++ b/src/qt/receivecoinsdialog.cpp @@ -99,6 +99,9 @@ void ReceiveCoinsDialog::setModel(WalletModel *_model) } else { ui->useBech32->setCheckState(Qt::Unchecked); } + + // eventually disable the main receive button if private key operations are disabled + ui->receiveButton->setEnabled(!model->privateKeysDisabled()); } } diff --git a/src/qt/trafficgraphwidget.cpp b/src/qt/trafficgraphwidget.cpp index 5a3b645f65..a5551ec014 100644 --- a/src/qt/trafficgraphwidget.cpp +++ b/src/qt/trafficgraphwidget.cpp @@ -80,7 +80,7 @@ void TrafficGraphWidget::paintEvent(QPaintEvent *) const QString units = tr("KB/s"); const float yMarginText = 2.0; - + // draw lines painter.setPen(axisCol); painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax-yMarginText, QString("%1 %2").arg(val).arg(units)); diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp index 389acf0a95..cd55b40b71 100644 --- a/src/qt/walletmodel.cpp +++ b/src/qt/walletmodel.cpp @@ -558,6 +558,11 @@ bool WalletModel::isWalletEnabled() return !gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET); } +bool WalletModel::privateKeysDisabled() const +{ + return m_wallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS); +} + QString WalletModel::getWalletName() const { return QString::fromStdString(m_wallet->getWalletName()); diff --git a/src/qt/walletmodel.h b/src/qt/walletmodel.h index 35ededb121..d8935c2fa8 100644 --- a/src/qt/walletmodel.h +++ b/src/qt/walletmodel.h @@ -197,6 +197,7 @@ public: bool bumpFee(uint256 hash); static bool isWalletEnabled(); + bool privateKeysDisabled() const; interfaces::Node& node() const { return m_node; } interfaces::Wallet& wallet() const { return *m_wallet; } diff --git a/src/qt/walletview.cpp b/src/qt/walletview.cpp index d529595dec..c53a2910e5 100644 --- a/src/qt/walletview.cpp +++ b/src/qt/walletview.cpp @@ -107,7 +107,7 @@ void WalletView::setBitcoinGUI(BitcoinGUI *gui) // Pass through transaction notifications connect(this, SIGNAL(incomingTransaction(QString,int,CAmount,QString,QString,QString,QString)), gui, SLOT(incomingTransaction(QString,int,CAmount,QString,QString,QString,QString))); - // Connect HD enabled state signal + // Connect HD enabled state signal connect(this, SIGNAL(hdEnabledStatusChanged()), gui, SLOT(updateWalletStatus())); } } diff --git a/src/reverse_iterator.h b/src/reverse_iterator.h index ab467f07c9..729d8c11cc 100644 --- a/src/reverse_iterator.h +++ b/src/reverse_iterator.h @@ -5,7 +5,7 @@ /** * Template used for reverse iteration in C++11 range-based for loops. - * + * * std::vector<int> v = {1, 2, 3, 4, 5}; * for (auto x : reverse_iterate(v)) * std::cout << x << " "; @@ -15,21 +15,21 @@ template <typename T> class reverse_range { T &m_x; - + public: explicit reverse_range(T &x) : m_x(x) {} - + auto begin() const -> decltype(this->m_x.rbegin()) { return m_x.rbegin(); } - + auto end() const -> decltype(this->m_x.rend()) { return m_x.rend(); } }; - + template <typename T> reverse_range<T> reverse_iterate(T &x) { diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp index ce608631ff..eb6b164075 100644 --- a/src/rpc/client.cpp +++ b/src/rpc/client.cpp @@ -110,6 +110,22 @@ static const CRPCConvertParam vRPCConvertParams[] = { "combinerawtransaction", 0, "txs" }, { "fundrawtransaction", 1, "options" }, { "fundrawtransaction", 2, "iswitness" }, + { "walletcreatefundedpsbt", 0, "inputs" }, + { "walletcreatefundedpsbt", 1, "outputs" }, + { "walletcreatefundedpsbt", 2, "locktime" }, + { "walletcreatefundedpsbt", 3, "replaceable" }, + { "walletcreatefundedpsbt", 4, "options" }, + { "walletcreatefundedpsbt", 5, "bip32derivs" }, + { "walletprocesspsbt", 1, "sign" }, + { "walletprocesspsbt", 3, "bip32derivs" }, + { "createpsbt", 0, "inputs" }, + { "createpsbt", 1, "outputs" }, + { "createpsbt", 2, "locktime" }, + { "createpsbt", 3, "replaceable" }, + { "combinepsbt", 0, "txs"}, + { "finalizepsbt", 1, "extract"}, + { "converttopsbt", 1, "permitsigdata"}, + { "converttopsbt", 2, "iswitness"}, { "gettxout", 1, "n" }, { "gettxout", 2, "include_mempool" }, { "gettxoutproof", 0, "txids" }, @@ -156,6 +172,7 @@ static const CRPCConvertParam vRPCConvertParams[] = { "echojson", 9, "arg9" }, { "rescanblockchain", 0, "start_height"}, { "rescanblockchain", 1, "stop_height"}, + { "createwallet", 1, "disable_private_keys"}, }; class CRPCConvertTable diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 1f1044d80b..e751587dc7 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -337,7 +337,6 @@ static UniValue getblocktemplate(const JSONRPCRequest& request) " \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n" " \"sigops\" : n, (numeric) total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero\n" " \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n" - " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n" " }\n" " ,...\n" " ],\n" diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 499b0c5e16..bb94e11fea 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -5,6 +5,7 @@ #include <chain.h> #include <coins.h> +#include <compat/byteswap.h> #include <consensus/validation.h> #include <core_io.h> #include <index/txindex.h> @@ -337,80 +338,25 @@ static UniValue verifytxoutproof(const JSONRPCRequest& request) return res; } -static UniValue createrawtransaction(const JSONRPCRequest& request) +CMutableTransaction ConstructTransaction(const UniValue& inputs_in, const UniValue& outputs_in, const UniValue& locktime, const UniValue& rbf) { - if (request.fHelp || request.params.size() < 2 || request.params.size() > 4) { - throw std::runtime_error( - // clang-format off - "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] [{\"address\":amount},{\"data\":\"hex\"},...] ( locktime ) ( replaceable )\n" - "\nCreate a transaction spending the given inputs and creating new outputs.\n" - "Outputs can be addresses or data.\n" - "Returns hex-encoded raw transaction.\n" - "Note that the transaction's inputs are not signed, and\n" - "it is not stored in the wallet or transmitted to the network.\n" - - "\nArguments:\n" - "1. \"inputs\" (array, required) A json array of json objects\n" - " [\n" - " {\n" - " \"txid\":\"id\", (string, required) The transaction id\n" - " \"vout\":n, (numeric, required) The output number\n" - " \"sequence\":n (numeric, optional) The sequence number\n" - " } \n" - " ,...\n" - " ]\n" - "2. \"outputs\" (array, required) a json array with outputs (key-value pairs)\n" - " [\n" - " {\n" - " \"address\": x.xxx, (obj, optional) A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + "\n" - " },\n" - " {\n" - " \"data\": \"hex\" (obj, optional) A key-value pair. The key must be \"data\", the value is hex encoded data\n" - " }\n" - " ,... More key-value pairs of the above form. For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n" - " accepted as second parameter.\n" - " ]\n" - "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n" - "4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125 replaceable.\n" - " Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible.\n" - "\nResult:\n" - "\"transaction\" (string) hex string of the transaction\n" - - "\nExamples:\n" - + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"address\\\":0.01}]\"") - + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") - + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"address\\\":0.01}]\"") - + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"data\\\":\\\"00010203\\\"}]\"") - // clang-format on - ); - } - - RPCTypeCheck(request.params, { - UniValue::VARR, - UniValueType(), // ARR or OBJ, checked later - UniValue::VNUM, - UniValue::VBOOL - }, true - ); - if (request.params[0].isNull() || request.params[1].isNull()) + if (inputs_in.isNull() || outputs_in.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null"); - UniValue inputs = request.params[0].get_array(); - const bool outputs_is_obj = request.params[1].isObject(); - UniValue outputs = outputs_is_obj ? - request.params[1].get_obj() : - request.params[1].get_array(); + UniValue inputs = inputs_in.get_array(); + const bool outputs_is_obj = outputs_in.isObject(); + UniValue outputs = outputs_is_obj ? outputs_in.get_obj() : outputs_in.get_array(); CMutableTransaction rawTx; - if (!request.params[2].isNull()) { - int64_t nLockTime = request.params[2].get_int64(); + if (!locktime.isNull()) { + int64_t nLockTime = locktime.get_int64(); if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range"); rawTx.nLockTime = nLockTime; } - bool rbfOptIn = request.params[3].isTrue(); + bool rbfOptIn = rbf.isTrue(); for (unsigned int idx = 0; idx < inputs.size(); idx++) { const UniValue& input = inputs[idx]; @@ -490,10 +436,71 @@ static UniValue createrawtransaction(const JSONRPCRequest& request) } } - if (!request.params[3].isNull() && rbfOptIn != SignalsOptInRBF(rawTx)) { + if (!rbf.isNull() && rbfOptIn != SignalsOptInRBF(rawTx)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter combination: Sequence number(s) contradict replaceable option"); } + return rawTx; +} + +static UniValue createrawtransaction(const JSONRPCRequest& request) +{ + if (request.fHelp || request.params.size() < 2 || request.params.size() > 4) { + throw std::runtime_error( + // clang-format off + "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] [{\"address\":amount},{\"data\":\"hex\"},...] ( locktime ) ( replaceable )\n" + "\nCreate a transaction spending the given inputs and creating new outputs.\n" + "Outputs can be addresses or data.\n" + "Returns hex-encoded raw transaction.\n" + "Note that the transaction's inputs are not signed, and\n" + "it is not stored in the wallet or transmitted to the network.\n" + + "\nArguments:\n" + "1. \"inputs\" (array, required) A json array of json objects\n" + " [\n" + " {\n" + " \"txid\":\"id\", (string, required) The transaction id\n" + " \"vout\":n, (numeric, required) The output number\n" + " \"sequence\":n (numeric, optional) The sequence number\n" + " } \n" + " ,...\n" + " ]\n" + "2. \"outputs\" (array, required) a json array with outputs (key-value pairs)\n" + " [\n" + " {\n" + " \"address\": x.xxx, (obj, optional) A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + "\n" + " },\n" + " {\n" + " \"data\": \"hex\" (obj, optional) A key-value pair. The key must be \"data\", the value is hex encoded data\n" + " }\n" + " ,... More key-value pairs of the above form. For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n" + " accepted as second parameter.\n" + " ]\n" + "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n" + "4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125 replaceable.\n" + " Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible.\n" + "\nResult:\n" + "\"transaction\" (string) hex string of the transaction\n" + + "\nExamples:\n" + + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"address\\\":0.01}]\"") + + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") + + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"address\\\":0.01}]\"") + + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"data\\\":\\\"00010203\\\"}]\"") + // clang-format on + ); + } + + RPCTypeCheck(request.params, { + UniValue::VARR, + UniValueType(), // ARR or OBJ, checked later + UniValue::VNUM, + UniValue::VBOOL + }, true + ); + + CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], request.params[3]); + return EncodeHexTx(rawTx); } @@ -838,23 +845,7 @@ UniValue SignTransaction(CMutableTransaction& mtx, const UniValue& prevTxsUnival } } - int nHashType = SIGHASH_ALL; - if (!hashType.isNull()) { - static std::map<std::string, int> mapSigHashValues = { - {std::string("ALL"), int(SIGHASH_ALL)}, - {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)}, - {std::string("NONE"), int(SIGHASH_NONE)}, - {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)}, - {std::string("SINGLE"), int(SIGHASH_SINGLE)}, - {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)}, - }; - std::string strHashType = hashType.get_str(); - if (mapSigHashValues.count(strHashType)) { - nHashType = mapSigHashValues[strHashType]; - } else { - throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); - } - } + int nHashType = ParseSighashString(hashType); bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); @@ -1263,6 +1254,553 @@ static UniValue testmempoolaccept(const JSONRPCRequest& request) return result; } +static std::string WriteHDKeypath(std::vector<uint32_t>& keypath) +{ + std::string keypath_str = "m"; + for (uint32_t num : keypath) { + keypath_str += "/"; + bool hardened = false; + if (num & 0x80000000) { + hardened = true; + num &= ~0x80000000; + } + + keypath_str += std::to_string(num); + if (hardened) { + keypath_str += "'"; + } + } + return keypath_str; +} + +UniValue decodepsbt(const JSONRPCRequest& request) +{ + if (request.fHelp || request.params.size() != 1) + throw std::runtime_error( + "decodepsbt \"psbt\"\n" + "\nReturn a JSON object representing the serialized, base64-encoded partially signed Bitcoin transaction.\n" + + "\nArguments:\n" + "1. \"psbt\" (string, required) The PSBT base64 string\n" + + "\nResult:\n" + "{\n" + " \"tx\" : { (json object) The decoded network-serialized unsigned transaction.\n" + " ... The layout is the same as the output of decoderawtransaction.\n" + " },\n" + " \"unknown\" : { (json object) The unknown global fields\n" + " \"key\" : \"value\" (key-value pair) An unknown key-value pair\n" + " ...\n" + " },\n" + " \"inputs\" : [ (array of json objects)\n" + " {\n" + " \"non_witness_utxo\" : { (json object, optional) Decoded network transaction for non-witness UTXOs\n" + " ...\n" + " },\n" + " \"witness_utxo\" : { (json object, optional) Transaction output for witness UTXOs\n" + " \"amount\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n" + " \"scriptPubKey\" : { (json object)\n" + " \"asm\" : \"asm\", (string) The asm\n" + " \"hex\" : \"hex\", (string) The hex\n" + " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" + " \"address\" : \"address\" (string) Bitcoin address if there is one\n" + " }\n" + " },\n" + " \"partial_signatures\" : { (json object, optional)\n" + " \"pubkey\" : \"signature\", (string) The public key and signature that corresponds to it.\n" + " ,...\n" + " }\n" + " \"sighash\" : \"type\", (string, optional) The sighash type to be used\n" + " \"redeem_script\" : { (json object, optional)\n" + " \"asm\" : \"asm\", (string) The asm\n" + " \"hex\" : \"hex\", (string) The hex\n" + " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" + " }\n" + " \"witness_script\" : { (json object, optional)\n" + " \"asm\" : \"asm\", (string) The asm\n" + " \"hex\" : \"hex\", (string) The hex\n" + " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" + " }\n" + " \"bip32_derivs\" : { (json object, optional)\n" + " \"pubkey\" : { (json object, optional) The public key with the derivation path as the value.\n" + " \"master_fingerprint\" : \"fingerprint\" (string) The fingerprint of the master key\n" + " \"path\" : \"path\", (string) The path\n" + " }\n" + " ,...\n" + " }\n" + " \"final_scriptsig\" : { (json object, optional)\n" + " \"asm\" : \"asm\", (string) The asm\n" + " \"hex\" : \"hex\", (string) The hex\n" + " }\n" + " \"final_scriptwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n" + " \"unknown\" : { (json object) The unknown global fields\n" + " \"key\" : \"value\" (key-value pair) An unknown key-value pair\n" + " ...\n" + " },\n" + " }\n" + " ,...\n" + " ]\n" + " \"outputs\" : [ (array of json objects)\n" + " {\n" + " \"redeem_script\" : { (json object, optional)\n" + " \"asm\" : \"asm\", (string) The asm\n" + " \"hex\" : \"hex\", (string) The hex\n" + " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" + " }\n" + " \"witness_script\" : { (json object, optional)\n" + " \"asm\" : \"asm\", (string) The asm\n" + " \"hex\" : \"hex\", (string) The hex\n" + " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" + " }\n" + " \"bip32_derivs\" : [ (array of json objects, optional)\n" + " {\n" + " \"pubkey\" : \"pubkey\", (string) The public key this path corresponds to\n" + " \"master_fingerprint\" : \"fingerprint\" (string) The fingerprint of the master key\n" + " \"path\" : \"path\", (string) The path\n" + " }\n" + " }\n" + " ,...\n" + " ],\n" + " \"unknown\" : { (json object) The unknown global fields\n" + " \"key\" : \"value\" (key-value pair) An unknown key-value pair\n" + " ...\n" + " },\n" + " }\n" + " ,...\n" + " ]\n" + " \"fee\" : fee (numeric, optional) The transaction fee paid if all UTXOs slots in the PSBT have been filled.\n" + "}\n" + + "\nExamples:\n" + + HelpExampleCli("decodepsbt", "\"psbt\"") + ); + + RPCTypeCheck(request.params, {UniValue::VSTR}); + + // Unserialize the transactions + PartiallySignedTransaction psbtx; + std::string error; + if (!DecodePSBT(psbtx, request.params[0].get_str(), error)) { + throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error)); + } + + UniValue result(UniValue::VOBJ); + + // Add the decoded tx + UniValue tx_univ(UniValue::VOBJ); + TxToUniv(CTransaction(*psbtx.tx), uint256(), tx_univ, false); + result.pushKV("tx", tx_univ); + + // Unknown data + UniValue unknowns(UniValue::VOBJ); + for (auto entry : psbtx.unknown) { + unknowns.pushKV(HexStr(entry.first), HexStr(entry.second)); + } + result.pushKV("unknown", unknowns); + + // inputs + CAmount total_in = 0; + bool have_all_utxos = true; + UniValue inputs(UniValue::VARR); + for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) { + const PSBTInput& input = psbtx.inputs[i]; + UniValue in(UniValue::VOBJ); + // UTXOs + if (!input.witness_utxo.IsNull()) { + const CTxOut& txout = input.witness_utxo; + + UniValue out(UniValue::VOBJ); + + out.pushKV("amount", ValueFromAmount(txout.nValue)); + total_in += txout.nValue; + + UniValue o(UniValue::VOBJ); + ScriptToUniv(txout.scriptPubKey, o, true); + out.pushKV("scriptPubKey", o); + in.pushKV("witness_utxo", out); + } else if (input.non_witness_utxo) { + UniValue non_wit(UniValue::VOBJ); + TxToUniv(*input.non_witness_utxo, uint256(), non_wit, false); + in.pushKV("non_witness_utxo", non_wit); + total_in += input.non_witness_utxo->vout[psbtx.tx->vin[i].prevout.n].nValue; + } else { + have_all_utxos = false; + } + + // Partial sigs + if (!input.partial_sigs.empty()) { + UniValue partial_sigs(UniValue::VOBJ); + for (const auto& sig : input.partial_sigs) { + partial_sigs.pushKV(HexStr(sig.second.first), HexStr(sig.second.second)); + } + in.pushKV("partial_signatures", partial_sigs); + } + + // Sighash + if (input.sighash_type > 0) { + in.pushKV("sighash", SighashToStr((unsigned char)input.sighash_type)); + } + + // Redeem script and witness script + if (!input.redeem_script.empty()) { + UniValue r(UniValue::VOBJ); + ScriptToUniv(input.redeem_script, r, false); + in.pushKV("redeem_script", r); + } + if (!input.witness_script.empty()) { + UniValue r(UniValue::VOBJ); + ScriptToUniv(input.witness_script, r, false); + in.pushKV("witness_script", r); + } + + // keypaths + if (!input.hd_keypaths.empty()) { + UniValue keypaths(UniValue::VARR); + for (auto entry : input.hd_keypaths) { + UniValue keypath(UniValue::VOBJ); + keypath.pushKV("pubkey", HexStr(entry.first)); + + uint32_t fingerprint = entry.second.at(0); + keypath.pushKV("master_fingerprint", strprintf("%08x", bswap_32(fingerprint))); + + entry.second.erase(entry.second.begin()); + keypath.pushKV("path", WriteHDKeypath(entry.second)); + keypaths.push_back(keypath); + } + in.pushKV("bip32_derivs", keypaths); + } + + // Final scriptSig and scriptwitness + if (!input.final_script_sig.empty()) { + UniValue scriptsig(UniValue::VOBJ); + scriptsig.pushKV("asm", ScriptToAsmStr(input.final_script_sig, true)); + scriptsig.pushKV("hex", HexStr(input.final_script_sig)); + in.pushKV("final_scriptSig", scriptsig); + } + if (!input.final_script_witness.IsNull()) { + UniValue txinwitness(UniValue::VARR); + for (const auto& item : input.final_script_witness.stack) { + txinwitness.push_back(HexStr(item.begin(), item.end())); + } + in.pushKV("final_scriptwitness", txinwitness); + } + + // Unknown data + if (input.unknown.size() > 0) { + UniValue unknowns(UniValue::VOBJ); + for (auto entry : input.unknown) { + unknowns.pushKV(HexStr(entry.first), HexStr(entry.second)); + } + in.pushKV("unknown", unknowns); + } + + inputs.push_back(in); + } + result.pushKV("inputs", inputs); + + // outputs + CAmount output_value = 0; + UniValue outputs(UniValue::VARR); + for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) { + const PSBTOutput& output = psbtx.outputs[i]; + UniValue out(UniValue::VOBJ); + // Redeem script and witness script + if (!output.redeem_script.empty()) { + UniValue r(UniValue::VOBJ); + ScriptToUniv(output.redeem_script, r, false); + out.pushKV("redeem_script", r); + } + if (!output.witness_script.empty()) { + UniValue r(UniValue::VOBJ); + ScriptToUniv(output.witness_script, r, false); + out.pushKV("witness_script", r); + } + + // keypaths + if (!output.hd_keypaths.empty()) { + UniValue keypaths(UniValue::VARR); + for (auto entry : output.hd_keypaths) { + UniValue keypath(UniValue::VOBJ); + keypath.pushKV("pubkey", HexStr(entry.first)); + + uint32_t fingerprint = entry.second.at(0); + keypath.pushKV("master_fingerprint", strprintf("%08x", bswap_32(fingerprint))); + + entry.second.erase(entry.second.begin()); + keypath.pushKV("path", WriteHDKeypath(entry.second)); + keypaths.push_back(keypath); + } + out.pushKV("bip32_derivs", keypaths); + } + + // Unknown data + if (output.unknown.size() > 0) { + UniValue unknowns(UniValue::VOBJ); + for (auto entry : output.unknown) { + unknowns.pushKV(HexStr(entry.first), HexStr(entry.second)); + } + out.pushKV("unknown", unknowns); + } + + outputs.push_back(out); + + // Fee calculation + output_value += psbtx.tx->vout[i].nValue; + } + result.pushKV("outputs", outputs); + if (have_all_utxos) { + result.pushKV("fee", ValueFromAmount(total_in - output_value)); + } + + return result; +} + +UniValue combinepsbt(const JSONRPCRequest& request) +{ + if (request.fHelp || request.params.size() != 1) + throw std::runtime_error( + "combinepsbt [\"psbt\",...]\n" + "\nCombine multiple partially signed Bitcoin transactions into one transaction.\n" + "Implements the Combiner role.\n" + "\nArguments:\n" + "1. \"txs\" (string) A json array of base64 strings of partially signed transactions\n" + " [\n" + " \"psbt\" (string) A base64 string of a PSBT\n" + " ,...\n" + " ]\n" + + "\nResult:\n" + " \"psbt\" (string) The base64-encoded partially signed transaction\n" + "\nExamples:\n" + + HelpExampleCli("combinepsbt", "[\"mybase64_1\", \"mybase64_2\", \"mybase64_3\"]") + ); + + RPCTypeCheck(request.params, {UniValue::VARR}, true); + + // Unserialize the transactions + std::vector<PartiallySignedTransaction> psbtxs; + UniValue txs = request.params[0].get_array(); + for (unsigned int i = 0; i < txs.size(); ++i) { + PartiallySignedTransaction psbtx; + std::string error; + if (!DecodePSBT(psbtx, txs[i].get_str(), error)) { + throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error)); + } + psbtxs.push_back(psbtx); + } + + PartiallySignedTransaction merged_psbt(psbtxs[0]); // Copy the first one + + // Merge + for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) { + if (*it != merged_psbt) { + throw JSONRPCError(RPC_INVALID_PARAMETER, "PSBTs do not refer to the same transactions."); + } + merged_psbt.Merge(*it); + } + if (!merged_psbt.IsSane()) { + throw JSONRPCError(RPC_INVALID_PARAMETER, "Merged PSBT is inconsistent"); + } + + UniValue result(UniValue::VOBJ); + CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); + ssTx << merged_psbt; + return EncodeBase64((unsigned char*)ssTx.data(), ssTx.size()); +} + +UniValue finalizepsbt(const JSONRPCRequest& request) +{ + if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) + throw std::runtime_error( + "finalizepsbt \"psbt\" ( extract )\n" + "Finalize the inputs of a PSBT. If the transaction is fully signed, it will produce a\n" + "network serialized transaction which can be broadcast with sendrawtransaction. Otherwise a PSBT will be\n" + "created which has the final_scriptSig and final_scriptWitness fields filled for inputs that are complete.\n" + "Implements the Finalizer and Extractor roles.\n" + "\nArguments:\n" + "1. \"psbt\" (string) A base64 string of a PSBT\n" + "2. \"extract\" (boolean, optional, default=true) If true and the transaction is complete, \n" + " extract and return the complete transaction in normal network serialization instead of the PSBT.\n" + + "\nResult:\n" + "{\n" + " \"psbt\" : \"value\", (string) The base64-encoded partially signed transaction if not extracted\n" + " \"hex\" : \"value\", (string) The hex-encoded network transaction if extracted\n" + " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n" + " ]\n" + "}\n" + + "\nExamples:\n" + + HelpExampleCli("finalizepsbt", "\"psbt\"") + ); + + RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL}, true); + + // Unserialize the transactions + PartiallySignedTransaction psbtx; + std::string error; + if (!DecodePSBT(psbtx, request.params[0].get_str(), error)) { + throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error)); + } + + // Get all of the previous transactions + bool complete = true; + for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) { + PSBTInput& input = psbtx.inputs.at(i); + + SignatureData sigdata; + complete &= SignPSBTInput(DUMMY_SIGNING_PROVIDER, *psbtx.tx, input, sigdata, i, 1); + } + + UniValue result(UniValue::VOBJ); + CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); + bool extract = request.params[1].isNull() || (!request.params[1].isNull() && request.params[1].get_bool()); + if (complete && extract) { + CMutableTransaction mtx(*psbtx.tx); + for (unsigned int i = 0; i < mtx.vin.size(); ++i) { + mtx.vin[i].scriptSig = psbtx.inputs[i].final_script_sig; + mtx.vin[i].scriptWitness = psbtx.inputs[i].final_script_witness; + } + ssTx << mtx; + result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end()))); + } else { + ssTx << psbtx; + result.push_back(Pair("psbt", EncodeBase64((unsigned char*)ssTx.data(), ssTx.size()))); + } + result.push_back(Pair("complete", complete)); + + return result; +} + +UniValue createpsbt(const JSONRPCRequest& request) +{ + if (request.fHelp || request.params.size() < 2 || request.params.size() > 4) + throw std::runtime_error( + "createpsbt [{\"txid\":\"id\",\"vout\":n},...] [{\"address\":amount},{\"data\":\"hex\"},...] ( locktime ) ( replaceable )\n" + "\nCreates a transaction in the Partially Signed Transaction format.\n" + "Implements the Creator role.\n" + "\nArguments:\n" + "1. \"inputs\" (array, required) A json array of json objects\n" + " [\n" + " {\n" + " \"txid\":\"id\", (string, required) The transaction id\n" + " \"vout\":n, (numeric, required) The output number\n" + " \"sequence\":n (numeric, optional) The sequence number\n" + " } \n" + " ,...\n" + " ]\n" + "2. \"outputs\" (array, required) a json array with outputs (key-value pairs)\n" + " [\n" + " {\n" + " \"address\": x.xxx, (obj, optional) A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + "\n" + " },\n" + " {\n" + " \"data\": \"hex\" (obj, optional) A key-value pair. The key must be \"data\", the value is hex encoded data\n" + " }\n" + " ,... More key-value pairs of the above form. For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n" + " accepted as second parameter.\n" + " ]\n" + "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n" + "4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125 replaceable.\n" + " Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible.\n" + "\nResult:\n" + " \"psbt\" (string) The resulting raw transaction (base64-encoded string)\n" + "\nExamples:\n" + + HelpExampleCli("createpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") + ); + + + RPCTypeCheck(request.params, { + UniValue::VARR, + UniValueType(), // ARR or OBJ, checked later + UniValue::VNUM, + UniValue::VBOOL, + }, true + ); + + CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], request.params[3]); + + // Make a blank psbt + PartiallySignedTransaction psbtx; + psbtx.tx = rawTx; + for (unsigned int i = 0; i < rawTx.vin.size(); ++i) { + psbtx.inputs.push_back(PSBTInput()); + } + for (unsigned int i = 0; i < rawTx.vout.size(); ++i) { + psbtx.outputs.push_back(PSBTOutput()); + } + + // Serialize the PSBT + CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); + ssTx << psbtx; + + return EncodeBase64((unsigned char*)ssTx.data(), ssTx.size()); +} + +UniValue converttopsbt(const JSONRPCRequest& request) +{ + if (request.fHelp || request.params.size() < 1 || request.params.size() > 3) + throw std::runtime_error( + "converttopsbt \"hexstring\" ( permitsigdata iswitness )\n" + "\nConverts a network serialized transaction to a PSBT. This should be used only with createrawtransaction and fundrawtransaction\n" + "createpsbt and walletcreatefundedpsbt should be used for new applications.\n" + "\nArguments:\n" + "1. \"hexstring\" (string, required) The hex string of a raw transaction\n" + "2. permitsigdata (boolean, optional, default=false) If true, any signatures in the input will be discarded and conversion.\n" + " will continue. If false, RPC will fail if any signatures are present.\n" + "3. iswitness (boolean, optional) Whether the transaction hex is a serialized witness transaction.\n" + " If iswitness is not present, heuristic tests will be used in decoding. If true, only witness deserializaion\n" + " will be tried. If false, only non-witness deserialization wil be tried. Only has an effect if\n" + " permitsigdata is true.\n" + "\nResult:\n" + " \"psbt\" (string) The resulting raw transaction (base64-encoded string)\n" + "\nExamples:\n" + "\nCreate a transaction\n" + + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") + + "\nConvert the transaction to a PSBT\n" + + HelpExampleCli("converttopsbt", "\"rawtransaction\"") + ); + + + RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL, UniValue::VBOOL}, true); + + // parse hex string from parameter + CMutableTransaction tx; + bool permitsigdata = request.params[1].isNull() ? false : request.params[1].get_bool(); + bool witness_specified = !request.params[2].isNull(); + bool iswitness = witness_specified ? request.params[2].get_bool() : false; + bool try_witness = permitsigdata ? (witness_specified ? iswitness : true) : false; + bool try_no_witness = permitsigdata ? (witness_specified ? !iswitness : true) : true; + if (!DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) { + throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); + } + + // Remove all scriptSigs and scriptWitnesses from inputs + for (CTxIn& input : tx.vin) { + if ((!input.scriptSig.empty() || !input.scriptWitness.IsNull()) && (request.params[1].isNull() || (!request.params[1].isNull() && request.params[1].get_bool()))) { + throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Inputs must not have scriptSigs and scriptWitnesses"); + } + input.scriptSig.clear(); + input.scriptWitness.SetNull(); + } + + // Make a blank psbt + PartiallySignedTransaction psbtx; + psbtx.tx = tx; + for (unsigned int i = 0; i < tx.vin.size(); ++i) { + psbtx.inputs.push_back(PSBTInput()); + } + for (unsigned int i = 0; i < tx.vout.size(); ++i) { + psbtx.outputs.push_back(PSBTOutput()); + } + + // Serialize the PSBT + CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); + ssTx << psbtx; + + return EncodeBase64((unsigned char*)ssTx.data(), ssTx.size()); +} + static const CRPCCommand commands[] = { // category name actor (function) argNames // --------------------- ------------------------ ----------------------- ---------- @@ -1275,6 +1813,11 @@ static const CRPCCommand commands[] = { "rawtransactions", "signrawtransaction", &signrawtransaction, {"hexstring","prevtxs","privkeys","sighashtype"} }, /* uses wallet if enabled */ { "rawtransactions", "signrawtransactionwithkey", &signrawtransactionwithkey, {"hexstring","privkeys","prevtxs","sighashtype"} }, { "rawtransactions", "testmempoolaccept", &testmempoolaccept, {"rawtxs","allowhighfees"} }, + { "rawtransactions", "decodepsbt", &decodepsbt, {"psbt"} }, + { "rawtransactions", "combinepsbt", &combinepsbt, {"txs"} }, + { "rawtransactions", "finalizepsbt", &finalizepsbt, {"psbt", "extract"} }, + { "rawtransactions", "createpsbt", &createpsbt, {"inputs","outputs","locktime","replaceable"} }, + { "rawtransactions", "converttopsbt", &converttopsbt, {"hexstring","permitsigdata","iswitness"} }, { "blockchain", "gettxoutproof", &gettxoutproof, {"txids", "blockhash"} }, { "blockchain", "verifytxoutproof", &verifytxoutproof, {"proof"} }, diff --git a/src/rpc/rawtransaction.h b/src/rpc/rawtransaction.h index ec9d1f2cf0..52dccc90e8 100644 --- a/src/rpc/rawtransaction.h +++ b/src/rpc/rawtransaction.h @@ -12,4 +12,7 @@ class UniValue; /** Sign a transaction with the given keystore and previous transactions */ UniValue SignTransaction(CMutableTransaction& mtx, const UniValue& prevTxs, CBasicKeyStore *keystore, bool tempKeystore, const UniValue& hashType); +/** Create a transaction from univalue parameters */ +CMutableTransaction ConstructTransaction(const UniValue& inputs_in, const UniValue& outputs_in, const UniValue& locktime, const UniValue& rbf); + #endif // BITCOIN_RPC_RAWTRANSACTION_H diff --git a/src/script/bitcoinconsensus.cpp b/src/script/bitcoinconsensus.cpp index 8cc44b675f..e2370c5e50 100644 --- a/src/script/bitcoinconsensus.cpp +++ b/src/script/bitcoinconsensus.cpp @@ -81,7 +81,7 @@ static int verify_script(const unsigned char *scriptPubKey, unsigned int scriptP unsigned int nIn, unsigned int flags, bitcoinconsensus_error* err) { if (!verify_flags(flags)) { - return bitcoinconsensus_ERR_INVALID_FLAGS; + return set_error(err, bitcoinconsensus_ERR_INVALID_FLAGS); } try { TxInputStream stream(SER_NETWORK, PROTOCOL_VERSION, txTo, txToLen); diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp index 4b982d647d..1936d44cd5 100644 --- a/src/script/interpreter.cpp +++ b/src/script/interpreter.cpp @@ -99,7 +99,7 @@ bool static IsCompressedPubKey(const valtype &vchPubKey) { * Where R and S are not negative (their first byte has its highest bit not set), and not * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows, * in which case a single 0 byte is necessary and even required). - * + * * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623 * * This function is consensus-critical since BIP66. @@ -139,7 +139,7 @@ bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) { // Verify that the length of the signature matches the sum of the length // of the elements. if ((size_t)(lenR + lenS + 7) != sig.size()) return false; - + // Check whether the R element is an integer. if (sig[2] != 0x02) return false; @@ -899,7 +899,7 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& popstack(stack); stack.push_back(vchHash); } - break; + break; case OP_CODESEPARATOR: { diff --git a/src/script/sign.cpp b/src/script/sign.cpp index 60a8a2655d..c2ae4ff2ea 100644 --- a/src/script/sign.cpp +++ b/src/script/sign.cpp @@ -49,9 +49,10 @@ static bool GetCScript(const SigningProvider& provider, const SignatureData& sig return false; } -static bool GetPubKey(const SigningProvider& provider, const SignatureData& sigdata, const CKeyID& address, CPubKey& pubkey) +static bool GetPubKey(const SigningProvider& provider, SignatureData& sigdata, const CKeyID& address, CPubKey& pubkey) { if (provider.GetPubKey(address, pubkey)) { + sigdata.misc_pubkeys.emplace(pubkey.GetID(), pubkey); return true; } // Look for pubkey in all partial sigs @@ -60,6 +61,12 @@ static bool GetPubKey(const SigningProvider& provider, const SignatureData& sigd pubkey = it->second.first; return true; } + // Look for pubkey in pubkey list + const auto& pk_it = sigdata.misc_pubkeys.find(address); + if (pk_it != sigdata.misc_pubkeys.end()) { + pubkey = pk_it->second; + return true; + } return false; } @@ -70,9 +77,9 @@ static bool CreateSig(const BaseSignatureCreator& creator, SignatureData& sigdat sig_out = it->second.second; return true; } + CPubKey pubkey; + GetPubKey(provider, sigdata, keyid, pubkey); if (creator.CreateSig(provider, sig_out, keyid, scriptcode, sigversion)) { - CPubKey pubkey; - GetPubKey(provider, sigdata, keyid, pubkey); auto i = sigdata.signatures.emplace(keyid, SigPair(pubkey, sig_out)); assert(i.second); return true; @@ -200,6 +207,7 @@ bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreato txnouttype subType; solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata); sigdata.scriptWitness.stack = result; + sigdata.witness = true; result.clear(); } else if (solved && whichType == TX_WITNESS_V0_SCRIPTHASH) @@ -210,7 +218,10 @@ bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreato solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata) && subType != TX_SCRIPTHASH && subType != TX_WITNESS_V0_SCRIPTHASH && subType != TX_WITNESS_V0_KEYHASH; result.push_back(std::vector<unsigned char>(witnessscript.begin(), witnessscript.end())); sigdata.scriptWitness.stack = result; + sigdata.witness = true; result.clear(); + } else if (solved && whichType == TX_WITNESS_UNKNOWN) { + sigdata.witness = true; } if (P2SH) { @@ -223,6 +234,32 @@ bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreato return sigdata.complete; } +bool SignPSBTInput(const SigningProvider& provider, const CMutableTransaction& tx, PSBTInput& input, SignatureData& sigdata, int index, int sighash) +{ + // if this input has a final scriptsig or scriptwitness, don't do anything with it + if (!input.final_script_sig.empty() || !input.final_script_witness.IsNull()) { + return true; + } + + // Fill SignatureData with input info + input.FillSignatureData(sigdata); + + // Get UTXO + CTxOut utxo; + if (input.non_witness_utxo) { + utxo = input.non_witness_utxo->vout[tx.vin[index].prevout.n]; + } else if (!input.witness_utxo.IsNull()) { + utxo = input.witness_utxo; + } else { + return false; + } + + MutableTransactionSignatureCreator creator(&tx, index, utxo.nValue, sighash); + bool sig_complete = ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata); + input.FromSignatureData(sigdata); + return sig_complete; +} + class SignatureExtractorChecker final : public BaseSignatureChecker { private: @@ -251,18 +288,11 @@ struct Stacks std::vector<valtype> script; std::vector<valtype> witness; - Stacks() {} - explicit Stacks(const std::vector<valtype>& scriptSigStack_) : script(scriptSigStack_), witness() {} + Stacks() = delete; + Stacks(const Stacks&) = delete; explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) { EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE); } - - SignatureData Output() const { - SignatureData result; - result.scriptSig = PushAll(script); - result.scriptWitness.stack = witness; - return result; - } }; } @@ -429,3 +459,161 @@ bool IsSolvable(const SigningProvider& provider, const CScript& script) } return false; } + + +bool PartiallySignedTransaction::IsNull() const +{ + return !tx && inputs.empty() && outputs.empty() && unknown.empty(); +} + +void PartiallySignedTransaction::Merge(const PartiallySignedTransaction& psbt) +{ + for (unsigned int i = 0; i < inputs.size(); ++i) { + inputs[i].Merge(psbt.inputs[i]); + } + for (unsigned int i = 0; i < outputs.size(); ++i) { + outputs[i].Merge(psbt.outputs[i]); + } +} + +bool PartiallySignedTransaction::IsSane() const +{ + for (PSBTInput input : inputs) { + if (!input.IsSane()) return false; + } + return true; +} + +bool PSBTInput::IsNull() const +{ + return !non_witness_utxo && witness_utxo.IsNull() && partial_sigs.empty() && unknown.empty() && hd_keypaths.empty() && redeem_script.empty() && witness_script.empty(); +} + +void PSBTInput::FillSignatureData(SignatureData& sigdata) const +{ + if (!final_script_sig.empty()) { + sigdata.scriptSig = final_script_sig; + sigdata.complete = true; + } + if (!final_script_witness.IsNull()) { + sigdata.scriptWitness = final_script_witness; + sigdata.complete = true; + } + if (sigdata.complete) { + return; + } + + sigdata.signatures.insert(partial_sigs.begin(), partial_sigs.end()); + if (!redeem_script.empty()) { + sigdata.redeem_script = redeem_script; + } + if (!witness_script.empty()) { + sigdata.witness_script = witness_script; + } + for (const auto& key_pair : hd_keypaths) { + sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair.first); + } +} + +void PSBTInput::FromSignatureData(const SignatureData& sigdata) +{ + if (sigdata.complete) { + partial_sigs.clear(); + hd_keypaths.clear(); + redeem_script.clear(); + witness_script.clear(); + + if (!sigdata.scriptSig.empty()) { + final_script_sig = sigdata.scriptSig; + } + if (!sigdata.scriptWitness.IsNull()) { + final_script_witness = sigdata.scriptWitness; + } + return; + } + + partial_sigs.insert(sigdata.signatures.begin(), sigdata.signatures.end()); + if (redeem_script.empty() && !sigdata.redeem_script.empty()) { + redeem_script = sigdata.redeem_script; + } + if (witness_script.empty() && !sigdata.witness_script.empty()) { + witness_script = sigdata.witness_script; + } +} + +void PSBTInput::Merge(const PSBTInput& input) +{ + if (!non_witness_utxo && input.non_witness_utxo) non_witness_utxo = input.non_witness_utxo; + if (witness_utxo.IsNull() && !input.witness_utxo.IsNull()) { + witness_utxo = input.witness_utxo; + non_witness_utxo = nullptr; // Clear out any non-witness utxo when we set a witness one. + } + + partial_sigs.insert(input.partial_sigs.begin(), input.partial_sigs.end()); + hd_keypaths.insert(input.hd_keypaths.begin(), input.hd_keypaths.end()); + unknown.insert(input.unknown.begin(), input.unknown.end()); + + if (redeem_script.empty() && !input.redeem_script.empty()) redeem_script = input.redeem_script; + if (witness_script.empty() && !input.witness_script.empty()) witness_script = input.witness_script; + if (final_script_sig.empty() && !input.final_script_sig.empty()) final_script_sig = input.final_script_sig; + if (final_script_witness.IsNull() && !input.final_script_witness.IsNull()) final_script_witness = input.final_script_witness; +} + +bool PSBTInput::IsSane() const +{ + // Cannot have both witness and non-witness utxos + if (!witness_utxo.IsNull() && non_witness_utxo) return false; + + // If we have a witness_script or a scriptWitness, we must also have a witness utxo + if (!witness_script.empty() && witness_utxo.IsNull()) return false; + if (!final_script_witness.IsNull() && witness_utxo.IsNull()) return false; + + return true; +} + +void PSBTOutput::FillSignatureData(SignatureData& sigdata) const +{ + if (!redeem_script.empty()) { + sigdata.redeem_script = redeem_script; + } + if (!witness_script.empty()) { + sigdata.witness_script = witness_script; + } + for (const auto& key_pair : hd_keypaths) { + sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair.first); + } +} + +void PSBTOutput::FromSignatureData(const SignatureData& sigdata) +{ + if (redeem_script.empty() && !sigdata.redeem_script.empty()) { + redeem_script = sigdata.redeem_script; + } + if (witness_script.empty() && !sigdata.witness_script.empty()) { + witness_script = sigdata.witness_script; + } +} + +bool PSBTOutput::IsNull() const +{ + return redeem_script.empty() && witness_script.empty() && hd_keypaths.empty() && unknown.empty(); +} + +void PSBTOutput::Merge(const PSBTOutput& output) +{ + hd_keypaths.insert(output.hd_keypaths.begin(), output.hd_keypaths.end()); + unknown.insert(output.unknown.begin(), output.unknown.end()); + + if (redeem_script.empty() && !output.redeem_script.empty()) redeem_script = output.redeem_script; + if (witness_script.empty() && !output.witness_script.empty()) witness_script = output.witness_script; +} + +bool PublicOnlySigningProvider::GetCScript(const CScriptID &scriptid, CScript& script) const +{ + return m_provider->GetCScript(scriptid, script); +} + +bool PublicOnlySigningProvider::GetPubKey(const CKeyID &address, CPubKey& pubkey) const +{ + return m_provider->GetPubKey(address, pubkey); +} diff --git a/src/script/sign.h b/src/script/sign.h index 3666859641..250b637035 100644 --- a/src/script/sign.h +++ b/src/script/sign.h @@ -6,7 +6,11 @@ #ifndef BITCOIN_SCRIPT_SIGN_H #define BITCOIN_SCRIPT_SIGN_H +#include <boost/optional.hpp> +#include <hash.h> +#include <pubkey.h> #include <script/interpreter.h> +#include <streams.h> class CKey; class CKeyID; @@ -28,6 +32,17 @@ public: extern const SigningProvider& DUMMY_SIGNING_PROVIDER; +class PublicOnlySigningProvider : public SigningProvider +{ +private: + const SigningProvider* m_provider; + +public: + PublicOnlySigningProvider(const SigningProvider* provider) : m_provider(provider) {} + bool GetCScript(const CScriptID &scriptid, CScript& script) const; + bool GetPubKey(const CKeyID &address, CPubKey& pubkey) const; +}; + /** Interface for signature creators. */ class BaseSignatureCreator { public: @@ -62,17 +77,565 @@ typedef std::pair<CPubKey, std::vector<unsigned char>> SigPair; // in order to construct final scriptSigs and scriptWitnesses. struct SignatureData { bool complete = false; ///< Stores whether the scriptSig and scriptWitness are complete + bool witness = false; ///< Stores whether the input this SigData corresponds to is a witness input CScript scriptSig; ///< The scriptSig of an input. Contains complete signatures or the traditional partial signatures format CScript redeem_script; ///< The redeemScript (if any) for the input CScript witness_script; ///< The witnessScript (if any) for the input. witnessScripts are used in P2WSH outputs. CScriptWitness scriptWitness; ///< The scriptWitness of an input. Contains complete signatures or the traditional partial signatures format. scriptWitness is part of a transaction input per BIP 144. std::map<CKeyID, SigPair> signatures; ///< BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a final scriptSig or scriptWitness. + std::map<CKeyID, CPubKey> misc_pubkeys; SignatureData() {} explicit SignatureData(const CScript& script) : scriptSig(script) {} void MergeSignatureData(SignatureData sigdata); }; +// Magic bytes +static constexpr uint8_t PSBT_MAGIC_BYTES[5] = {'p', 's', 'b', 't', 0xff}; + +// Global types +static constexpr uint8_t PSBT_GLOBAL_UNSIGNED_TX = 0x00; + +// Input types +static constexpr uint8_t PSBT_IN_NON_WITNESS_UTXO = 0x00; +static constexpr uint8_t PSBT_IN_WITNESS_UTXO = 0x01; +static constexpr uint8_t PSBT_IN_PARTIAL_SIG = 0x02; +static constexpr uint8_t PSBT_IN_SIGHASH = 0x03; +static constexpr uint8_t PSBT_IN_REDEEMSCRIPT = 0x04; +static constexpr uint8_t PSBT_IN_WITNESSSCRIPT = 0x05; +static constexpr uint8_t PSBT_IN_BIP32_DERIVATION = 0x06; +static constexpr uint8_t PSBT_IN_SCRIPTSIG = 0x07; +static constexpr uint8_t PSBT_IN_SCRIPTWITNESS = 0x08; + +// Output types +static constexpr uint8_t PSBT_OUT_REDEEMSCRIPT = 0x00; +static constexpr uint8_t PSBT_OUT_WITNESSSCRIPT = 0x01; +static constexpr uint8_t PSBT_OUT_BIP32_DERIVATION = 0x02; + +// The separator is 0x00. Reading this in means that the unserializer can interpret it +// as a 0 length key which indicates that this is the separator. The separator has no value. +static constexpr uint8_t PSBT_SEPARATOR = 0x00; + +// Takes a stream and multiple arguments and serializes them as if first serialized into a vector and then into the stream +// The resulting output into the stream has the total serialized length of all of the objects followed by all objects concatenated with each other. +template<typename Stream, typename... X> +void SerializeToVector(Stream& s, const X&... args) +{ + WriteCompactSize(s, GetSerializeSizeMany(s, args...)); + SerializeMany(s, args...); +} + +// Takes a stream and multiple arguments and unserializes them first as a vector then each object individually in the order provided in the arguments +template<typename Stream, typename... X> +void UnserializeFromVector(Stream& s, X&... args) +{ + size_t expected_size = ReadCompactSize(s); + size_t remaining_before = s.size(); + UnserializeMany(s, args...); + size_t remaining_after = s.size(); + if (remaining_after + expected_size != remaining_before) { + throw std::ios_base::failure("Size of value was not the stated size"); + } +} + +// Deserialize HD keypaths into a map +template<typename Stream> +void DeserializeHDKeypaths(Stream& s, const std::vector<unsigned char>& key, std::map<CPubKey, std::vector<uint32_t>>& hd_keypaths) +{ + // Make sure that the key is the size of pubkey + 1 + if (key.size() != CPubKey::PUBLIC_KEY_SIZE + 1 && key.size() != CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 1) { + throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath"); + } + // Read in the pubkey from key + CPubKey pubkey(key.begin() + 1, key.end()); + if (!pubkey.IsFullyValid()) { + throw std::ios_base::failure("Invalid pubkey"); + } + if (hd_keypaths.count(pubkey) > 0) { + throw std::ios_base::failure("Duplicate Key, pubkey derivation path already provided"); + } + + // Read in key path + uint64_t value_len = ReadCompactSize(s); + std::vector<uint32_t> keypath; + for (unsigned int i = 0; i < value_len; i += sizeof(uint32_t)) { + uint32_t index; + s >> index; + keypath.push_back(index); + } + + // Add to map + hd_keypaths.emplace(pubkey, keypath); +} + +// Serialize HD keypaths to a stream from a map +template<typename Stream> +void SerializeHDKeypaths(Stream& s, const std::map<CPubKey, std::vector<uint32_t>>& hd_keypaths, uint8_t type) +{ + for (auto keypath_pair : hd_keypaths) { + SerializeToVector(s, type, MakeSpan(keypath_pair.first)); + WriteCompactSize(s, keypath_pair.second.size() * sizeof(uint32_t)); + for (auto& path : keypath_pair.second) { + s << path; + } + } +} + +/** A structure for PSBTs which contain per-input information */ +struct PSBTInput +{ + CTransactionRef non_witness_utxo; + CTxOut witness_utxo; + CScript redeem_script; + CScript witness_script; + CScript final_script_sig; + CScriptWitness final_script_witness; + std::map<CPubKey, std::vector<uint32_t>> hd_keypaths; + std::map<CKeyID, SigPair> partial_sigs; + std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown; + int sighash_type = 0; + + bool IsNull() const; + void FillSignatureData(SignatureData& sigdata) const; + void FromSignatureData(const SignatureData& sigdata); + void Merge(const PSBTInput& input); + bool IsSane() const; + PSBTInput() {} + + template <typename Stream> + inline void Serialize(Stream& s) const { + // Write the utxo + // If there is a non-witness utxo, then don't add the witness one. + if (non_witness_utxo) { + SerializeToVector(s, PSBT_IN_NON_WITNESS_UTXO); + SerializeToVector(s, non_witness_utxo); + } else if (!witness_utxo.IsNull()) { + SerializeToVector(s, PSBT_IN_WITNESS_UTXO); + SerializeToVector(s, witness_utxo); + } + + if (final_script_sig.empty() && final_script_witness.IsNull()) { + // Write any partial signatures + for (auto sig_pair : partial_sigs) { + SerializeToVector(s, PSBT_IN_PARTIAL_SIG, MakeSpan(sig_pair.second.first)); + s << sig_pair.second.second; + } + + // Write the sighash type + if (sighash_type > 0) { + SerializeToVector(s, PSBT_IN_SIGHASH); + SerializeToVector(s, sighash_type); + } + + // Write the redeem script + if (!redeem_script.empty()) { + SerializeToVector(s, PSBT_IN_REDEEMSCRIPT); + s << redeem_script; + } + + // Write the witness script + if (!witness_script.empty()) { + SerializeToVector(s, PSBT_IN_WITNESSSCRIPT); + s << witness_script; + } + + // Write any hd keypaths + SerializeHDKeypaths(s, hd_keypaths, PSBT_IN_BIP32_DERIVATION); + } + + // Write script sig + if (!final_script_sig.empty()) { + SerializeToVector(s, PSBT_IN_SCRIPTSIG); + s << final_script_sig; + } + // write script witness + if (!final_script_witness.IsNull()) { + SerializeToVector(s, PSBT_IN_SCRIPTWITNESS); + SerializeToVector(s, final_script_witness.stack); + } + + // Write unknown things + for (auto& entry : unknown) { + s << entry.first; + s << entry.second; + } + + s << PSBT_SEPARATOR; + } + + + template <typename Stream> + inline void Unserialize(Stream& s) { + // Read loop + while(!s.empty()) { + // Read + std::vector<unsigned char> key; + s >> key; + + // the key is empty if that was actually a separator byte + // This is a special case for key lengths 0 as those are not allowed (except for separator) + if (key.empty()) return; + + // First byte of key is the type + unsigned char type = key[0]; + + // Do stuff based on type + switch(type) { + case PSBT_IN_NON_WITNESS_UTXO: + if (non_witness_utxo) { + throw std::ios_base::failure("Duplicate Key, input non-witness utxo already provided"); + } + UnserializeFromVector(s, non_witness_utxo); + break; + case PSBT_IN_WITNESS_UTXO: + if (!witness_utxo.IsNull()) { + throw std::ios_base::failure("Duplicate Key, input witness utxo already provided"); + } + UnserializeFromVector(s, witness_utxo); + break; + case PSBT_IN_PARTIAL_SIG: + { + // Make sure that the key is the size of pubkey + 1 + if (key.size() != CPubKey::PUBLIC_KEY_SIZE + 1 && key.size() != CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 1) { + throw std::ios_base::failure("Size of key was not the expected size for the type partial signature pubkey"); + } + // Read in the pubkey from key + CPubKey pubkey(key.begin() + 1, key.end()); + if (!pubkey.IsFullyValid()) { + throw std::ios_base::failure("Invalid pubkey"); + } + if (partial_sigs.count(pubkey.GetID()) > 0) { + throw std::ios_base::failure("Duplicate Key, input partial signature for pubkey already provided"); + } + + // Read in the signature from value + std::vector<unsigned char> sig; + s >> sig; + + // Add to list + partial_sigs.emplace(pubkey.GetID(), SigPair(pubkey, std::move(sig))); + break; + } + case PSBT_IN_SIGHASH: + if (sighash_type > 0) { + throw std::ios_base::failure("Duplicate Key, input sighash type already provided"); + } + UnserializeFromVector(s, sighash_type); + break; + case PSBT_IN_REDEEMSCRIPT: + { + if (!redeem_script.empty()) { + throw std::ios_base::failure("Duplicate Key, input redeemScript already provided"); + } + s >> redeem_script; + break; + } + case PSBT_IN_WITNESSSCRIPT: + { + if (!witness_script.empty()) { + throw std::ios_base::failure("Duplicate Key, input witnessScript already provided"); + } + s >> witness_script; + break; + } + case PSBT_IN_BIP32_DERIVATION: + { + DeserializeHDKeypaths(s, key, hd_keypaths); + break; + } + case PSBT_IN_SCRIPTSIG: + { + if (!final_script_sig.empty()) { + throw std::ios_base::failure("Duplicate Key, input final scriptSig already provided"); + } + s >> final_script_sig; + break; + } + case PSBT_IN_SCRIPTWITNESS: + { + if (!final_script_witness.IsNull()) { + throw std::ios_base::failure("Duplicate Key, input final scriptWitness already provided"); + } + UnserializeFromVector(s, final_script_witness.stack); + break; + } + // Unknown stuff + default: + if (unknown.count(key) > 0) { + throw std::ios_base::failure("Duplicate Key, key for unknown value already provided"); + } + // Read in the value + std::vector<unsigned char> val_bytes; + s >> val_bytes; + unknown.emplace(std::move(key), std::move(val_bytes)); + break; + } + } + } + + template <typename Stream> + PSBTInput(deserialize_type, Stream& s) { + Unserialize(s); + } +}; + +/** A structure for PSBTs which contains per output information */ +struct PSBTOutput +{ + CScript redeem_script; + CScript witness_script; + std::map<CPubKey, std::vector<uint32_t>> hd_keypaths; + std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown; + + bool IsNull() const; + void FillSignatureData(SignatureData& sigdata) const; + void FromSignatureData(const SignatureData& sigdata); + void Merge(const PSBTOutput& output); + bool IsSane() const; + PSBTOutput() {} + + template <typename Stream> + inline void Serialize(Stream& s) const { + // Write the redeem script + if (!redeem_script.empty()) { + SerializeToVector(s, PSBT_OUT_REDEEMSCRIPT); + s << redeem_script; + } + + // Write the witness script + if (!witness_script.empty()) { + SerializeToVector(s, PSBT_OUT_WITNESSSCRIPT); + s << witness_script; + } + + // Write any hd keypaths + SerializeHDKeypaths(s, hd_keypaths, PSBT_OUT_BIP32_DERIVATION); + + // Write unknown things + for (auto& entry : unknown) { + s << entry.first; + s << entry.second; + } + + s << PSBT_SEPARATOR; + } + + + template <typename Stream> + inline void Unserialize(Stream& s) { + // Read loop + while(!s.empty()) { + // Read + std::vector<unsigned char> key; + s >> key; + + // the key is empty if that was actually a separator byte + // This is a special case for key lengths 0 as those are not allowed (except for separator) + if (key.empty()) return; + + // First byte of key is the type + unsigned char type = key[0]; + + // Do stuff based on type + switch(type) { + case PSBT_OUT_REDEEMSCRIPT: + { + if (!redeem_script.empty()) { + throw std::ios_base::failure("Duplicate Key, output redeemScript already provided"); + } + s >> redeem_script; + break; + } + case PSBT_OUT_WITNESSSCRIPT: + { + if (!witness_script.empty()) { + throw std::ios_base::failure("Duplicate Key, output witnessScript already provided"); + } + s >> witness_script; + break; + } + case PSBT_OUT_BIP32_DERIVATION: + { + DeserializeHDKeypaths(s, key, hd_keypaths); + break; + } + // Unknown stuff + default: { + if (unknown.count(key) > 0) { + throw std::ios_base::failure("Duplicate Key, key for unknown value already provided"); + } + // Read in the value + std::vector<unsigned char> val_bytes; + s >> val_bytes; + unknown.emplace(std::move(key), std::move(val_bytes)); + break; + } + } + } + } + + template <typename Stream> + PSBTOutput(deserialize_type, Stream& s) { + Unserialize(s); + } +}; + +/** A version of CTransaction with the PSBT format*/ +struct PartiallySignedTransaction +{ + boost::optional<CMutableTransaction> tx; + std::vector<PSBTInput> inputs; + std::vector<PSBTOutput> outputs; + std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown; + + bool IsNull() const; + void Merge(const PartiallySignedTransaction& psbt); + bool IsSane() const; + PartiallySignedTransaction() {} + PartiallySignedTransaction(const PartiallySignedTransaction& psbt_in) : tx(psbt_in.tx), inputs(psbt_in.inputs), outputs(psbt_in.outputs), unknown(psbt_in.unknown) {} + + // Only checks if they refer to the same transaction + friend bool operator==(const PartiallySignedTransaction& a, const PartiallySignedTransaction &b) + { + return a.tx->GetHash() == b.tx->GetHash(); + } + friend bool operator!=(const PartiallySignedTransaction& a, const PartiallySignedTransaction &b) + { + return !(a == b); + } + + template <typename Stream> + inline void Serialize(Stream& s) const { + + // magic bytes + s << PSBT_MAGIC_BYTES; + + // unsigned tx flag + SerializeToVector(s, PSBT_GLOBAL_UNSIGNED_TX); + + // Write serialized tx to a stream + SerializeToVector(s, *tx); + + // Write the unknown things + for (auto& entry : unknown) { + s << entry.first; + s << entry.second; + } + + // Separator + s << PSBT_SEPARATOR; + + // Write inputs + for (const PSBTInput& input : inputs) { + s << input; + } + // Write outputs + for (const PSBTOutput& output : outputs) { + s << output; + } + } + + + template <typename Stream> + inline void Unserialize(Stream& s) { + // Read the magic bytes + uint8_t magic[5]; + s >> magic; + if (!std::equal(magic, magic + 5, PSBT_MAGIC_BYTES)) { + throw std::ios_base::failure("Invalid PSBT magic bytes"); + } + + // Read global data + while(!s.empty()) { + // Read + std::vector<unsigned char> key; + s >> key; + + // the key is empty if that was actually a separator byte + // This is a special case for key lengths 0 as those are not allowed (except for separator) + if (key.empty()) break; + + // First byte of key is the type + unsigned char type = key[0]; + + // Do stuff based on type + switch(type) { + case PSBT_GLOBAL_UNSIGNED_TX: + { + if (tx) { + throw std::ios_base::failure("Duplicate Key, unsigned tx already provided"); + } + CMutableTransaction mtx; + UnserializeFromVector(s, mtx); + tx = std::move(mtx); + // Make sure that all scriptSigs and scriptWitnesses are empty + for (const CTxIn& txin : tx->vin) { + if (!txin.scriptSig.empty() || !txin.scriptWitness.IsNull()) { + throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses."); + } + } + break; + } + // Unknown stuff + default: { + if (unknown.count(key) > 0) { + throw std::ios_base::failure("Duplicate Key, key for unknown value already provided"); + } + // Read in the value + std::vector<unsigned char> val_bytes; + s >> val_bytes; + unknown.emplace(std::move(key), std::move(val_bytes)); + } + } + } + + // Make sure that we got an unsigned tx + if (!tx) { + throw std::ios_base::failure("No unsigned transcation was provided"); + } + + // Read input data + unsigned int i = 0; + while (!s.empty() && i < tx->vin.size()) { + PSBTInput input; + s >> input; + inputs.push_back(input); + + // Make sure the non-witness utxo matches the outpoint + if (input.non_witness_utxo && input.non_witness_utxo->GetHash() != tx->vin[i].prevout.hash) { + throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash"); + } + ++i; + } + // Make sure that the number of inputs matches the number of inputs in the transaction + if (inputs.size() != tx->vin.size()) { + throw std::ios_base::failure("Inputs provided does not match the number of inputs in transaction."); + } + + // Read output data + i = 0; + while (!s.empty() && i < tx->vout.size()) { + PSBTOutput output; + s >> output; + outputs.push_back(output); + ++i; + } + // Make sure that the number of outputs matches the number of outputs in the transaction + if (outputs.size() != tx->vout.size()) { + throw std::ios_base::failure("Outputs provided does not match the number of outputs in transaction."); + } + // Sanity check + if (!IsSane()) { + throw std::ios_base::failure("PSBT is not sane."); + } + } + + template <typename Stream> + PartiallySignedTransaction(deserialize_type, Stream& s) { + Unserialize(s); + } +}; + /** Produce a script signature using a generic signature creator. */ bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey, SignatureData& sigdata); @@ -80,6 +643,9 @@ bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreato bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType); bool SignSignature(const SigningProvider &provider, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType); +/** Signs a PSBTInput */ +bool SignPSBTInput(const SigningProvider& provider, const CMutableTransaction& tx, PSBTInput& input, SignatureData& sigdata, int index, int sighash = 1); + /** Extract signature data from a transaction input, and insert it. */ SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout); void UpdateInput(CTxIn& input, const SignatureData& data); diff --git a/src/script/standard.cpp b/src/script/standard.cpp index f0b2c62a91..d7b1724790 100644 --- a/src/script/standard.cpp +++ b/src/script/standard.cpp @@ -324,8 +324,6 @@ CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys) CScript GetScriptForWitness(const CScript& redeemscript) { - CScript ret; - txnouttype typ; std::vector<std::vector<unsigned char> > vSolutions; if (Solver(redeemscript, typ, vSolutions)) { diff --git a/src/serialize.h b/src/serialize.h index df3b47ba87..99d4c893f2 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -173,11 +173,11 @@ template<typename X> const X& ReadWriteAsHelper(const X& x) { return x; } #define READWRITE(...) (::SerReadWriteMany(s, ser_action, __VA_ARGS__)) #define READWRITEAS(type, obj) (::SerReadWriteMany(s, ser_action, ReadWriteAsHelper<type>(obj))) -/** +/** * Implement three methods for serializable objects. These are actually wrappers over * "SerializationOp" template, which implements the body of each class' serialization * code. Adding "ADD_SERIALIZE_METHODS" in the body of the class causes these wrappers to be - * added as members. + * added as members. */ #define ADD_SERIALIZE_METHODS \ template<typename Stream> \ @@ -312,16 +312,16 @@ uint64_t ReadCompactSize(Stream& is) * sure the encoding is one-to-one, one is subtracted from all but the last digit. * Thus, the byte sequence a[] with length len, where all but the last byte * has bit 128 set, encodes the number: - * + * * (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1)) - * + * * Properties: * * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes) * * Every integer has exactly one encoding * * Encoding does not depend on size of original integer type * * No redundancy: every (infinite) byte sequence corresponds to a list * of encoded integers. - * + * * 0: [0x00] 256: [0x81 0x00] * 1: [0x01] 16383: [0xFE 0x7F] * 127: [0x7F] 16384: [0xFF 0x00] @@ -991,4 +991,12 @@ size_t GetSerializeSize(const S& s, const T& t) return (CSizeComputer(s.GetType(), s.GetVersion()) << t).size(); } +template <typename S, typename... T> +size_t GetSerializeSizeMany(const S& s, const T&... t) +{ + CSizeComputer sc(s.GetType(), s.GetVersion()); + SerializeMany(sc, t...); + return sc.size(); +} + #endif // BITCOIN_SERIALIZE_H diff --git a/src/streams.h b/src/streams.h index 6ba4f103da..ed2e985d76 100644 --- a/src/streams.h +++ b/src/streams.h @@ -348,7 +348,7 @@ public: if (nReadPosNext > vch.size()) { throw std::ios_base::failure("CDataStream::read(): end of data"); } - memcpy(pch, &vch[nReadPos], nSize); + memcpy(pch, &vch[nReadPos], nSize); if (nReadPosNext == vch.size()) { nReadPos = 0; @@ -456,7 +456,7 @@ private: const int nType; const int nVersion; - FILE* file; + FILE* file; public: CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn) : nType(nTypeIn), nVersion(nVersionIn) diff --git a/src/test/README.md b/src/test/README.md index 01da32109b..f2a4cb1818 100644 --- a/src/test/README.md +++ b/src/test/README.md @@ -42,12 +42,12 @@ unit tests as possible). The build system is setup to compile an executable called `test_bitcoin` that runs all of the unit tests. The main source file is called -test_bitcoin.cpp. To add a new unit test file to our test suite you need -to add the file to `src/Makefile.test.include`. The pattern is to create -one test file for each class or source file for which you want to create -unit tests. The file naming convention is `<source_filename>_tests.cpp` -and such files should wrap their tests in a test suite -called `<source_filename>_tests`. For an example of this pattern, +test_bitcoin.cpp. To add a new unit test file to our test suite you need +to add the file to `src/Makefile.test.include`. The pattern is to create +one test file for each class or source file for which you want to create +unit tests. The file naming convention is `<source_filename>_tests.cpp` +and such files should wrap their tests in a test suite +called `<source_filename>_tests`. For an example of this pattern, examine `uint256_tests.cpp`. For further reading, I found the following website to be helpful in diff --git a/src/test/data/key_io_invalid.json b/src/test/data/key_io_invalid.json index 2056c7491c..9b52943ac6 100644 --- a/src/test/data/key_io_invalid.json +++ b/src/test/data/key_io_invalid.json @@ -1,151 +1,151 @@ [ [ "" - ], + ], [ "x" - ], + ], [ "37qgekLpCCHrQuSjvX3fs496FWTGsHFHizjJAs6NPcR47aefnnCWECAhHV6E3g4YN7u7Yuwod5Y" - ], + ], [ "dzb7VV1Ui55BARxv7ATxAtCUeJsANKovDGWFVgpTbhq9gvPqP3yv" - ], + ], [ "MuNu7ZAEDFiHthiunm7dPjwKqrVNCM3mAz6rP9zFveQu14YA8CxExSJTHcVP9DErn6u84E6Ej7S" - ], + ], [ "rPpQpYknyNQ5AEHuY6H8ijJJrYc2nDKKk9jjmKEXsWzyAQcFGpDLU2Zvsmoi8JLR7hAwoy3RQWf" - ], + ], [ "4Uc3FmN6NQ6zLBK5QQBXRBUREaaHwCZYsGCueHauuDmJpZKn6jkEskMB2Zi2CNgtb5r6epWEFfUJq" - ], + ], [ "7aQgR5DFQ25vyXmqZAWmnVCjL3PkBcdVkBUpjrjMTcghHx3E8wb" - ], + ], [ "17QpPprjeg69fW1DV8DcYYCKvWjYhXvWkov6MJ1iTTvMFj6weAqW7wybZeH57WTNxXVCRH4veVs" - ], + ], [ "KxuACDviz8Xvpn1xAh9MfopySZNuyajYMZWz16Dv2mHHryznWUp3" - ], + ], [ "7nK3GSmqdXJQtdohvGfJ7KsSmn3TmGqExug49583bDAL91pVSGq5xS9SHoAYL3Wv3ijKTit65th" - ], + ], [ "cTivdBmq7bay3RFGEBBuNfMh2P1pDCgRYN2Wbxmgwr4ki3jNUL2va" - ], + ], [ "gjMV4vjNjyMrna4fsAr8bWxAbwtmMUBXJS3zL4NJt5qjozpbQLmAfK1uA3CquSqsZQMpoD1g2nk" - ], + ], [ "emXm1naBMoVzPjbk7xpeTVMFy4oDEe25UmoyGgKEB1gGWsK8kRGs" - ], + ], [ "7VThQnNRj1o3Zyvc7XHPRrjDf8j2oivPTeDXnRPYWeYGE4pXeRJDZgf28ppti5hsHWXS2GSobdqyo" - ], + ], [ "1G9u6oCVCPh2o8m3t55ACiYvG1y5BHewUkDSdiQarDcYXXhFHYdzMdYfUAhfxn5vNZBwpgUNpso" - ], + ], [ "31QQ7ZMLkScDiB4VyZjuptr7AEc9j1SjstF7pRoLhHTGkW4Q2y9XELobQmhhWxeRvqcukGd1XCq" - ], + ], [ "DHqKSnpxa8ZdQyH8keAhvLTrfkyBMQxqngcQA5N8LQ9KVt25kmGN" - ], + ], [ "2LUHcJPbwLCy9GLH1qXmfmAwvadWw4bp4PCpDfduLqV17s6iDcy1imUwhQJhAoNoN1XNmweiJP4i" - ], + ], [ "7USRzBXAnmck8fX9HmW7RAb4qt92VFX6soCnts9s74wxm4gguVhtG5of8fZGbNPJA83irHVY6bCos" - ], + ], [ "1DGezo7BfVebZxAbNT3XGujdeHyNNBF3vnficYoTSp4PfK2QaML9bHzAMxke3wdKdHYWmsMTJVu" - ], + ], [ "2D12DqDZKwCxxkzs1ZATJWvgJGhQ4cFi3WrizQ5zLAyhN5HxuAJ1yMYaJp8GuYsTLLxTAz6otCfb" - ], + ], [ "8AFJzuTujXjw1Z6M3fWhQ1ujDW7zsV4ePeVjVo7D1egERqSW9nZ" - ], + ], [ "163Q17qLbTCue8YY3AvjpUhotuaodLm2uqMhpYirsKjVqnxJRWTEoywMVY3NbBAHuhAJ2cF9GAZ" - ], + ], [ "2MnmgiRH4eGLyLc9eAqStzk7dFgBjFtUCtu" - ], + ], [ "461QQ2sYWxU7H2PV4oBwJGNch8XVTYYbZxU" - ], + ], [ "2UCtv53VttmQYkVU4VMtXB31REvQg4ABzs41AEKZ8UcB7DAfVzdkV9JDErwGwyj5AUHLkmgZeobs" - ], + ], [ "cSNjAsnhgtiFMi6MtfvgscMB2Cbhn2v1FUYfviJ1CdjfidvmeW6mn" - ], + ], [ "gmsow2Y6EWAFDFE1CE4Hd3Tpu2BvfmBfG1SXsuRARbnt1WjkZnFh1qGTiptWWbjsq2Q6qvpgJVj" - ], + ], [ "nksUKSkzS76v8EsSgozXGMoQFiCoCHzCVajFKAXqzK5on9ZJYVHMD5CKwgmX3S3c7M1U3xabUny" - ], + ], [ "L3favK1UzFGgdzYBF2oBT5tbayCo4vtVBLJhg2iYuMeePxWG8SQc" - ], + ], [ "7VxLxGGtYT6N99GdEfi6xz56xdQ8nP2dG1CavuXx7Rf2PrvNMTBNevjkfgs9JmkcGm6EXpj8ipyPZ" - ], + ], [ "2mbZwFXF6cxShaCo2czTRB62WTx9LxhTtpP" - ], + ], [ "dB7cwYdcPSgiyAwKWL3JwCVwSk6epU2txw" - ], + ], [ "HPhFUhUAh8ZQQisH8QQWafAxtQYju3SFTX" - ], + ], [ "4ctAH6AkHzq5ioiM1m9T3E2hiYEev5mTsB" - ], + ], [ "Hn1uFi4dNexWrqARpjMqgT6cX1UsNPuV3cHdGg9ExyXw8HTKadbktRDtdeVmY3M1BxJStiL4vjJ" - ], + ], [ "Sq3fDbvutABmnAHHExJDgPLQn44KnNC7UsXuT7KZecpaYDMU9Txs" - ], + ], [ "6TqWyrqdgUEYDQU1aChMuFMMEimHX44qHFzCUgGfqxGgZNMUVWJ" - ], + ], [ "giqJo7oWqFxNKWyrgcBxAVHXnjJ1t6cGoEffce5Y1y7u649Noj5wJ4mmiUAKEVVrYAGg2KPB3Y4" - ], + ], [ "cNzHY5e8vcmM3QVJUcjCyiKMYfeYvyueq5qCMV3kqcySoLyGLYUK" - ], + ], [ "37uTe568EYc9WLoHEd9jXEvUiWbq5LFLscNyqvAzLU5vBArUJA6eydkLmnMwJDjkL5kXc2VK7ig" - ], + ], [ "EsYbG4tWWWY45G31nox838qNdzksbPySWc" - ], + ], [ "nbuzhfwMoNzA3PaFnyLcRxE9bTJPDkjZ6Rf6Y6o2ckXZfzZzXBT" - ], + ], [ "cQN9PoxZeCWK1x56xnz6QYAsvR11XAce3Ehp3gMUdfSQ53Y2mPzx" - ], + ], [ "1Gm3N3rkef6iMbx4voBzaxtXcmmiMTqZPhcuAepRzYUJQW4qRpEnHvMojzof42hjFRf8PE2jPde" - ], + ], [ "2TAq2tuN6x6m233bpT7yqdYQPELdTDJn1eU" - ], + ], [ "ntEtnnGhqPii4joABvBtSEJG6BxjT2tUZqE8PcVYgk3RHpgxgHDCQxNbLJf7ardf1dDk2oCQ7Cf" - ], + ], [ "Ky1YjoZNgQ196HJV3HpdkecfhRBmRZdMJk89Hi5KGfpfPwS2bUbfd" - ], + ], [ "2A1q1YsMZowabbvta7kTy2Fd6qN4r5ZCeG3qLpvZBMzCixMUdkN2Y4dHB1wPsZAeVXUGD83MfRED" ], diff --git a/src/test/data/script_tests.json b/src/test/data/script_tests.json index 97edc98bf6..9b320b6943 100644 --- a/src/test/data/script_tests.json +++ b/src/test/data/script_tests.json @@ -712,7 +712,7 @@ ["0x17 0x3014020002107777777777777777777777777777777701", "0 CHECKSIG NOT", "", "OK", "Zero-length R is correctly encoded"], ["0x17 0x3014021077777777777777777777777777777777020001", "0 CHECKSIG NOT", "", "OK", "Zero-length S is correctly encoded for DERSIG"], ["0x27 0x302402107777777777777777777777777777777702108777777777777777777777777777777701", "0 CHECKSIG NOT", "", "OK", "Negative S is correctly encoded"], - + ["2147483648", "CHECKSEQUENCEVERIFY", "CHECKSEQUENCEVERIFY", "OK", "CSV passes if stack top bit 1 << 31 is set"], ["", "DEPTH", "P2SH,STRICTENC", "EVAL_FALSE", "Test the test: we should have an empty stack after scriptSig evaluation"], diff --git a/src/test/dbwrapper_tests.cpp b/src/test/dbwrapper_tests.cpp index fac7418cba..5ba54ef9b0 100644 --- a/src/test/dbwrapper_tests.cpp +++ b/src/test/dbwrapper_tests.cpp @@ -20,9 +20,9 @@ static bool is_null_key(const std::vector<unsigned char>& key) { return isnull; } - + BOOST_FIXTURE_TEST_SUITE(dbwrapper_tests, BasicTestingSetup) - + BOOST_AUTO_TEST_CASE(dbwrapper) { // Perform tests both obfuscated and non-obfuscated. @@ -142,7 +142,7 @@ BOOST_AUTO_TEST_CASE(existing_data_no_obfuscate) // Now, set up another wrapper that wants to obfuscate the same directory CDBWrapper odbw(ph, (1 << 10), false, false, true); - // Check that the key/val we wrote with unobfuscated wrapper exists and + // Check that the key/val we wrote with unobfuscated wrapper exists and // is readable. uint256 res2; BOOST_CHECK(odbw.Read(key, res2)); @@ -153,13 +153,13 @@ BOOST_AUTO_TEST_CASE(existing_data_no_obfuscate) uint256 in2 = InsecureRand256(); uint256 res3; - + // Check that we can write successfully BOOST_CHECK(odbw.Write(key, in2)); BOOST_CHECK(odbw.Read(key, res3)); BOOST_CHECK_EQUAL(res3.ToString(), in2.ToString()); } - + // Ensure that we start obfuscating during a reindex. BOOST_AUTO_TEST_CASE(existing_data_reindex) { @@ -190,7 +190,7 @@ BOOST_AUTO_TEST_CASE(existing_data_reindex) uint256 in2 = InsecureRand256(); uint256 res3; - + // Check that we can write successfully BOOST_CHECK(odbw.Write(key, in2)); BOOST_CHECK(odbw.Read(key, res3)); diff --git a/src/test/limitedmap_tests.cpp b/src/test/limitedmap_tests.cpp index a4bd63cdef..7871ff6f74 100644 --- a/src/test/limitedmap_tests.cpp +++ b/src/test/limitedmap_tests.cpp @@ -50,10 +50,10 @@ BOOST_AUTO_TEST_CASE(limitedmap_test) // use the iterator to check for the expected key and value BOOST_CHECK(it->first == i); BOOST_CHECK(it->second == i + 1); - + // use find to check for the value BOOST_CHECK(map.find(i)->second == i + 1); - + // update and recheck map.update(it, i + 2); BOOST_CHECK(map.find(i)->second == i + 2); diff --git a/src/test/mempool_tests.cpp b/src/test/mempool_tests.cpp index 0264d29455..e2d76dc293 100644 --- a/src/test/mempool_tests.cpp +++ b/src/test/mempool_tests.cpp @@ -66,7 +66,7 @@ BOOST_AUTO_TEST_CASE(MempoolRemoveTest) poolSize = testPool.size(); testPool.removeRecursive(txParent); BOOST_CHECK_EQUAL(testPool.size(), poolSize - 1); - + // Parent, children, grandchildren: testPool.addUnchecked(txParent.GetHash(), entry.FromTx(txParent)); for (int i = 0; i < 3; i++) diff --git a/src/test/miner_tests.cpp b/src/test/miner_tests.cpp index 9a325f5f4c..10c7fd00e8 100644 --- a/src/test/miner_tests.cpp +++ b/src/test/miner_tests.cpp @@ -209,7 +209,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) const CChainParams& chainparams = *chainParams; CScript scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; std::unique_ptr<CBlockTemplate> pblocktemplate; - CMutableTransaction tx,tx2; + CMutableTransaction tx; CScript script; uint256 hash; TestMemPoolEntryHelper entry; diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp index 2a77e0e1ec..f7861d9b8a 100644 --- a/src/test/net_tests.cpp +++ b/src/test/net_tests.cpp @@ -173,7 +173,7 @@ BOOST_AUTO_TEST_CASE(cnode_simple_test) in_addr ipv4Addr; ipv4Addr.s_addr = 0xa0b0c001; - + CAddress addr = CAddress(CService(ipv4Addr, 7777), NODE_NETWORK); std::string pszDest; bool fInboundIn = false; diff --git a/src/test/netbase_tests.cpp b/src/test/netbase_tests.cpp index bc90e5ae09..67f7c37f3b 100644 --- a/src/test/netbase_tests.cpp +++ b/src/test/netbase_tests.cpp @@ -82,10 +82,10 @@ bool static TestSplitHost(std::string test, std::string host, int port) BOOST_AUTO_TEST_CASE(netbase_splithost) { - BOOST_CHECK(TestSplitHost("www.bitcoin.org", "www.bitcoin.org", -1)); - BOOST_CHECK(TestSplitHost("[www.bitcoin.org]", "www.bitcoin.org", -1)); - BOOST_CHECK(TestSplitHost("www.bitcoin.org:80", "www.bitcoin.org", 80)); - BOOST_CHECK(TestSplitHost("[www.bitcoin.org]:80", "www.bitcoin.org", 80)); + BOOST_CHECK(TestSplitHost("www.bitcoincore.org", "www.bitcoincore.org", -1)); + BOOST_CHECK(TestSplitHost("[www.bitcoincore.org]", "www.bitcoincore.org", -1)); + BOOST_CHECK(TestSplitHost("www.bitcoincore.org:80", "www.bitcoincore.org", 80)); + BOOST_CHECK(TestSplitHost("[www.bitcoincore.org]:80", "www.bitcoincore.org", 80)); BOOST_CHECK(TestSplitHost("127.0.0.1", "127.0.0.1", -1)); BOOST_CHECK(TestSplitHost("127.0.0.1:8333", "127.0.0.1", 8333)); BOOST_CHECK(TestSplitHost("[127.0.0.1]", "127.0.0.1", -1)); diff --git a/src/test/prevector_tests.cpp b/src/test/prevector_tests.cpp index fe6f10d845..5f00009354 100644 --- a/src/test/prevector_tests.cpp +++ b/src/test/prevector_tests.cpp @@ -36,7 +36,7 @@ class prevector_tester { { local_check(a == b); } - void local_check(bool b) + void local_check(bool b) { passed &= b; } diff --git a/src/test/raii_event_tests.cpp b/src/test/raii_event_tests.cpp index 7bc81c7f64..3dfa09e09e 100644 --- a/src/test/raii_event_tests.cpp +++ b/src/test/raii_event_tests.cpp @@ -41,7 +41,7 @@ BOOST_FIXTURE_TEST_SUITE(raii_event_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(raii_event_creation) { event_set_mem_functions(tag_malloc, realloc, tag_free); - + void* base_ptr = nullptr; { auto base = obtain_event_base(); @@ -49,7 +49,7 @@ BOOST_AUTO_TEST_CASE(raii_event_creation) BOOST_CHECK(tags[base_ptr] == 1); } BOOST_CHECK(tags[base_ptr] == 0); - + void* event_ptr = nullptr; { auto base = obtain_event_base(); @@ -63,14 +63,14 @@ BOOST_AUTO_TEST_CASE(raii_event_creation) } BOOST_CHECK(tags[base_ptr] == 0); BOOST_CHECK(tags[event_ptr] == 0); - + event_set_mem_functions(malloc, realloc, free); } BOOST_AUTO_TEST_CASE(raii_event_order) { event_set_mem_functions(tag_malloc, realloc, tag_free); - + void* base_ptr = nullptr; void* event_ptr = nullptr; { diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index c7cdd7ca82..510910e149 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -515,7 +515,7 @@ BOOST_AUTO_TEST_CASE(script_build) tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG, "P2SH(P2PK), bad redeemscript", SCRIPT_VERIFY_P2SH, true ).PushSig(keys.key0).PushRedeem().DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE)); - + tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey0.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG, "P2SH(P2PKH)", SCRIPT_VERIFY_P2SH, true ).PushSig(keys.key0).Push(keys.pubkey0).PushRedeem()); @@ -1495,4 +1495,146 @@ BOOST_AUTO_TEST_CASE(script_can_append_self) BOOST_CHECK(s == d); } + +#if defined(HAVE_CONSENSUS_LIB) + +/* Test simple (successful) usage of bitcoinconsensus_verify_script */ +BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_returns_true) +{ + unsigned int libconsensus_flags = 0; + int nIn = 0; + + CScript scriptPubKey; + CScript scriptSig; + CScriptWitness wit; + + scriptPubKey << OP_1; + CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1); + CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx); + + CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); + stream << spendTx; + + bitcoinconsensus_error err; + int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), nIn, libconsensus_flags, &err); + BOOST_CHECK_EQUAL(result, 1); + BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_OK); +} + +/* Test bitcoinconsensus_verify_script returns invalid tx index err*/ +BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_index_err) +{ + unsigned int libconsensus_flags = 0; + int nIn = 3; + + CScript scriptPubKey; + CScript scriptSig; + CScriptWitness wit; + + scriptPubKey << OP_EQUAL; + CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1); + CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx); + + CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); + stream << spendTx; + + bitcoinconsensus_error err; + int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), nIn, libconsensus_flags, &err); + BOOST_CHECK_EQUAL(result, 0); + BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_TX_INDEX); +} + +/* Test bitcoinconsensus_verify_script returns tx size mismatch err*/ +BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_size) +{ + unsigned int libconsensus_flags = 0; + int nIn = 0; + + CScript scriptPubKey; + CScript scriptSig; + CScriptWitness wit; + + scriptPubKey << OP_EQUAL; + CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1); + CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx); + + CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); + stream << spendTx; + + bitcoinconsensus_error err; + int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size() * 2, nIn, libconsensus_flags, &err); + BOOST_CHECK_EQUAL(result, 0); + BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_TX_SIZE_MISMATCH); +} + +/* Test bitcoinconsensus_verify_script returns invalid tx serialization error */ +BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_serialization) +{ + unsigned int libconsensus_flags = 0; + int nIn = 0; + + CScript scriptPubKey; + CScript scriptSig; + CScriptWitness wit; + + scriptPubKey << OP_EQUAL; + CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1); + CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx); + + CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); + stream << 0xffffffff; + + bitcoinconsensus_error err; + int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), nIn, libconsensus_flags, &err); + BOOST_CHECK_EQUAL(result, 0); + BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_TX_DESERIALIZE); +} + +/* Test bitcoinconsensus_verify_script returns amount required error */ +BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_amount_required_err) +{ + unsigned int libconsensus_flags = bitcoinconsensus_SCRIPT_FLAGS_VERIFY_WITNESS; + int nIn = 0; + + CScript scriptPubKey; + CScript scriptSig; + CScriptWitness wit; + + scriptPubKey << OP_EQUAL; + CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1); + CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx); + + CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); + stream << spendTx; + + bitcoinconsensus_error err; + int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), nIn, libconsensus_flags, &err); + BOOST_CHECK_EQUAL(result, 0); + BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_AMOUNT_REQUIRED); +} + +/* Test bitcoinconsensus_verify_script returns invalid flags err */ +BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_invalid_flags) +{ + unsigned int libconsensus_flags = 1 << 3; + int nIn = 0; + + CScript scriptPubKey; + CScript scriptSig; + CScriptWitness wit; + + scriptPubKey << OP_EQUAL; + CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1); + CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx); + + CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); + stream << spendTx; + + bitcoinconsensus_error err; + int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), nIn, libconsensus_flags, &err); + BOOST_CHECK_EQUAL(result, 0); + BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_INVALID_FLAGS); +} + +#endif BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/serialize_tests.cpp b/src/test/serialize_tests.cpp index eba58e0042..a0dafaaf5c 100644 --- a/src/test/serialize_tests.cpp +++ b/src/test/serialize_tests.cpp @@ -252,8 +252,8 @@ static bool isCanonicalException(const std::ios_base::failure& ex) // The string returned by what() can be different for different platforms. // Instead of directly comparing the ex.what() with an expected string, - // create an instance of exception to see if ex.what() matches - // the expected explanatory string returned by the exception instance. + // create an instance of exception to see if ex.what() matches + // the expected explanatory string returned by the exception instance. return strcmp(expectedException.what(), ex.what()) == 0; } diff --git a/src/test/streams_tests.cpp b/src/test/streams_tests.cpp index e1e77f7c92..8ca668ba01 100644 --- a/src/test/streams_tests.cpp +++ b/src/test/streams_tests.cpp @@ -76,19 +76,19 @@ BOOST_AUTO_TEST_CASE(streams_serializedata_xor) CDataStream ds(in, 0, 0); // Degenerate case - + key.push_back('\x00'); key.push_back('\x00'); ds.Xor(key); BOOST_CHECK_EQUAL( - std::string(expected_xor.begin(), expected_xor.end()), + std::string(expected_xor.begin(), expected_xor.end()), std::string(ds.begin(), ds.end())); in.push_back('\x0f'); in.push_back('\xf0'); expected_xor.push_back('\xf0'); expected_xor.push_back('\x0f'); - + // Single character key ds.clear(); @@ -98,9 +98,9 @@ BOOST_AUTO_TEST_CASE(streams_serializedata_xor) key.push_back('\xff'); ds.Xor(key); BOOST_CHECK_EQUAL( - std::string(expected_xor.begin(), expected_xor.end()), - std::string(ds.begin(), ds.end())); - + std::string(expected_xor.begin(), expected_xor.end()), + std::string(ds.begin(), ds.end())); + // Multi character key in.clear(); @@ -109,7 +109,7 @@ BOOST_AUTO_TEST_CASE(streams_serializedata_xor) in.push_back('\x0f'); expected_xor.push_back('\x0f'); expected_xor.push_back('\x00'); - + ds.clear(); ds.insert(ds.begin(), in.begin(), in.end()); @@ -119,8 +119,8 @@ BOOST_AUTO_TEST_CASE(streams_serializedata_xor) ds.Xor(key); BOOST_CHECK_EQUAL( - std::string(expected_xor.begin(), expected_xor.end()), - std::string(ds.begin(), ds.end())); -} + std::string(expected_xor.begin(), expected_xor.end()), + std::string(ds.begin(), ds.end())); +} BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp index 45dc0e3571..aff270942e 100644 --- a/src/test/transaction_tests.cpp +++ b/src/test/transaction_tests.cpp @@ -547,7 +547,6 @@ BOOST_AUTO_TEST_CASE(test_witness) CTransactionRef output1, output2; CMutableTransaction input1, input2; - SignatureData sigdata; // Normal pay-to-compressed-pubkey. CreateCreditAndSpend(keystore, scriptPubkey1, output1, input1); diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp index d535f74e91..3661c762fc 100644 --- a/src/test/util_tests.cpp +++ b/src/test/util_tests.cpp @@ -806,6 +806,21 @@ BOOST_AUTO_TEST_CASE(gettime) BOOST_CHECK((GetTime() & ~0xFFFFFFFFLL) == 0); } +BOOST_AUTO_TEST_CASE(test_IsDigit) +{ + BOOST_CHECK_EQUAL(IsDigit('0'), true); + BOOST_CHECK_EQUAL(IsDigit('1'), true); + BOOST_CHECK_EQUAL(IsDigit('8'), true); + BOOST_CHECK_EQUAL(IsDigit('9'), true); + + BOOST_CHECK_EQUAL(IsDigit('0' - 1), false); + BOOST_CHECK_EQUAL(IsDigit('9' + 1), false); + BOOST_CHECK_EQUAL(IsDigit(0), false); + BOOST_CHECK_EQUAL(IsDigit(1), false); + BOOST_CHECK_EQUAL(IsDigit(8), false); + BOOST_CHECK_EQUAL(IsDigit(9), false); +} + BOOST_AUTO_TEST_CASE(test_ParseInt32) { int32_t n; diff --git a/src/timedata.h b/src/timedata.h index 23584f67e5..a4fefb5983 100644 --- a/src/timedata.h +++ b/src/timedata.h @@ -14,7 +14,7 @@ static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT = 70 * 60; class CNetAddr; -/** +/** * Median filter over a stream of values. * Returns the median of the last N numbers */ diff --git a/src/txdb.cpp b/src/txdb.cpp index 3635d0ab4b..1fc7919442 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -53,7 +53,7 @@ struct CoinEntry { } -CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe, true) +CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe, true) { } diff --git a/src/txmempool.cpp b/src/txmempool.cpp index 8090172e3f..2108e6ba2d 100644 --- a/src/txmempool.cpp +++ b/src/txmempool.cpp @@ -284,7 +284,7 @@ void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, b // should be a bit faster. // However, if we happen to be in the middle of processing a reorg, then // the mempool can be in an inconsistent state. In this case, the set - // of ancestors reachable via mapLinks will be the same as the set of + // of ancestors reachable via mapLinks will be the same as the set of // ancestors whose packages include this transaction, because when we // add a new transaction to the mempool in addUnchecked(), we assume it // has no children, and in the case of a reorg where that assumption is @@ -542,7 +542,7 @@ void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMem void CTxMemPool::removeConflicts(const CTransaction &tx) { // Remove transactions which depend on inputs of tx, recursively - LOCK(cs); + AssertLockHeld(cs); for (const CTxIn &txin : tx.vin) { auto it = mapNextTx.find(txin.prevout); if (it != mapNextTx.end()) { @@ -716,7 +716,6 @@ void CTxMemPool::check(const CCoinsViewCache *pcoins) const while (!waitingOnDependants.empty()) { const CTxMemPoolEntry* entry = waitingOnDependants.front(); waitingOnDependants.pop_front(); - CValidationState state; if (!mempoolDuplicate.HaveInputs(entry->GetTx())) { waitingOnDependants.push_back(entry); stepsSinceLastRemove++; diff --git a/src/txmempool.h b/src/txmempool.h index ebfcf36e11..f3b8a68a9d 100644 --- a/src/txmempool.h +++ b/src/txmempool.h @@ -544,7 +544,7 @@ public: void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN); void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags); - void removeConflicts(const CTransaction &tx); + void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs); void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight); void clear(); @@ -692,7 +692,7 @@ private: void removeUnchecked(txiter entry, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN) EXCLUSIVE_LOCKS_REQUIRED(cs); }; -/** +/** * CCoinsView that brings transactions from a mempool into view. * It does not check for spendings by memory pool transactions. * Instead, it provides access to all Coins which are either unspent in the diff --git a/src/util.cpp b/src/util.cpp index ab262b4063..2f81f50a71 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -72,7 +72,6 @@ #endif #include <boost/interprocess/sync/file_lock.hpp> -#include <boost/program_options/detail/config_file.hpp> #include <boost/thread.hpp> #include <openssl/crypto.h> #include <openssl/rand.h> @@ -447,7 +446,7 @@ bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::strin // Check that the arg is known if (!(IsSwitchChar(key[0]) && key.size() == 1)) { - if (!IsArgKnown(key, error)) { + if (!IsArgKnown(key)) { error = strprintf("Invalid parameter %s", key.c_str()); return false; } @@ -467,7 +466,7 @@ bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::strin return true; } -bool ArgsManager::IsArgKnown(const std::string& key, std::string& error) +bool ArgsManager::IsArgKnown(const std::string& key) const { size_t option_index = key.find('.'); std::string arg_no_net; @@ -592,7 +591,7 @@ void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names) } } -std::string ArgsManager::GetHelpMessage() +std::string ArgsManager::GetHelpMessage() const { const bool show_debug = gArgs.GetBoolArg("-help-debug", false); @@ -811,17 +810,47 @@ fs::path GetConfigFile(const std::string& confPath) return AbsPathForConfigVal(fs::path(confPath), false); } +static std::string TrimString(const std::string& str, const std::string& pattern) +{ + std::string::size_type front = str.find_first_not_of(pattern); + if (front == std::string::npos) { + return std::string(); + } + std::string::size_type end = str.find_last_not_of(pattern); + return str.substr(front, end - front + 1); +} + +static std::vector<std::pair<std::string, std::string>> GetConfigOptions(std::istream& stream) +{ + std::vector<std::pair<std::string, std::string>> options; + std::string str, prefix; + std::string::size_type pos; + while (std::getline(stream, str)) { + if ((pos = str.find('#')) != std::string::npos) { + str = str.substr(0, pos); + } + const static std::string pattern = " \t\r\n"; + str = TrimString(str, pattern); + if (!str.empty()) { + if (*str.begin() == '[' && *str.rbegin() == ']') { + prefix = str.substr(1, str.size() - 2) + '.'; + } else if ((pos = str.find('=')) != std::string::npos) { + std::string name = prefix + TrimString(str.substr(0, pos), pattern); + std::string value = TrimString(str.substr(pos + 1), pattern); + options.emplace_back(name, value); + } + } + } + return options; +} + bool ArgsManager::ReadConfigStream(std::istream& stream, std::string& error, bool ignore_invalid_keys) { LOCK(cs_args); - std::set<std::string> setOptions; - setOptions.insert("*"); - - for (boost::program_options::detail::config_file_iterator it(stream, setOptions), end; it != end; ++it) - { - std::string strKey = std::string("-") + it->string_key; - std::string strValue = it->value[0]; + for (const std::pair<std::string, std::string>& option : GetConfigOptions(stream)) { + std::string strKey = std::string("-") + option.first; + std::string strValue = option.second; if (InterpretNegatedOption(strKey, strValue)) { m_config_args[strKey].clear(); @@ -830,8 +859,8 @@ bool ArgsManager::ReadConfigStream(std::istream& stream, std::string& error, boo } // Check that the arg is known - if (!IsArgKnown(strKey, error) && !ignore_invalid_keys) { - error = strprintf("Invalid configuration value %s", it->string_key.c_str()); + if (!IsArgKnown(strKey) && !ignore_invalid_keys) { + error = strprintf("Invalid configuration value %s", option.first.c_str()); return false; } } @@ -992,7 +1021,7 @@ bool FileCommit(FILE *file) LogPrintf("%s: fdatasync failed: %d\n", __func__, errno); return false; } - #elif defined(__APPLE__) && defined(F_FULLFSYNC) + #elif defined(MAC_OSX) && defined(F_FULLFSYNC) if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno); return false; diff --git a/src/util.h b/src/util.h index f8bcc0192c..23b2a787e4 100644 --- a/src/util.h +++ b/src/util.h @@ -276,12 +276,12 @@ public: /** * Get the help string */ - std::string GetHelpMessage(); + std::string GetHelpMessage() const; /** * Check whether we know of this arg */ - bool IsArgKnown(const std::string& key, std::string& error); + bool IsArgKnown(const std::string& key) const; }; extern ArgsManager gArgs; @@ -355,4 +355,18 @@ std::string CopyrightHolders(const std::string& strPrefix); */ int ScheduleBatchPriority(void); +namespace util { + +//! Simplification of std insertion +template <typename Tdst, typename Tsrc> +inline void insert(Tdst& dst, const Tsrc& src) { + dst.insert(dst.begin(), src.begin(), src.end()); +} +template <typename TsetT, typename Tsrc> +inline void insert(std::set<TsetT>& dst, const Tsrc& src) { + dst.insert(src.begin(), src.end()); +} + +} // namespace util + #endif // BITCOIN_UTIL_H diff --git a/src/utilstrencodings.cpp b/src/utilstrencodings.cpp index d1025fc7bf..c6927021cb 100644 --- a/src/utilstrencodings.cpp +++ b/src/utilstrencodings.cpp @@ -473,7 +473,7 @@ bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out) /* pass single 0 */ ++ptr; } else if (val[ptr] >= '1' && val[ptr] <= '9') { - while (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') { + while (ptr < end && IsDigit(val[ptr])) { if (!ProcessMantissaDigit(val[ptr], mantissa, mantissa_tzeros)) return false; /* overflow */ ++ptr; @@ -483,9 +483,9 @@ bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out) if (ptr < end && val[ptr] == '.') { ++ptr; - if (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') + if (ptr < end && IsDigit(val[ptr])) { - while (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') { + while (ptr < end && IsDigit(val[ptr])) { if (!ProcessMantissaDigit(val[ptr], mantissa, mantissa_tzeros)) return false; /* overflow */ ++ptr; @@ -502,8 +502,8 @@ bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out) exponent_sign = true; ++ptr; } - if (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') { - while (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') { + if (ptr < end && IsDigit(val[ptr])) { + while (ptr < end && IsDigit(val[ptr])) { if (exponent > (UPPER_BOUND / 10LL)) return false; /* overflow */ exponent = exponent * 10 + val[ptr] - '0'; diff --git a/src/utilstrencodings.h b/src/utilstrencodings.h index 1c9cca90b2..47f9afba1c 100644 --- a/src/utilstrencodings.h +++ b/src/utilstrencodings.h @@ -62,6 +62,16 @@ int64_t atoi64(const std::string& str); int atoi(const std::string& str); /** + * Tests if the given character is a decimal digit. + * @param[in] c character to test + * @return true if the argument is a decimal digit; otherwise false. + */ +constexpr bool IsDigit(char c) +{ + return c >= '0' && c <= '9'; +} + +/** * Convert string to signed 32-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, * false if not the entire string could be parsed or when overflow or underflow occurred. diff --git a/src/validation.cpp b/src/validation.cpp index a30f1fd0ce..f1b63b5b44 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -45,7 +45,6 @@ #include <sstream> #include <boost/algorithm/string/replace.hpp> -#include <boost/algorithm/string/join.hpp> #include <boost/thread.hpp> #if defined(NDEBUG) @@ -2242,6 +2241,13 @@ static void DoWarning(const std::string& strWarning) } } +/** Private helper function that concatenates warning messages. */ +static void AppendWarning(std::string& res, const std::string& warn) +{ + if (!res.empty()) res += ", "; + res += warn; +} + /** Check warning conditions and do some notifications on new chain tip set. */ void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainParams) { // New best block @@ -2253,7 +2259,7 @@ void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainPar g_best_block_cv.notify_all(); } - std::vector<std::string> warningMessages; + std::string warningMessages; if (!IsInitialBlockDownload()) { int nUpgraded = 0; @@ -2266,7 +2272,7 @@ void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainPar if (state == ThresholdState::ACTIVE) { DoWarning(strWarning); } else { - warningMessages.push_back(strWarning); + AppendWarning(warningMessages, strWarning); } } } @@ -2279,7 +2285,7 @@ void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainPar pindex = pindex->pprev; } if (nUpgraded > 0) - warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded)); + AppendWarning(warningMessages, strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded)); if (nUpgraded > 100/2) { std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect"); @@ -2293,7 +2299,7 @@ void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainPar FormatISO8601DateTime(pindexNew->GetBlockTime()), GuessVerificationProgress(chainParams.TxData(), pindexNew), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize()); if (!warningMessages.empty()) - LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", ")); /* Continued */ + LogPrintf(" warning='%s'", warningMessages); /* Continued */ LogPrintf("\n"); } diff --git a/src/validation.h b/src/validation.h index 869f847cdb..1aff10f025 100644 --- a/src/validation.h +++ b/src/validation.h @@ -207,7 +207,7 @@ static const unsigned int DEFAULT_CHECKLEVEL = 3; // Setting the target to > than 550MB will make it likely we can respect the target. static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024; -/** +/** * Process an incoming block. This only returns after the best known valid * block is made active. Note that it does not, however, guarantee that the * specific block passed to it has been checked for validity! @@ -218,7 +218,7 @@ static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024; * * Note that we guarantee that either the proof-of-work is valid on pblock, or * (and possibly also) BlockChecked will have been called. - * + * * May not be called in a * validationinterface callback. * @@ -351,7 +351,7 @@ bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp = null /** * Closure representing one script verification - * Note that this stores references to the spending transaction + * Note that this stores references to the spending transaction */ class CScriptCheck { diff --git a/src/wallet/coincontrol.cpp b/src/wallet/coincontrol.cpp new file mode 100644 index 0000000000..645981faa4 --- /dev/null +++ b/src/wallet/coincontrol.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2018 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include <wallet/coincontrol.h> + +#include <util.h> + +void CCoinControl::SetNull() +{ + destChange = CNoDestination(); + m_change_type.reset(); + fAllowOtherInputs = false; + fAllowWatchOnly = false; + m_avoid_partial_spends = gArgs.GetBoolArg("-avoidpartialspends", DEFAULT_AVOIDPARTIALSPENDS); + setSelected.clear(); + m_feerate.reset(); + fOverrideFeeRate = false; + m_confirm_target.reset(); + m_signal_bip125_rbf.reset(); + m_fee_mode = FeeEstimateMode::UNSET; +} + diff --git a/src/wallet/coincontrol.h b/src/wallet/coincontrol.h index 98b4298507..fbe6c43e24 100644 --- a/src/wallet/coincontrol.h +++ b/src/wallet/coincontrol.h @@ -32,6 +32,8 @@ public: boost::optional<unsigned int> m_confirm_target; //! Override the wallet's m_signal_rbf if set boost::optional<bool> m_signal_bip125_rbf; + //! Avoid partial use of funds sent to a given address + bool m_avoid_partial_spends; //! Fee estimation mode to control arguments to estimateSmartFee FeeEstimateMode m_fee_mode; @@ -40,19 +42,7 @@ public: SetNull(); } - void SetNull() - { - destChange = CNoDestination(); - m_change_type.reset(); - fAllowOtherInputs = false; - fAllowWatchOnly = false; - setSelected.clear(); - m_feerate.reset(); - fOverrideFeeRate = false; - m_confirm_target.reset(); - m_signal_bip125_rbf.reset(); - m_fee_mode = FeeEstimateMode::UNSET; - } + void SetNull(); bool HasSelected() const { diff --git a/src/wallet/coinselection.cpp b/src/wallet/coinselection.cpp index a403411e5b..1a810e763f 100644 --- a/src/wallet/coinselection.cpp +++ b/src/wallet/coinselection.cpp @@ -8,7 +8,7 @@ // Descending order comparator struct { - bool operator()(const CInputCoin& a, const CInputCoin& b) const + bool operator()(const OutputGroup& a, const OutputGroup& b) const { return a.effective_value > b.effective_value; } @@ -59,7 +59,7 @@ struct { static const size_t TOTAL_TRIES = 100000; -bool SelectCoinsBnB(std::vector<CInputCoin>& utxo_pool, const CAmount& target_value, const CAmount& cost_of_change, std::set<CInputCoin>& out_set, CAmount& value_ret, CAmount not_input_fees) +bool SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& target_value, const CAmount& cost_of_change, std::set<CInputCoin>& out_set, CAmount& value_ret, CAmount not_input_fees) { out_set.clear(); CAmount curr_value = 0; @@ -70,7 +70,7 @@ bool SelectCoinsBnB(std::vector<CInputCoin>& utxo_pool, const CAmount& target_va // Calculate curr_available_value CAmount curr_available_value = 0; - for (const CInputCoin& utxo : utxo_pool) { + for (const OutputGroup& utxo : utxo_pool) { // Assert that this utxo is not negative. It should never be negative, effective value calculation should have removed it assert(utxo.effective_value > 0); curr_available_value += utxo.effective_value; @@ -115,7 +115,7 @@ bool SelectCoinsBnB(std::vector<CInputCoin>& utxo_pool, const CAmount& target_va while (!curr_selection.empty() && !curr_selection.back()) { curr_selection.pop_back(); curr_available_value += utxo_pool.at(curr_selection.size()).effective_value; - }; + } if (curr_selection.empty()) { // We have walked back to the first utxo and no branch is untraversed. All solutions searched break; @@ -123,11 +123,11 @@ bool SelectCoinsBnB(std::vector<CInputCoin>& utxo_pool, const CAmount& target_va // Output was included on previous iterations, try excluding now. curr_selection.back() = false; - CInputCoin& utxo = utxo_pool.at(curr_selection.size() - 1); + OutputGroup& utxo = utxo_pool.at(curr_selection.size() - 1); curr_value -= utxo.effective_value; curr_waste -= utxo.fee - utxo.long_term_fee; } else { // Moving forwards, continuing down this branch - CInputCoin& utxo = utxo_pool.at(curr_selection.size()); + OutputGroup& utxo = utxo_pool.at(curr_selection.size()); // Remove this utxo from the curr_available_value utxo amount curr_available_value -= utxo.effective_value; @@ -156,32 +156,32 @@ bool SelectCoinsBnB(std::vector<CInputCoin>& utxo_pool, const CAmount& target_va value_ret = 0; for (size_t i = 0; i < best_selection.size(); ++i) { if (best_selection.at(i)) { - out_set.insert(utxo_pool.at(i)); - value_ret += utxo_pool.at(i).txout.nValue; + util::insert(out_set, utxo_pool.at(i).m_outputs); + value_ret += utxo_pool.at(i).m_value; } } return true; } -static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue, +static void ApproximateBestSubset(const std::vector<OutputGroup>& groups, const CAmount& nTotalLower, const CAmount& nTargetValue, std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000) { std::vector<char> vfIncluded; - vfBest.assign(vValue.size(), true); + vfBest.assign(groups.size(), true); nBest = nTotalLower; FastRandomContext insecure_rand; for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { - vfIncluded.assign(vValue.size(), false); + vfIncluded.assign(groups.size(), false); CAmount nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { - for (unsigned int i = 0; i < vValue.size(); i++) + for (unsigned int i = 0; i < groups.size(); i++) { //The solver here uses a randomized algorithm, //the randomness serves no real security purpose but is just @@ -191,7 +191,7 @@ static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const C //the selection random. if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i]) { - nTotal += vValue[i].txout.nValue; + nTotal += groups[i].m_value; vfIncluded[i] = true; if (nTotal >= nTargetValue) { @@ -201,7 +201,7 @@ static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const C nBest = nTotal; vfBest = vfIncluded; } - nTotal -= vValue[i].txout.nValue; + nTotal -= groups[i].m_value; vfIncluded[i] = false; } } @@ -210,86 +210,75 @@ static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const C } } -bool KnapsackSolver(const CAmount& nTargetValue, std::vector<CInputCoin>& vCoins, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) +bool KnapsackSolver(const CAmount& nTargetValue, std::vector<OutputGroup>& groups, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) { setCoinsRet.clear(); nValueRet = 0; // List of values less than target - boost::optional<CInputCoin> coinLowestLarger; - std::vector<CInputCoin> vValue; + boost::optional<OutputGroup> lowest_larger; + std::vector<OutputGroup> applicable_groups; CAmount nTotalLower = 0; - random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); + random_shuffle(groups.begin(), groups.end(), GetRandInt); - for (const CInputCoin &coin : vCoins) - { - if (coin.txout.nValue == nTargetValue) - { - setCoinsRet.insert(coin); - nValueRet += coin.txout.nValue; + for (const OutputGroup& group : groups) { + if (group.m_value == nTargetValue) { + util::insert(setCoinsRet, group.m_outputs); + nValueRet += group.m_value; return true; - } - else if (coin.txout.nValue < nTargetValue + MIN_CHANGE) - { - vValue.push_back(coin); - nTotalLower += coin.txout.nValue; - } - else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue) - { - coinLowestLarger = coin; + } else if (group.m_value < nTargetValue + MIN_CHANGE) { + applicable_groups.push_back(group); + nTotalLower += group.m_value; + } else if (!lowest_larger || group.m_value < lowest_larger->m_value) { + lowest_larger = group; } } - if (nTotalLower == nTargetValue) - { - for (const auto& input : vValue) - { - setCoinsRet.insert(input); - nValueRet += input.txout.nValue; + if (nTotalLower == nTargetValue) { + for (const auto& group : applicable_groups) { + util::insert(setCoinsRet, group.m_outputs); + nValueRet += group.m_value; } return true; } - if (nTotalLower < nTargetValue) - { - if (!coinLowestLarger) - return false; - setCoinsRet.insert(coinLowestLarger.get()); - nValueRet += coinLowestLarger->txout.nValue; + if (nTotalLower < nTargetValue) { + if (!lowest_larger) return false; + util::insert(setCoinsRet, lowest_larger->m_outputs); + nValueRet += lowest_larger->m_value; return true; } // Solve subset sum by stochastic approximation - std::sort(vValue.begin(), vValue.end(), descending); + std::sort(applicable_groups.begin(), applicable_groups.end(), descending); std::vector<char> vfBest; CAmount nBest; - ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest); - if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE) - ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest); + ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue, vfBest, nBest); + if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE) { + ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest); + } // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin - if (coinLowestLarger && - ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest)) - { - setCoinsRet.insert(coinLowestLarger.get()); - nValueRet += coinLowestLarger->txout.nValue; - } - else { - for (unsigned int i = 0; i < vValue.size(); i++) - if (vfBest[i]) - { - setCoinsRet.insert(vValue[i]); - nValueRet += vValue[i].txout.nValue; + if (lowest_larger && + ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || lowest_larger->m_value <= nBest)) { + util::insert(setCoinsRet, lowest_larger->m_outputs); + nValueRet += lowest_larger->m_value; + } else { + for (unsigned int i = 0; i < applicable_groups.size(); i++) { + if (vfBest[i]) { + util::insert(setCoinsRet, applicable_groups[i].m_outputs); + nValueRet += applicable_groups[i].m_value; } + } if (LogAcceptCategory(BCLog::SELECTCOINS)) { LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: "); /* Continued */ - for (unsigned int i = 0; i < vValue.size(); i++) { + for (unsigned int i = 0; i < applicable_groups.size(); i++) { if (vfBest[i]) { - LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue)); /* Continued */ + LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(applicable_groups[i].m_value)); /* Continued */ } } LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest)); @@ -298,3 +287,40 @@ bool KnapsackSolver(const CAmount& nTargetValue, std::vector<CInputCoin>& vCoins return true; } + +/****************************************************************************** + + OutputGroup + + ******************************************************************************/ + +void OutputGroup::Insert(const CInputCoin& output, int depth, bool from_me, size_t ancestors, size_t descendants) { + m_outputs.push_back(output); + m_from_me &= from_me; + m_value += output.effective_value; + m_depth = std::min(m_depth, depth); + // m_ancestors is currently the max ancestor count for all coins in the group; however, this is + // not ideal, as a wallet will consider e.g. thirty 2-ancestor coins as having two ancestors, + // when in reality it has 60 ancestors. + m_ancestors = std::max(m_ancestors, ancestors); + // m_descendants is the count as seen from the top ancestor, not the descendants as seen from the + // coin itself; thus, this value is accurate + m_descendants = std::max(m_descendants, descendants); + effective_value = m_value; +} + +std::vector<CInputCoin>::iterator OutputGroup::Discard(const CInputCoin& output) { + auto it = m_outputs.begin(); + while (it != m_outputs.end() && it->outpoint != output.outpoint) ++it; + if (it == m_outputs.end()) return it; + m_value -= output.effective_value; + effective_value -= output.effective_value; + return m_outputs.erase(it); +} + +bool OutputGroup::EligibleForSpending(const CoinEligibilityFilter& eligibility_filter) const +{ + return m_depth >= (m_from_me ? eligibility_filter.conf_mine : eligibility_filter.conf_theirs) + && m_ancestors <= eligibility_filter.max_ancestors + && m_descendants <= eligibility_filter.max_descendants; +} diff --git a/src/wallet/coinselection.h b/src/wallet/coinselection.h index 2b185879c6..1be776e695 100644 --- a/src/wallet/coinselection.h +++ b/src/wallet/coinselection.h @@ -28,11 +28,17 @@ public: effective_value = txout.nValue; } + CInputCoin(const CTransactionRef& tx, unsigned int i, int input_bytes) : CInputCoin(tx, i) + { + m_input_bytes = input_bytes; + } + COutPoint outpoint; CTxOut txout; CAmount effective_value; - CAmount fee = 0; - CAmount long_term_fee = 0; + + /** Pre-computed estimated size of this output as a fully-signed input in a transaction. Can be -1 if it could not be calculated */ + int m_input_bytes{-1}; bool operator<(const CInputCoin& rhs) const { return outpoint < rhs.outpoint; @@ -47,8 +53,49 @@ public: } }; -bool SelectCoinsBnB(std::vector<CInputCoin>& utxo_pool, const CAmount& target_value, const CAmount& cost_of_change, std::set<CInputCoin>& out_set, CAmount& value_ret, CAmount not_input_fees); +struct CoinEligibilityFilter +{ + const int conf_mine; + const int conf_theirs; + const uint64_t max_ancestors; + const uint64_t max_descendants; + + CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors), max_descendants(max_ancestors) {} + CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors, uint64_t max_descendants) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors), max_descendants(max_descendants) {} +}; + +struct OutputGroup +{ + std::vector<CInputCoin> m_outputs; + bool m_from_me{true}; + CAmount m_value{0}; + int m_depth{999}; + size_t m_ancestors{0}; + size_t m_descendants{0}; + CAmount effective_value{0}; + CAmount fee{0}; + CAmount long_term_fee{0}; + + OutputGroup() {} + OutputGroup(std::vector<CInputCoin>&& outputs, bool from_me, CAmount value, int depth, size_t ancestors, size_t descendants) + : m_outputs(std::move(outputs)) + , m_from_me(from_me) + , m_value(value) + , m_depth(depth) + , m_ancestors(ancestors) + , m_descendants(descendants) + {} + OutputGroup(const CInputCoin& output, int depth, bool from_me, size_t ancestors, size_t descendants) : OutputGroup() { + Insert(output, depth, from_me, ancestors, descendants); + } + void Insert(const CInputCoin& output, int depth, bool from_me, size_t ancestors, size_t descendants); + std::vector<CInputCoin>::iterator Discard(const CInputCoin& output); + bool EligibleForSpending(const CoinEligibilityFilter& eligibility_filter) const; +}; + +bool SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& target_value, const CAmount& cost_of_change, std::set<CInputCoin>& out_set, CAmount& value_ret, CAmount not_input_fees); // Original coin selection algorithm as a fallback -bool KnapsackSolver(const CAmount& nTargetValue, std::vector<CInputCoin>& vCoins, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet); +bool KnapsackSolver(const CAmount& nTargetValue, std::vector<OutputGroup>& groups, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet); + #endif // BITCOIN_WALLET_COINSELECTION_H diff --git a/src/wallet/init.cpp b/src/wallet/init.cpp index 076134cdd1..52c7e6c70f 100644 --- a/src/wallet/init.cpp +++ b/src/wallet/init.cpp @@ -54,6 +54,7 @@ const WalletInitInterface& g_wallet_init_interface = WalletInit(); void WalletInit::AddWalletOptions() const { gArgs.AddArg("-addresstype", strprintf("What type of addresses to use (\"legacy\", \"p2sh-segwit\", or \"bech32\", default: \"%s\")", FormatOutputType(DEFAULT_ADDRESS_TYPE)), false, OptionsCategory::WALLET); + gArgs.AddArg("-avoidpartialspends", strprintf(_("Group outputs by address, selecting all or none, instead of selecting on a per-output basis. Privacy is improved as an address is only used once (unless someone sends to it after spending from it), but may result in slightly higher fees as suboptimal coin selection may result due to the added limitation (default: %u)"), DEFAULT_AVOIDPARTIALSPENDS), false, OptionsCategory::WALLET); gArgs.AddArg("-changetype", "What type of change to use (\"legacy\", \"p2sh-segwit\", or \"bech32\"). Default is same as -addresstype, except when -addresstype=p2sh-segwit a native segwit output is used when sending to a native segwit address)", false, OptionsCategory::WALLET); gArgs.AddArg("-disablewallet", "Do not load the wallet and disable wallet RPC calls", false, OptionsCategory::WALLET); gArgs.AddArg("-discardfee=<amt>", strprintf("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). " diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp index 882ddbbe4e..4e1f6548df 100644 --- a/src/wallet/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -257,9 +257,9 @@ UniValue importaddress(const JSONRPCRequest& request) if (request.fHelp || request.params.size() < 1 || request.params.size() > 4) throw std::runtime_error( "importaddress \"address\" ( \"label\" rescan p2sh )\n" - "\nAdds a script (in hex) or address that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n" + "\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n" "\nArguments:\n" - "1. \"script\" (string, required) The hex-encoded script (or address)\n" + "1. \"address\" (string, required) The Bitcoin address (or hex-encoded script)\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "4. p2sh (boolean, optional, default=false) Add the P2SH version of the script as well\n" @@ -269,12 +269,12 @@ UniValue importaddress(const JSONRPCRequest& request) "\nNote: If you import a non-standard raw script in hex form, outputs sending to it will be treated\n" "as change, and not show up in many RPCs.\n" "\nExamples:\n" - "\nImport a script with rescan\n" - + HelpExampleCli("importaddress", "\"myscript\"") + + "\nImport an address with rescan\n" + + HelpExampleCli("importaddress", "\"myaddress\"") + "\nImport using a label without rescan\n" - + HelpExampleCli("importaddress", "\"myscript\" \"testing\" false") + + + HelpExampleCli("importaddress", "\"myaddress\" \"testing\" false") + "\nAs a JSON-RPC call\n" - + HelpExampleRpc("importaddress", "\"myscript\", \"testing\", false") + + HelpExampleRpc("importaddress", "\"myaddress\", \"testing\", false") ); @@ -585,13 +585,13 @@ UniValue importwallet(const JSONRPCRequest& request) std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { - if (boost::algorithm::starts_with(vstr[nStr], "#")) + if (vstr[nStr].front() == '#') break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; - if (boost::algorithm::starts_with(vstr[nStr], "label=")) { + if (vstr[nStr].substr(0,6) == "label=") { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 893310cf2f..73dfebf114 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -161,6 +161,10 @@ static UniValue getnewaddress(const JSONRPCRequest& request) + HelpExampleRpc("getnewaddress", "") ); + if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { + throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet"); + } + LOCK2(cs_main, pwallet->cs_wallet); // Parse the label first so we don't generate a key if there's an error @@ -268,6 +272,10 @@ static UniValue getrawchangeaddress(const JSONRPCRequest& request) + HelpExampleRpc("getrawchangeaddress", "") ); + if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { + throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet"); + } + LOCK2(cs_main, pwallet->cs_wallet); if (!pwallet->IsLocked()) { @@ -2506,6 +2514,10 @@ static UniValue keypoolrefill(const JSONRPCRequest& request) + HelpExampleRpc("keypoolrefill", "") ); + if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { + throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet"); + } + LOCK2(cs_main, pwallet->cs_wallet); // 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool @@ -2990,19 +3002,20 @@ static UniValue getwalletinfo(const JSONRPCRequest& request) "Returns an object containing various wallet state info.\n" "\nResult:\n" "{\n" - " \"walletname\": xxxxx, (string) the wallet name\n" - " \"walletversion\": xxxxx, (numeric) the wallet version\n" - " \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n" - " \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n" - " \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n" - " \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n" - " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since Unix epoch) of the oldest pre-generated key in the key pool\n" - " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated (only counts external keys)\n" - " \"keypoolsize_hd_internal\": xxxx, (numeric) how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)\n" - " \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n" - " \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n" - " \"hdseedid\": \"<hash160>\" (string, optional) the Hash160 of the HD seed (only present when HD is enabled)\n" - " \"hdmasterkeyid\": \"<hash160>\" (string, optional) alias for hdseedid retained for backwards-compatibility. Will be removed in V0.18.\n" + " \"walletname\": xxxxx, (string) the wallet name\n" + " \"walletversion\": xxxxx, (numeric) the wallet version\n" + " \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n" + " \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n" + " \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n" + " \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n" + " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since Unix epoch) of the oldest pre-generated key in the key pool\n" + " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated (only counts external keys)\n" + " \"keypoolsize_hd_internal\": xxxx, (numeric) how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)\n" + " \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n" + " \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n" + " \"hdseedid\": \"<hash160>\" (string, optional) the Hash160 of the HD seed (only present when HD is enabled)\n" + " \"hdmasterkeyid\": \"<hash160>\" (string, optional) alias for hdseedid retained for backwards-compatibility. Will be removed in V0.18.\n" + " \"private_keys_enabled\": true|false (boolean) false if privatekeys are disabled for this wallet (enforced watch-only wallet)\n" "}\n" "\nExamples:\n" + HelpExampleCli("getwalletinfo", "") @@ -3038,6 +3051,7 @@ static UniValue getwalletinfo(const JSONRPCRequest& request) obj.pushKV("hdseedid", seed_id.GetHex()); obj.pushKV("hdmasterkeyid", seed_id.GetHex()); } + obj.pushKV("private_keys_enabled", !pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)); return obj; } @@ -3128,12 +3142,13 @@ static UniValue loadwallet(const JSONRPCRequest& request) static UniValue createwallet(const JSONRPCRequest& request) { - if (request.fHelp || request.params.size() != 1) { + if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw std::runtime_error( - "createwallet \"wallet_name\"\n" + "createwallet \"wallet_name\" ( disable_private_keys )\n" "\nCreates and loads a new wallet.\n" "\nArguments:\n" - "1. \"wallet_name\" (string, required) The name for the new wallet. If this is a path, the wallet will be created at the path location.\n" + "1. \"wallet_name\" (string, required) The name for the new wallet. If this is a path, the wallet will be created at the path location.\n" + "2. disable_private_keys (boolean, optional, default: false) Disable the possibility of private keys (only watchonlys are possible in this mode).\n" "\nResult:\n" "{\n" " \"name\" : <wallet_name>, (string) The wallet name if created successfully. If the wallet was created using a full path, the wallet_name will be the full path.\n" @@ -3148,6 +3163,11 @@ static UniValue createwallet(const JSONRPCRequest& request) std::string error; std::string warning; + bool disable_privatekeys = false; + if (!request.params[1].isNull()) { + disable_privatekeys = request.params[1].get_bool(); + } + fs::path wallet_path = fs::absolute(wallet_name, GetWalletDir()); if (fs::symlink_status(wallet_path).type() != fs::file_not_found) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet " + wallet_name + " already exists."); @@ -3158,7 +3178,7 @@ static UniValue createwallet(const JSONRPCRequest& request) throw JSONRPCError(RPC_WALLET_ERROR, "Wallet file verification failed: " + error); } - std::shared_ptr<CWallet> const wallet = CWallet::CreateWalletFromFile(wallet_name, fs::absolute(wallet_name, GetWalletDir())); + std::shared_ptr<CWallet> const wallet = CWallet::CreateWalletFromFile(wallet_name, fs::absolute(wallet_name, GetWalletDir()), (disable_privatekeys ? (uint64_t)WALLET_FLAG_DISABLE_PRIVATE_KEYS : 0)); if (!wallet) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet creation failed."); } @@ -3432,95 +3452,25 @@ static UniValue listunspent(const JSONRPCRequest& request) return results; } -static UniValue fundrawtransaction(const JSONRPCRequest& request) +void FundTransaction(CWallet* const pwallet, CMutableTransaction& tx, CAmount& fee_out, int& change_position, UniValue options) { - std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); - CWallet* const pwallet = wallet.get(); - - if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { - return NullUniValue; - } - - if (request.fHelp || request.params.size() < 1 || request.params.size() > 3) - throw std::runtime_error( - "fundrawtransaction \"hexstring\" ( options iswitness )\n" - "\nAdd inputs to a transaction until it has enough in value to meet its out value.\n" - "This will not modify existing inputs, and will add at most one change output to the outputs.\n" - "No existing outputs will be modified unless \"subtractFeeFromOutputs\" is specified.\n" - "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n" - "The inputs added will not be signed, use signrawtransaction for that.\n" - "Note that all existing inputs must have their previous output transaction be in the wallet.\n" - "Note that all inputs selected must be of standard form and P2SH scripts must be\n" - "in the wallet using importaddress or addmultisigaddress (to calculate fees).\n" - "You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n" - "Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n" - "\nArguments:\n" - "1. \"hexstring\" (string, required) The hex string of the raw transaction\n" - "2. options (object, optional)\n" - " {\n" - " \"changeAddress\" (string, optional, default pool address) The bitcoin address to receive the change\n" - " \"changePosition\" (numeric, optional, default random) The index of the change output\n" - " \"change_type\" (string, optional) The output type to use. Only valid if changeAddress is not specified. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\". Default is set by -changetype.\n" - " \"includeWatching\" (boolean, optional, default false) Also select inputs which are watch only\n" - " \"lockUnspents\" (boolean, optional, default false) Lock selected unspent outputs\n" - " \"feeRate\" (numeric, optional, default not set: makes wallet determine the fee) Set a specific fee rate in " + CURRENCY_UNIT + "/kB\n" - " \"subtractFeeFromOutputs\" (array, optional) A json array of integers.\n" - " The fee will be equally deducted from the amount of each specified output.\n" - " The outputs are specified by their zero-based index, before any change output is added.\n" - " Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n" - " If no outputs are specified here, the sender pays the fee.\n" - " [vout_index,...]\n" - " \"replaceable\" (boolean, optional) Marks this transaction as BIP125 replaceable.\n" - " Allows this transaction to be replaced by a transaction with higher fees\n" - " \"conf_target\" (numeric, optional) Confirmation target (in blocks)\n" - " \"estimate_mode\" (string, optional, default=UNSET) The fee estimate mode, must be one of:\n" - " \"UNSET\"\n" - " \"ECONOMICAL\"\n" - " \"CONSERVATIVE\"\n" - " }\n" - " for backward compatibility: passing in a true instead of an object will result in {\"includeWatching\":true}\n" - "3. iswitness (boolean, optional) Whether the transaction hex is a serialized witness transaction \n" - " If iswitness is not present, heuristic tests will be used in decoding\n" - - "\nResult:\n" - "{\n" - " \"hex\": \"value\", (string) The resulting raw transaction (hex-encoded string)\n" - " \"fee\": n, (numeric) Fee in " + CURRENCY_UNIT + " the resulting transaction pays\n" - " \"changepos\": n (numeric) The position of the added change output, or -1\n" - "}\n" - "\nExamples:\n" - "\nCreate a transaction with no inputs\n" - + HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") + - "\nAdd sufficient unsigned inputs to meet the output value\n" - + HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") + - "\nSign the transaction\n" - + HelpExampleCli("signrawtransaction", "\"fundedtransactionhex\"") + - "\nSend the transaction\n" - + HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"") - ); - - RPCTypeCheck(request.params, {UniValue::VSTR}); - // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); CCoinControl coinControl; - int changePosition = -1; + change_position = -1; bool lockUnspents = false; UniValue subtractFeeFromOutputs; std::set<int> setSubtractFeeFromOutputs; - if (!request.params[1].isNull()) { - if (request.params[1].type() == UniValue::VBOOL) { + if (!options.isNull()) { + if (options.type() == UniValue::VBOOL) { // backward compatibility bool only fallback - coinControl.fAllowWatchOnly = request.params[1].get_bool(); + coinControl.fAllowWatchOnly = options.get_bool(); } else { - RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VOBJ, UniValue::VBOOL}); - - UniValue options = request.params[1]; - + RPCTypeCheckArgument(options, UniValue::VOBJ); RPCTypeCheckObj(options, { {"changeAddress", UniValueType(UniValue::VSTR)}, @@ -3547,7 +3497,7 @@ static UniValue fundrawtransaction(const JSONRPCRequest& request) } if (options.exists("changePosition")) - changePosition = options["changePosition"].get_int(); + change_position = options["changePosition"].get_int(); if (options.exists("change_type")) { if (options.exists("changeAddress")) { @@ -3594,18 +3544,10 @@ static UniValue fundrawtransaction(const JSONRPCRequest& request) } } - // parse hex string from parameter - CMutableTransaction tx; - bool try_witness = request.params[2].isNull() ? true : request.params[2].get_bool(); - bool try_no_witness = request.params[2].isNull() ? true : !request.params[2].get_bool(); - if (!DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) { - throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); - } - if (tx.vout.size() == 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output"); - if (changePosition != -1 && (changePosition < 0 || (unsigned int)changePosition > tx.vout.size())) + if (change_position != -1 && (change_position < 0 || (unsigned int)change_position > tx.vout.size())) throw JSONRPCError(RPC_INVALID_PARAMETER, "changePosition out of bounds"); for (unsigned int idx = 0; idx < subtractFeeFromOutputs.size(); idx++) { @@ -3619,17 +3561,98 @@ static UniValue fundrawtransaction(const JSONRPCRequest& request) setSubtractFeeFromOutputs.insert(pos); } - CAmount nFeeOut; std::string strFailReason; - if (!pwallet->FundTransaction(tx, nFeeOut, changePosition, strFailReason, lockUnspents, setSubtractFeeFromOutputs, coinControl)) { + if (!pwallet->FundTransaction(tx, fee_out, change_position, strFailReason, lockUnspents, setSubtractFeeFromOutputs, coinControl)) { throw JSONRPCError(RPC_WALLET_ERROR, strFailReason); } +} + +static UniValue fundrawtransaction(const JSONRPCRequest& request) +{ + std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); + CWallet* const pwallet = wallet.get(); + + if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { + return NullUniValue; + } + + if (request.fHelp || request.params.size() < 1 || request.params.size() > 3) + throw std::runtime_error( + "fundrawtransaction \"hexstring\" ( options iswitness )\n" + "\nAdd inputs to a transaction until it has enough in value to meet its out value.\n" + "This will not modify existing inputs, and will add at most one change output to the outputs.\n" + "No existing outputs will be modified unless \"subtractFeeFromOutputs\" is specified.\n" + "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n" + "The inputs added will not be signed, use signrawtransaction for that.\n" + "Note that all existing inputs must have their previous output transaction be in the wallet.\n" + "Note that all inputs selected must be of standard form and P2SH scripts must be\n" + "in the wallet using importaddress or addmultisigaddress (to calculate fees).\n" + "You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n" + "Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n" + "\nArguments:\n" + "1. \"hexstring\" (string, required) The hex string of the raw transaction\n" + "2. options (object, optional)\n" + " {\n" + " \"changeAddress\" (string, optional, default pool address) The bitcoin address to receive the change\n" + " \"changePosition\" (numeric, optional, default random) The index of the change output\n" + " \"change_type\" (string, optional) The output type to use. Only valid if changeAddress is not specified. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\". Default is set by -changetype.\n" + " \"includeWatching\" (boolean, optional, default false) Also select inputs which are watch only\n" + " \"lockUnspents\" (boolean, optional, default false) Lock selected unspent outputs\n" + " \"feeRate\" (numeric, optional, default not set: makes wallet determine the fee) Set a specific fee rate in " + CURRENCY_UNIT + "/kB\n" + " \"subtractFeeFromOutputs\" (array, optional) A json array of integers.\n" + " The fee will be equally deducted from the amount of each specified output.\n" + " The outputs are specified by their zero-based index, before any change output is added.\n" + " Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n" + " If no outputs are specified here, the sender pays the fee.\n" + " [vout_index,...]\n" + " \"replaceable\" (boolean, optional) Marks this transaction as BIP125 replaceable.\n" + " Allows this transaction to be replaced by a transaction with higher fees\n" + " \"conf_target\" (numeric, optional) Confirmation target (in blocks)\n" + " \"estimate_mode\" (string, optional, default=UNSET) The fee estimate mode, must be one of:\n" + " \"UNSET\"\n" + " \"ECONOMICAL\"\n" + " \"CONSERVATIVE\"\n" + " }\n" + " for backward compatibility: passing in a true instead of an object will result in {\"includeWatching\":true}\n" + "3. iswitness (boolean, optional) Whether the transaction hex is a serialized witness transaction \n" + " If iswitness is not present, heuristic tests will be used in decoding\n" + + "\nResult:\n" + "{\n" + " \"hex\": \"value\", (string) The resulting raw transaction (hex-encoded string)\n" + " \"fee\": n, (numeric) Fee in " + CURRENCY_UNIT + " the resulting transaction pays\n" + " \"changepos\": n (numeric) The position of the added change output, or -1\n" + "}\n" + "\nExamples:\n" + "\nCreate a transaction with no inputs\n" + + HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") + + "\nAdd sufficient unsigned inputs to meet the output value\n" + + HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") + + "\nSign the transaction\n" + + HelpExampleCli("signrawtransaction", "\"fundedtransactionhex\"") + + "\nSend the transaction\n" + + HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"") + ); + + RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType(), UniValue::VBOOL}); + + // parse hex string from parameter + CMutableTransaction tx; + bool try_witness = request.params[2].isNull() ? true : request.params[2].get_bool(); + bool try_no_witness = request.params[2].isNull() ? true : !request.params[2].get_bool(); + if (!DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) { + throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); + } + + CAmount fee; + int change_position; + FundTransaction(pwallet, tx, fee, change_position, request.params[1]); UniValue result(UniValue::VOBJ); result.pushKV("hex", EncodeHexTx(tx)); - result.pushKV("changepos", changePosition); - result.pushKV("fee", ValueFromAmount(nFeeOut)); + result.pushKV("fee", ValueFromAmount(fee)); + result.pushKV("changepos", change_position); return result; } @@ -4400,6 +4423,334 @@ UniValue sethdseed(const JSONRPCRequest& request) return NullUniValue; } +bool ParseHDKeypath(std::string keypath_str, std::vector<uint32_t>& keypath) +{ + std::stringstream ss(keypath_str); + std::string item; + bool first = true; + while (std::getline(ss, item, '/')) { + if (item.compare("m") == 0) { + if (first) { + first = false; + continue; + } + return false; + } + // Finds whether it is hardened + uint32_t path = 0; + size_t pos = item.find("'"); + if (pos != std::string::npos) { + // The hardened tick can only be in the last index of the string + if (pos != item.size() - 1) { + return false; + } + path |= 0x80000000; + item = item.substr(0, item.size() - 1); // Drop the last character which is the hardened tick + } + + // Ensure this is only numbers + if (item.find_first_not_of( "0123456789" ) != std::string::npos) { + return false; + } + uint32_t number; + if (!ParseUInt32(item, &number)) { + return false; + } + path |= number; + + keypath.push_back(path); + first = false; + } + return true; +} + +void AddKeypathToMap(const CWallet* pwallet, const CKeyID& keyID, std::map<CPubKey, std::vector<uint32_t>>& hd_keypaths) +{ + CPubKey vchPubKey; + if (!pwallet->GetPubKey(keyID, vchPubKey)) { + return; + } + CKeyMetadata meta; + auto it = pwallet->mapKeyMetadata.find(keyID); + if (it != pwallet->mapKeyMetadata.end()) { + meta = it->second; + } + std::vector<uint32_t> keypath; + if (!meta.hdKeypath.empty()) { + if (!ParseHDKeypath(meta.hdKeypath, keypath)) { + throw JSONRPCError(RPC_INTERNAL_ERROR, "Internal keypath is broken"); + } + // Get the proper master key id + CKey key; + pwallet->GetKey(meta.hd_seed_id, key); + CExtKey masterKey; + masterKey.SetSeed(key.begin(), key.size()); + // Add to map + keypath.insert(keypath.begin(), ReadLE32(masterKey.key.GetPubKey().GetID().begin())); + } else { // Single pubkeys get the master fingerprint of themselves + keypath.insert(keypath.begin(), ReadLE32(vchPubKey.GetID().begin())); + } + hd_keypaths.emplace(vchPubKey, keypath); +} + +bool FillPSBT(const CWallet* pwallet, PartiallySignedTransaction& psbtx, const CTransaction* txConst, int sighash_type, bool sign, bool bip32derivs) +{ + LOCK(pwallet->cs_wallet); + // Get all of the previous transactions + bool complete = true; + for (unsigned int i = 0; i < txConst->vin.size(); ++i) { + const CTxIn& txin = txConst->vin[i]; + PSBTInput& input = psbtx.inputs.at(i); + + // If we don't know about this input, skip it and let someone else deal with it + const uint256& txhash = txin.prevout.hash; + const auto& it = pwallet->mapWallet.find(txhash); + if (it != pwallet->mapWallet.end()) { + const CWalletTx& wtx = it->second; + CTxOut utxo = wtx.tx->vout[txin.prevout.n]; + input.non_witness_utxo = wtx.tx; + input.witness_utxo = utxo; + } + + // Get the Sighash type + if (sign && input.sighash_type > 0 && input.sighash_type != sighash_type) { + throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Specified Sighash and sighash in PSBT do not match."); + } + + SignatureData sigdata; + if (sign) { + complete &= SignPSBTInput(*pwallet, *psbtx.tx, input, sigdata, i, sighash_type); + } else { + complete &= SignPSBTInput(PublicOnlySigningProvider(pwallet), *psbtx.tx, input, sigdata, i, sighash_type); + } + + // Drop the unnecessary UTXO + if (sigdata.witness) { + input.non_witness_utxo = nullptr; + } else { + input.witness_utxo.SetNull(); + } + + // Get public key paths + if (bip32derivs) { + for (const auto& pubkey_it : sigdata.misc_pubkeys) { + AddKeypathToMap(pwallet, pubkey_it.first, input.hd_keypaths); + } + } + } + + // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change + for (unsigned int i = 0; i < txConst->vout.size(); ++i) { + const CTxOut& out = txConst->vout.at(i); + PSBTOutput& psbt_out = psbtx.outputs.at(i); + + // Dummy tx so we can use ProduceSignature to get stuff out + CMutableTransaction dummy_tx; + dummy_tx.vin.push_back(CTxIn()); + dummy_tx.vout.push_back(CTxOut()); + + // Fill a SignatureData with output info + SignatureData sigdata; + psbt_out.FillSignatureData(sigdata); + + MutableTransactionSignatureCreator creator(psbtx.tx.get_ptr(), 0, out.nValue, 1); + ProduceSignature(*pwallet, creator, out.scriptPubKey, sigdata); + psbt_out.FromSignatureData(sigdata); + + // Get public key paths + if (bip32derivs) { + for (const auto& pubkey_it : sigdata.misc_pubkeys) { + AddKeypathToMap(pwallet, pubkey_it.first, psbt_out.hd_keypaths); + } + } + } + return complete; +} + +UniValue walletprocesspsbt(const JSONRPCRequest& request) +{ + std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); + CWallet* const pwallet = wallet.get(); + + if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { + return NullUniValue; + } + + if (request.fHelp || request.params.size() < 1 || request.params.size() > 4) + throw std::runtime_error( + "walletprocesspsbt \"psbt\" ( sign \"sighashtype\" bip32derivs )\n" + "\nUpdate a PSBT with input information from our wallet and then sign inputs\n" + "that we can sign for.\n" + + HelpRequiringPassphrase(pwallet) + "\n" + + "\nArguments:\n" + "1. \"psbt\" (string, required) The transaction base64 string\n" + "2. sign (boolean, optional, default=true) Also sign the transaction when updating\n" + "3. \"sighashtype\" (string, optional, default=ALL) The signature hash type to sign with if not specified by the PSBT. Must be one of\n" + " \"ALL\"\n" + " \"NONE\"\n" + " \"SINGLE\"\n" + " \"ALL|ANYONECANPAY\"\n" + " \"NONE|ANYONECANPAY\"\n" + " \"SINGLE|ANYONECANPAY\"\n" + "4. bip32derivs (boolean, optiona, default=false) If true, includes the BIP 32 derivation paths for public keys if we know them\n" + + "\nResult:\n" + "{\n" + " \"psbt\" : \"value\", (string) The base64-encoded partially signed transaction\n" + " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n" + " ]\n" + "}\n" + + "\nExamples:\n" + + HelpExampleCli("walletprocesspsbt", "\"psbt\"") + ); + + RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL, UniValue::VSTR}); + + // Unserialize the transaction + PartiallySignedTransaction psbtx; + std::string error; + if (!DecodePSBT(psbtx, request.params[0].get_str(), error)) { + throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error)); + } + + // Get the sighash type + int nHashType = ParseSighashString(request.params[2]); + + // Use CTransaction for the constant parts of the + // transaction to avoid rehashing. + const CTransaction txConst(*psbtx.tx); + + // Fill transaction with our data and also sign + bool sign = request.params[1].isNull() ? true : request.params[1].get_bool(); + bool bip32derivs = request.params[3].isNull() ? false : request.params[3].get_bool(); + bool complete = FillPSBT(pwallet, psbtx, &txConst, nHashType, sign, bip32derivs); + + UniValue result(UniValue::VOBJ); + CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); + ssTx << psbtx; + result.push_back(Pair("psbt", EncodeBase64((unsigned char*)ssTx.data(), ssTx.size()))); + result.push_back(Pair("complete", complete)); + + return result; +} + +UniValue walletcreatefundedpsbt(const JSONRPCRequest& request) +{ + std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); + CWallet* const pwallet = wallet.get(); + + if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { + return NullUniValue; + } + + if (request.fHelp || request.params.size() < 2 || request.params.size() > 6) + throw std::runtime_error( + "walletcreatefundedpsbt [{\"txid\":\"id\",\"vout\":n},...] [{\"address\":amount},{\"data\":\"hex\"},...] ( locktime ) ( replaceable ) ( options bip32derivs )\n" + "\nCreates and funds a transaction in the Partially Signed Transaction format. Inputs will be added if supplied inputs are not enough\n" + "Implements the Creator and Updater roles.\n" + "\nArguments:\n" + "1. \"inputs\" (array, required) A json array of json objects\n" + " [\n" + " {\n" + " \"txid\":\"id\", (string, required) The transaction id\n" + " \"vout\":n, (numeric, required) The output number\n" + " \"sequence\":n (numeric, optional) The sequence number\n" + " } \n" + " ,...\n" + " ]\n" + "2. \"outputs\" (array, required) a json array with outputs (key-value pairs)\n" + " [\n" + " {\n" + " \"address\": x.xxx, (obj, optional) A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + "\n" + " },\n" + " {\n" + " \"data\": \"hex\" (obj, optional) A key-value pair. The key must be \"data\", the value is hex encoded data\n" + " }\n" + " ,... More key-value pairs of the above form. For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n" + " accepted as second parameter.\n" + " ]\n" + "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n" + "4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125 replaceable.\n" + " Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible.\n" + "5. options (object, optional)\n" + " {\n" + " \"changeAddress\" (string, optional, default pool address) The bitcoin address to receive the change\n" + " \"changePosition\" (numeric, optional, default random) The index of the change output\n" + " \"change_type\" (string, optional) The output type to use. Only valid if changeAddress is not specified. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\". Default is set by -changetype.\n" + " \"includeWatching\" (boolean, optional, default false) Also select inputs which are watch only\n" + " \"lockUnspents\" (boolean, optional, default false) Lock selected unspent outputs\n" + " \"feeRate\" (numeric, optional, default not set: makes wallet determine the fee) Set a specific fee rate in " + CURRENCY_UNIT + "/kB\n" + " \"subtractFeeFromOutputs\" (array, optional) A json array of integers.\n" + " The fee will be equally deducted from the amount of each specified output.\n" + " The outputs are specified by their zero-based index, before any change output is added.\n" + " Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n" + " If no outputs are specified here, the sender pays the fee.\n" + " [vout_index,...]\n" + " \"replaceable\" (boolean, optional) Marks this transaction as BIP125 replaceable.\n" + " Allows this transaction to be replaced by a transaction with higher fees\n" + " \"conf_target\" (numeric, optional) Confirmation target (in blocks)\n" + " \"estimate_mode\" (string, optional, default=UNSET) The fee estimate mode, must be one of:\n" + " \"UNSET\"\n" + " \"ECONOMICAL\"\n" + " \"CONSERVATIVE\"\n" + " }\n" + "6. bip32derivs (boolean, optiona, default=false) If true, includes the BIP 32 derivation paths for public keys if we know them\n" + "\nResult:\n" + "{\n" + " \"psbt\": \"value\", (string) The resulting raw transaction (base64-encoded string)\n" + " \"fee\": n, (numeric) Fee in " + CURRENCY_UNIT + " the resulting transaction pays\n" + " \"changepos\": n (numeric) The position of the added change output, or -1\n" + "}\n" + "\nExamples:\n" + "\nCreate a transaction with no inputs\n" + + HelpExampleCli("walletcreatefundedpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") + ); + + RPCTypeCheck(request.params, { + UniValue::VARR, + UniValueType(), // ARR or OBJ, checked later + UniValue::VNUM, + UniValue::VBOOL, + UniValue::VOBJ + }, true + ); + + CAmount fee; + int change_position; + CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], request.params[3]); + FundTransaction(pwallet, rawTx, fee, change_position, request.params[4]); + + // Make a blank psbt + PartiallySignedTransaction psbtx; + psbtx.tx = rawTx; + for (unsigned int i = 0; i < rawTx.vin.size(); ++i) { + psbtx.inputs.push_back(PSBTInput()); + } + for (unsigned int i = 0; i < rawTx.vout.size(); ++i) { + psbtx.outputs.push_back(PSBTOutput()); + } + + // Use CTransaction for the constant parts of the + // transaction to avoid rehashing. + const CTransaction txConst(*psbtx.tx); + + // Fill transaction with out data but don't sign + bool bip32derivs = request.params[5].isNull() ? false : request.params[5].get_bool(); + FillPSBT(pwallet, psbtx, &txConst, 1, false, bip32derivs); + + // Serialize the PSBT + CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); + ssTx << psbtx; + + UniValue result(UniValue::VOBJ); + result.pushKV("psbt", EncodeBase64((unsigned char*)ssTx.data(), ssTx.size())); + result.pushKV("fee", ValueFromAmount(fee)); + result.pushKV("changepos", change_position); + return result; +} + extern UniValue abortrescan(const JSONRPCRequest& request); // in rpcdump.cpp extern UniValue dumpprivkey(const JSONRPCRequest& request); // in rpcdump.cpp extern UniValue importprivkey(const JSONRPCRequest& request); @@ -4416,6 +4767,8 @@ static const CRPCCommand commands[] = { // category name actor (function) argNames // --------------------- ------------------------ ----------------------- ---------- { "rawtransactions", "fundrawtransaction", &fundrawtransaction, {"hexstring","options","iswitness"} }, + { "wallet", "walletprocesspsbt", &walletprocesspsbt, {"psbt","sign","sighashtype","bip32derivs"} }, + { "wallet", "walletcreatefundedpsbt", &walletcreatefundedpsbt, {"inputs","outputs","locktime","replaceable","options","bip32derivs"} }, { "hidden", "resendwallettransactions", &resendwallettransactions, {} }, { "wallet", "abandontransaction", &abandontransaction, {"txid"} }, { "wallet", "abortrescan", &abortrescan, {} }, @@ -4423,7 +4776,7 @@ static const CRPCCommand commands[] = { "hidden", "addwitnessaddress", &addwitnessaddress, {"address","p2sh"} }, { "wallet", "backupwallet", &backupwallet, {"destination"} }, { "wallet", "bumpfee", &bumpfee, {"txid", "options"} }, - { "wallet", "createwallet", &createwallet, {"wallet_name"} }, + { "wallet", "createwallet", &createwallet, {"wallet_name", "disable_private_keys"} }, { "wallet", "dumpprivkey", &dumpprivkey, {"address"} }, { "wallet", "dumpwallet", &dumpwallet, {"filename"} }, { "wallet", "encryptwallet", &encryptwallet, {"passphrase"} }, diff --git a/src/wallet/rpcwallet.h b/src/wallet/rpcwallet.h index b841f3e424..64556b5824 100644 --- a/src/wallet/rpcwallet.h +++ b/src/wallet/rpcwallet.h @@ -11,6 +11,8 @@ class CRPCTable; class CWallet; class JSONRPCRequest; class UniValue; +struct PartiallySignedTransaction; +class CTransaction; void RegisterWalletRPCCommands(CRPCTable &t); @@ -28,4 +30,5 @@ bool EnsureWalletIsAvailable(CWallet *, bool avoidException); UniValue getaddressinfo(const JSONRPCRequest& request); UniValue signrawtransactionwithwallet(const JSONRPCRequest& request); +bool FillPSBT(const CWallet* pwallet, PartiallySignedTransaction& psbtx, const CTransaction* txConst, int sighash_type = 1, bool sign = true, bool bip32derivs = false); #endif //BITCOIN_WALLET_RPCWALLET_H diff --git a/src/wallet/test/coinselector_tests.cpp b/src/wallet/test/coinselector_tests.cpp index d90be33000..1561760577 100644 --- a/src/wallet/test/coinselector_tests.cpp +++ b/src/wallet/test/coinselector_tests.cpp @@ -102,6 +102,22 @@ static CAmount make_hard_case(int utxos, std::vector<CInputCoin>& utxo_pool) return target; } +inline std::vector<OutputGroup>& GroupCoins(const std::vector<CInputCoin>& coins) +{ + static std::vector<OutputGroup> static_groups; + static_groups.clear(); + for (auto& coin : coins) static_groups.emplace_back(coin, 0, true, 0, 0); + return static_groups; +} + +inline std::vector<OutputGroup>& GroupCoins(const std::vector<COutput>& coins) +{ + static std::vector<OutputGroup> static_groups; + static_groups.clear(); + for (auto& coin : coins) static_groups.emplace_back(coin.GetInputCoin(), coin.nDepth, coin.tx->fDebitCached && coin.tx->nDebitCached == 1 /* HACK: we can't figure out the is_me flag so we use the conditions defined above; perhaps set safe to false for !fIsFromMe in add_coin() */, 0, 0); + return static_groups; +} + // Branch and bound coin selection tests BOOST_AUTO_TEST_CASE(bnb_search_test) { @@ -121,7 +137,7 @@ BOOST_AUTO_TEST_CASE(bnb_search_test) BOOST_TEST_MESSAGE("Testing known outcomes"); // Empty utxo pool - BOOST_CHECK(!SelectCoinsBnB(utxo_pool, 1 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); + BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); selection.clear(); // Add utxos @@ -132,14 +148,14 @@ BOOST_AUTO_TEST_CASE(bnb_search_test) // Select 1 Cent add_coin(1 * CENT, 1, actual_selection); - BOOST_CHECK(SelectCoinsBnB(utxo_pool, 1 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); + BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); BOOST_CHECK(equal_sets(selection, actual_selection)); actual_selection.clear(); selection.clear(); // Select 2 Cent add_coin(2 * CENT, 2, actual_selection); - BOOST_CHECK(SelectCoinsBnB(utxo_pool, 2 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); + BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 2 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); BOOST_CHECK(equal_sets(selection, actual_selection)); actual_selection.clear(); selection.clear(); @@ -147,13 +163,13 @@ BOOST_AUTO_TEST_CASE(bnb_search_test) // Select 5 Cent add_coin(3 * CENT, 3, actual_selection); add_coin(2 * CENT, 2, actual_selection); - BOOST_CHECK(SelectCoinsBnB(utxo_pool, 5 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); + BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 5 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); BOOST_CHECK(equal_sets(selection, actual_selection)); actual_selection.clear(); selection.clear(); // Select 11 Cent, not possible - BOOST_CHECK(!SelectCoinsBnB(utxo_pool, 11 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); + BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 11 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); actual_selection.clear(); selection.clear(); @@ -163,7 +179,7 @@ BOOST_AUTO_TEST_CASE(bnb_search_test) add_coin(3 * CENT, 3, actual_selection); add_coin(2 * CENT, 2, actual_selection); add_coin(1 * CENT, 1, actual_selection); - BOOST_CHECK(SelectCoinsBnB(utxo_pool, 10 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); + BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 10 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); BOOST_CHECK(equal_sets(selection, actual_selection)); actual_selection.clear(); selection.clear(); @@ -173,18 +189,18 @@ BOOST_AUTO_TEST_CASE(bnb_search_test) add_coin(5 * CENT, 5, actual_selection); add_coin(3 * CENT, 3, actual_selection); add_coin(2 * CENT, 2, actual_selection); - BOOST_CHECK(SelectCoinsBnB(utxo_pool, 10 * CENT, 5000, selection, value_ret, not_input_fees)); + BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 10 * CENT, 5000, selection, value_ret, not_input_fees)); // Select 0.25 Cent, not possible - BOOST_CHECK(!SelectCoinsBnB(utxo_pool, 0.25 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); + BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 0.25 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); actual_selection.clear(); selection.clear(); // Iteration exhaustion test CAmount target = make_hard_case(17, utxo_pool); - BOOST_CHECK(!SelectCoinsBnB(utxo_pool, target, 0, selection, value_ret, not_input_fees)); // Should exhaust + BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), target, 0, selection, value_ret, not_input_fees)); // Should exhaust target = make_hard_case(14, utxo_pool); - BOOST_CHECK(SelectCoinsBnB(utxo_pool, target, 0, selection, value_ret, not_input_fees)); // Should not exhaust + BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), target, 0, selection, value_ret, not_input_fees)); // Should not exhaust // Test same value early bailout optimization add_coin(7 * CENT, 7, actual_selection); @@ -200,7 +216,7 @@ BOOST_AUTO_TEST_CASE(bnb_search_test) for (int i = 0; i < 50000; ++i) { add_coin(5 * CENT, 7, utxo_pool); } - BOOST_CHECK(SelectCoinsBnB(utxo_pool, 30 * CENT, 5000, selection, value_ret, not_input_fees)); + BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 30 * CENT, 5000, selection, value_ret, not_input_fees)); //////////////////// // Behavior tests // @@ -212,7 +228,7 @@ BOOST_AUTO_TEST_CASE(bnb_search_test) } // Run 100 times, to make sure it is never finding a solution for (int i = 0; i < 100; ++i) { - BOOST_CHECK(!SelectCoinsBnB(utxo_pool, 1 * CENT, 2 * CENT, selection, value_ret, not_input_fees)); + BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 2 * CENT, selection, value_ret, not_input_fees)); } // Make sure that effective value is working in SelectCoinsMinConf when BnB is used @@ -223,7 +239,7 @@ BOOST_AUTO_TEST_CASE(bnb_search_test) empty_wallet(); add_coin(1); vCoins.at(0).nInputBytes = 40; // Make sure that it has a negative effective value. The next check should assert if this somehow got through. Otherwise it will fail - BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params_bnb, bnb_used)); + BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params_bnb, bnb_used)); // Make sure that we aren't using BnB when there are preset inputs empty_wallet(); @@ -252,24 +268,24 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) empty_wallet(); // with an empty wallet we can't even pay one cent - BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); add_coin(1*CENT, 4); // add a new 1 cent coin // with a new 1 cent coin, we still can't find a mature 1 cent - BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); // but we can find a new 1 cent - BOOST_CHECK( testWallet.SelectCoinsMinConf( 1 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf( 1 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 1 * CENT); add_coin(2*CENT); // add a mature 2 cent coin // we can't make 3 cents of mature coins - BOOST_CHECK(!testWallet.SelectCoinsMinConf( 3 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(!testWallet.SelectCoinsMinConf( 3 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); // we can make 3 cents of new coins - BOOST_CHECK( testWallet.SelectCoinsMinConf( 3 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf( 3 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 3 * CENT); add_coin(5*CENT); // add a mature 5 cent coin, @@ -279,33 +295,33 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) // now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38 // we can't make 38 cents only if we disallow new coins: - BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); // we can't even make 37 cents if we don't allow new coins even if they're from us - BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, filter_standard_extra, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, filter_standard_extra, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); // but we can make 37 cents if we accept new coins from ourself - BOOST_CHECK( testWallet.SelectCoinsMinConf(37 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(37 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 37 * CENT); // and we can make 38 cents if we accept all new coins - BOOST_CHECK( testWallet.SelectCoinsMinConf(38 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(38 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 38 * CENT); // try making 34 cents from 1,2,5,10,20 - we can't do it exactly - BOOST_CHECK( testWallet.SelectCoinsMinConf(34 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(34 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 35 * CENT); // but 35 cents is closest BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); // the best should be 20+10+5. it's incredibly unlikely the 1 or 2 got included (but possible) // when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5 - BOOST_CHECK( testWallet.SelectCoinsMinConf( 7 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf( 7 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 7 * CENT); BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // when we try making 8 cents, the smaller coins (1,2,5) are exactly enough. - BOOST_CHECK( testWallet.SelectCoinsMinConf( 8 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf( 8 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK(nValueRet == 8 * CENT); BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); // when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger coin (10) - BOOST_CHECK( testWallet.SelectCoinsMinConf( 9 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf( 9 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 10 * CENT); BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); @@ -319,30 +335,30 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) add_coin(30*CENT); // now we have 6+7+8+20+30 = 71 cents total // check that we have 71 and not 72 - BOOST_CHECK( testWallet.SelectCoinsMinConf(71 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); - BOOST_CHECK(!testWallet.SelectCoinsMinConf(72 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(71 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(!testWallet.SelectCoinsMinConf(72 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); // now try making 16 cents. the best smaller coins can do is 6+7+8 = 21; not as good at the next biggest coin, 20 - BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 20 * CENT); // we should get 20 in one coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); add_coin( 5*CENT); // now we have 5+6+7+8+20+30 = 75 cents total // now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, better than the next biggest coin, 20 - BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 3 coins BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); add_coin( 18*CENT); // now we have 5+6+7+8+18+20+30 // and now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, the same as the next biggest coin, 18 - BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 1 coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // because in the event of a tie, the biggest coin wins // now try making 11 cents. we should get 5+6 - BOOST_CHECK( testWallet.SelectCoinsMinConf(11 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(11 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 11 * CENT); BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); @@ -351,11 +367,11 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) add_coin( 2*COIN); add_coin( 3*COIN); add_coin( 4*COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents - BOOST_CHECK( testWallet.SelectCoinsMinConf(95 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(95 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 1 * COIN); // we should get 1 BTC in 1 coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); - BOOST_CHECK( testWallet.SelectCoinsMinConf(195 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(195 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 2 * COIN); // we should get 2 BTC in 1 coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); @@ -370,14 +386,14 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) // try making 1 * MIN_CHANGE from the 1.5 * MIN_CHANGE // we'll get change smaller than MIN_CHANGE whatever happens, so can expect MIN_CHANGE exactly - BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE); // but if we add a bigger coin, small change is avoided add_coin(1111*MIN_CHANGE); // try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5 - BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount // if we add more small coins: @@ -385,7 +401,7 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) add_coin(MIN_CHANGE * 7 / 10); // and try again to make 1.0 * MIN_CHANGE - BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount // run the 'mtgox' test (see http://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf) @@ -394,7 +410,7 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) for (int j = 0; j < 20; j++) add_coin(50000 * COIN); - BOOST_CHECK( testWallet.SelectCoinsMinConf(500000 * COIN, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(500000 * COIN, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 500000 * COIN); // we should get the exact amount BOOST_CHECK_EQUAL(setCoinsRet.size(), 10U); // in ten coins @@ -407,7 +423,7 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) add_coin(MIN_CHANGE * 6 / 10); add_coin(MIN_CHANGE * 7 / 10); add_coin(1111 * MIN_CHANGE); - BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 1111 * MIN_CHANGE); // we get the bigger coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); @@ -417,7 +433,7 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) add_coin(MIN_CHANGE * 6 / 10); add_coin(MIN_CHANGE * 8 / 10); add_coin(1111 * MIN_CHANGE); - BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE); // we should get the exact amount BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // in two coins 0.4+0.6 @@ -428,12 +444,12 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) add_coin(MIN_CHANGE * 100); // trying to make 100.01 from these three coins - BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 10001 / 100, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 10001 / 100, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE * 10105 / 100); // we should get all coins BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); // but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change - BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 9990 / 100, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 9990 / 100, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 101 * MIN_CHANGE); BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); @@ -443,7 +459,7 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) // Create 676 inputs (= (old MAX_STANDARD_TX_SIZE == 100000) / 148 bytes per input) for (uint16_t j = 0; j < 676; j++) add_coin(amt); - BOOST_CHECK(testWallet.SelectCoinsMinConf(2000, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(testWallet.SelectCoinsMinConf(2000, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); if (amt - 2000 < MIN_CHANGE) { // needs more than one input: uint16_t returnSize = std::ceil((2000.0 + MIN_CHANGE)/amt); @@ -465,8 +481,8 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) // picking 50 from 100 coins doesn't depend on the shuffle, // but does depend on randomness in the stochastic approximation code - BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, filter_standard, vCoins, setCoinsRet , nValueRet, coin_selection_params, bnb_used)); - BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, filter_standard, vCoins, setCoinsRet2, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, filter_standard, GroupCoins(vCoins), setCoinsRet , nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, filter_standard, GroupCoins(vCoins), setCoinsRet2, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK(!equal_sets(setCoinsRet, setCoinsRet2)); int fails = 0; @@ -474,8 +490,8 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) { // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time // run the test RANDOM_REPEATS times and only complain if all of them fail - BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, filter_standard, vCoins, setCoinsRet , nValueRet, coin_selection_params, bnb_used)); - BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, filter_standard, vCoins, setCoinsRet2, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, filter_standard, GroupCoins(vCoins), setCoinsRet , nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, filter_standard, GroupCoins(vCoins), setCoinsRet2, nValueRet, coin_selection_params, bnb_used)); if (equal_sets(setCoinsRet, setCoinsRet2)) fails++; } @@ -495,8 +511,8 @@ BOOST_AUTO_TEST_CASE(knapsack_solver_test) { // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time // run the test RANDOM_REPEATS times and only complain if all of them fail - BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, filter_standard, vCoins, setCoinsRet , nValueRet, coin_selection_params, bnb_used)); - BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, filter_standard, vCoins, setCoinsRet2, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, filter_standard, GroupCoins(vCoins), setCoinsRet , nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, filter_standard, GroupCoins(vCoins), setCoinsRet2, nValueRet, coin_selection_params, bnb_used)); if (equal_sets(setCoinsRet, setCoinsRet2)) fails++; } @@ -521,7 +537,7 @@ BOOST_AUTO_TEST_CASE(ApproximateBestSubset) add_coin(1000 * COIN); add_coin(3 * COIN); - BOOST_CHECK(testWallet.SelectCoinsMinConf(1003 * COIN, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + BOOST_CHECK(testWallet.SelectCoinsMinConf(1003 * COIN, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 1003 * COIN); BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); @@ -559,8 +575,8 @@ BOOST_AUTO_TEST_CASE(SelectCoins_test) CoinSet out_set; CAmount out_value = 0; bool bnb_used = false; - BOOST_CHECK(testWallet.SelectCoinsMinConf(target, filter_standard, vCoins, out_set, out_value, coin_selection_params_bnb, bnb_used) || - testWallet.SelectCoinsMinConf(target, filter_standard, vCoins, out_set, out_value, coin_selection_params_knapsack, bnb_used)); + BOOST_CHECK(testWallet.SelectCoinsMinConf(target, filter_standard, GroupCoins(vCoins), out_set, out_value, coin_selection_params_bnb, bnb_used) || + testWallet.SelectCoinsMinConf(target, filter_standard, GroupCoins(vCoins), out_set, out_value, coin_selection_params_knapsack, bnb_used)); BOOST_CHECK_GE(out_value, target); } } diff --git a/src/wallet/test/psbt_wallet_tests.cpp b/src/wallet/test/psbt_wallet_tests.cpp new file mode 100644 index 0000000000..2cc995bf04 --- /dev/null +++ b/src/wallet/test/psbt_wallet_tests.cpp @@ -0,0 +1,150 @@ +// Copyright (c) 2017 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include <key_io.h> +#include <script/sign.h> +#include <utilstrencodings.h> +#include <wallet/rpcwallet.h> +#include <wallet/wallet.h> +#include <univalue.h> + +#include <boost/test/unit_test.hpp> +#include <test/test_bitcoin.h> +#include <wallet/test/wallet_test_fixture.h> + +extern bool ParseHDKeypath(std::string keypath_str, std::vector<uint32_t>& keypath); + +BOOST_FIXTURE_TEST_SUITE(psbt_wallet_tests, WalletTestingSetup) + +BOOST_AUTO_TEST_CASE(psbt_updater_test) +{ + // Create prevtxs and add to wallet + CDataStream s_prev_tx1(ParseHex("0200000000010158e87a21b56daf0c23be8e7070456c336f7cbaa5c8757924f545887bb2abdd7501000000171600145f275f436b09a8cc9a2eb2a2f528485c68a56323feffffff02d8231f1b0100000017a914aed962d6654f9a2b36608eb9d64d2b260db4f1118700c2eb0b0000000017a914b7f5faf40e3d40a5a459b1db3535f2b72fa921e88702483045022100a22edcc6e5bc511af4cc4ae0de0fcd75c7e04d8c1c3a8aa9d820ed4b967384ec02200642963597b9b1bc22c75e9f3e117284a962188bf5e8a74c895089046a20ad770121035509a48eb623e10aace8bfd0212fdb8a8e5af3c94b0b133b95e114cab89e4f7965000000"), SER_NETWORK, PROTOCOL_VERSION); + CTransactionRef prev_tx1; + s_prev_tx1 >> prev_tx1; + CWalletTx prev_wtx1(&m_wallet, prev_tx1); + m_wallet.mapWallet.emplace(prev_wtx1.GetHash(), std::move(prev_wtx1)); + + CDataStream s_prev_tx2(ParseHex("0200000001aad73931018bd25f84ae400b68848be09db706eac2ac18298babee71ab656f8b0000000048473044022058f6fc7c6a33e1b31548d481c826c015bd30135aad42cd67790dab66d2ad243b02204a1ced2604c6735b6393e5b41691dd78b00f0c5942fb9f751856faa938157dba01feffffff0280f0fa020000000017a9140fb9463421696b82c833af241c78c17ddbde493487d0f20a270100000017a91429ca74f8a08f81999428185c97b5d852e4063f618765000000"), SER_NETWORK, PROTOCOL_VERSION); + CTransactionRef prev_tx2; + s_prev_tx2 >> prev_tx2; + CWalletTx prev_wtx2(&m_wallet, prev_tx2); + m_wallet.mapWallet.emplace(prev_wtx2.GetHash(), std::move(prev_wtx2)); + + // Add scripts + CScript rs1; + CDataStream s_rs1(ParseHex("475221029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f2102dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d752ae"), SER_NETWORK, PROTOCOL_VERSION); + s_rs1 >> rs1; + m_wallet.AddCScript(rs1); + + CScript rs2; + CDataStream s_rs2(ParseHex("2200208c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903"), SER_NETWORK, PROTOCOL_VERSION); + s_rs2 >> rs2; + m_wallet.AddCScript(rs2); + + CScript ws1; + CDataStream s_ws1(ParseHex("47522103089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc21023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e7352ae"), SER_NETWORK, PROTOCOL_VERSION); + s_ws1 >> ws1; + m_wallet.AddCScript(ws1); + + // Add hd seed + CKey key = DecodeSecret("5KSSJQ7UNfFGwVgpCZDSHm5rVNhMFcFtvWM3zQ8mW4qNDEN7LFd"); // Mainnet and uncompressed form of cUkG8i1RFfWGWy5ziR11zJ5V4U4W3viSFCfyJmZnvQaUsd1xuF3T + CPubKey master_pub_key = m_wallet.DeriveNewSeed(key); + m_wallet.SetHDSeed(master_pub_key); + m_wallet.NewKeyPool(); + + // Call FillPSBT + PartiallySignedTransaction psbtx; + CDataStream ssData(ParseHex("70736274ff01009a020000000258e87a21b56daf0c23be8e7070456c336f7cbaa5c8757924f545887bb2abdd750000000000ffffffff838d0427d0ec650a68aa46bb0b098aea4422c071b2ca78352a077959d07cea1d0100000000ffffffff0270aaf00800000000160014d85c2b71d0060b09c9886aeb815e50991dda124d00e1f5050000000016001400aea9a2e5f0f876a588df5546e8742d1d87008f000000000000000000"), SER_NETWORK, PROTOCOL_VERSION); + ssData >> psbtx; + + // Use CTransaction for the constant parts of the + // transaction to avoid rehashing. + const CTransaction txConst(*psbtx.tx); + + // Fill transaction with our data + FillPSBT(&m_wallet, psbtx, &txConst, 1, false, true); + + // Get the final tx + CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); + ssTx << psbtx; + std::string final_hex = HexStr(ssTx.begin(), ssTx.end()); + BOOST_CHECK_EQUAL(final_hex, "70736274ff01009a020000000258e87a21b56daf0c23be8e7070456c336f7cbaa5c8757924f545887bb2abdd750000000000ffffffff838d0427d0ec650a68aa46bb0b098aea4422c071b2ca78352a077959d07cea1d0100000000ffffffff0270aaf00800000000160014d85c2b71d0060b09c9886aeb815e50991dda124d00e1f5050000000016001400aea9a2e5f0f876a588df5546e8742d1d87008f00000000000100bb0200000001aad73931018bd25f84ae400b68848be09db706eac2ac18298babee71ab656f8b0000000048473044022058f6fc7c6a33e1b31548d481c826c015bd30135aad42cd67790dab66d2ad243b02204a1ced2604c6735b6393e5b41691dd78b00f0c5942fb9f751856faa938157dba01feffffff0280f0fa020000000017a9140fb9463421696b82c833af241c78c17ddbde493487d0f20a270100000017a91429ca74f8a08f81999428185c97b5d852e4063f6187650000000104475221029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f2102dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d752ae2206029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f10d90c6a4f000000800000008000000080220602dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d710d90c6a4f0000008000000080010000800001012000c2eb0b0000000017a914b7f5faf40e3d40a5a459b1db3535f2b72fa921e88701042200208c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903010547522103089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc21023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e7352ae2206023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e7310d90c6a4f000000800000008003000080220603089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc10d90c6a4f00000080000000800200008000220203a9a4c37f5996d3aa25dbac6b570af0650394492942460b354753ed9eeca5877110d90c6a4f000000800000008004000080002202027f6399757d2eff55a136ad02c684b1838b6556e5f1b6b34282a94b6b5005109610d90c6a4f00000080000000800500008000"); +} + +BOOST_AUTO_TEST_CASE(parse_hd_keypath) +{ + std::vector<uint32_t> keypath; + + BOOST_CHECK(ParseHDKeypath("1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1", keypath)); + BOOST_CHECK(!ParseHDKeypath("///////////////////////////", keypath)); + + BOOST_CHECK(ParseHDKeypath("1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1'/1", keypath)); + BOOST_CHECK(!ParseHDKeypath("//////////////////////////'/", keypath)); + + BOOST_CHECK(ParseHDKeypath("1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/", keypath)); + BOOST_CHECK(!ParseHDKeypath("1///////////////////////////", keypath)); + + BOOST_CHECK(ParseHDKeypath("1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1'/", keypath)); + BOOST_CHECK(!ParseHDKeypath("1/'//////////////////////////", keypath)); + + BOOST_CHECK(ParseHDKeypath("", keypath)); + BOOST_CHECK(!ParseHDKeypath(" ", keypath)); + + BOOST_CHECK(ParseHDKeypath("0", keypath)); + BOOST_CHECK(!ParseHDKeypath("O", keypath)); + + BOOST_CHECK(ParseHDKeypath("0000'/0000'/0000'", keypath)); + BOOST_CHECK(!ParseHDKeypath("0000,/0000,/0000,", keypath)); + + BOOST_CHECK(ParseHDKeypath("01234", keypath)); + BOOST_CHECK(!ParseHDKeypath("0x1234", keypath)); + + BOOST_CHECK(ParseHDKeypath("1", keypath)); + BOOST_CHECK(!ParseHDKeypath(" 1", keypath)); + + BOOST_CHECK(ParseHDKeypath("42", keypath)); + BOOST_CHECK(!ParseHDKeypath("m42", keypath)); + + BOOST_CHECK(ParseHDKeypath("4294967295", keypath)); // 4294967295 == 0xFFFFFFFF (uint32_t max) + BOOST_CHECK(!ParseHDKeypath("4294967296", keypath)); // 4294967296 == 0xFFFFFFFF (uint32_t max) + 1 + + BOOST_CHECK(ParseHDKeypath("m", keypath)); + BOOST_CHECK(!ParseHDKeypath("n", keypath)); + + BOOST_CHECK(ParseHDKeypath("m/", keypath)); + BOOST_CHECK(!ParseHDKeypath("n/", keypath)); + + BOOST_CHECK(ParseHDKeypath("m/0", keypath)); + BOOST_CHECK(!ParseHDKeypath("n/0", keypath)); + + BOOST_CHECK(ParseHDKeypath("m/0'", keypath)); + BOOST_CHECK(!ParseHDKeypath("m/0''", keypath)); + + BOOST_CHECK(ParseHDKeypath("m/0'/0'", keypath)); + BOOST_CHECK(!ParseHDKeypath("m/'0/0'", keypath)); + + BOOST_CHECK(ParseHDKeypath("m/0/0", keypath)); + BOOST_CHECK(!ParseHDKeypath("n/0/0", keypath)); + + BOOST_CHECK(ParseHDKeypath("m/0/0/00", keypath)); + BOOST_CHECK(!ParseHDKeypath("m/0/0/f00", keypath)); + + BOOST_CHECK(ParseHDKeypath("m/0/0/000000000000000000000000000000000000000000000000000000000000000000000000000000000000", keypath)); + BOOST_CHECK(!ParseHDKeypath("m/1/1/111111111111111111111111111111111111111111111111111111111111111111111111111111111111", keypath)); + + BOOST_CHECK(ParseHDKeypath("m/0/00/0", keypath)); + BOOST_CHECK(!ParseHDKeypath("m/0'/00/'0", keypath)); + + BOOST_CHECK(ParseHDKeypath("m/1/", keypath)); + BOOST_CHECK(!ParseHDKeypath("m/1//", keypath)); + + BOOST_CHECK(ParseHDKeypath("m/0/4294967295", keypath)); // 4294967295 == 0xFFFFFFFF (uint32_t max) + BOOST_CHECK(!ParseHDKeypath("m/0/4294967296", keypath)); // 4294967296 == 0xFFFFFFFF (uint32_t max) + 1 + + BOOST_CHECK(ParseHDKeypath("m/4294967295", keypath)); // 4294967295 == 0xFFFFFFFF (uint32_t max) + BOOST_CHECK(!ParseHDKeypath("m/4294967296", keypath)); // 4294967296 == 0xFFFFFFFF (uint32_t max) + 1 +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp index a946b565f1..c89b8f252f 100644 --- a/src/wallet/test/wallet_tests.cpp +++ b/src/wallet/test/wallet_tests.cpp @@ -365,4 +365,13 @@ BOOST_FIXTURE_TEST_CASE(ListCoins, ListCoinsTestingSetup) BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U); } +BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup) +{ + std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>("dummy", WalletDatabase::CreateDummy()); + wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS); + BOOST_CHECK(!wallet->TopUpKeyPool(1000)); + CPubKey pubkey; + BOOST_CHECK(!wallet->GetKeyFromPool(pubkey, false)); +} + BOOST_AUTO_TEST_SUITE_END() diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 067015c006..3ec6aefaec 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -164,6 +164,7 @@ const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const CPubKey CWallet::GenerateNewKey(WalletBatch &batch, bool internal) { + assert(!IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)); AssertLockHeld(cs_wallet); // mapKeyMetadata bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets @@ -1444,6 +1445,7 @@ CAmount CWallet::GetChange(const CTransaction& tx) const CPubKey CWallet::GenerateNewSeed() { + assert(!IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)); CKey key; key.MakeNewKey(true); return DeriveNewSeed(key); @@ -1505,6 +1507,34 @@ bool CWallet::IsHDEnabled() const return !hdChain.seed_id.IsNull(); } +void CWallet::SetWalletFlag(uint64_t flags) +{ + LOCK(cs_wallet); + m_wallet_flags |= flags; + if (!WalletBatch(*database).WriteWalletFlags(m_wallet_flags)) + throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed"); +} + +bool CWallet::IsWalletFlagSet(uint64_t flag) +{ + return (m_wallet_flags & flag); +} + +bool CWallet::SetWalletFlags(uint64_t overwriteFlags, bool memonly) +{ + LOCK(cs_wallet); + m_wallet_flags = overwriteFlags; + if (((overwriteFlags & g_known_wallet_flags) >> 32) ^ (overwriteFlags >> 32)) { + // contains unknown non-tolerable wallet flags + return false; + } + if (!memonly && !WalletBatch(*database).WriteWalletFlags(m_wallet_flags)) { + throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed"); + } + + return true; +} + int64_t CWalletTx::GetTxTime() const { int64_t n = nTimeSmart; @@ -1947,6 +1977,7 @@ CAmount CWalletTx::GetAvailableCredit(bool fUseCache, const isminefilter& filter if (cache) { *cache = nCredit; + assert(cache_used); *cache_used = true; } return nCredit; @@ -2384,32 +2415,14 @@ const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int out return ptx->vout[n]; } -bool CWallet::OutputEligibleForSpending(const COutput& output, const CoinEligibilityFilter& eligibility_filter) const -{ - if (!output.fSpendable) - return false; - - if (output.nDepth < (output.tx->IsFromMe(ISMINE_ALL) ? eligibility_filter.conf_mine : eligibility_filter.conf_theirs)) - return false; - - size_t ancestors, descendants; - mempool.GetTransactionAncestry(output.tx->GetHash(), ancestors, descendants); - if (ancestors > eligibility_filter.max_ancestors || descendants > eligibility_filter.max_descendants) { - return false; - } - - return true; -} - -bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<COutput> vCoins, +bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<OutputGroup> groups, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const { setCoinsRet.clear(); nValueRet = 0; - std::vector<CInputCoin> utxo_pool; + std::vector<OutputGroup> utxo_pool; if (coin_selection_params.use_bnb) { - // Get long term estimate FeeCalculation feeCalc; CCoinControl temp; @@ -2420,19 +2433,26 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibil CAmount cost_of_change = GetDiscardRate(*this, ::feeEstimator).GetFee(coin_selection_params.change_spend_size) + coin_selection_params.effective_fee.GetFee(coin_selection_params.change_output_size); // Filter by the min conf specs and add to utxo_pool and calculate effective value - for (const COutput &output : vCoins) - { - if (!OutputEligibleForSpending(output, eligibility_filter)) - continue; - - CInputCoin coin(output.tx->tx, output.i); - coin.effective_value = coin.txout.nValue - (output.nInputBytes < 0 ? 0 : coin_selection_params.effective_fee.GetFee(output.nInputBytes)); - // Only include outputs that are positive effective value (i.e. not dust) - if (coin.effective_value > 0) { - coin.fee = output.nInputBytes < 0 ? 0 : coin_selection_params.effective_fee.GetFee(output.nInputBytes); - coin.long_term_fee = output.nInputBytes < 0 ? 0 : long_term_feerate.GetFee(output.nInputBytes); - utxo_pool.push_back(coin); + for (OutputGroup& group : groups) { + if (!group.EligibleForSpending(eligibility_filter)) continue; + + group.fee = 0; + group.long_term_fee = 0; + group.effective_value = 0; + for (auto it = group.m_outputs.begin(); it != group.m_outputs.end(); ) { + const CInputCoin& coin = *it; + CAmount effective_value = coin.txout.nValue - (coin.m_input_bytes < 0 ? 0 : coin_selection_params.effective_fee.GetFee(coin.m_input_bytes)); + // Only include outputs that are positive effective value (i.e. not dust) + if (effective_value > 0) { + group.fee += coin.m_input_bytes < 0 ? 0 : coin_selection_params.effective_fee.GetFee(coin.m_input_bytes); + group.long_term_fee += coin.m_input_bytes < 0 ? 0 : long_term_feerate.GetFee(coin.m_input_bytes); + group.effective_value += effective_value; + ++it; + } else { + it = group.Discard(coin); + } } + if (group.effective_value > 0) utxo_pool.push_back(group); } // Calculate the fees for things that aren't inputs CAmount not_input_fees = coin_selection_params.effective_fee.GetFee(coin_selection_params.tx_noinputs_size); @@ -2440,13 +2460,9 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibil return SelectCoinsBnB(utxo_pool, nTargetValue, cost_of_change, setCoinsRet, nValueRet, not_input_fees); } else { // Filter by the min conf specs and add to utxo_pool - for (const COutput &output : vCoins) - { - if (!OutputEligibleForSpending(output, eligibility_filter)) - continue; - - CInputCoin coin = CInputCoin(output.tx->tx, output.i); - utxo_pool.push_back(coin); + for (const OutputGroup& group : groups) { + if (!group.EligibleForSpending(eligibility_filter)) continue; + utxo_pool.push_back(group); } bnb_used = false; return KnapsackSolver(nTargetValue, utxo_pool, setCoinsRet, nValueRet); @@ -2468,7 +2484,7 @@ bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAm if (!out.fSpendable) continue; nValueRet += out.tx->tx->vout[out.i].nValue; - setCoinsRet.insert(CInputCoin(out.tx->tx, out.i)); + setCoinsRet.insert(out.GetInputCoin()); } return (nValueRet >= nTargetValue); } @@ -2502,27 +2518,31 @@ bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAm // remove preset inputs from vCoins for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coin_control.HasSelected();) { - if (setPresetCoins.count(CInputCoin(it->tx->tx, it->i))) + if (setPresetCoins.count(it->GetInputCoin())) it = vCoins.erase(it); else ++it; } + // form groups from remaining coins; note that preset coins will not + // automatically have their associated (same address) coins included + std::vector<OutputGroup> groups = GroupOutputs(vCoins, !coin_control.m_avoid_partial_spends); + size_t max_ancestors = (size_t)std::max<int64_t>(1, gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT)); size_t max_descendants = (size_t)std::max<int64_t>(1, gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT)); bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS); bool res = nTargetValue <= nValueFromPresetInputs || - SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(1, 6, 0), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used) || - SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(1, 1, 0), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used) || - (m_spend_zero_conf_change && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, 2), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) || - (m_spend_zero_conf_change && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, std::min((size_t)4, max_ancestors/3), std::min((size_t)4, max_descendants/3)), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) || - (m_spend_zero_conf_change && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, max_ancestors/2, max_descendants/2), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) || - (m_spend_zero_conf_change && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, max_ancestors-1, max_descendants-1), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) || - (m_spend_zero_conf_change && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, std::numeric_limits<uint64_t>::max()), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); + SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(1, 6, 0), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used) || + SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(1, 1, 0), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used) || + (m_spend_zero_conf_change && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, 2), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) || + (m_spend_zero_conf_change && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, std::min((size_t)4, max_ancestors/3), std::min((size_t)4, max_descendants/3)), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) || + (m_spend_zero_conf_change && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, max_ancestors/2, max_descendants/2), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) || + (m_spend_zero_conf_change && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, max_ancestors-1, max_descendants-1), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) || + (m_spend_zero_conf_change && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, std::numeric_limits<uint64_t>::max()), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)); // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset - setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end()); + util::insert(setCoinsRet, setPresetCoins); // add preset inputs to the total value selected nValueRet += nValueFromPresetInputs; @@ -2636,7 +2656,7 @@ OutputType CWallet::TransactionChangeType(OutputType change_type, const std::vec } bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CReserveKey& reservekey, CAmount& nFeeRet, - int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign) + int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign) { CAmount nValue = 0; int nChangePosRequest = nChangePosInOut; @@ -2720,6 +2740,10 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CTransac // post-backup change. // Reserve a new key pair from key pool + if (IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { + strFailReason = _("Can't generate a change-address key. Private keys are disabled for this wallet."); + return false; + } CPubKey vchPubKey; bool ret; ret = reservekey.GetReservedKey(vchPubKey, true); @@ -3120,7 +3144,7 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet) { LOCK(cs_KeyStore); // This wallet is in its first run if all of these are empty - fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty(); + fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty() && !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS); } if (nLoadWalletRet != DBErrors::LOAD_OK) @@ -3244,6 +3268,9 @@ const std::string& CWallet::GetLabelName(const CScript& scriptPubKey) const */ bool CWallet::NewKeyPool() { + if (IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { + return false; + } { LOCK(cs_wallet); WalletBatch batch(*database); @@ -3302,6 +3329,9 @@ void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool) bool CWallet::TopUpKeyPool(unsigned int kpSize) { + if (IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { + return false; + } { LOCK(cs_wallet); @@ -3426,6 +3456,10 @@ void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey) bool CWallet::GetKeyFromPool(CPubKey& result, bool internal) { + if (IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { + return false; + } + CKeyPool keypool; { LOCK(cs_wallet); @@ -3965,7 +3999,7 @@ bool CWallet::Verify(std::string wallet_file, bool salvage_wallet, std::string& return WalletBatch::VerifyDatabaseFile(wallet_path, warning_string, error_string); } -std::shared_ptr<CWallet> CWallet::CreateWalletFromFile(const std::string& name, const fs::path& path) +std::shared_ptr<CWallet> CWallet::CreateWalletFromFile(const std::string& name, const fs::path& path, uint64_t wallet_creation_flags) { const std::string& walletFile = name; @@ -4025,7 +4059,7 @@ std::shared_ptr<CWallet> CWallet::CreateWalletFromFile(const std::string& name, if (nMaxVersion == 0) // the -upgradewallet without argument case { LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST); - nMaxVersion = CLIENT_VERSION; + nMaxVersion = FEATURE_LATEST; walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately } else @@ -4090,18 +4124,33 @@ std::shared_ptr<CWallet> CWallet::CreateWalletFromFile(const std::string& name, } walletInstance->SetMinVersion(FEATURE_LATEST); - // generate a new seed - CPubKey seed = walletInstance->GenerateNewSeed(); - if (!walletInstance->SetHDSeed(seed)) - throw std::runtime_error(std::string(__func__) + ": Storing HD seed failed"); + if ((wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { + //selective allow to set flags + walletInstance->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS); + } else { + // generate a new seed + CPubKey seed = walletInstance->GenerateNewSeed(); + if (!walletInstance->SetHDSeed(seed)) { + throw std::runtime_error(std::string(__func__) + ": Storing HD seed failed"); + } + } // Top up the keypool - if (!walletInstance->TopUpKeyPool()) { + if (!walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !walletInstance->TopUpKeyPool()) { InitError(_("Unable to generate initial keys") += "\n"); return nullptr; } walletInstance->ChainStateFlushed(chainActive.GetLocator()); + } else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) { + // Make it impossible to disable private keys after creation + InitError(strprintf(_("Error loading %s: Private keys can only be disabled during creation"), walletFile)); + return NULL; + } else if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { + LOCK(walletInstance->cs_KeyStore); + if (!walletInstance->mapKeys.empty() || !walletInstance->mapCryptedKeys.empty()) { + InitWarning(strprintf(_("Warning: Private keys detected in wallet {%s} with disabled private keys"), walletFile)); + } } else if (gArgs.IsArgSet("-usehd")) { bool useHD = gArgs.GetBoolArg("-usehd", true); if (walletInstance->IsHDEnabled() && !useHD) { @@ -4379,3 +4428,29 @@ void CWallet::LearnAllRelatedScripts(const CPubKey& key) LearnRelatedScripts(key, OutputType::P2SH_SEGWIT); } +std::vector<OutputGroup> CWallet::GroupOutputs(const std::vector<COutput>& outputs, bool single_coin) const { + std::vector<OutputGroup> groups; + std::map<CTxDestination, OutputGroup> gmap; + CTxDestination dst; + for (const auto& output : outputs) { + if (output.fSpendable) { + CInputCoin input_coin = output.GetInputCoin(); + + size_t ancestors, descendants; + mempool.GetTransactionAncestry(output.tx->GetHash(), ancestors, descendants); + if (!single_coin && ExtractDestination(output.tx->tx->vout[output.i].scriptPubKey, dst)) { + if (gmap.count(dst) == 10) { + groups.push_back(gmap[dst]); + gmap.erase(dst); + } + gmap[dst].Insert(input_coin, output.nDepth, output.tx->IsFromMe(ISMINE_ALL), ancestors, descendants); + } else { + groups.emplace_back(input_coin, output.nDepth, output.tx->IsFromMe(ISMINE_ALL), ancestors, descendants); + } + } + } + if (!single_coin) { + for (const auto& it : gmap) groups.push_back(it.second); + } + return groups; +} diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 2e53ca0c55..122649d575 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -55,6 +55,8 @@ static const CAmount WALLET_INCREMENTAL_RELAY_FEE = 5000; static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true; //! Default for -walletrejectlongchains static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS = false; +//! Default for -avoidpartialspends +static const bool DEFAULT_AVOIDPARTIALSPENDS = false; //! -txconfirmtarget default static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6; //! -walletrbf default @@ -100,6 +102,16 @@ constexpr OutputType DEFAULT_ADDRESS_TYPE{OutputType::P2SH_SEGWIT}; //! Default for -changetype constexpr OutputType DEFAULT_CHANGE_TYPE{OutputType::CHANGE_AUTO}; +enum WalletFlags : uint64_t { + // wallet flags in the upper section (> 1 << 31) will lead to not opening the wallet if flag is unknown + // unkown wallet flags in the lower section <= (1 << 31) will be tolerated + + // will enforce the rule that the wallet can't contain any private keys (only watch-only/pubkeys) + WALLET_FLAG_DISABLE_PRIVATE_KEYS = (1ULL << 32), +}; + +static constexpr uint64_t g_known_wallet_flags = WALLET_FLAG_DISABLE_PRIVATE_KEYS; + /** A key pool entry */ class CKeyPool { @@ -515,10 +527,12 @@ public: } std::string ToString() const; -}; - - + inline CInputCoin GetInputCoin() const + { + return CInputCoin(tx->tx, i, nInputBytes); + } +}; /** Private key that includes an expiration date in case it never gets used. */ class CWalletKey @@ -642,17 +656,6 @@ struct CoinSelectionParams CoinSelectionParams() {} }; -struct CoinEligibilityFilter -{ - const int conf_mine; - const int conf_theirs; - const uint64_t max_ancestors; - const uint64_t max_descendants; - - CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors), max_descendants(max_ancestors) {} - CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors, uint64_t max_descendants) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors), max_descendants(max_descendants) {} -}; - class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime /** * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances, @@ -726,6 +729,7 @@ private: std::set<int64_t> set_pre_split_keypool; int64_t m_max_keypool_index = 0; std::map<CKeyID, int64_t> m_pool_key_to_index; + std::atomic<uint64_t> m_wallet_flags{0}; int64_t nTimeFirstKey = 0; @@ -853,10 +857,11 @@ public: * completion the coin set and corresponding actual target value is * assembled */ - bool SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<COutput> vCoins, + bool SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<OutputGroup> groups, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const; bool IsSpent(const uint256& hash, unsigned int n) const; + std::vector<OutputGroup> GroupOutputs(const std::vector<COutput>& outputs, bool single_coin) const; bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet); void LockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet); @@ -1132,7 +1137,7 @@ public: static bool Verify(std::string wallet_file, bool salvage_wallet, std::string& error_string, std::string& warning_string); /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */ - static std::shared_ptr<CWallet> CreateWalletFromFile(const std::string& name, const fs::path& path); + static std::shared_ptr<CWallet> CreateWalletFromFile(const std::string& name, const fs::path& path, uint64_t wallet_creation_flags = 0); /** * Wallet post-init setup @@ -1183,8 +1188,15 @@ public: */ void LearnAllRelatedScripts(const CPubKey& key); - /** Whether a given output is spendable by this wallet */ - bool OutputEligibleForSpending(const COutput& output, const CoinEligibilityFilter& eligibility_filter) const; + /** set a single wallet flag */ + void SetWalletFlag(uint64_t flags); + + /** check if a certain wallet flag is set */ + bool IsWalletFlagSet(uint64_t flag); + + /** overwrite all flags by the given uint64_t + returns false if unknown, non-tolerable flags are present */ + bool SetWalletFlags(uint64_t overwriteFlags, bool memOnly); }; /** A key allocated from the key pool. */ diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp index 4b4460a794..67fcaa725b 100644 --- a/src/wallet/walletdb.cpp +++ b/src/wallet/walletdb.cpp @@ -510,7 +510,14 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, strErr = "Error reading wallet database: SetHDChain failed"; return false; } - } else if (strType != "bestblock" && strType != "bestblock_nomerkle"){ + } else if (strType == "flags") { + uint64_t flags; + ssValue >> flags; + if (!pwallet->SetWalletFlags(flags, true)) { + strErr = "Error reading wallet database: Unknown non-tolerable wallet flags found"; + return false; + } + } else if (strType != "bestblock" && strType != "bestblock_nomerkle") { wss.m_unknown_records++; } } catch (...) @@ -537,7 +544,7 @@ DBErrors WalletBatch::LoadWallet(CWallet* pwallet) int nMinVersion = 0; if (m_batch.Read((std::string)"minversion", nMinVersion)) { - if (nMinVersion > CLIENT_VERSION) + if (nMinVersion > FEATURE_LATEST) return DBErrors::TOO_NEW; pwallet->LoadMinVersion(nMinVersion); } @@ -570,10 +577,12 @@ DBErrors WalletBatch::LoadWallet(CWallet* pwallet) { // losing keys is considered a catastrophic error, anything else // we assume the user can live with: - if (IsKeyType(strType) || strType == "defaultkey") + if (IsKeyType(strType) || strType == "defaultkey") { result = DBErrors::CORRUPT; - else - { + } else if(strType == "flags") { + // reading the wallet flags can only fail if unknown flags are present + result = DBErrors::TOO_NEW; + } else { // Leave other errors alone, if we try to fix them we might make things worse. fNoncriticalErrors = true; // ... but do warn the user there is something wrong. if (strType == "tx") @@ -640,7 +649,7 @@ DBErrors WalletBatch::FindWalletTx(std::vector<uint256>& vTxHash, std::vector<CW int nMinVersion = 0; if (m_batch.Read((std::string)"minversion", nMinVersion)) { - if (nMinVersion > CLIENT_VERSION) + if (nMinVersion > FEATURE_LATEST) return DBErrors::TOO_NEW; } @@ -840,6 +849,11 @@ bool WalletBatch::WriteHDChain(const CHDChain& chain) return WriteIC(std::string("hdchain"), chain); } +bool WalletBatch::WriteWalletFlags(const uint64_t flags) +{ + return WriteIC(std::string("flags"), flags); +} + bool WalletBatch::TxnBegin() { return m_batch.TxnBegin(); diff --git a/src/wallet/walletdb.h b/src/wallet/walletdb.h index 3237376f63..674d1c2201 100644 --- a/src/wallet/walletdb.h +++ b/src/wallet/walletdb.h @@ -234,6 +234,7 @@ public: //! write the hdchain model (external chain child index counter) bool WriteHDChain(const CHDChain& chain); + bool WriteWalletFlags(const uint64_t flags); //! Begin a new transaction bool TxnBegin(); //! Commit current transaction |