Compare commits

...

7 Commits

Author SHA1 Message Date
maflcko
1be366c419
Merge fa02e1295dc5c8a715da235f21ee40759f8a4200 into 5f4422d68dc3530c353af1f87499de1c864b60ad 2025-03-17 09:54:10 +07:00
merge-script
5f4422d68d
Merge bitcoin/bitcoin#32010: qa: Fix TxIndex race conditions
3301d2cbe8c3b76c97285d75fa59637cb6952d0b qa: Wait for txindex to avoid race condition (Hodlinator)
9bfb0d75ba10591cc6c9620f9fd1ecc0e55e7a48 qa: Remove unnecessary -txindex args (Hodlinator)
7ac281c19cd3d11f316dbbb3308eabf1ad4f26d6 qa: Add missing coverage of corrupt indexes (Hodlinator)

Pull request description:

  - Add synchronization in 3 places where if the Transaction Index happens to be slow, we get rare test failures when querying it for transactions (one such case experienced on Windows, prompting investigation).
  - Remove unnecessary TxIndex initialization in some tests.
  - Add some test coverage where TxIndex aspect could be tested in feature_init.py.

ACKs for top commit:
  fjahr:
    re-ACK 3301d2cbe8c3b76c97285d75fa59637cb6952d0b
  mzumsande:
    Code Review ACK 3301d2cbe8c3b76c97285d75fa59637cb6952d0b
  furszy:
    Code review ACK 3301d2cbe8c3b76c97285d75fa59637cb6952d0b
  Prabhat1308:
    Concept ACK [`3301d2c`](3301d2cbe8)

Tree-SHA512: 7c2019e38455f344856aaf6b381faafbd88d53dc88d13309deb718c1dcfbee4ccca7c7f1b66917395503a6f94c3b216a007ad432cc8b93d0309db9805f38d602
2025-03-17 10:28:14 +08:00
Hodlinator
3301d2cbe8
qa: Wait for txindex to avoid race condition
Can be verified to be necessary through adding std::this_thread::sleep_for(0.5s) at the beginning of TxIndex::CustomAppend.
2025-03-10 15:24:16 +01:00
Hodlinator
9bfb0d75ba
qa: Remove unnecessary -txindex args
(Parent commit ensured indexes in feature_init.py are actually used, otherwise they would be removed here as well).
2025-03-07 22:22:31 +01:00
Hodlinator
7ac281c19c
qa: Add missing coverage of corrupt indexes 2025-03-07 22:22:31 +01:00
MarcoFalke
fa02e1295d
refactor: Enforce readability-avoid-const-params-in-decls 2025-02-20 22:09:19 +01:00
MarcoFalke
333325fd1f
refactor: Avoid copies by using const references or by move-construction 2025-02-20 22:09:00 +01:00
58 changed files with 136 additions and 112 deletions

View File

@ -22,6 +22,7 @@ performance-*,
-performance-no-int-to-ptr, -performance-no-int-to-ptr,
-performance-noexcept-move-constructor, -performance-noexcept-move-constructor,
-performance-unnecessary-value-param, -performance-unnecessary-value-param,
readability-avoid-const-params-in-decls,
readability-const-return-type, readability-const-return-type,
readability-redundant-declaration, readability-redundant-declaration,
readability-redundant-string-init, readability-redundant-string-init,

View File

@ -172,7 +172,7 @@ public:
* *
* @return A vector of randomly selected addresses from vRandom. * @return A vector of randomly selected addresses from vRandom.
*/ */
std::vector<CAddress> GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered = true) const; std::vector<CAddress> GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network, bool filtered = true) const;
/** /**
* Returns an information-location pair for all addresses in the selected addrman table. * Returns an information-location pair for all addresses in the selected addrman table.

View File

@ -135,7 +135,7 @@ public:
std::pair<CAddress, NodeSeconds> Select(bool new_only, const std::unordered_set<Network>& networks) const std::pair<CAddress, NodeSeconds> Select(bool new_only, const std::unordered_set<Network>& networks) const
EXCLUSIVE_LOCKS_REQUIRED(!cs); EXCLUSIVE_LOCKS_REQUIRED(!cs);
std::vector<CAddress> GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered = true) const std::vector<CAddress> GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network, bool filtered = true) const
EXCLUSIVE_LOCKS_REQUIRED(!cs); EXCLUSIVE_LOCKS_REQUIRED(!cs);
std::vector<std::pair<AddrInfo, AddressPosition>> GetEntries(bool from_tried) const std::vector<std::pair<AddrInfo, AddressPosition>> GetEntries(bool from_tried) const
@ -267,7 +267,7 @@ private:
* */ * */
nid_type GetEntry(bool use_tried, size_t bucket, size_t position) const EXCLUSIVE_LOCKS_REQUIRED(cs); nid_type GetEntry(bool use_tried, size_t bucket, size_t position) const EXCLUSIVE_LOCKS_REQUIRED(cs);
std::vector<CAddress> GetAddr_(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered = true) const EXCLUSIVE_LOCKS_REQUIRED(cs); std::vector<CAddress> GetAddr_(size_t max_addresses, size_t max_pct, std::optional<Network> network, bool filtered = true) const EXCLUSIVE_LOCKS_REQUIRED(cs);
std::vector<std::pair<AddrInfo, AddressPosition>> GetEntries_(bool from_tried) const EXCLUSIVE_LOCKS_REQUIRED(cs); std::vector<std::pair<AddrInfo, AddressPosition>> GetEntries_(bool from_tried) const EXCLUSIVE_LOCKS_REQUIRED(cs);

View File

@ -114,7 +114,7 @@ public:
/** /**
* @param[in] nonce This should be randomly generated, and is used for the siphash secret key * @param[in] nonce This should be randomly generated, and is used for the siphash secret key
*/ */
CBlockHeaderAndShortTxIDs(const CBlock& block, const uint64_t nonce); CBlockHeaderAndShortTxIDs(const CBlock& block, uint64_t nonce);
uint64_t GetShortID(const Wtxid& wtxid) const; uint64_t GetShortID(const Wtxid& wtxid) const;

View File

@ -15,7 +15,7 @@ class ArgsManager;
/** /**
* Creates and returns a std::unique_ptr<CChainParams> of the chosen chain. * Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
*/ */
std::unique_ptr<const CChainParams> CreateChainParams(const ArgsManager& args, const ChainType chain); std::unique_ptr<const CChainParams> CreateChainParams(const ArgsManager& args, ChainType chain);
/** /**
* Return the currently selected parameters. This won't change after app * Return the currently selected parameters. This won't change after app
@ -26,6 +26,6 @@ const CChainParams &Params();
/** /**
* Sets the params returned by Params() to those for the given chain type. * Sets the params returned by Params() to those for the given chain type.
*/ */
void SelectParams(const ChainType chain); void SelectParams(ChainType chain);
#endif // BITCOIN_CHAINPARAMS_H #endif // BITCOIN_CHAINPARAMS_H

View File

@ -35,7 +35,7 @@ private:
/** /**
* Creates and returns a std::unique_ptr<CBaseChainParams> of the chosen chain. * Creates and returns a std::unique_ptr<CBaseChainParams> of the chosen chain.
*/ */
std::unique_ptr<CBaseChainParams> CreateBaseChainParams(const ChainType chain); std::unique_ptr<CBaseChainParams> CreateBaseChainParams(ChainType chain);
/** /**
*Set the arguments for chainparams *Set the arguments for chainparams
@ -49,7 +49,7 @@ void SetupChainParamsBaseOptions(ArgsManager& argsman);
const CBaseChainParams& BaseParams(); const CBaseChainParams& BaseParams();
/** Sets the params returned by Params() to those for the given chain. */ /** Sets the params returned by Params() to those for the given chain. */
void SelectBaseParams(const ChainType chain); void SelectBaseParams(ChainType chain);
/** List of possible chain / network names */ /** List of possible chain / network names */
#define LIST_CHAIN_NAMES "main, test, testnet4, signet, regtest" #define LIST_CHAIN_NAMES "main, test, testnet4, signet, regtest"

View File

@ -61,7 +61,7 @@ public:
* It should generally always be a random value (and is largely only exposed for unit testing) * It should generally always be a random value (and is largely only exposed for unit testing)
* nFlags should be one of the BLOOM_UPDATE_* enums (not _MASK) * nFlags should be one of the BLOOM_UPDATE_* enums (not _MASK)
*/ */
CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweak, unsigned char nFlagsIn); CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweak, unsigned char nFlagsIn);
CBloomFilter() : nHashFuncs(0), nTweak(0), nFlags(0) {} CBloomFilter() : nHashFuncs(0), nTweak(0), nFlags(0) {}
SERIALIZE_METHODS(CBloomFilter, obj) { READWRITE(obj.vData, obj.nHashFuncs, obj.nTweak, obj.nFlags); } SERIALIZE_METHODS(CBloomFilter, obj) { READWRITE(obj.vData, obj.nHashFuncs, obj.nTweak, obj.nFlags); }
@ -108,7 +108,7 @@ public:
class CRollingBloomFilter class CRollingBloomFilter
{ {
public: public:
CRollingBloomFilter(const unsigned int nElements, const double nFPRate); CRollingBloomFilter(unsigned int nElements, double nFPRate);
void insert(Span<const unsigned char> vKey); void insert(Span<const unsigned char> vKey);
bool contains(Span<const unsigned char> vKey) const; bool contains(Span<const unsigned char> vKey) const;

View File

@ -30,7 +30,7 @@ std::string FeeModeInfo(std::pair<std::string, FeeEstimateMode>& mode);
std::string FeeModesDetail(std::string default_info); std::string FeeModesDetail(std::string default_info);
std::string InvalidEstimateModeErrorMessage(); std::string InvalidEstimateModeErrorMessage();
bilingual_str PSBTErrorString(PSBTError error); bilingual_str PSBTErrorString(PSBTError error);
bilingual_str TransactionErrorString(const node::TransactionError error); bilingual_str TransactionErrorString(node::TransactionError error);
bilingual_str ResolveErrMsg(const std::string& optname, const std::string& strBind); bilingual_str ResolveErrMsg(const std::string& optname, const std::string& strBind);
bilingual_str InvalidPortErrMsg(const std::string& optname, const std::string& strPort); bilingual_str InvalidPortErrMsg(const std::string& optname, const std::string& strPort);
bilingual_str AmountHighWarn(const std::string& optname); bilingual_str AmountHighWarn(const std::string& optname);

View File

@ -72,6 +72,6 @@ bool MessageSign(
*/ */
uint256 MessageHash(const std::string& message); uint256 MessageHash(const std::string& message);
std::string SigningResultString(const SigningResult res); std::string SigningResultString(SigningResult res);
#endif // BITCOIN_COMMON_SIGNMESSAGE_H #endif // BITCOIN_COMMON_SIGNMESSAGE_H

View File

@ -33,7 +33,7 @@ enum class TxVerbosity {
// core_read.cpp // core_read.cpp
CScript ParseScript(const std::string& s); CScript ParseScript(const std::string& s);
std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode = false); std::string ScriptToAsmStr(const CScript& script, bool fAttemptSighashDecode = false);
[[nodiscard]] bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness = false, bool try_witness = true); [[nodiscard]] bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness = false, bool try_witness = true);
[[nodiscard]] bool DecodeHexBlk(CBlock&, const std::string& strHexBlk); [[nodiscard]] bool DecodeHexBlk(CBlock&, const std::string& strHexBlk);
bool DecodeHexBlockHeader(CBlockHeader&, const std::string& hex_header); bool DecodeHexBlockHeader(CBlockHeader&, const std::string& hex_header);
@ -41,7 +41,7 @@ bool DecodeHexBlockHeader(CBlockHeader&, const std::string& hex_header);
[[nodiscard]] util::Result<int> SighashFromStr(const std::string& sighash); [[nodiscard]] util::Result<int> SighashFromStr(const std::string& sighash);
// core_write.cpp // core_write.cpp
UniValue ValueFromAmount(const CAmount amount); UniValue ValueFromAmount(CAmount amount);
std::string FormatScript(const CScript& script); std::string FormatScript(const CScript& script);
std::string EncodeHexTx(const CTransaction& tx); std::string EncodeHexTx(const CTransaction& tx);
std::string SighashToStr(unsigned char sighash_type); std::string SighashToStr(unsigned char sighash_type);

View File

@ -14,7 +14,7 @@
/** /**
* Convert a span of bytes to a lower-case hexadecimal string. * Convert a span of bytes to a lower-case hexadecimal string.
*/ */
std::string HexStr(const Span<const uint8_t> s); std::string HexStr(Span<const uint8_t> s);
inline std::string HexStr(const Span<const char> s) { return HexStr(MakeUCharSpan(s)); } inline std::string HexStr(const Span<const char> s) { return HexStr(MakeUCharSpan(s)); }
inline std::string HexStr(const Span<const std::byte> s) { return HexStr(MakeUCharSpan(s)); } inline std::string HexStr(const Span<const std::byte> s) { return HexStr(MakeUCharSpan(s)); }

View File

@ -27,6 +27,6 @@ inline std::string DeploymentName(Consensus::DeploymentPos pos)
return VersionBitsDeploymentInfo[pos].name; return VersionBitsDeploymentInfo[pos].name;
} }
std::optional<Consensus::BuriedDeployment> GetBuriedDeployment(const std::string_view deployment_name); std::optional<Consensus::BuriedDeployment> GetBuriedDeployment(std::string_view deployment_name);
#endif // BITCOIN_DEPLOYMENTINFO_H #endif // BITCOIN_DEPLOYMENTINFO_H

View File

@ -15,14 +15,15 @@
#include <string> #include <string>
#include <vector> #include <vector>
ExternalSigner::ExternalSigner(const std::string& command, const std::string chain, const std::string& fingerprint, const std::string name): m_command(command), m_chain(chain), m_fingerprint(fingerprint), m_name(name) {} ExternalSigner::ExternalSigner(std::string command, std::string chain, std::string fingerprint, std::string name)
: m_command{std::move(command)}, m_chain{std::move(chain)}, m_fingerprint{std::move(fingerprint)}, m_name{std::move(name)} {}
std::string ExternalSigner::NetworkArg() const std::string ExternalSigner::NetworkArg() const
{ {
return " --chain " + m_chain; return " --chain " + m_chain;
} }
bool ExternalSigner::Enumerate(const std::string& command, std::vector<ExternalSigner>& signers, const std::string chain) bool ExternalSigner::Enumerate(const std::string& command, std::vector<ExternalSigner>& signers, const std::string& chain)
{ {
// Call <command> enumerate // Call <command> enumerate
const UniValue result = RunCommandParseJSON(command + " enumerate"); const UniValue result = RunCommandParseJSON(command + " enumerate");

View File

@ -31,7 +31,7 @@ public:
//! @param[in] fingerprint master key fingerprint of the signer //! @param[in] fingerprint master key fingerprint of the signer
//! @param[in] chain "main", "test", "regtest" or "signet" //! @param[in] chain "main", "test", "regtest" or "signet"
//! @param[in] name device name //! @param[in] name device name
ExternalSigner(const std::string& command, const std::string chain, const std::string& fingerprint, const std::string name); ExternalSigner(std::string command, std::string chain, std::string fingerprint, std::string name);
//! Master key fingerprint of the signer //! Master key fingerprint of the signer
std::string m_fingerprint; std::string m_fingerprint;
@ -44,7 +44,7 @@ public:
//! @param[in,out] signers vector to which new signers (with a unique master key fingerprint) are added //! @param[in,out] signers vector to which new signers (with a unique master key fingerprint) are added
//! @param chain "main", "test", "regtest" or "signet" //! @param chain "main", "test", "regtest" or "signet"
//! @returns success //! @returns success
static bool Enumerate(const std::string& command, std::vector<ExternalSigner>& signers, const std::string chain); static bool Enumerate(const std::string& command, std::vector<ExternalSigner>& signers, const std::string& chain);
//! Display address on the device. Calls `<command> displayaddress --desc <descriptor>`. //! Display address on the device. Calls `<command> displayaddress --desc <descriptor>`.
//! @param[in] descriptor Descriptor specifying which address to display. //! @param[in] descriptor Descriptor specifying which address to display.
@ -55,7 +55,7 @@ public:
//! Calls `<command> getdescriptors --account <account>` //! Calls `<command> getdescriptors --account <account>`
//! @param[in] account which BIP32 account to use (e.g. `m/44'/0'/account'`) //! @param[in] account which BIP32 account to use (e.g. `m/44'/0'/account'`)
//! @returns see doc/external-signer.md //! @returns see doc/external-signer.md
UniValue GetDescriptors(const int account); UniValue GetDescriptors(int account);
//! Sign PartiallySignedTransaction on the device. //! Sign PartiallySignedTransaction on the device.
//! Calls `<command> signtransaction` and passes the PSBT via stdin. //! Calls `<command> signtransaction` and passes the PSBT via stdin.

View File

@ -96,7 +96,7 @@ public:
virtual std::string getWalletName() = 0; virtual std::string getWalletName() = 0;
// Get a new address. // Get a new address.
virtual util::Result<CTxDestination> getNewDestination(const OutputType type, const std::string& label) = 0; virtual util::Result<CTxDestination> getNewDestination(OutputType type, const std::string& label) = 0;
//! Get public key. //! Get public key.
virtual bool getPubKey(const CScript& script, const CKeyID& address, CPubKey& pub_key) = 0; virtual bool getPubKey(const CScript& script, const CKeyID& address, CPubKey& pub_key) = 0;
@ -135,7 +135,7 @@ public:
virtual util::Result<void> displayAddress(const CTxDestination& dest) = 0; virtual util::Result<void> displayAddress(const CTxDestination& dest) = 0;
//! Lock coin. //! Lock coin.
virtual bool lockCoin(const COutPoint& output, const bool write_to_db) = 0; virtual bool lockCoin(const COutPoint& output, bool write_to_db) = 0;
//! Unlock coin. //! Unlock coin.
virtual bool unlockCoin(const COutPoint& output) = 0; virtual bool unlockCoin(const COutPoint& output) = 0;

View File

@ -414,7 +414,7 @@ private:
size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0}; size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
public: public:
explicit V1Transport(const NodeId node_id) noexcept; explicit V1Transport(NodeId node_id) noexcept;
bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex) bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
{ {
@ -1175,7 +1175,7 @@ public:
* @param[in] network Select only addresses of this network (nullopt = all). * @param[in] network Select only addresses of this network (nullopt = all).
* @param[in] filtered Select only addresses that are considered high quality (false = all). * @param[in] filtered Select only addresses that are considered high quality (false = all).
*/ */
std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered = true) const; std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network, bool filtered = true) const;
/** /**
* Cache is used to minimize topology leaks, so it should * Cache is used to minimize topology leaks, so it should
* be used for all non-trusted calls, for example, p2p. * be used for all non-trusted calls, for example, p2p.

View File

@ -514,7 +514,7 @@ public:
}; };
void UnitTestMisbehaving(NodeId peer_id) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex) { Misbehaving(*Assert(GetPeerRef(peer_id)), ""); }; void UnitTestMisbehaving(NodeId peer_id) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex) { Misbehaving(*Assert(GetPeerRef(peer_id)), ""); };
void ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv, void ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv,
const std::chrono::microseconds time_received, const std::atomic<bool>& interruptMsgProc) override std::chrono::microseconds time_received, const std::atomic<bool>& interruptMsgProc) override
EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex, g_msgproc_mutex, !m_tx_download_mutex); EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex, g_msgproc_mutex, !m_tx_download_mutex);
void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) override; void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) override;
ServiceFlags GetDesirableServiceFlags(ServiceFlags services) const override; ServiceFlags GetDesirableServiceFlags(ServiceFlags services) const override;

View File

@ -125,7 +125,7 @@ public:
/** Process a single message from a peer. Public for fuzz testing */ /** Process a single message from a peer. Public for fuzz testing */
virtual void ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv, virtual void ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv,
const std::chrono::microseconds time_received, const std::atomic<bool>& interruptMsgProc) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0; std::chrono::microseconds time_received, const std::atomic<bool>& interruptMsgProc) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
/** This function is used for testing the stale tip eviction logic, see denialofservice_tests.cpp */ /** This function is used for testing the stale tip eviction logic, see denialofservice_tests.cpp */
virtual void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) = 0; virtual void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) = 0;

View File

@ -205,7 +205,7 @@ public:
std::vector<unsigned char> GetAddrBytes() const; std::vector<unsigned char> GetAddrBytes() const;
int GetReachabilityFrom(const CNetAddr& paddrPartner) const; int GetReachabilityFrom(const CNetAddr& paddrPartner) const;
explicit CNetAddr(const struct in6_addr& pipv6Addr, const uint32_t scope = 0); explicit CNetAddr(const struct in6_addr& pipv6Addr, uint32_t scope = 0);
bool GetIn6Addr(struct in6_addr* pipv6Addr) const; bool GetIn6Addr(struct in6_addr* pipv6Addr) const;
friend bool operator==(const CNetAddr& a, const CNetAddr& b); friend bool operator==(const CNetAddr& a, const CNetAddr& b);

View File

@ -316,7 +316,7 @@ public:
CBlockIndex* InsertBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); CBlockIndex* InsertBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
//! Mark one block file as pruned (modify associated database entries) //! Mark one block file as pruned (modify associated database entries)
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main); void PruneOneBlockFile(int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
CBlockIndex* LookupBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); CBlockIndex* LookupBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
const CBlockIndex* LookupBlockIndex(const uint256& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main); const CBlockIndex* LookupBlockIndex(const uint256& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);

View File

@ -63,7 +63,7 @@ static const CAmount DEFAULT_MAX_BURN_AMOUNT{0};
* @param[out] hashBlock The block hash, if the tx was found via -txindex or block_index * @param[out] hashBlock The block hash, if the tx was found via -txindex or block_index
* @returns The tx if found, otherwise nullptr * @returns The tx if found, otherwise nullptr
*/ */
CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const uint256& hash, uint256& hashBlock, const BlockManager& blockman); CTransactionRef GetTransaction(const CBlockIndex* block_index, const CTxMemPool* mempool, const uint256& hash, uint256& hashBlock, const BlockManager& blockman);
} // namespace node } // namespace node
#endif // BITCOIN_NODE_TRANSACTION_H #endif // BITCOIN_NODE_TRANSACTION_H

View File

@ -199,7 +199,7 @@ private:
const fs::path m_estimation_filepath; const fs::path m_estimation_filepath;
public: public:
/** Create new BlockPolicyEstimator and initialize stats tracking classes with default values */ /** Create new BlockPolicyEstimator and initialize stats tracking classes with default values */
CBlockPolicyEstimator(const fs::path& estimation_filepath, const bool read_stale_estimates); CBlockPolicyEstimator(const fs::path& estimation_filepath, bool read_stale_estimates);
virtual ~CBlockPolicyEstimator(); virtual ~CBlockPolicyEstimator();
/** Process all the transactions that have been included in a block */ /** Process all the transactions that have been included in a block */

View File

@ -295,7 +295,7 @@ bool PSBTInputSigned(const PSBTInput& input)
return !input.final_script_sig.empty() || !input.final_script_witness.IsNull(); return !input.final_script_sig.empty() || !input.final_script_witness.IsNull();
} }
bool PSBTInputSignedAndVerified(const PartiallySignedTransaction psbt, unsigned int input_index, const PrecomputedTransactionData* txdata) bool PSBTInputSignedAndVerified(const PartiallySignedTransaction& psbt, unsigned int input_index, const PrecomputedTransactionData* txdata)
{ {
CTxOut utxo; CTxOut utxo;
assert(psbt.inputs.size() >= input_index); assert(psbt.inputs.size() >= input_index);

View File

@ -1229,7 +1229,7 @@ PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction&
bool PSBTInputSigned(const PSBTInput& input); bool PSBTInputSigned(const PSBTInput& input);
/** Checks whether a PSBTInput is already signed by doing script verification using final fields. */ /** Checks whether a PSBTInput is already signed by doing script verification using final fields. */
bool PSBTInputSignedAndVerified(const PartiallySignedTransaction psbt, unsigned int input_index, const PrecomputedTransactionData* txdata); bool PSBTInputSignedAndVerified(const PartiallySignedTransaction& psbt, unsigned int input_index, const PrecomputedTransactionData* txdata);
/** Signs a PSBTInput, verifying that all provided data matches what is being signed. /** Signs a PSBTInput, verifying that all provided data matches what is being signed.
* *

View File

@ -70,7 +70,7 @@ public:
/* Add an address to the model. /* Add an address to the model.
Returns the added address on success, and an empty string otherwise. Returns the added address on success, and an empty string otherwise.
*/ */
QString addRow(const QString &type, const QString &label, const QString &address, const OutputType address_type); QString addRow(const QString& type, const QString& label, const QString& address, OutputType address_type);
/** Look up label for address in address book, if not found return empty string. */ /** Look up label for address in address book, if not found return empty string. */
QString labelForAddress(const QString &address) const; QString labelForAddress(const QString &address) const;

View File

@ -16,7 +16,7 @@ class NetworkStyle
{ {
public: public:
/** Get style associated with provided network id, or 0 if not known */ /** Get style associated with provided network id, or 0 if not known */
static const NetworkStyle* instantiate(const ChainType networkId); static const NetworkStyle* instantiate(ChainType networkId);
const QString &getAppName() const { return appName; } const QString &getAppName() const { return appName; }
const QIcon &getAppIcon() const { return appIcon; } const QIcon &getAppIcon() const { return appIcon; }
@ -24,7 +24,7 @@ public:
const QString &getTitleAddText() const { return titleAddText; } const QString &getTitleAddText() const { return titleAddText; }
private: private:
NetworkStyle(const QString &appName, const int iconColorHueShift, const int iconColorSaturationReduction, const char *titleAddText); NetworkStyle(const QString& appName, int iconColorHueShift, int iconColorSaturationReduction, const char* titleAddText);
QString appName; QString appName;
QIcon appIcon; QIcon appIcon;

View File

@ -46,7 +46,7 @@ public:
explicit RPCConsole(interfaces::Node& node, const PlatformStyle *platformStyle, QWidget *parent); explicit RPCConsole(interfaces::Node& node, const PlatformStyle *platformStyle, QWidget *parent);
~RPCConsole(); ~RPCConsole();
static bool RPCParseCommandLine(interfaces::Node* node, std::string &strResult, const std::string &strCommand, bool fExecute, std::string * const pstrFilteredOut = nullptr, const WalletModel* wallet_model = nullptr); static bool RPCParseCommandLine(interfaces::Node* node, std::string& strResult, const std::string& strCommand, bool fExecute, std::string* pstrFilteredOut = nullptr, const WalletModel* wallet_model = nullptr);
static bool RPCExecuteCommandLine(interfaces::Node& node, std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = nullptr, const WalletModel* wallet_model = nullptr) { static bool RPCExecuteCommandLine(interfaces::Node& node, std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = nullptr, const WalletModel* wallet_model = nullptr) {
return RPCParseCommandLine(&node, strResult, strCommand, true, pstrFilteredOut, wallet_model); return RPCParseCommandLine(&node, strResult, strCommand, true, pstrFilteredOut, wallet_model);
} }
@ -54,8 +54,8 @@ public:
void setClientModel(ClientModel *model = nullptr, int bestblock_height = 0, int64_t bestblock_date = 0, double verification_progress = 0.0); void setClientModel(ClientModel *model = nullptr, int bestblock_height = 0, int64_t bestblock_date = 0, double verification_progress = 0.0);
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
void addWallet(WalletModel* const walletModel); void addWallet(WalletModel* walletModel);
void removeWallet(WalletModel* const walletModel); void removeWallet(WalletModel* walletModel);
#endif // ENABLE_WALLET #endif // ENABLE_WALLET
enum MessageClass { enum MessageClass {
@ -136,7 +136,7 @@ public Q_SLOTS:
void setTabFocus(enum TabTypes tabType); void setTabFocus(enum TabTypes tabType);
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
/** Set the current (ie - active) wallet */ /** Set the current (ie - active) wallet */
void setCurrentWallet(WalletModel* const wallet_model); void setCurrentWallet(WalletModel* wallet_model);
#endif // ENABLE_WALLET #endif // ENABLE_WALLET
private: private:

View File

@ -95,7 +95,7 @@ void RandAddPeriodic() noexcept;
* *
* Thread-safe. * Thread-safe.
*/ */
void RandAddEvent(const uint32_t event_info) noexcept; void RandAddEvent(uint32_t event_info) noexcept;
/* =========================== BASE RANDOMNESS GENERATION FUNCTIONS =========================== /* =========================== BASE RANDOMNESS GENERATION FUNCTIONS ===========================

View File

@ -133,7 +133,7 @@ std::string HelpExampleRpcNamed(const std::string& methodname, const RPCArgList&
CPubKey HexToPubKey(const std::string& hex_in); CPubKey HexToPubKey(const std::string& hex_in);
CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in); CPubKey AddrToPubKey(const FillableSigningProvider& keystore, const std::string& addr_in);
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector<CPubKey>& pubkeys, OutputType type, FlatSigningProvider& keystore, CScript& script_out); CTxDestination AddAndGetMultisigDestination(int required, const std::vector<CPubKey>& pubkeys, OutputType type, FlatSigningProvider& keystore, CScript& script_out);
UniValue DescribeAddress(const CTxDestination& dest); UniValue DescribeAddress(const CTxDestination& dest);
@ -151,7 +151,7 @@ UniValue JSONRPCTransactionError(node::TransactionError terr, const std::string&
std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value); std::pair<int64_t, int64_t> ParseDescriptorRange(const UniValue& value);
/** Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range of 1000. */ /** Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range of 1000. */
std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, const bool expand_priv = false); std::vector<CScript> EvalDescriptorStringOrObject(const UniValue& scanobject, FlatSigningProvider& provider, bool expand_priv = false);
/** /**
* Serializing JSON objects depends on the outer type. Only arrays and * Serializing JSON objects depends on the outer type. Only arrays and
@ -369,7 +369,7 @@ struct RPCResult {
: RPCResult{type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), skip_type_check} {} : RPCResult{type, std::move(m_key_name), /*optional=*/false, std::move(description), std::move(inner), skip_type_check} {}
/** Append the sections of the result. */ /** Append the sections of the result. */
void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, const int current_indent = 0) const; void ToSections(Sections& sections, OuterType outer_type = OuterType::NONE, int current_indent = 0) const;
/** Return the type string of the result when it is in an object (dict). */ /** Return the type string of the result when it is in an object (dict). */
std::string ToStringObj() const; std::string ToStringObj() const;
/** Return the description string, including the result type. */ /** Return the description string, including the result type. */

View File

@ -1744,7 +1744,7 @@ enum class ParseContext {
CLOSE_BRACKET, CLOSE_BRACKET,
}; };
int FindNextChar(Span<const char> in, const char m); int FindNextChar(Span<const char> in, char m);
/** Parse a key string ending at the end of the fragment's text representation. */ /** Parse a key string ending at the end of the fragment's text representation. */
template<typename Key, typename Ctx> template<typename Key, typename Ctx>

View File

@ -87,6 +87,6 @@ typedef enum ScriptError_t
#define SCRIPT_ERR_LAST SCRIPT_ERR_ERROR_COUNT #define SCRIPT_ERR_LAST SCRIPT_ERR_ERROR_COUNT
std::string ScriptErrorString(const ScriptError error); std::string ScriptErrorString(ScriptError error);
#endif // BITCOIN_SCRIPT_SCRIPT_ERROR_H #endif // BITCOIN_SCRIPT_SCRIPT_ERROR_H

View File

@ -55,7 +55,7 @@ public:
void ComputeEntrySchnorr(uint256& entry, const uint256 &hash, Span<const unsigned char> sig, const XOnlyPubKey& pubkey) const; void ComputeEntrySchnorr(uint256& entry, const uint256 &hash, Span<const unsigned char> sig, const XOnlyPubKey& pubkey) const;
bool Get(const uint256& entry, const bool erase); bool Get(const uint256& entry, bool erase);
void Set(const uint256& entry); void Set(const uint256& entry);
}; };

View File

@ -146,11 +146,11 @@ template <typename WeakEnumType, size_t size>
[[nodiscard]] int64_t ConsumeTime(FuzzedDataProvider& fuzzed_data_provider, const std::optional<int64_t>& min = std::nullopt, const std::optional<int64_t>& max = std::nullopt) noexcept; [[nodiscard]] int64_t ConsumeTime(FuzzedDataProvider& fuzzed_data_provider, const std::optional<int64_t>& min = std::nullopt, const std::optional<int64_t>& max = std::nullopt) noexcept;
[[nodiscard]] CMutableTransaction ConsumeTransaction(FuzzedDataProvider& fuzzed_data_provider, const std::optional<std::vector<Txid>>& prevout_txids, const int max_num_in = 10, const int max_num_out = 10) noexcept; [[nodiscard]] CMutableTransaction ConsumeTransaction(FuzzedDataProvider& fuzzed_data_provider, const std::optional<std::vector<Txid>>& prevout_txids, int max_num_in = 10, int max_num_out = 10) noexcept;
[[nodiscard]] CScriptWitness ConsumeScriptWitness(FuzzedDataProvider& fuzzed_data_provider, const size_t max_stack_elem_size = 32) noexcept; [[nodiscard]] CScriptWitness ConsumeScriptWitness(FuzzedDataProvider& fuzzed_data_provider, size_t max_stack_elem_size = 32) noexcept;
[[nodiscard]] CScript ConsumeScript(FuzzedDataProvider& fuzzed_data_provider, const bool maybe_p2wsh = false) noexcept; [[nodiscard]] CScript ConsumeScript(FuzzedDataProvider& fuzzed_data_provider, bool maybe_p2wsh = false) noexcept;
[[nodiscard]] uint32_t ConsumeSequence(FuzzedDataProvider& fuzzed_data_provider) noexcept; [[nodiscard]] uint32_t ConsumeSequence(FuzzedDataProvider& fuzzed_data_provider) noexcept;

View File

@ -53,7 +53,7 @@ constexpr int MAX_DEPTH{2};
* Whether the buffer, if it represents a valid descriptor, contains a derivation path deeper than * Whether the buffer, if it represents a valid descriptor, contains a derivation path deeper than
* a given maximum depth. Note this may also be hit for deriv paths in origins. * a given maximum depth. Note this may also be hit for deriv paths in origins.
*/ */
bool HasDeepDerivPath(const FuzzBufferType& buff, const int max_depth = MAX_DEPTH); bool HasDeepDerivPath(const FuzzBufferType& buff, int max_depth = MAX_DEPTH);
//! Default maximum number of sub-fragments. //! Default maximum number of sub-fragments.
constexpr int MAX_SUBS{1'000}; constexpr int MAX_SUBS{1'000};
@ -64,8 +64,8 @@ constexpr size_t MAX_NESTED_SUBS{10'000};
* Whether the buffer, if it represents a valid descriptor, contains a fragment with more * Whether the buffer, if it represents a valid descriptor, contains a fragment with more
* sub-fragments than the given maximum. * sub-fragments than the given maximum.
*/ */
bool HasTooManySubFrag(const FuzzBufferType& buff, const int max_subs = MAX_SUBS, bool HasTooManySubFrag(const FuzzBufferType& buff, int max_subs = MAX_SUBS,
const size_t max_nested_subs = MAX_NESTED_SUBS); size_t max_nested_subs = MAX_NESTED_SUBS);
//! Default maximum number of wrappers per fragment. //! Default maximum number of wrappers per fragment.
constexpr int MAX_WRAPPERS{100}; constexpr int MAX_WRAPPERS{100};
@ -74,6 +74,6 @@ constexpr int MAX_WRAPPERS{100};
* Whether the buffer, if it represents a valid descriptor, contains a fragment with more * Whether the buffer, if it represents a valid descriptor, contains a fragment with more
* wrappers than the given maximum. * wrappers than the given maximum.
*/ */
bool HasTooManyWrappers(const FuzzBufferType& buff, const int max_wrappers = MAX_WRAPPERS); bool HasTooManyWrappers(const FuzzBufferType& buff, int max_wrappers = MAX_WRAPPERS);
#endif // BITCOIN_TEST_FUZZ_UTIL_DESCRIPTOR_H #endif // BITCOIN_TEST_FUZZ_UTIL_DESCRIPTOR_H

View File

@ -22,8 +22,8 @@ struct HeadersGeneratorSetup : public RegTestingSetup {
* prev_time, and with a fixed merkle root hash. * prev_time, and with a fixed merkle root hash.
*/ */
void GenerateHeaders(std::vector<CBlockHeader>& headers, size_t count, void GenerateHeaders(std::vector<CBlockHeader>& headers, size_t count,
const uint256& starting_hash, const int nVersion, int prev_time, const uint256& starting_hash, int nVersion, int prev_time,
const uint256& merkle_root, const uint32_t nBits); const uint256& merkle_root, uint32_t nBits);
}; };
void HeadersGeneratorSetup::FindProofOfWork(CBlockHeader& starting_header) void HeadersGeneratorSetup::FindProofOfWork(CBlockHeader& starting_header)

View File

@ -73,7 +73,7 @@ struct BasicTestingSetup {
m_rng.Reseed(GetRandHash()); m_rng.Reseed(GetRandHash());
} }
explicit BasicTestingSetup(const ChainType chainType = ChainType::MAIN, TestOpts = {}); explicit BasicTestingSetup(ChainType chainType = ChainType::MAIN, TestOpts = {});
~BasicTestingSetup(); ~BasicTestingSetup();
fs::path m_path_root; fs::path m_path_root;
@ -109,7 +109,7 @@ struct ChainTestingSetup : public BasicTestingSetup {
bool m_block_tree_db_in_memory{true}; bool m_block_tree_db_in_memory{true};
std::function<void()> m_make_chainman{}; std::function<void()> m_make_chainman{};
explicit ChainTestingSetup(const ChainType chainType = ChainType::MAIN, TestOpts = {}); explicit ChainTestingSetup(ChainType chainType = ChainType::MAIN, TestOpts = {});
~ChainTestingSetup(); ~ChainTestingSetup();
// Supplies a chainstate, if one is needed // Supplies a chainstate, if one is needed
@ -120,7 +120,7 @@ struct ChainTestingSetup : public BasicTestingSetup {
*/ */
struct TestingSetup : public ChainTestingSetup { struct TestingSetup : public ChainTestingSetup {
explicit TestingSetup( explicit TestingSetup(
const ChainType chainType = ChainType::MAIN, ChainType chainType = ChainType::MAIN,
TestOpts = {}); TestOpts = {});
}; };
@ -145,7 +145,7 @@ class CScript;
*/ */
struct TestChain100Setup : public TestingSetup { struct TestChain100Setup : public TestingSetup {
TestChain100Setup( TestChain100Setup(
const ChainType chain_type = ChainType::REGTEST, ChainType chain_type = ChainType::REGTEST,
TestOpts = {}); TestOpts = {});
/** /**

View File

@ -27,7 +27,7 @@ struct MinerTestingSetup : public RegTestingSetup {
std::shared_ptr<const CBlock> GoodBlock(const uint256& prev_hash); std::shared_ptr<const CBlock> GoodBlock(const uint256& prev_hash);
std::shared_ptr<const CBlock> BadBlock(const uint256& prev_hash); std::shared_ptr<const CBlock> BadBlock(const uint256& prev_hash);
std::shared_ptr<CBlock> FinalizeBlock(std::shared_ptr<CBlock> pblock); std::shared_ptr<CBlock> FinalizeBlock(std::shared_ptr<CBlock> pblock);
void BuildChain(const uint256& root, int height, const unsigned int invalid_rate, const unsigned int branch_rate, const unsigned int max_size, std::vector<std::shared_ptr<const CBlock>>& blocks); void BuildChain(const uint256& root, int height, unsigned int invalid_rate, unsigned int branch_rate, unsigned int max_size, std::vector<std::shared_ptr<const CBlock>>& blocks);
}; };
} // namespace validation_block_tests } // namespace validation_block_tests

View File

@ -681,7 +681,7 @@ public:
}; };
/** Removes a transaction from the unbroadcast set */ /** Removes a transaction from the unbroadcast set */
void RemoveUnbroadcastTx(const uint256& txid, const bool unchecked = false); void RemoveUnbroadcastTx(const uint256& txid, bool unchecked = false);
/** Returns transactions in unbroadcast set */ /** Returns transactions in unbroadcast set */
std::set<uint256> GetUnbroadcastTxs() const std::set<uint256> GetUnbroadcastTxs() const
@ -829,7 +829,7 @@ public:
using TxHandle = CTxMemPool::txiter; using TxHandle = CTxMemPool::txiter;
TxHandle StageAddition(const CTransactionRef& tx, const CAmount fee, int64_t time, unsigned int entry_height, uint64_t entry_sequence, bool spends_coinbase, int64_t sigops_cost, LockPoints lp); TxHandle StageAddition(const CTransactionRef& tx, CAmount fee, int64_t time, unsigned int entry_height, uint64_t entry_sequence, bool spends_coinbase, int64_t sigops_cost, LockPoints lp);
void StageRemoval(CTxMemPool::txiter it) { m_to_remove.insert(it); } void StageRemoval(CTxMemPool::txiter it) { m_to_remove.insert(it); }
const CTxMemPool::setEntries& GetRemovals() const { return m_to_remove; } const CTxMemPool::setEntries& GetRemovals() const { return m_to_remove; }

View File

@ -17,7 +17,7 @@
/* Do not use these functions to represent or parse monetary amounts to or from /* Do not use these functions to represent or parse monetary amounts to or from
* JSON but use AmountFromValue and ValueFromAmount for that. * JSON but use AmountFromValue and ValueFromAmount for that.
*/ */
std::string FormatMoney(const CAmount n); std::string FormatMoney(CAmount n);
/** Parse an amount denoted in full coins. E.g. "0.0034" supplied on the command line. **/ /** Parse an amount denoted in full coins. E.g. "0.0034" supplied on the command line. **/
std::optional<CAmount> ParseMoney(const std::string& str); std::optional<CAmount> ParseMoney(const std::string& str);

View File

@ -194,7 +194,7 @@ protected:
BerkeleyDatabase& m_database; BerkeleyDatabase& m_database;
public: public:
explicit BerkeleyBatch(BerkeleyDatabase& database, const bool fReadOnly, bool fFlushOnCloseIn=true); explicit BerkeleyBatch(BerkeleyDatabase& database, bool fReadOnly, bool fFlushOnCloseIn = true);
~BerkeleyBatch() override; ~BerkeleyBatch() override;
BerkeleyBatch(const BerkeleyBatch&) = delete; BerkeleyBatch(const BerkeleyBatch&) = delete;

View File

@ -308,7 +308,7 @@ typedef std::map<CoinEligibilityFilter, OutputGroupTypeMap> FilteredOutputGroups
* @param[in] payment_value Average payment value of the transaction output(s). * @param[in] payment_value Average payment value of the transaction output(s).
* @param[in] change_fee Fee for creating a change output. * @param[in] change_fee Fee for creating a change output.
*/ */
[[nodiscard]] CAmount GenerateChangeTarget(const CAmount payment_value, const CAmount change_fee, FastRandomContext& rng); [[nodiscard]] CAmount GenerateChangeTarget(CAmount payment_value, CAmount change_fee, FastRandomContext& rng);
enum class SelectionAlgorithm : uint8_t enum class SelectionAlgorithm : uint8_t
{ {
@ -319,7 +319,7 @@ enum class SelectionAlgorithm : uint8_t
MANUAL = 4, MANUAL = 4,
}; };
std::string GetAlgorithmName(const SelectionAlgorithm algo); std::string GetAlgorithmName(SelectionAlgorithm algo);
struct SelectionResult struct SelectionResult
{ {
@ -373,7 +373,7 @@ public:
void AddInputs(const std::set<std::shared_ptr<COutput>>& inputs, bool subtract_fee_outputs); void AddInputs(const std::set<std::shared_ptr<COutput>>& inputs, bool subtract_fee_outputs);
/** How much individual inputs overestimated the bump fees for shared ancestries */ /** How much individual inputs overestimated the bump fees for shared ancestries */
void SetBumpFeeDiscount(const CAmount discount); void SetBumpFeeDiscount(CAmount discount);
/** Calculates and stores the waste for this result given the cost of change /** Calculates and stores the waste for this result given the cost of change
* and the opportunity cost of spending these inputs now vs in the future. * and the opportunity cost of spending these inputs now vs in the future.
@ -387,7 +387,7 @@ public:
* used if there is change, in which case it must be non-negative. * used if there is change, in which case it must be non-negative.
* @param[in] change_fee The fee for creating a change output * @param[in] change_fee The fee for creating a change output
*/ */
void RecalculateWaste(const CAmount min_viable_change, const CAmount change_cost, const CAmount change_fee); void RecalculateWaste(CAmount min_viable_change, CAmount change_cost, CAmount change_fee);
[[nodiscard]] CAmount GetWaste() const; [[nodiscard]] CAmount GetWaste() const;
/** Tracks that algorithm was able to exhaustively search the entire combination space before hitting limit of tries */ /** Tracks that algorithm was able to exhaustively search the entire combination space before hitting limit of tries */
@ -434,7 +434,7 @@ public:
* @returns Amount for change output, 0 when there is no change. * @returns Amount for change output, 0 when there is no change.
* *
*/ */
CAmount GetChange(const CAmount min_viable_change, const CAmount change_fee) const; CAmount GetChange(CAmount min_viable_change, CAmount change_fee) const;
CAmount GetTarget() const { return m_target; } CAmount GetTarget() const { return m_target; }

View File

@ -78,7 +78,7 @@ private:
int BytesToKeySHA512AES(std::span<const unsigned char> salt, const SecureString& key_data, int count, unsigned char* key, unsigned char* iv) const; int BytesToKeySHA512AES(std::span<const unsigned char> salt, const SecureString& key_data, int count, unsigned char* key, unsigned char* iv) const;
public: public:
bool SetKeyFromPassphrase(const SecureString& key_data, std::span<const unsigned char> salt, const unsigned int rounds, const unsigned int derivation_method); bool SetKeyFromPassphrase(const SecureString& key_data, std::span<const unsigned char> salt, unsigned int rounds, unsigned int derivation_method);
bool Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext) const; bool Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext) const;
bool Decrypt(std::span<const unsigned char> ciphertext, CKeyingMaterial& plaintext) const; bool Decrypt(std::span<const unsigned char> ciphertext, CKeyingMaterial& plaintext) const;
bool SetKey(const CKeyingMaterial& new_key, std::span<const unsigned char> new_iv); bool SetKey(const CKeyingMaterial& new_key, std::span<const unsigned char> new_iv);

View File

@ -136,7 +136,7 @@ void PushParentDescriptors(const CWallet& wallet, const CScript& script_pubkey,
entry.pushKV("parent_descs", std::move(parent_descs)); entry.pushKV("parent_descs", std::move(parent_descs));
} }
void HandleWalletError(const std::shared_ptr<CWallet> wallet, DatabaseStatus& status, bilingual_str& error) void HandleWalletError(const std::shared_ptr<CWallet>& wallet, DatabaseStatus& status, bilingual_str& error)
{ {
if (!wallet) { if (!wallet) {
// Map bad format to not found, since bad format is returned when the // Map bad format to not found, since bad format is returned when the

View File

@ -50,7 +50,7 @@ std::string LabelFromValue(const UniValue& value);
//! Fetch parent descriptors of this scriptPubKey. //! Fetch parent descriptors of this scriptPubKey.
void PushParentDescriptors(const CWallet& wallet, const CScript& script_pubkey, UniValue& entry); void PushParentDescriptors(const CWallet& wallet, const CScript& script_pubkey, UniValue& entry);
void HandleWalletError(const std::shared_ptr<CWallet> wallet, DatabaseStatus& status, bilingual_str& error); void HandleWalletError(const std::shared_ptr<CWallet>& wallet, DatabaseStatus& status, bilingual_str& error);
void AppendLastProcessedBlock(UniValue& entry, const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet); void AppendLastProcessedBlock(UniValue& entry, const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet);
} // namespace wallet } // namespace wallet

View File

@ -323,7 +323,7 @@ util::Result<CTxDestination> LegacyScriptPubKeyMan::GetReservedDestination(const
return GetDestinationForKey(keypool.vchPubKey, type); return GetDestinationForKey(keypool.vchPubKey, type);
} }
bool LegacyScriptPubKeyMan::TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal) bool LegacyScriptPubKeyMan::TopUpInactiveHDChain(const CKeyID& seed_id, int64_t index, bool internal)
{ {
LOCK(cs_KeyStore); LOCK(cs_KeyStore);
@ -1601,7 +1601,7 @@ bool LegacyScriptPubKeyMan::AddKeyOriginWithDB(WalletBatch& batch, const CPubKey
return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true); return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
} }
bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts, int64_t timestamp) bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript>& scripts, int64_t timestamp)
{ {
WalletBatch batch(m_storage.GetDatabase()); WalletBatch batch(m_storage.GetDatabase());
for (const auto& entry : scripts) { for (const auto& entry : scripts) {

View File

@ -408,7 +408,7 @@ private:
//! Adds a key to the store, and saves it to disk. //! Adds a key to the store, and saves it to disk.
bool AddKeyPubKeyWithDB(WalletBatch &batch,const CKey& key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore); bool AddKeyPubKeyWithDB(WalletBatch &batch,const CKey& key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
void AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch); void AddKeypoolPubkeyWithDB(const CPubKey& pubkey, bool internal, WalletBatch& batch);
//! Adds a script to the store and saves it to disk //! Adds a script to the store and saves it to disk
bool AddCScriptWithDB(WalletBatch& batch, const CScript& script); bool AddCScriptWithDB(WalletBatch& batch, const CScript& script);
@ -423,7 +423,7 @@ private:
std::map<int64_t, CKeyID> m_index_to_reserved_key; std::map<int64_t, CKeyID> m_index_to_reserved_key;
//! Fetches a key from the keypool //! Fetches a key from the keypool
bool GetKeyFromPool(CPubKey &key, const OutputType type); bool GetKeyFromPool(CPubKey& key, OutputType type);
/** /**
* Reserves a key from the keypool and sets nIndex to its index * Reserves a key from the keypool and sets nIndex to its index
@ -451,17 +451,17 @@ private:
* *
* @return true if seed was found and keys were derived. false if unable to derive seeds * @return true if seed was found and keys were derived. false if unable to derive seeds
*/ */
bool TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal); bool TopUpInactiveHDChain(const CKeyID& seed_id, int64_t index, bool internal);
bool TopUpChain(WalletBatch& batch, CHDChain& chain, unsigned int size); bool TopUpChain(WalletBatch& batch, CHDChain& chain, unsigned int size);
public: public:
LegacyScriptPubKeyMan(WalletStorage& storage, int64_t keypool_size) : LegacyDataSPKM(storage), m_keypool_size(keypool_size) {} LegacyScriptPubKeyMan(WalletStorage& storage, int64_t keypool_size) : LegacyDataSPKM(storage), m_keypool_size(keypool_size) {}
util::Result<CTxDestination> GetNewDestination(const OutputType type) override; util::Result<CTxDestination> GetNewDestination(OutputType type) override;
bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) override; bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) override;
util::Result<CTxDestination> GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool) override; util::Result<CTxDestination> GetReservedDestination(OutputType type, bool internal, int64_t& index, CKeyPool& keypool) override;
void KeepDestination(int64_t index, const OutputType& type) override; void KeepDestination(int64_t index, const OutputType& type) override;
void ReturnDestination(int64_t index, bool internal, const CTxDestination&) override; void ReturnDestination(int64_t index, bool internal, const CTxDestination&) override;
@ -523,10 +523,10 @@ public:
bool NewKeyPool(); bool NewKeyPool();
void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore); void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore); bool ImportScripts(const std::set<CScript>& scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore); bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
bool ImportPubKeys(const std::vector<std::pair<CKeyID, bool>>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore); bool ImportPubKeys(const std::vector<std::pair<CKeyID, bool>>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, bool add_keypool, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
bool ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore); bool ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, bool have_solving_data, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
/* Returns true if the wallet can generate new keys */ /* Returns true if the wallet can generate new keys */
bool CanGenerateKeys() const; bool CanGenerateKeys() const;
@ -638,13 +638,13 @@ public:
mutable RecursiveMutex cs_desc_man; mutable RecursiveMutex cs_desc_man;
util::Result<CTxDestination> GetNewDestination(const OutputType type) override; util::Result<CTxDestination> GetNewDestination(OutputType type) override;
isminetype IsMine(const CScript& script) const override; isminetype IsMine(const CScript& script) const override;
bool CheckDecryptionKey(const CKeyingMaterial& master_key) override; bool CheckDecryptionKey(const CKeyingMaterial& master_key) override;
bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) override; bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) override;
util::Result<CTxDestination> GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool) override; util::Result<CTxDestination> GetReservedDestination(OutputType type, bool internal, int64_t& index, CKeyPool& keypool) override;
void ReturnDestination(int64_t index, bool internal, const CTxDestination& addr) override; void ReturnDestination(int64_t index, bool internal, const CTxDestination& addr) override;
// Tops up the descriptor cache and m_map_script_pub_keys. The cache is stored in the wallet file // Tops up the descriptor cache and m_map_script_pub_keys. The cache is stored in the wallet file
@ -704,7 +704,7 @@ public:
std::unordered_set<CScript, SaltedSipHasher> GetScriptPubKeys(int32_t minimum_index) const; std::unordered_set<CScript, SaltedSipHasher> GetScriptPubKeys(int32_t minimum_index) const;
int32_t GetEndRange() const; int32_t GetEndRange() const;
[[nodiscard]] bool GetDescriptorString(std::string& out, const bool priv) const; [[nodiscard]] bool GetDescriptorString(std::string& out, bool priv) const;
void UpgradeDescriptorCache(); void UpgradeDescriptorCache();
}; };

View File

@ -18,7 +18,7 @@ namespace wallet {
/** Get the marginal bytes if spending the specified output from this transaction. /** Get the marginal bytes if spending the specified output from this transaction.
* Use CoinControl to determine whether to expect signature grinding when calculating the size of the input spend. */ * Use CoinControl to determine whether to expect signature grinding when calculating the size of the input spend. */
int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* pwallet, const CCoinControl* coin_control); int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* pwallet, const CCoinControl* coin_control);
int CalculateMaximumSignedInputSize(const CTxOut& txout, const COutPoint outpoint, const SigningProvider* pwallet, bool can_grind_r, const CCoinControl* coin_control); int CalculateMaximumSignedInputSize(const CTxOut& txout, COutPoint outpoint, const SigningProvider* pwallet, bool can_grind_r, const CCoinControl* coin_control);
struct TxSize { struct TxSize {
int64_t vsize{-1}; int64_t vsize{-1};
int64_t weight{-1}; int64_t weight{-1};

View File

@ -14,7 +14,7 @@
namespace wallet { namespace wallet {
struct InitWalletDirTestingSetup: public BasicTestingSetup { struct InitWalletDirTestingSetup: public BasicTestingSetup {
explicit InitWalletDirTestingSetup(const ChainType chain_type = ChainType::MAIN); explicit InitWalletDirTestingSetup(ChainType chain_type = ChainType::MAIN);
~InitWalletDirTestingSetup(); ~InitWalletDirTestingSetup();
void SetWalletDir(const fs::path& walletdir_path); void SetWalletDir(const fs::path& walletdir_path);

View File

@ -20,7 +20,7 @@ namespace wallet {
/** Testing setup and teardown for wallet. /** Testing setup and teardown for wallet.
*/ */
struct WalletTestingSetup : public TestingSetup { struct WalletTestingSetup : public TestingSetup {
explicit WalletTestingSetup(const ChainType chainType = ChainType::MAIN); explicit WalletTestingSetup(ChainType chainType = ChainType::MAIN);
~WalletTestingSetup(); ~WalletTestingSetup();
std::unique_ptr<interfaces::WalletLoader> m_wallet_loader; std::unique_ptr<interfaces::WalletLoader> m_wallet_loader;

View File

@ -1778,7 +1778,7 @@ void CWallet::InitWalletFlags(uint64_t flags)
if (!LoadWalletFlags(flags)) assert(false); if (!LoadWalletFlags(flags)) assert(false);
} }
bool CWallet::ImportScripts(const std::set<CScript> scripts, int64_t timestamp) bool CWallet::ImportScripts(const std::set<CScript>& scripts, int64_t timestamp)
{ {
auto spk_man = GetLegacyScriptPubKeyMan(); auto spk_man = GetLegacyScriptPubKeyMan();
if (!spk_man) { if (!spk_man) {
@ -2583,7 +2583,7 @@ bool CWallet::TopUpKeyPool(unsigned int kpSize)
return res; return res;
} }
util::Result<CTxDestination> CWallet::GetNewDestination(const OutputType type, const std::string label) util::Result<CTxDestination> CWallet::GetNewDestination(const OutputType type, const std::string& label)
{ {
LOCK(cs_wallet); LOCK(cs_wallet);
auto spk_man = GetScriptPubKeyMan(type, /*internal=*/false); auto spk_man = GetScriptPubKeyMan(type, /*internal=*/false);

View File

@ -433,7 +433,7 @@ private:
* block locator and m_last_block_processed, and registering for * block locator and m_last_block_processed, and registering for
* notifications about new blocks and transactions. * notifications about new blocks and transactions.
*/ */
static bool AttachChain(const std::shared_ptr<CWallet>& wallet, interfaces::Chain& chain, const bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings); static bool AttachChain(const std::shared_ptr<CWallet>& wallet, interfaces::Chain& chain, bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings);
static NodeClock::time_point GetDefaultNextResend(); static NodeClock::time_point GetDefaultNextResend();
@ -630,7 +630,7 @@ public:
//! USER_ABORT. //! USER_ABORT.
uint256 last_failed_block; uint256 last_failed_block;
}; };
ScanResult ScanForWalletTransactions(const uint256& start_block, int start_height, std::optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate, const bool save_progress); ScanResult ScanForWalletTransactions(const uint256& start_block, int start_height, std::optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate, bool save_progress);
void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) override; void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) override;
/** Set the next time this wallet should resend transactions to 12-36 hours from now, ~1 day on average. */ /** Set the next time this wallet should resend transactions to 12-36 hours from now, ~1 day on average. */
void SetNextResend() { m_next_resend = GetDefaultNextResend(); } void SetNextResend() { m_next_resend = GetDefaultNextResend(); }
@ -684,10 +684,10 @@ public:
bool SubmitTxMemoryPoolAndRelay(CWalletTx& wtx, std::string& err_string, bool relay) const bool SubmitTxMemoryPoolAndRelay(CWalletTx& wtx, std::string& err_string, bool relay) const
EXCLUSIVE_LOCKS_REQUIRED(cs_wallet); EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet); bool ImportScripts(const std::set<CScript>& scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet); bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
bool ImportPubKeys(const std::vector<std::pair<CKeyID, bool>>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet); bool ImportPubKeys(const std::vector<std::pair<CKeyID, bool>>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, bool add_keypool, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
bool ImportScriptPubKeys(const std::string& label, const std::set<CScript>& script_pub_keys, const bool have_solving_data, const bool apply_label, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet); bool ImportScriptPubKeys(const std::string& label, const std::set<CScript>& script_pub_keys, bool have_solving_data, bool apply_label, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
/** Updates wallet birth time if 'time' is below it */ /** Updates wallet birth time if 'time' is below it */
void MaybeUpdateBirthTime(int64_t time); void MaybeUpdateBirthTime(int64_t time);
@ -757,7 +757,7 @@ public:
/** /**
* Retrieve all the known labels in the address book * Retrieve all the known labels in the address book
*/ */
std::set<std::string> ListAddrBookLabels(const std::optional<AddressPurpose> purpose) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet); std::set<std::string> ListAddrBookLabels(std::optional<AddressPurpose> purpose) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
/** /**
* Walk-through the address book entries. * Walk-through the address book entries.
@ -772,8 +772,8 @@ public:
*/ */
void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet); void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
util::Result<CTxDestination> GetNewDestination(const OutputType type, const std::string label); util::Result<CTxDestination> GetNewDestination(OutputType type, const std::string& label);
util::Result<CTxDestination> GetNewChangeDestination(const OutputType type); util::Result<CTxDestination> GetNewChangeDestination(OutputType type);
isminetype IsMine(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet); isminetype IsMine(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
isminetype IsMine(const CScript& script) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet); isminetype IsMine(const CScript& script) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);

View File

@ -239,7 +239,7 @@ public:
bool WriteTx(const CWalletTx& wtx); bool WriteTx(const CWalletTx& wtx);
bool EraseTx(uint256 hash); bool EraseTx(uint256 hash);
bool WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, const bool overwrite); bool WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, bool overwrite);
bool WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata &keyMeta); bool WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata &keyMeta);
bool WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, const CKeyMetadata &keyMeta); bool WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, const CKeyMetadata &keyMeta);
bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey); bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey);
@ -291,7 +291,7 @@ public:
//! Delete records of the given types //! Delete records of the given types
bool EraseRecords(const std::unordered_set<std::string>& types); bool EraseRecords(const std::unordered_set<std::string>& types);
bool WriteWalletFlags(const uint64_t flags); bool WriteWalletFlags(uint64_t flags);
//! Begin a new transaction //! Begin a new transaction
bool TxnBegin(); bool TxnBegin();
//! Commit current transaction //! Commit current transaction

View File

@ -88,7 +88,7 @@ class InitTest(BitcoinTestFramework):
args = ['-txindex=1', '-blockfilterindex=1', '-coinstatsindex=1'] args = ['-txindex=1', '-blockfilterindex=1', '-coinstatsindex=1']
for terminate_line in lines_to_terminate_after: for terminate_line in lines_to_terminate_after:
self.log.info(f"Starting node and will exit after line {terminate_line}") self.log.info(f"Starting node and will terminate after line {terminate_line}")
with node.busy_wait_for_debug_log([terminate_line]): with node.busy_wait_for_debug_log([terminate_line]):
if platform.system() == 'Windows': if platform.system() == 'Windows':
# CREATE_NEW_PROCESS_GROUP is required in order to be able # CREATE_NEW_PROCESS_GROUP is required in order to be able
@ -108,12 +108,22 @@ class InitTest(BitcoinTestFramework):
'blocks/index/*.ldb': 'Error opening block database.', 'blocks/index/*.ldb': 'Error opening block database.',
'chainstate/*.ldb': 'Error opening coins database.', 'chainstate/*.ldb': 'Error opening coins database.',
'blocks/blk*.dat': 'Error loading block database.', 'blocks/blk*.dat': 'Error loading block database.',
'indexes/txindex/MANIFEST*': 'LevelDB error: Corruption: CURRENT points to a non-existent file',
# Removing these files does not result in a startup error:
# 'indexes/blockfilter/basic/*.dat', 'indexes/blockfilter/basic/db/*.*', 'indexes/coinstats/db/*.*',
# 'indexes/txindex/*.log', 'indexes/txindex/CURRENT', 'indexes/txindex/LOCK'
} }
files_to_perturb = { files_to_perturb = {
'blocks/index/*.ldb': 'Error loading block database.', 'blocks/index/*.ldb': 'Error loading block database.',
'chainstate/*.ldb': 'Error opening coins database.', 'chainstate/*.ldb': 'Error opening coins database.',
'blocks/blk*.dat': 'Corrupted block database detected.', 'blocks/blk*.dat': 'Corrupted block database detected.',
'indexes/blockfilter/basic/db/*.*': 'LevelDB error: Corruption',
'indexes/coinstats/db/*.*': 'LevelDB error: Corruption',
'indexes/txindex/*.log': 'LevelDB error: Corruption',
'indexes/txindex/CURRENT': 'LevelDB error: Corruption',
# Perturbing these files does not result in a startup error:
# 'indexes/blockfilter/basic/*.dat', 'indexes/txindex/MANIFEST*', 'indexes/txindex/LOCK'
} }
for file_patt, err_fragment in files_to_delete.items(): for file_patt, err_fragment in files_to_delete.items():
@ -135,9 +145,10 @@ class InitTest(BitcoinTestFramework):
self.stop_node(0) self.stop_node(0)
self.log.info("Test startup errors after perturbing certain essential files") self.log.info("Test startup errors after perturbing certain essential files")
dirs = ["blocks", "chainstate", "indexes"]
for file_patt, err_fragment in files_to_perturb.items(): for file_patt, err_fragment in files_to_perturb.items():
shutil.copytree(node.chain_path / "blocks", node.chain_path / "blocks_bak") for dir in dirs:
shutil.copytree(node.chain_path / "chainstate", node.chain_path / "chainstate_bak") shutil.copytree(node.chain_path / dir, node.chain_path / f"{dir}_bak")
target_files = list(node.chain_path.glob(file_patt)) target_files = list(node.chain_path.glob(file_patt))
for target_file in target_files: for target_file in target_files:
@ -151,10 +162,9 @@ class InitTest(BitcoinTestFramework):
start_expecting_error(err_fragment) start_expecting_error(err_fragment)
shutil.rmtree(node.chain_path / "blocks") for dir in dirs:
shutil.rmtree(node.chain_path / "chainstate") shutil.rmtree(node.chain_path / dir)
shutil.move(node.chain_path / "blocks_bak", node.chain_path / "blocks") shutil.move(node.chain_path / f"{dir}_bak", node.chain_path / dir)
shutil.move(node.chain_path / "chainstate_bak", node.chain_path / "chainstate")
def init_pid_test(self): def init_pid_test(self):
BITCOIN_PID_FILENAME_CUSTOM = "my_fancy_bitcoin_pid_file.foobar" BITCOIN_PID_FILENAME_CUSTOM = "my_fancy_bitcoin_pid_file.foobar"

View File

@ -45,6 +45,7 @@ from test_framework.util import (
assert_equal, assert_equal,
assert_greater_than, assert_greater_than,
assert_raises_rpc_error, assert_raises_rpc_error,
sync_txindex,
) )
from test_framework.wallet import MiniWallet from test_framework.wallet import MiniWallet
from test_framework.wallet_util import generate_keypair from test_framework.wallet_util import generate_keypair
@ -270,6 +271,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
self.log.info('A coinbase transaction') self.log.info('A coinbase transaction')
# Pick the input of the first tx we created, so it has to be a coinbase tx # Pick the input of the first tx we created, so it has to be a coinbase tx
sync_txindex(self, node)
raw_tx_coinbase_spent = node.getrawtransaction(txid=node.decoderawtransaction(hexstring=raw_tx_in_block)['vin'][0]['txid']) raw_tx_coinbase_spent = node.getrawtransaction(txid=node.decoderawtransaction(hexstring=raw_tx_in_block)['vin'][0]['txid'])
tx = tx_from_hex(raw_tx_coinbase_spent) tx = tx_from_hex(raw_tx_coinbase_spent)
self.check_mempool_result( self.check_mempool_result(

View File

@ -34,6 +34,7 @@ from test_framework.util import (
assert_equal, assert_equal,
assert_greater_than, assert_greater_than,
assert_raises_rpc_error, assert_raises_rpc_error,
sync_txindex,
) )
from test_framework.wallet import ( from test_framework.wallet import (
getnewdestination, getnewdestination,
@ -70,7 +71,7 @@ class RawTransactionsTest(BitcoinTestFramework):
self.num_nodes = 3 self.num_nodes = 3
self.extra_args = [ self.extra_args = [
["-txindex"], ["-txindex"],
["-txindex"], [],
["-fastprune", "-prune=1"], ["-fastprune", "-prune=1"],
] ]
# whitelist peers to speed up tx relay / mempool sync # whitelist peers to speed up tx relay / mempool sync
@ -109,6 +110,7 @@ class RawTransactionsTest(BitcoinTestFramework):
self.log.info(f"Test getrawtransaction {'with' if n == 0 else 'without'} -txindex") self.log.info(f"Test getrawtransaction {'with' if n == 0 else 'without'} -txindex")
if n == 0: if n == 0:
sync_txindex(self, self.nodes[n])
# With -txindex. # With -txindex.
# 1. valid parameters - only supply txid # 1. valid parameters - only supply txid
assert_equal(self.nodes[n].getrawtransaction(txId), tx['hex']) assert_equal(self.nodes[n].getrawtransaction(txId), tx['hex'])

View File

@ -12,6 +12,7 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import ( from test_framework.util import (
assert_equal, assert_equal,
assert_raises_rpc_error, assert_raises_rpc_error,
sync_txindex,
) )
from test_framework.wallet import MiniWallet from test_framework.wallet import MiniWallet
@ -77,6 +78,7 @@ class MerkleBlockTest(BitcoinTestFramework):
assert_equal(sorted(self.nodes[0].verifytxoutproof(self.nodes[0].gettxoutproof([txid1, txid2]))), sorted(txlist)) assert_equal(sorted(self.nodes[0].verifytxoutproof(self.nodes[0].gettxoutproof([txid1, txid2]))), sorted(txlist))
assert_equal(sorted(self.nodes[0].verifytxoutproof(self.nodes[0].gettxoutproof([txid2, txid1]))), sorted(txlist)) assert_equal(sorted(self.nodes[0].verifytxoutproof(self.nodes[0].gettxoutproof([txid2, txid1]))), sorted(txlist))
# We can always get a proof if we have a -txindex # We can always get a proof if we have a -txindex
sync_txindex(self, self.nodes[1])
assert_equal(self.nodes[0].verifytxoutproof(self.nodes[1].gettxoutproof([txid_spent])), [txid_spent]) assert_equal(self.nodes[0].verifytxoutproof(self.nodes[1].gettxoutproof([txid_spent])), [txid_spent])
# We can't get a proof if we specify transactions from different blocks # We can't get a proof if we specify transactions from different blocks
assert_raises_rpc_error(-5, "Not all transactions found in specified or retrieved block", self.nodes[0].gettxoutproof, [txid1, txid3]) assert_raises_rpc_error(-5, "Not all transactions found in specified or retrieved block", self.nodes[0].gettxoutproof, [txid1, txid3])

View File

@ -592,3 +592,10 @@ def find_vout_for_address(node, txid, addr):
if addr == tx["vout"][i]["scriptPubKey"]["address"]: if addr == tx["vout"][i]["scriptPubKey"]["address"]:
return i return i
raise RuntimeError("Vout not found for address: txid=%s, addr=%s" % (txid, addr)) raise RuntimeError("Vout not found for address: txid=%s, addr=%s" % (txid, addr))
def sync_txindex(test_framework, node):
test_framework.log.debug("Waiting for node txindex to sync")
sync_start = int(time.time())
test_framework.wait_until(lambda: node.getindexinfo("txindex")["txindex"]["synced"])
test_framework.log.debug(f"Synced in {time.time() - sync_start} seconds")

View File

@ -117,7 +117,6 @@ class AddressInputTypeGrouping(BitcoinTestFramework):
self.extra_args = [ self.extra_args = [
[ [
"-addresstype=bech32", "-addresstype=bech32",
"-txindex",
], ],
[ [
"-addresstype=p2sh-segwit", "-addresstype=p2sh-segwit",