repo_id
stringlengths
0
42
file_path
stringlengths
15
97
content
stringlengths
2
2.41M
__index_level_0__
int64
0
0
bitcoin
bitcoin/src/addrman_impl.h
// Copyright (c) 2021-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_ADDRMAN_IMPL_H #define BITCOIN_ADDRMAN_IMPL_H #include <logging.h> #include <logging/timer.h> #include <netaddress.h> #include <protocol.h> #include <serialize.h> #include <sync.h> #include <timedata.h> #include <uint256.h> #include <util/time.h> #include <cstdint> #include <optional> #include <set> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> /** Total number of buckets for tried addresses */ static constexpr int32_t ADDRMAN_TRIED_BUCKET_COUNT_LOG2{8}; static constexpr int ADDRMAN_TRIED_BUCKET_COUNT{1 << ADDRMAN_TRIED_BUCKET_COUNT_LOG2}; /** Total number of buckets for new addresses */ static constexpr int32_t ADDRMAN_NEW_BUCKET_COUNT_LOG2{10}; static constexpr int ADDRMAN_NEW_BUCKET_COUNT{1 << ADDRMAN_NEW_BUCKET_COUNT_LOG2}; /** Maximum allowed number of entries in buckets for new and tried addresses */ static constexpr int32_t ADDRMAN_BUCKET_SIZE_LOG2{6}; static constexpr int ADDRMAN_BUCKET_SIZE{1 << ADDRMAN_BUCKET_SIZE_LOG2}; /** * Extended statistics about a CAddress */ class AddrInfo : public CAddress { public: //! last try whatsoever by us (memory only) NodeSeconds m_last_try{0s}; //! last counted attempt (memory only) NodeSeconds m_last_count_attempt{0s}; //! where knowledge about this address first came from CNetAddr source; //! last successful connection by us NodeSeconds m_last_success{0s}; //! connection attempts since last successful attempt int nAttempts{0}; //! reference count in new sets (memory only) int nRefCount{0}; //! in tried set? (memory only) bool fInTried{false}; //! position in vRandom mutable int nRandomPos{-1}; SERIALIZE_METHODS(AddrInfo, obj) { READWRITE(AsBase<CAddress>(obj), obj.source, Using<ChronoFormatter<int64_t>>(obj.m_last_success), obj.nAttempts); } AddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn), source(addrSource) { } AddrInfo() : CAddress(), source() { } //! Calculate in which "tried" bucket this entry belongs int GetTriedBucket(const uint256& nKey, const NetGroupManager& netgroupman) const; //! Calculate in which "new" bucket this entry belongs, given a certain source int GetNewBucket(const uint256& nKey, const CNetAddr& src, const NetGroupManager& netgroupman) const; //! Calculate in which "new" bucket this entry belongs, using its default source int GetNewBucket(const uint256& nKey, const NetGroupManager& netgroupman) const { return GetNewBucket(nKey, source, netgroupman); } //! Calculate in which position of a bucket to store this entry. int GetBucketPosition(const uint256 &nKey, bool fNew, int bucket) const; //! Determine whether the statistics about this entry are bad enough so that it can just be deleted bool IsTerrible(NodeSeconds now = Now<NodeSeconds>()) const; //! Calculate the relative chance this entry should be given when selecting nodes to connect to double GetChance(NodeSeconds now = Now<NodeSeconds>()) const; }; class AddrManImpl { public: AddrManImpl(const NetGroupManager& netgroupman, bool deterministic, int32_t consistency_check_ratio); ~AddrManImpl(); template <typename Stream> void Serialize(Stream& s_) const EXCLUSIVE_LOCKS_REQUIRED(!cs); template <typename Stream> void Unserialize(Stream& s_) EXCLUSIVE_LOCKS_REQUIRED(!cs); size_t Size(std::optional<Network> net, std::optional<bool> in_new) const EXCLUSIVE_LOCKS_REQUIRED(!cs); bool Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty) EXCLUSIVE_LOCKS_REQUIRED(!cs); bool Good(const CService& addr, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(!cs); void Attempt(const CService& addr, bool fCountFailure, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(!cs); void ResolveCollisions() EXCLUSIVE_LOCKS_REQUIRED(!cs); std::pair<CAddress, NodeSeconds> SelectTriedCollision() EXCLUSIVE_LOCKS_REQUIRED(!cs); std::pair<CAddress, NodeSeconds> Select(bool new_only, std::optional<Network> network) 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<std::pair<AddrInfo, AddressPosition>> GetEntries(bool from_tried) const EXCLUSIVE_LOCKS_REQUIRED(!cs); void Connected(const CService& addr, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(!cs); void SetServices(const CService& addr, ServiceFlags nServices) EXCLUSIVE_LOCKS_REQUIRED(!cs); std::optional<AddressPosition> FindAddressEntry(const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(!cs); friend class AddrManDeterministic; private: //! A mutex to protect the inner data structures. mutable Mutex cs; //! Source of random numbers for randomization in inner loops mutable FastRandomContext insecure_rand GUARDED_BY(cs); //! secret key to randomize bucket select with uint256 nKey; //! Serialization versions. enum Format : uint8_t { V0_HISTORICAL = 0, //!< historic format, before commit e6b343d88 V1_DETERMINISTIC = 1, //!< for pre-asmap files V2_ASMAP = 2, //!< for files including asmap version V3_BIP155 = 3, //!< same as V2_ASMAP plus addresses are in BIP155 format V4_MULTIPORT = 4, //!< adds support for multiple ports per IP }; //! The maximum format this software knows it can unserialize. Also, we always serialize //! in this format. //! The format (first byte in the serialized stream) can be higher than this and //! still this software may be able to unserialize the file - if the second byte //! (see `lowest_compatible` in `Unserialize()`) is less or equal to this. static constexpr Format FILE_FORMAT = Format::V4_MULTIPORT; //! The initial value of a field that is incremented every time an incompatible format //! change is made (such that old software versions would not be able to parse and //! understand the new file format). This is 32 because we overtook the "key size" //! field which was 32 historically. //! @note Don't increment this. Increment `lowest_compatible` in `Serialize()` instead. static constexpr uint8_t INCOMPATIBILITY_BASE = 32; //! last used nId int nIdCount GUARDED_BY(cs){0}; //! table with information about all nIds std::unordered_map<int, AddrInfo> mapInfo GUARDED_BY(cs); //! find an nId based on its network address and port. std::unordered_map<CService, int, CServiceHash> mapAddr GUARDED_BY(cs); //! randomly-ordered vector of all nIds //! This is mutable because it is unobservable outside the class, so any //! changes to it (even in const methods) are also unobservable. mutable std::vector<int> vRandom GUARDED_BY(cs); // number of "tried" entries int nTried GUARDED_BY(cs){0}; //! list of "tried" buckets int vvTried[ADDRMAN_TRIED_BUCKET_COUNT][ADDRMAN_BUCKET_SIZE] GUARDED_BY(cs); //! number of (unique) "new" entries int nNew GUARDED_BY(cs){0}; //! list of "new" buckets int vvNew[ADDRMAN_NEW_BUCKET_COUNT][ADDRMAN_BUCKET_SIZE] GUARDED_BY(cs); //! last time Good was called (memory only). Initially set to 1 so that "never" is strictly worse. NodeSeconds m_last_good GUARDED_BY(cs){1s}; //! Holds addrs inserted into tried table that collide with existing entries. Test-before-evict discipline used to resolve these collisions. std::set<int> m_tried_collisions; /** Perform consistency checks every m_consistency_check_ratio operations (if non-zero). */ const int32_t m_consistency_check_ratio; /** Reference to the netgroup manager. netgroupman must be constructed before addrman and destructed after. */ const NetGroupManager& m_netgroupman; struct NewTriedCount { size_t n_new; size_t n_tried; }; /** Number of entries in addrman per network and new/tried table. */ std::unordered_map<Network, NewTriedCount> m_network_counts GUARDED_BY(cs); //! Find an entry. AddrInfo* Find(const CService& addr, int* pnId = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs); //! Create a new entry and add it to the internal data structures mapInfo, mapAddr and vRandom. AddrInfo* Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs); //! Swap two elements in vRandom. void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2) const EXCLUSIVE_LOCKS_REQUIRED(cs); //! Delete an entry. It must not be in tried, and have refcount 0. void Delete(int nId) EXCLUSIVE_LOCKS_REQUIRED(cs); //! Clear a position in a "new" table. This is the only place where entries are actually deleted. void ClearNew(int nUBucket, int nUBucketPos) EXCLUSIVE_LOCKS_REQUIRED(cs); //! Move an entry from the "new" table(s) to the "tried" table void MakeTried(AddrInfo& info, int nId) EXCLUSIVE_LOCKS_REQUIRED(cs); /** Attempt to add a single address to addrman's new table. * @see AddrMan::Add() for parameters. */ bool AddSingle(const CAddress& addr, const CNetAddr& source, std::chrono::seconds time_penalty) EXCLUSIVE_LOCKS_REQUIRED(cs); bool Good_(const CService& addr, bool test_before_evict, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(cs); bool Add_(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty) EXCLUSIVE_LOCKS_REQUIRED(cs); void Attempt_(const CService& addr, bool fCountFailure, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(cs); std::pair<CAddress, NodeSeconds> Select_(bool new_only, std::optional<Network> network) const EXCLUSIVE_LOCKS_REQUIRED(cs); /** Helper to generalize looking up an addrman entry from either table. * * @return int The nid of the entry. If the addrman position is empty or not found, returns -1. * */ int 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<std::pair<AddrInfo, AddressPosition>> GetEntries_(bool from_tried) const EXCLUSIVE_LOCKS_REQUIRED(cs); void Connected_(const CService& addr, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(cs); void SetServices_(const CService& addr, ServiceFlags nServices) EXCLUSIVE_LOCKS_REQUIRED(cs); void ResolveCollisions_() EXCLUSIVE_LOCKS_REQUIRED(cs); std::pair<CAddress, NodeSeconds> SelectTriedCollision_() EXCLUSIVE_LOCKS_REQUIRED(cs); std::optional<AddressPosition> FindAddressEntry_(const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(cs); size_t Size_(std::optional<Network> net, std::optional<bool> in_new) const EXCLUSIVE_LOCKS_REQUIRED(cs); //! Consistency check, taking into account m_consistency_check_ratio. //! Will std::abort if an inconsistency is detected. void Check() const EXCLUSIVE_LOCKS_REQUIRED(cs); //! Perform consistency check, regardless of m_consistency_check_ratio. //! @returns an error code or zero. int CheckAddrman() const EXCLUSIVE_LOCKS_REQUIRED(cs); }; #endif // BITCOIN_ADDRMAN_IMPL_H
0
bitcoin
bitcoin/src/Makefile.test_fuzz.include
# Copyright (c) 2013-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. LIBTEST_FUZZ=libtest_fuzz.a EXTRA_LIBRARIES += \ $(LIBTEST_FUZZ) TEST_FUZZ_H = \ test/fuzz/fuzz.h \ test/fuzz/FuzzedDataProvider.h \ test/fuzz/util.h \ test/fuzz/util/descriptor.h \ test/fuzz/util/mempool.h \ test/fuzz/util/net.h libtest_fuzz_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BOOST_CPPFLAGS) libtest_fuzz_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libtest_fuzz_a_SOURCES = \ test/fuzz/fuzz.cpp \ test/fuzz/util.cpp \ test/fuzz/util/descriptor.cpp \ test/fuzz/util/mempool.cpp \ test/fuzz/util/net.cpp \ $(TEST_FUZZ_H)
0
bitcoin
bitcoin/src/attributes.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_ATTRIBUTES_H #define BITCOIN_ATTRIBUTES_H #if defined(__clang__) # if __has_attribute(lifetimebound) # define LIFETIMEBOUND [[clang::lifetimebound]] # else # define LIFETIMEBOUND # endif #else # define LIFETIMEBOUND #endif #if defined(__GNUC__) # define ALWAYS_INLINE inline __attribute__((always_inline)) #elif defined(_MSC_VER) # define ALWAYS_INLINE __forceinline #else # error No known always_inline attribute for this platform. #endif #endif // BITCOIN_ATTRIBUTES_H
0
bitcoin
bitcoin/src/timedata.h
// Copyright (c) 2014-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TIMEDATA_H #define BITCOIN_TIMEDATA_H #include <util/time.h> #include <algorithm> #include <cassert> #include <chrono> #include <cstdint> #include <vector> 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 */ template <typename T> class CMedianFilter { private: std::vector<T> vValues; std::vector<T> vSorted; unsigned int nSize; public: CMedianFilter(unsigned int _size, T initial_value) : nSize(_size) { vValues.reserve(_size); vValues.push_back(initial_value); vSorted = vValues; } void input(T value) { if (vValues.size() == nSize) { vValues.erase(vValues.begin()); } vValues.push_back(value); vSorted.resize(vValues.size()); std::copy(vValues.begin(), vValues.end(), vSorted.begin()); std::sort(vSorted.begin(), vSorted.end()); } T median() const { int vSortedSize = vSorted.size(); assert(vSortedSize > 0); if (vSortedSize & 1) // Odd number of elements { return vSorted[vSortedSize / 2]; } else // Even number of elements { return (vSorted[vSortedSize / 2 - 1] + vSorted[vSortedSize / 2]) / 2; } } int size() const { return vValues.size(); } std::vector<T> sorted() const { return vSorted; } }; /** Functions to keep track of adjusted P2P time */ int64_t GetTimeOffset(); NodeClock::time_point GetAdjustedTime(); void AddTimeData(const CNetAddr& ip, int64_t nTime); /** * Reset the internal state of GetTimeOffset(), GetAdjustedTime() and AddTimeData(). */ void TestOnlyResetTimeData(); #endif // BITCOIN_TIMEDATA_H
0
bitcoin
bitcoin/src/addresstype.cpp
// Copyright (c) 2023 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or https://www.opensource.org/licenses/mit-license.php. #include <addresstype.h> #include <crypto/sha256.h> #include <hash.h> #include <pubkey.h> #include <script/script.h> #include <script/solver.h> #include <uint256.h> #include <util/hash_type.h> #include <cassert> #include <vector> typedef std::vector<unsigned char> valtype; ScriptHash::ScriptHash(const CScript& in) : BaseHash(Hash160(in)) {} ScriptHash::ScriptHash(const CScriptID& in) : BaseHash{in} {} PKHash::PKHash(const CPubKey& pubkey) : BaseHash(pubkey.GetID()) {} PKHash::PKHash(const CKeyID& pubkey_id) : BaseHash(pubkey_id) {} WitnessV0KeyHash::WitnessV0KeyHash(const CPubKey& pubkey) : BaseHash(pubkey.GetID()) {} WitnessV0KeyHash::WitnessV0KeyHash(const PKHash& pubkey_hash) : BaseHash{pubkey_hash} {} CKeyID ToKeyID(const PKHash& key_hash) { return CKeyID{uint160{key_hash}}; } CKeyID ToKeyID(const WitnessV0KeyHash& key_hash) { return CKeyID{uint160{key_hash}}; } CScriptID ToScriptID(const ScriptHash& script_hash) { return CScriptID{uint160{script_hash}}; } WitnessV0ScriptHash::WitnessV0ScriptHash(const CScript& in) { CSHA256().Write(in.data(), in.size()).Finalize(begin()); } bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet) { std::vector<valtype> vSolutions; TxoutType whichType = Solver(scriptPubKey, vSolutions); switch (whichType) { case TxoutType::PUBKEY: { CPubKey pubKey(vSolutions[0]); if (!pubKey.IsValid()) { addressRet = CNoDestination(scriptPubKey); } else { addressRet = PubKeyDestination(pubKey); } return false; } case TxoutType::PUBKEYHASH: { addressRet = PKHash(uint160(vSolutions[0])); return true; } case TxoutType::SCRIPTHASH: { addressRet = ScriptHash(uint160(vSolutions[0])); return true; } case TxoutType::WITNESS_V0_KEYHASH: { WitnessV0KeyHash hash; std::copy(vSolutions[0].begin(), vSolutions[0].end(), hash.begin()); addressRet = hash; return true; } case TxoutType::WITNESS_V0_SCRIPTHASH: { WitnessV0ScriptHash hash; std::copy(vSolutions[0].begin(), vSolutions[0].end(), hash.begin()); addressRet = hash; return true; } case TxoutType::WITNESS_V1_TAPROOT: { WitnessV1Taproot tap; std::copy(vSolutions[0].begin(), vSolutions[0].end(), tap.begin()); addressRet = tap; return true; } case TxoutType::WITNESS_UNKNOWN: { addressRet = WitnessUnknown{vSolutions[0][0], vSolutions[1]}; return true; } case TxoutType::MULTISIG: case TxoutType::NULL_DATA: case TxoutType::NONSTANDARD: addressRet = CNoDestination(scriptPubKey); return false; } // no default case, so the compiler can warn about missing cases assert(false); } namespace { class CScriptVisitor { public: CScript operator()(const CNoDestination& dest) const { return dest.GetScript(); } CScript operator()(const PubKeyDestination& dest) const { return CScript() << ToByteVector(dest.GetPubKey()) << OP_CHECKSIG; } CScript operator()(const PKHash& keyID) const { return CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; } CScript operator()(const ScriptHash& scriptID) const { return CScript() << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL; } CScript operator()(const WitnessV0KeyHash& id) const { return CScript() << OP_0 << ToByteVector(id); } CScript operator()(const WitnessV0ScriptHash& id) const { return CScript() << OP_0 << ToByteVector(id); } CScript operator()(const WitnessV1Taproot& tap) const { return CScript() << OP_1 << ToByteVector(tap); } CScript operator()(const WitnessUnknown& id) const { return CScript() << CScript::EncodeOP_N(id.GetWitnessVersion()) << id.GetWitnessProgram(); } }; class ValidDestinationVisitor { public: bool operator()(const CNoDestination& dest) const { return false; } bool operator()(const PubKeyDestination& dest) const { return false; } bool operator()(const PKHash& dest) const { return true; } bool operator()(const ScriptHash& dest) const { return true; } bool operator()(const WitnessV0KeyHash& dest) const { return true; } bool operator()(const WitnessV0ScriptHash& dest) const { return true; } bool operator()(const WitnessV1Taproot& dest) const { return true; } bool operator()(const WitnessUnknown& dest) const { return true; } }; } // namespace CScript GetScriptForDestination(const CTxDestination& dest) { return std::visit(CScriptVisitor(), dest); } bool IsValidDestination(const CTxDestination& dest) { return std::visit(ValidDestinationVisitor(), dest); }
0
bitcoin
bitcoin/src/deploymentstatus.h
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_DEPLOYMENTSTATUS_H #define BITCOIN_DEPLOYMENTSTATUS_H #include <chain.h> #include <versionbits.h> #include <limits> /** Determine if a deployment is active for the next block */ inline bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::BuriedDeployment dep, [[maybe_unused]] VersionBitsCache& versionbitscache) { assert(Consensus::ValidDeployment(dep)); return (pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1) >= params.DeploymentHeight(dep); } inline bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos dep, VersionBitsCache& versionbitscache) { assert(Consensus::ValidDeployment(dep)); return ThresholdState::ACTIVE == versionbitscache.State(pindexPrev, params, dep); } /** Determine if a deployment is active for this block */ inline bool DeploymentActiveAt(const CBlockIndex& index, const Consensus::Params& params, Consensus::BuriedDeployment dep, [[maybe_unused]] VersionBitsCache& versionbitscache) { assert(Consensus::ValidDeployment(dep)); return index.nHeight >= params.DeploymentHeight(dep); } inline bool DeploymentActiveAt(const CBlockIndex& index, const Consensus::Params& params, Consensus::DeploymentPos dep, VersionBitsCache& versionbitscache) { assert(Consensus::ValidDeployment(dep)); return DeploymentActiveAfter(index.pprev, params, dep, versionbitscache); } /** Determine if a deployment is enabled (can ever be active) */ inline bool DeploymentEnabled(const Consensus::Params& params, Consensus::BuriedDeployment dep) { assert(Consensus::ValidDeployment(dep)); return params.DeploymentHeight(dep) != std::numeric_limits<int>::max(); } inline bool DeploymentEnabled(const Consensus::Params& params, Consensus::DeploymentPos dep) { assert(Consensus::ValidDeployment(dep)); return params.vDeployments[dep].nStartTime != Consensus::BIP9Deployment::NEVER_ACTIVE; } #endif // BITCOIN_DEPLOYMENTSTATUS_H
0
bitcoin
bitcoin/src/.bear-tidy-config
{ "output": { "content": { "include_only_existing_source": true, "paths_to_include": [], "paths_to_exclude": [ "src/crc32c", "src/crypto/ctaes", "src/leveldb", "src/minisketch", "src/bench/nanobench.cpp", "src/bench/nanobench.h", "src/secp256k1" ] }, "format": { "command_as_array": true, "drop_output_field": false } } }
0
bitcoin
bitcoin/src/txrequest.cpp
// Copyright (c) 2020-2021 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 <txrequest.h> #include <crypto/siphash.h> #include <net.h> #include <primitives/transaction.h> #include <random.h> #include <uint256.h> #include <boost/multi_index/indexed_by.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/multi_index/tag.hpp> #include <boost/multi_index_container.hpp> #include <boost/tuple/tuple.hpp> #include <chrono> #include <unordered_map> #include <utility> #include <assert.h> namespace { /** The various states a (txhash,peer) pair can be in. * * Note that CANDIDATE is split up into 3 substates (DELAYED, BEST, READY), allowing more efficient implementation. * Also note that the sorting order of ByTxHashView relies on the specific order of values in this enum. * * Expected behaviour is: * - When first announced by a peer, the state is CANDIDATE_DELAYED until reqtime is reached. * - Announcements that have reached their reqtime but not been requested will be either CANDIDATE_READY or * CANDIDATE_BEST. Neither of those has an expiration time; they remain in that state until they're requested or * no longer needed. CANDIDATE_READY announcements are promoted to CANDIDATE_BEST when they're the best one left. * - When requested, an announcement will be in state REQUESTED until expiry is reached. * - If expiry is reached, or the peer replies to the request (either with NOTFOUND or the tx), the state becomes * COMPLETED. */ enum class State : uint8_t { /** A CANDIDATE announcement whose reqtime is in the future. */ CANDIDATE_DELAYED, /** A CANDIDATE announcement that's not CANDIDATE_DELAYED or CANDIDATE_BEST. */ CANDIDATE_READY, /** The best CANDIDATE for a given txhash; only if there is no REQUESTED announcement already for that txhash. * The CANDIDATE_BEST is the highest-priority announcement among all CANDIDATE_READY (and _BEST) ones for that * txhash. */ CANDIDATE_BEST, /** A REQUESTED announcement. */ REQUESTED, /** A COMPLETED announcement. */ COMPLETED, }; //! Type alias for sequence numbers. using SequenceNumber = uint64_t; /** An announcement. This is the data we track for each txid or wtxid that is announced to us by each peer. */ struct Announcement { /** Txid or wtxid that was announced. */ const uint256 m_txhash; /** For CANDIDATE_{DELAYED,BEST,READY} the reqtime; for REQUESTED the expiry. */ std::chrono::microseconds m_time; /** What peer the request was from. */ const NodeId m_peer; /** What sequence number this announcement has. */ const SequenceNumber m_sequence : 59; /** Whether the request is preferred. */ const bool m_preferred : 1; /** Whether this is a wtxid request. */ const bool m_is_wtxid : 1; /** What state this announcement is in. */ State m_state : 3 {State::CANDIDATE_DELAYED}; State GetState() const { return m_state; } void SetState(State state) { m_state = state; } /** Whether this announcement is selected. There can be at most 1 selected peer per txhash. */ bool IsSelected() const { return GetState() == State::CANDIDATE_BEST || GetState() == State::REQUESTED; } /** Whether this announcement is waiting for a certain time to pass. */ bool IsWaiting() const { return GetState() == State::REQUESTED || GetState() == State::CANDIDATE_DELAYED; } /** Whether this announcement can feasibly be selected if the current IsSelected() one disappears. */ bool IsSelectable() const { return GetState() == State::CANDIDATE_READY || GetState() == State::CANDIDATE_BEST; } /** Construct a new announcement from scratch, initially in CANDIDATE_DELAYED state. */ Announcement(const GenTxid& gtxid, NodeId peer, bool preferred, std::chrono::microseconds reqtime, SequenceNumber sequence) : m_txhash(gtxid.GetHash()), m_time(reqtime), m_peer(peer), m_sequence(sequence), m_preferred(preferred), m_is_wtxid{gtxid.IsWtxid()} {} }; //! Type alias for priorities. using Priority = uint64_t; /** A functor with embedded salt that computes priority of an announcement. * * Higher priorities are selected first. */ class PriorityComputer { const uint64_t m_k0, m_k1; public: explicit PriorityComputer(bool deterministic) : m_k0{deterministic ? 0 : GetRand(0xFFFFFFFFFFFFFFFF)}, m_k1{deterministic ? 0 : GetRand(0xFFFFFFFFFFFFFFFF)} {} Priority operator()(const uint256& txhash, NodeId peer, bool preferred) const { uint64_t low_bits = CSipHasher(m_k0, m_k1).Write(txhash).Write(peer).Finalize() >> 1; return low_bits | uint64_t{preferred} << 63; } Priority operator()(const Announcement& ann) const { return operator()(ann.m_txhash, ann.m_peer, ann.m_preferred); } }; // Definitions for the 3 indexes used in the main data structure. // // Each index has a By* type to identify it, a By*View data type to represent the view of announcement it is sorted // by, and an By*ViewExtractor type to convert an announcement into the By*View type. // See https://www.boost.org/doc/libs/1_58_0/libs/multi_index/doc/reference/key_extraction.html#key_extractors // for more information about the key extraction concept. // The ByPeer index is sorted by (peer, state == CANDIDATE_BEST, txhash) // // Uses: // * Looking up existing announcements by peer/txhash, by checking both (peer, false, txhash) and // (peer, true, txhash). // * Finding all CANDIDATE_BEST announcements for a given peer in GetRequestable. struct ByPeer {}; using ByPeerView = std::tuple<NodeId, bool, const uint256&>; struct ByPeerViewExtractor { using result_type = ByPeerView; result_type operator()(const Announcement& ann) const { return ByPeerView{ann.m_peer, ann.GetState() == State::CANDIDATE_BEST, ann.m_txhash}; } }; // The ByTxHash index is sorted by (txhash, state, priority). // // Note: priority == 0 whenever state != CANDIDATE_READY. // // Uses: // * Deleting all announcements with a given txhash in ForgetTxHash. // * Finding the best CANDIDATE_READY to convert to CANDIDATE_BEST, when no other CANDIDATE_READY or REQUESTED // announcement exists for that txhash. // * Determining when no more non-COMPLETED announcements for a given txhash exist, so the COMPLETED ones can be // deleted. struct ByTxHash {}; using ByTxHashView = std::tuple<const uint256&, State, Priority>; class ByTxHashViewExtractor { const PriorityComputer& m_computer; public: explicit ByTxHashViewExtractor(const PriorityComputer& computer) : m_computer(computer) {} using result_type = ByTxHashView; result_type operator()(const Announcement& ann) const { const Priority prio = (ann.GetState() == State::CANDIDATE_READY) ? m_computer(ann) : 0; return ByTxHashView{ann.m_txhash, ann.GetState(), prio}; } }; enum class WaitState { //! Used for announcements that need efficient testing of "is their timestamp in the future?". FUTURE_EVENT, //! Used for announcements whose timestamp is not relevant. NO_EVENT, //! Used for announcements that need efficient testing of "is their timestamp in the past?". PAST_EVENT, }; WaitState GetWaitState(const Announcement& ann) { if (ann.IsWaiting()) return WaitState::FUTURE_EVENT; if (ann.IsSelectable()) return WaitState::PAST_EVENT; return WaitState::NO_EVENT; } // The ByTime index is sorted by (wait_state, time). // // All announcements with a timestamp in the future can be found by iterating the index forward from the beginning. // All announcements with a timestamp in the past can be found by iterating the index backwards from the end. // // Uses: // * Finding CANDIDATE_DELAYED announcements whose reqtime has passed, and REQUESTED announcements whose expiry has // passed. // * Finding CANDIDATE_READY/BEST announcements whose reqtime is in the future (when the clock time went backwards). struct ByTime {}; using ByTimeView = std::pair<WaitState, std::chrono::microseconds>; struct ByTimeViewExtractor { using result_type = ByTimeView; result_type operator()(const Announcement& ann) const { return ByTimeView{GetWaitState(ann), ann.m_time}; } }; /** Data type for the main data structure (Announcement objects with ByPeer/ByTxHash/ByTime indexes). */ using Index = boost::multi_index_container< Announcement, boost::multi_index::indexed_by< boost::multi_index::ordered_unique<boost::multi_index::tag<ByPeer>, ByPeerViewExtractor>, boost::multi_index::ordered_non_unique<boost::multi_index::tag<ByTxHash>, ByTxHashViewExtractor>, boost::multi_index::ordered_non_unique<boost::multi_index::tag<ByTime>, ByTimeViewExtractor> > >; /** Helper type to simplify syntax of iterator types. */ template<typename Tag> using Iter = typename Index::index<Tag>::type::iterator; /** Per-peer statistics object. */ struct PeerInfo { size_t m_total = 0; //!< Total number of announcements for this peer. size_t m_completed = 0; //!< Number of COMPLETED announcements for this peer. size_t m_requested = 0; //!< Number of REQUESTED announcements for this peer. }; /** Per-txhash statistics object. Only used for sanity checking. */ struct TxHashInfo { //! Number of CANDIDATE_DELAYED announcements for this txhash. size_t m_candidate_delayed = 0; //! Number of CANDIDATE_READY announcements for this txhash. size_t m_candidate_ready = 0; //! Number of CANDIDATE_BEST announcements for this txhash (at most one). size_t m_candidate_best = 0; //! Number of REQUESTED announcements for this txhash (at most one; mutually exclusive with CANDIDATE_BEST). size_t m_requested = 0; //! The priority of the CANDIDATE_BEST announcement if one exists, or max() otherwise. Priority m_priority_candidate_best = std::numeric_limits<Priority>::max(); //! The highest priority of all CANDIDATE_READY announcements (or min() if none exist). Priority m_priority_best_candidate_ready = std::numeric_limits<Priority>::min(); //! All peers we have an announcement for this txhash for. std::vector<NodeId> m_peers; }; /** Compare two PeerInfo objects. Only used for sanity checking. */ bool operator==(const PeerInfo& a, const PeerInfo& b) { return std::tie(a.m_total, a.m_completed, a.m_requested) == std::tie(b.m_total, b.m_completed, b.m_requested); }; /** (Re)compute the PeerInfo map from the index. Only used for sanity checking. */ std::unordered_map<NodeId, PeerInfo> RecomputePeerInfo(const Index& index) { std::unordered_map<NodeId, PeerInfo> ret; for (const Announcement& ann : index) { PeerInfo& info = ret[ann.m_peer]; ++info.m_total; info.m_requested += (ann.GetState() == State::REQUESTED); info.m_completed += (ann.GetState() == State::COMPLETED); } return ret; } /** Compute the TxHashInfo map. Only used for sanity checking. */ std::map<uint256, TxHashInfo> ComputeTxHashInfo(const Index& index, const PriorityComputer& computer) { std::map<uint256, TxHashInfo> ret; for (const Announcement& ann : index) { TxHashInfo& info = ret[ann.m_txhash]; // Classify how many announcements of each state we have for this txhash. info.m_candidate_delayed += (ann.GetState() == State::CANDIDATE_DELAYED); info.m_candidate_ready += (ann.GetState() == State::CANDIDATE_READY); info.m_candidate_best += (ann.GetState() == State::CANDIDATE_BEST); info.m_requested += (ann.GetState() == State::REQUESTED); // And track the priority of the best CANDIDATE_READY/CANDIDATE_BEST announcements. if (ann.GetState() == State::CANDIDATE_BEST) { info.m_priority_candidate_best = computer(ann); } if (ann.GetState() == State::CANDIDATE_READY) { info.m_priority_best_candidate_ready = std::max(info.m_priority_best_candidate_ready, computer(ann)); } // Also keep track of which peers this txhash has an announcement for (so we can detect duplicates). info.m_peers.push_back(ann.m_peer); } return ret; } GenTxid ToGenTxid(const Announcement& ann) { return ann.m_is_wtxid ? GenTxid::Wtxid(ann.m_txhash) : GenTxid::Txid(ann.m_txhash); } } // namespace /** Actual implementation for TxRequestTracker's data structure. */ class TxRequestTracker::Impl { //! The current sequence number. Increases for every announcement. This is used to sort txhashes returned by //! GetRequestable in announcement order. SequenceNumber m_current_sequence{0}; //! This tracker's priority computer. const PriorityComputer m_computer; //! This tracker's main data structure. See SanityCheck() for the invariants that apply to it. Index m_index; //! Map with this tracker's per-peer statistics. std::unordered_map<NodeId, PeerInfo> m_peerinfo; public: void SanityCheck() const { // Recompute m_peerdata from m_index. This verifies the data in it as it should just be caching statistics // on m_index. It also verifies the invariant that no PeerInfo announcements with m_total==0 exist. assert(m_peerinfo == RecomputePeerInfo(m_index)); // Calculate per-txhash statistics from m_index, and validate invariants. for (auto& item : ComputeTxHashInfo(m_index, m_computer)) { TxHashInfo& info = item.second; // Cannot have only COMPLETED peer (txhash should have been forgotten already) assert(info.m_candidate_delayed + info.m_candidate_ready + info.m_candidate_best + info.m_requested > 0); // Can have at most 1 CANDIDATE_BEST/REQUESTED peer assert(info.m_candidate_best + info.m_requested <= 1); // If there are any CANDIDATE_READY announcements, there must be exactly one CANDIDATE_BEST or REQUESTED // announcement. if (info.m_candidate_ready > 0) { assert(info.m_candidate_best + info.m_requested == 1); } // If there is both a CANDIDATE_READY and a CANDIDATE_BEST announcement, the CANDIDATE_BEST one must be // at least as good (equal or higher priority) as the best CANDIDATE_READY. if (info.m_candidate_ready && info.m_candidate_best) { assert(info.m_priority_candidate_best >= info.m_priority_best_candidate_ready); } // No txhash can have been announced by the same peer twice. std::sort(info.m_peers.begin(), info.m_peers.end()); assert(std::adjacent_find(info.m_peers.begin(), info.m_peers.end()) == info.m_peers.end()); } } void PostGetRequestableSanityCheck(std::chrono::microseconds now) const { for (const Announcement& ann : m_index) { if (ann.IsWaiting()) { // REQUESTED and CANDIDATE_DELAYED must have a time in the future (they should have been converted // to COMPLETED/CANDIDATE_READY respectively). assert(ann.m_time > now); } else if (ann.IsSelectable()) { // CANDIDATE_READY and CANDIDATE_BEST cannot have a time in the future (they should have remained // CANDIDATE_DELAYED, or should have been converted back to it if time went backwards). assert(ann.m_time <= now); } } } private: //! Wrapper around Index::...::erase that keeps m_peerinfo up to date. template<typename Tag> Iter<Tag> Erase(Iter<Tag> it) { auto peerit = m_peerinfo.find(it->m_peer); peerit->second.m_completed -= it->GetState() == State::COMPLETED; peerit->second.m_requested -= it->GetState() == State::REQUESTED; if (--peerit->second.m_total == 0) m_peerinfo.erase(peerit); return m_index.get<Tag>().erase(it); } //! Wrapper around Index::...::modify that keeps m_peerinfo up to date. template<typename Tag, typename Modifier> void Modify(Iter<Tag> it, Modifier modifier) { auto peerit = m_peerinfo.find(it->m_peer); peerit->second.m_completed -= it->GetState() == State::COMPLETED; peerit->second.m_requested -= it->GetState() == State::REQUESTED; m_index.get<Tag>().modify(it, std::move(modifier)); peerit->second.m_completed += it->GetState() == State::COMPLETED; peerit->second.m_requested += it->GetState() == State::REQUESTED; } //! Convert a CANDIDATE_DELAYED announcement into a CANDIDATE_READY. If this makes it the new best //! CANDIDATE_READY (and no REQUESTED exists) and better than the CANDIDATE_BEST (if any), it becomes the new //! CANDIDATE_BEST. void PromoteCandidateReady(Iter<ByTxHash> it) { assert(it != m_index.get<ByTxHash>().end()); assert(it->GetState() == State::CANDIDATE_DELAYED); // Convert CANDIDATE_DELAYED to CANDIDATE_READY first. Modify<ByTxHash>(it, [](Announcement& ann){ ann.SetState(State::CANDIDATE_READY); }); // The following code relies on the fact that the ByTxHash is sorted by txhash, and then by state (first // _DELAYED, then _READY, then _BEST/REQUESTED). Within the _READY announcements, the best one (highest // priority) comes last. Thus, if an existing _BEST exists for the same txhash that this announcement may // be preferred over, it must immediately follow the newly created _READY. auto it_next = std::next(it); if (it_next == m_index.get<ByTxHash>().end() || it_next->m_txhash != it->m_txhash || it_next->GetState() == State::COMPLETED) { // This is the new best CANDIDATE_READY, and there is no IsSelected() announcement for this txhash // already. Modify<ByTxHash>(it, [](Announcement& ann){ ann.SetState(State::CANDIDATE_BEST); }); } else if (it_next->GetState() == State::CANDIDATE_BEST) { Priority priority_old = m_computer(*it_next); Priority priority_new = m_computer(*it); if (priority_new > priority_old) { // There is a CANDIDATE_BEST announcement already, but this one is better. Modify<ByTxHash>(it_next, [](Announcement& ann){ ann.SetState(State::CANDIDATE_READY); }); Modify<ByTxHash>(it, [](Announcement& ann){ ann.SetState(State::CANDIDATE_BEST); }); } } } //! Change the state of an announcement to something non-IsSelected(). If it was IsSelected(), the next best //! announcement will be marked CANDIDATE_BEST. void ChangeAndReselect(Iter<ByTxHash> it, State new_state) { assert(new_state == State::COMPLETED || new_state == State::CANDIDATE_DELAYED); assert(it != m_index.get<ByTxHash>().end()); if (it->IsSelected() && it != m_index.get<ByTxHash>().begin()) { auto it_prev = std::prev(it); // The next best CANDIDATE_READY, if any, immediately precedes the REQUESTED or CANDIDATE_BEST // announcement in the ByTxHash index. if (it_prev->m_txhash == it->m_txhash && it_prev->GetState() == State::CANDIDATE_READY) { // If one such CANDIDATE_READY exists (for this txhash), convert it to CANDIDATE_BEST. Modify<ByTxHash>(it_prev, [](Announcement& ann){ ann.SetState(State::CANDIDATE_BEST); }); } } Modify<ByTxHash>(it, [new_state](Announcement& ann){ ann.SetState(new_state); }); } //! Check if 'it' is the only announcement for a given txhash that isn't COMPLETED. bool IsOnlyNonCompleted(Iter<ByTxHash> it) { assert(it != m_index.get<ByTxHash>().end()); assert(it->GetState() != State::COMPLETED); // Not allowed to call this on COMPLETED announcements. // This announcement has a predecessor that belongs to the same txhash. Due to ordering, and the // fact that 'it' is not COMPLETED, its predecessor cannot be COMPLETED here. if (it != m_index.get<ByTxHash>().begin() && std::prev(it)->m_txhash == it->m_txhash) return false; // This announcement has a successor that belongs to the same txhash, and is not COMPLETED. if (std::next(it) != m_index.get<ByTxHash>().end() && std::next(it)->m_txhash == it->m_txhash && std::next(it)->GetState() != State::COMPLETED) return false; return true; } /** Convert any announcement to a COMPLETED one. If there are no non-COMPLETED announcements left for this * txhash, they are deleted. If this was a REQUESTED announcement, and there are other CANDIDATEs left, the * best one is made CANDIDATE_BEST. Returns whether the announcement still exists. */ bool MakeCompleted(Iter<ByTxHash> it) { assert(it != m_index.get<ByTxHash>().end()); // Nothing to be done if it's already COMPLETED. if (it->GetState() == State::COMPLETED) return true; if (IsOnlyNonCompleted(it)) { // This is the last non-COMPLETED announcement for this txhash. Delete all. uint256 txhash = it->m_txhash; do { it = Erase<ByTxHash>(it); } while (it != m_index.get<ByTxHash>().end() && it->m_txhash == txhash); return false; } // Mark the announcement COMPLETED, and select the next best announcement (the first CANDIDATE_READY) if // needed. ChangeAndReselect(it, State::COMPLETED); return true; } //! Make the data structure consistent with a given point in time: //! - REQUESTED announcements with expiry <= now are turned into COMPLETED. //! - CANDIDATE_DELAYED announcements with reqtime <= now are turned into CANDIDATE_{READY,BEST}. //! - CANDIDATE_{READY,BEST} announcements with reqtime > now are turned into CANDIDATE_DELAYED. void SetTimePoint(std::chrono::microseconds now, std::vector<std::pair<NodeId, GenTxid>>* expired) { if (expired) expired->clear(); // Iterate over all CANDIDATE_DELAYED and REQUESTED from old to new, as long as they're in the past, // and convert them to CANDIDATE_READY and COMPLETED respectively. while (!m_index.empty()) { auto it = m_index.get<ByTime>().begin(); if (it->GetState() == State::CANDIDATE_DELAYED && it->m_time <= now) { PromoteCandidateReady(m_index.project<ByTxHash>(it)); } else if (it->GetState() == State::REQUESTED && it->m_time <= now) { if (expired) expired->emplace_back(it->m_peer, ToGenTxid(*it)); MakeCompleted(m_index.project<ByTxHash>(it)); } else { break; } } while (!m_index.empty()) { // If time went backwards, we may need to demote CANDIDATE_BEST and CANDIDATE_READY announcements back // to CANDIDATE_DELAYED. This is an unusual edge case, and unlikely to matter in production. However, // it makes it much easier to specify and test TxRequestTracker::Impl's behaviour. auto it = std::prev(m_index.get<ByTime>().end()); if (it->IsSelectable() && it->m_time > now) { ChangeAndReselect(m_index.project<ByTxHash>(it), State::CANDIDATE_DELAYED); } else { break; } } } public: explicit Impl(bool deterministic) : m_computer(deterministic), // Explicitly initialize m_index as we need to pass a reference to m_computer to ByTxHashViewExtractor. m_index(boost::make_tuple( boost::make_tuple(ByPeerViewExtractor(), std::less<ByPeerView>()), boost::make_tuple(ByTxHashViewExtractor(m_computer), std::less<ByTxHashView>()), boost::make_tuple(ByTimeViewExtractor(), std::less<ByTimeView>()) )) {} // Disable copying and assigning (a default copy won't work due the stateful ByTxHashViewExtractor). Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; void DisconnectedPeer(NodeId peer) { auto& index = m_index.get<ByPeer>(); auto it = index.lower_bound(ByPeerView{peer, false, uint256::ZERO}); while (it != index.end() && it->m_peer == peer) { // Check what to continue with after this iteration. 'it' will be deleted in what follows, so we need to // decide what to continue with afterwards. There are a number of cases to consider: // - std::next(it) is end() or belongs to a different peer. In that case, this is the last iteration // of the loop (denote this by setting it_next to end()). // - 'it' is not the only non-COMPLETED announcement for its txhash. This means it will be deleted, but // no other Announcement objects will be modified. Continue with std::next(it) if it belongs to the // same peer, but decide this ahead of time (as 'it' may change position in what follows). // - 'it' is the only non-COMPLETED announcement for its txhash. This means it will be deleted along // with all other announcements for the same txhash - which may include std::next(it). However, other // than 'it', no announcements for the same peer can be affected (due to (peer, txhash) uniqueness). // In other words, the situation where std::next(it) is deleted can only occur if std::next(it) // belongs to a different peer but the same txhash as 'it'. This is covered by the first bulletpoint // already, and we'll have set it_next to end(). auto it_next = (std::next(it) == index.end() || std::next(it)->m_peer != peer) ? index.end() : std::next(it); // If the announcement isn't already COMPLETED, first make it COMPLETED (which will mark other // CANDIDATEs as CANDIDATE_BEST, or delete all of a txhash's announcements if no non-COMPLETED ones are // left). if (MakeCompleted(m_index.project<ByTxHash>(it))) { // Then actually delete the announcement (unless it was already deleted by MakeCompleted). Erase<ByPeer>(it); } it = it_next; } } void ForgetTxHash(const uint256& txhash) { auto it = m_index.get<ByTxHash>().lower_bound(ByTxHashView{txhash, State::CANDIDATE_DELAYED, 0}); while (it != m_index.get<ByTxHash>().end() && it->m_txhash == txhash) { it = Erase<ByTxHash>(it); } } void ReceivedInv(NodeId peer, const GenTxid& gtxid, bool preferred, std::chrono::microseconds reqtime) { // Bail out if we already have a CANDIDATE_BEST announcement for this (txhash, peer) combination. The case // where there is a non-CANDIDATE_BEST announcement already will be caught by the uniqueness property of the // ByPeer index when we try to emplace the new object below. if (m_index.get<ByPeer>().count(ByPeerView{peer, true, gtxid.GetHash()})) return; // Try creating the announcement with CANDIDATE_DELAYED state (which will fail due to the uniqueness // of the ByPeer index if a non-CANDIDATE_BEST announcement already exists with the same txhash and peer). // Bail out in that case. auto ret = m_index.get<ByPeer>().emplace(gtxid, peer, preferred, reqtime, m_current_sequence); if (!ret.second) return; // Update accounting metadata. ++m_peerinfo[peer].m_total; ++m_current_sequence; } //! Find the GenTxids to request now from peer. std::vector<GenTxid> GetRequestable(NodeId peer, std::chrono::microseconds now, std::vector<std::pair<NodeId, GenTxid>>* expired) { // Move time. SetTimePoint(now, expired); // Find all CANDIDATE_BEST announcements for this peer. std::vector<const Announcement*> selected; auto it_peer = m_index.get<ByPeer>().lower_bound(ByPeerView{peer, true, uint256::ZERO}); while (it_peer != m_index.get<ByPeer>().end() && it_peer->m_peer == peer && it_peer->GetState() == State::CANDIDATE_BEST) { selected.emplace_back(&*it_peer); ++it_peer; } // Sort by sequence number. std::sort(selected.begin(), selected.end(), [](const Announcement* a, const Announcement* b) { return a->m_sequence < b->m_sequence; }); // Convert to GenTxid and return. std::vector<GenTxid> ret; ret.reserve(selected.size()); std::transform(selected.begin(), selected.end(), std::back_inserter(ret), [](const Announcement* ann) { return ToGenTxid(*ann); }); return ret; } void RequestedTx(NodeId peer, const uint256& txhash, std::chrono::microseconds expiry) { auto it = m_index.get<ByPeer>().find(ByPeerView{peer, true, txhash}); if (it == m_index.get<ByPeer>().end()) { // There is no CANDIDATE_BEST announcement, look for a _READY or _DELAYED instead. If the caller only // ever invokes RequestedTx with the values returned by GetRequestable, and no other non-const functions // other than ForgetTxHash and GetRequestable in between, this branch will never execute (as txhashes // returned by GetRequestable always correspond to CANDIDATE_BEST announcements). it = m_index.get<ByPeer>().find(ByPeerView{peer, false, txhash}); if (it == m_index.get<ByPeer>().end() || (it->GetState() != State::CANDIDATE_DELAYED && it->GetState() != State::CANDIDATE_READY)) { // There is no CANDIDATE announcement tracked for this peer, so we have nothing to do. Either this // txhash wasn't tracked at all (and the caller should have called ReceivedInv), or it was already // requested and/or completed for other reasons and this is just a superfluous RequestedTx call. return; } // Look for an existing CANDIDATE_BEST or REQUESTED with the same txhash. We only need to do this if the // found announcement had a different state than CANDIDATE_BEST. If it did, invariants guarantee that no // other CANDIDATE_BEST or REQUESTED can exist. auto it_old = m_index.get<ByTxHash>().lower_bound(ByTxHashView{txhash, State::CANDIDATE_BEST, 0}); if (it_old != m_index.get<ByTxHash>().end() && it_old->m_txhash == txhash) { if (it_old->GetState() == State::CANDIDATE_BEST) { // The data structure's invariants require that there can be at most one CANDIDATE_BEST or one // REQUESTED announcement per txhash (but not both simultaneously), so we have to convert any // existing CANDIDATE_BEST to another CANDIDATE_* when constructing another REQUESTED. // It doesn't matter whether we pick CANDIDATE_READY or _DELAYED here, as SetTimePoint() // will correct it at GetRequestable() time. If time only goes forward, it will always be // _READY, so pick that to avoid extra work in SetTimePoint(). Modify<ByTxHash>(it_old, [](Announcement& ann) { ann.SetState(State::CANDIDATE_READY); }); } else if (it_old->GetState() == State::REQUESTED) { // As we're no longer waiting for a response to the previous REQUESTED announcement, convert it // to COMPLETED. This also helps guaranteeing progress. Modify<ByTxHash>(it_old, [](Announcement& ann) { ann.SetState(State::COMPLETED); }); } } } Modify<ByPeer>(it, [expiry](Announcement& ann) { ann.SetState(State::REQUESTED); ann.m_time = expiry; }); } void ReceivedResponse(NodeId peer, const uint256& txhash) { // We need to search the ByPeer index for both (peer, false, txhash) and (peer, true, txhash). auto it = m_index.get<ByPeer>().find(ByPeerView{peer, false, txhash}); if (it == m_index.get<ByPeer>().end()) { it = m_index.get<ByPeer>().find(ByPeerView{peer, true, txhash}); } if (it != m_index.get<ByPeer>().end()) MakeCompleted(m_index.project<ByTxHash>(it)); } size_t CountInFlight(NodeId peer) const { auto it = m_peerinfo.find(peer); if (it != m_peerinfo.end()) return it->second.m_requested; return 0; } size_t CountCandidates(NodeId peer) const { auto it = m_peerinfo.find(peer); if (it != m_peerinfo.end()) return it->second.m_total - it->second.m_requested - it->second.m_completed; return 0; } size_t Count(NodeId peer) const { auto it = m_peerinfo.find(peer); if (it != m_peerinfo.end()) return it->second.m_total; return 0; } //! Count how many announcements are being tracked in total across all peers and transactions. size_t Size() const { return m_index.size(); } uint64_t ComputePriority(const uint256& txhash, NodeId peer, bool preferred) const { // Return Priority as a uint64_t as Priority is internal. return uint64_t{m_computer(txhash, peer, preferred)}; } }; TxRequestTracker::TxRequestTracker(bool deterministic) : m_impl{std::make_unique<TxRequestTracker::Impl>(deterministic)} {} TxRequestTracker::~TxRequestTracker() = default; void TxRequestTracker::ForgetTxHash(const uint256& txhash) { m_impl->ForgetTxHash(txhash); } void TxRequestTracker::DisconnectedPeer(NodeId peer) { m_impl->DisconnectedPeer(peer); } size_t TxRequestTracker::CountInFlight(NodeId peer) const { return m_impl->CountInFlight(peer); } size_t TxRequestTracker::CountCandidates(NodeId peer) const { return m_impl->CountCandidates(peer); } size_t TxRequestTracker::Count(NodeId peer) const { return m_impl->Count(peer); } size_t TxRequestTracker::Size() const { return m_impl->Size(); } void TxRequestTracker::SanityCheck() const { m_impl->SanityCheck(); } void TxRequestTracker::PostGetRequestableSanityCheck(std::chrono::microseconds now) const { m_impl->PostGetRequestableSanityCheck(now); } void TxRequestTracker::ReceivedInv(NodeId peer, const GenTxid& gtxid, bool preferred, std::chrono::microseconds reqtime) { m_impl->ReceivedInv(peer, gtxid, preferred, reqtime); } void TxRequestTracker::RequestedTx(NodeId peer, const uint256& txhash, std::chrono::microseconds expiry) { m_impl->RequestedTx(peer, txhash, expiry); } void TxRequestTracker::ReceivedResponse(NodeId peer, const uint256& txhash) { m_impl->ReceivedResponse(peer, txhash); } std::vector<GenTxid> TxRequestTracker::GetRequestable(NodeId peer, std::chrono::microseconds now, std::vector<std::pair<NodeId, GenTxid>>* expired) { return m_impl->GetRequestable(peer, now, expired); } uint64_t TxRequestTracker::ComputePriority(const uint256& txhash, NodeId peer, bool preferred) const { return m_impl->ComputePriority(txhash, peer, preferred); }
0
bitcoin
bitcoin/src/httpserver.cpp
// Copyright (c) 2015-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <httpserver.h> #include <chainparamsbase.h> #include <common/args.h> #include <compat/compat.h> #include <logging.h> #include <netbase.h> #include <node/interface_ui.h> #include <rpc/protocol.h> // For HTTP status codes #include <sync.h> #include <util/check.h> #include <util/signalinterrupt.h> #include <util/strencodings.h> #include <util/threadnames.h> #include <util/translation.h> #include <condition_variable> #include <cstdio> #include <cstdlib> #include <deque> #include <memory> #include <optional> #include <string> #include <unordered_map> #include <sys/types.h> #include <sys/stat.h> #include <event2/buffer.h> #include <event2/bufferevent.h> #include <event2/http.h> #include <event2/http_struct.h> #include <event2/keyvalq_struct.h> #include <event2/thread.h> #include <event2/util.h> #include <support/events.h> /** Maximum size of http request (request line + headers) */ static const size_t MAX_HEADERS_SIZE = 8192; /** HTTP request work item */ class HTTPWorkItem final : public HTTPClosure { public: HTTPWorkItem(std::unique_ptr<HTTPRequest> _req, const std::string &_path, const HTTPRequestHandler& _func): req(std::move(_req)), path(_path), func(_func) { } void operator()() override { func(req.get(), path); } std::unique_ptr<HTTPRequest> req; private: std::string path; HTTPRequestHandler func; }; /** Simple work queue for distributing work over multiple threads. * Work items are simply callable objects. */ template <typename WorkItem> class WorkQueue { private: Mutex cs; std::condition_variable cond GUARDED_BY(cs); std::deque<std::unique_ptr<WorkItem>> queue GUARDED_BY(cs); bool running GUARDED_BY(cs){true}; const size_t maxDepth; public: explicit WorkQueue(size_t _maxDepth) : maxDepth(_maxDepth) { } /** Precondition: worker threads have all stopped (they have been joined). */ ~WorkQueue() = default; /** Enqueue a work item */ bool Enqueue(WorkItem* item) EXCLUSIVE_LOCKS_REQUIRED(!cs) { LOCK(cs); if (!running || queue.size() >= maxDepth) { return false; } queue.emplace_back(std::unique_ptr<WorkItem>(item)); cond.notify_one(); return true; } /** Thread function */ void Run() EXCLUSIVE_LOCKS_REQUIRED(!cs) { while (true) { std::unique_ptr<WorkItem> i; { WAIT_LOCK(cs, lock); while (running && queue.empty()) cond.wait(lock); if (!running && queue.empty()) break; i = std::move(queue.front()); queue.pop_front(); } (*i)(); } } /** Interrupt and exit loops */ void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!cs) { LOCK(cs); running = false; cond.notify_all(); } }; struct HTTPPathHandler { HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler): prefix(_prefix), exactMatch(_exactMatch), handler(_handler) { } std::string prefix; bool exactMatch; HTTPRequestHandler handler; }; /** HTTP module state */ //! libevent event loop static struct event_base* eventBase = nullptr; //! HTTP server static struct evhttp* eventHTTP = nullptr; //! List of subnets to allow RPC connections from static std::vector<CSubNet> rpc_allow_subnets; //! Work queue for handling longer requests off the event loop thread static std::unique_ptr<WorkQueue<HTTPClosure>> g_work_queue{nullptr}; //! Handlers for (sub)paths static GlobalMutex g_httppathhandlers_mutex; static std::vector<HTTPPathHandler> pathHandlers GUARDED_BY(g_httppathhandlers_mutex); //! Bound listening sockets static std::vector<evhttp_bound_socket *> boundSockets; /** * @brief Helps keep track of open `evhttp_connection`s with active `evhttp_requests` * */ class HTTPRequestTracker { private: mutable Mutex m_mutex; mutable std::condition_variable m_cv; //! For each connection, keep a counter of how many requests are open std::unordered_map<const evhttp_connection*, size_t> m_tracker GUARDED_BY(m_mutex); void RemoveConnectionInternal(const decltype(m_tracker)::iterator it) EXCLUSIVE_LOCKS_REQUIRED(m_mutex) { m_tracker.erase(it); if (m_tracker.empty()) m_cv.notify_all(); } public: //! Increase request counter for the associated connection by 1 void AddRequest(evhttp_request* req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) { const evhttp_connection* conn{Assert(evhttp_request_get_connection(Assert(req)))}; WITH_LOCK(m_mutex, ++m_tracker[conn]); } //! Decrease request counter for the associated connection by 1, remove connection if counter is 0 void RemoveRequest(evhttp_request* req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) { const evhttp_connection* conn{Assert(evhttp_request_get_connection(Assert(req)))}; LOCK(m_mutex); auto it{m_tracker.find(conn)}; if (it != m_tracker.end() && it->second > 0) { if (--(it->second) == 0) RemoveConnectionInternal(it); } } //! Remove a connection entirely void RemoveConnection(const evhttp_connection* conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) { LOCK(m_mutex); auto it{m_tracker.find(Assert(conn))}; if (it != m_tracker.end()) RemoveConnectionInternal(it); } size_t CountActiveConnections() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) { return WITH_LOCK(m_mutex, return m_tracker.size()); } //! Wait until there are no more connections with active requests in the tracker void WaitUntilEmpty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) { WAIT_LOCK(m_mutex, lock); m_cv.wait(lock, [this]() EXCLUSIVE_LOCKS_REQUIRED(m_mutex) { return m_tracker.empty(); }); } }; //! Track active requests static HTTPRequestTracker g_requests; /** Check if a network address is allowed to access the HTTP server */ static bool ClientAllowed(const CNetAddr& netaddr) { if (!netaddr.IsValid()) return false; for(const CSubNet& subnet : rpc_allow_subnets) if (subnet.Match(netaddr)) return true; return false; } /** Initialize ACL list for HTTP server */ static bool InitHTTPAllowList() { rpc_allow_subnets.clear(); rpc_allow_subnets.emplace_back(LookupHost("127.0.0.1", false).value(), 8); // always allow IPv4 local subnet rpc_allow_subnets.emplace_back(LookupHost("::1", false).value()); // always allow IPv6 localhost for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) { const CSubNet subnet{LookupSubNet(strAllow)}; if (!subnet.IsValid()) { uiInterface.ThreadSafeMessageBox( strprintf(Untranslated("Invalid -rpcallowip subnet specification: %s. Valid 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)."), strAllow), "", CClientUIInterface::MSG_ERROR); return false; } rpc_allow_subnets.push_back(subnet); } std::string strAllowed; for (const CSubNet& subnet : rpc_allow_subnets) strAllowed += subnet.ToString() + " "; LogPrint(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed); return true; } /** HTTP request method as string - use for logging only */ std::string RequestMethodString(HTTPRequest::RequestMethod m) { switch (m) { case HTTPRequest::GET: return "GET"; case HTTPRequest::POST: return "POST"; case HTTPRequest::HEAD: return "HEAD"; case HTTPRequest::PUT: return "PUT"; case HTTPRequest::UNKNOWN: return "unknown"; } // no default case, so the compiler can warn about missing cases assert(false); } /** HTTP request callback */ static void http_request_cb(struct evhttp_request* req, void* arg) { evhttp_connection* conn{evhttp_request_get_connection(req)}; // Track active requests { g_requests.AddRequest(req); evhttp_request_set_on_complete_cb(req, [](struct evhttp_request* req, void*) { g_requests.RemoveRequest(req); }, nullptr); evhttp_connection_set_closecb(conn, [](evhttp_connection* conn, void* arg) { g_requests.RemoveConnection(conn); }, nullptr); } // Disable reading to work around a libevent bug, fixed in 2.1.9 // See https://github.com/libevent/libevent/commit/5ff8eb26371c4dc56f384b2de35bea2d87814779 // and https://github.com/bitcoin/bitcoin/pull/11593. if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) { if (conn) { bufferevent* bev = evhttp_connection_get_bufferevent(conn); if (bev) { bufferevent_disable(bev, EV_READ); } } } auto hreq{std::make_unique<HTTPRequest>(req, *static_cast<const util::SignalInterrupt*>(arg))}; // Early address-based allow check if (!ClientAllowed(hreq->GetPeer())) { LogPrint(BCLog::HTTP, "HTTP request from %s rejected: Client network is not allowed RPC access\n", hreq->GetPeer().ToStringAddrPort()); hreq->WriteReply(HTTP_FORBIDDEN); return; } // Early reject unknown HTTP methods if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) { LogPrint(BCLog::HTTP, "HTTP request from %s rejected: Unknown HTTP request method\n", hreq->GetPeer().ToStringAddrPort()); hreq->WriteReply(HTTP_BAD_METHOD); return; } LogPrint(BCLog::HTTP, "Received a %s request for %s from %s\n", RequestMethodString(hreq->GetRequestMethod()), SanitizeString(hreq->GetURI(), SAFE_CHARS_URI).substr(0, 100), hreq->GetPeer().ToStringAddrPort()); // Find registered handler for prefix std::string strURI = hreq->GetURI(); std::string path; LOCK(g_httppathhandlers_mutex); std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin(); std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end(); for (; i != iend; ++i) { bool match = false; if (i->exactMatch) match = (strURI == i->prefix); else match = (strURI.substr(0, i->prefix.size()) == i->prefix); if (match) { path = strURI.substr(i->prefix.size()); break; } } // Dispatch to worker thread if (i != iend) { std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler)); assert(g_work_queue); if (g_work_queue->Enqueue(item.get())) { item.release(); /* if true, queue took ownership */ } else { LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n"); item->req->WriteReply(HTTP_SERVICE_UNAVAILABLE, "Work queue depth exceeded"); } } else { hreq->WriteReply(HTTP_NOT_FOUND); } } /** Callback to reject HTTP requests after shutdown. */ static void http_reject_request_cb(struct evhttp_request* req, void*) { LogPrint(BCLog::HTTP, "Rejecting request while shutting down\n"); evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr); } /** Event dispatcher thread */ static void ThreadHTTP(struct event_base* base) { util::ThreadRename("http"); LogPrint(BCLog::HTTP, "Entering http event loop\n"); event_base_dispatch(base); // Event loop will be interrupted by InterruptHTTPServer() LogPrint(BCLog::HTTP, "Exited http event loop\n"); } /** Bind HTTP server to specified addresses */ static bool HTTPBindAddresses(struct evhttp* http) { uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))}; std::vector<std::pair<std::string, uint16_t>> endpoints; // Determine what addresses to bind to if (!(gArgs.IsArgSet("-rpcallowip") && gArgs.IsArgSet("-rpcbind"))) { // Default to loopback if not allowing external IPs endpoints.emplace_back("::1", http_port); endpoints.emplace_back("127.0.0.1", http_port); if (gArgs.IsArgSet("-rpcallowip")) { LogPrintf("WARNING: option -rpcallowip was specified without -rpcbind; this doesn't usually make sense\n"); } if (gArgs.IsArgSet("-rpcbind")) { LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n"); } } else if (gArgs.IsArgSet("-rpcbind")) { // Specific bind address for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) { uint16_t port{http_port}; std::string host; SplitHostPort(strRPCBind, port, host); endpoints.emplace_back(host, port); } } // Bind addresses for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) { LogPrintf("Binding RPC on address %s port %i\n", i->first, i->second); evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second); if (bind_handle) { const std::optional<CNetAddr> addr{LookupHost(i->first, false)}; if (i->first.empty() || (addr.has_value() && addr->IsBindAny())) { LogPrintf("WARNING: the RPC server is not safe to expose to untrusted networks such as the public internet\n"); } boundSockets.push_back(bind_handle); } else { LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second); } } return !boundSockets.empty(); } /** Simple wrapper to set thread name and run work queue */ static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue, int worker_num) { util::ThreadRename(strprintf("httpworker.%i", worker_num)); queue->Run(); } /** libevent event log callback */ static void libevent_log_cb(int severity, const char *msg) { BCLog::Level level; switch (severity) { case EVENT_LOG_DEBUG: level = BCLog::Level::Debug; break; case EVENT_LOG_MSG: level = BCLog::Level::Info; break; case EVENT_LOG_WARN: level = BCLog::Level::Warning; break; default: // EVENT_LOG_ERR and others are mapped to error level = BCLog::Level::Error; break; } LogPrintLevel(BCLog::LIBEVENT, level, "%s\n", msg); } bool InitHTTPServer(const util::SignalInterrupt& interrupt) { if (!InitHTTPAllowList()) return false; // Redirect libevent's logging to our own log event_set_log_callback(&libevent_log_cb); // Update libevent's log handling. UpdateHTTPServerLogging(LogInstance().WillLogCategory(BCLog::LIBEVENT)); #ifdef WIN32 evthread_use_windows_threads(); #else evthread_use_pthreads(); #endif raii_event_base base_ctr = obtain_event_base(); /* Create a new evhttp object to handle requests. */ raii_evhttp http_ctr = obtain_evhttp(base_ctr.get()); struct evhttp* http = http_ctr.get(); if (!http) { LogPrintf("couldn't create evhttp. Exiting.\n"); return false; } evhttp_set_timeout(http, gArgs.GetIntArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT)); evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE); evhttp_set_max_body_size(http, MAX_SIZE); evhttp_set_gencb(http, http_request_cb, (void*)&interrupt); if (!HTTPBindAddresses(http)) { LogPrintf("Unable to bind any endpoint for RPC server\n"); return false; } LogPrint(BCLog::HTTP, "Initialized HTTP server\n"); int workQueueDepth = std::max((long)gArgs.GetIntArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L); LogPrintfCategory(BCLog::HTTP, "creating work queue of depth %d\n", workQueueDepth); g_work_queue = std::make_unique<WorkQueue<HTTPClosure>>(workQueueDepth); // transfer ownership to eventBase/HTTP via .release() eventBase = base_ctr.release(); eventHTTP = http_ctr.release(); return true; } void UpdateHTTPServerLogging(bool enable) { if (enable) { event_enable_debug_logging(EVENT_DBG_ALL); } else { event_enable_debug_logging(EVENT_DBG_NONE); } } static std::thread g_thread_http; static std::vector<std::thread> g_thread_http_workers; void StartHTTPServer() { LogPrint(BCLog::HTTP, "Starting HTTP server\n"); int rpcThreads = std::max((long)gArgs.GetIntArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L); LogPrintfCategory(BCLog::HTTP, "starting %d worker threads\n", rpcThreads); g_thread_http = std::thread(ThreadHTTP, eventBase); for (int i = 0; i < rpcThreads; i++) { g_thread_http_workers.emplace_back(HTTPWorkQueueRun, g_work_queue.get(), i); } } void InterruptHTTPServer() { LogPrint(BCLog::HTTP, "Interrupting HTTP server\n"); if (eventHTTP) { // Reject requests on current connections evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr); } if (g_work_queue) { g_work_queue->Interrupt(); } } void StopHTTPServer() { LogPrint(BCLog::HTTP, "Stopping HTTP server\n"); if (g_work_queue) { LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n"); for (auto& thread : g_thread_http_workers) { thread.join(); } g_thread_http_workers.clear(); } // Unlisten sockets, these are what make the event loop running, which means // that after this and all connections are closed the event loop will quit. for (evhttp_bound_socket *socket : boundSockets) { evhttp_del_accept_socket(eventHTTP, socket); } boundSockets.clear(); { if (const auto n_connections{g_requests.CountActiveConnections()}; n_connections != 0) { LogPrint(BCLog::HTTP, "Waiting for %d connections to stop HTTP server\n", n_connections); } g_requests.WaitUntilEmpty(); } if (eventHTTP) { // Schedule a callback to call evhttp_free in the event base thread, so // that evhttp_free does not need to be called again after the handling // of unfinished request connections that follows. event_base_once(eventBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) { evhttp_free(eventHTTP); eventHTTP = nullptr; }, nullptr, nullptr); } if (eventBase) { LogPrint(BCLog::HTTP, "Waiting for HTTP event thread to exit\n"); if (g_thread_http.joinable()) g_thread_http.join(); event_base_free(eventBase); eventBase = nullptr; } g_work_queue.reset(); LogPrint(BCLog::HTTP, "Stopped HTTP server\n"); } struct event_base* EventBase() { return eventBase; } static void httpevent_callback_fn(evutil_socket_t, short, void* data) { // Static handler: simply call inner handler HTTPEvent *self = static_cast<HTTPEvent*>(data); self->handler(); if (self->deleteWhenTriggered) delete self; } HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void()>& _handler): deleteWhenTriggered(_deleteWhenTriggered), handler(_handler) { ev = event_new(base, -1, 0, httpevent_callback_fn, this); assert(ev); } HTTPEvent::~HTTPEvent() { event_free(ev); } void HTTPEvent::trigger(struct timeval* tv) { if (tv == nullptr) event_active(ev, 0, 0); // immediately trigger event in main thread else evtimer_add(ev, tv); // trigger after timeval passed } HTTPRequest::HTTPRequest(struct evhttp_request* _req, const util::SignalInterrupt& interrupt, bool _replySent) : req(_req), m_interrupt(interrupt), replySent(_replySent) { } HTTPRequest::~HTTPRequest() { if (!replySent) { // Keep track of whether reply was sent to avoid request leaks LogPrintf("%s: Unhandled request\n", __func__); WriteReply(HTTP_INTERNAL_SERVER_ERROR, "Unhandled request"); } // evhttpd cleans up the request, as long as a reply was sent. } std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr) const { const struct evkeyvalq* headers = evhttp_request_get_input_headers(req); assert(headers); const char* val = evhttp_find_header(headers, hdr.c_str()); if (val) return std::make_pair(true, val); else return std::make_pair(false, ""); } std::string HTTPRequest::ReadBody() { struct evbuffer* buf = evhttp_request_get_input_buffer(req); if (!buf) return ""; size_t size = evbuffer_get_length(buf); /** Trivial implementation: if this is ever a performance bottleneck, * internal copying can be avoided in multi-segment buffers by using * evbuffer_peek and an awkward loop. Though in that case, it'd be even * better to not copy into an intermediate string but use a stream * abstraction to consume the evbuffer on the fly in the parsing algorithm. */ const char* data = (const char*)evbuffer_pullup(buf, size); if (!data) // returns nullptr in case of empty buffer return ""; std::string rv(data, size); evbuffer_drain(buf, size); return rv; } void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value) { struct evkeyvalq* headers = evhttp_request_get_output_headers(req); assert(headers); evhttp_add_header(headers, hdr.c_str(), value.c_str()); } /** Closure sent to main thread to request a reply to be sent to * a HTTP request. * Replies must be sent in the main loop in the main http thread, * this cannot be done from worker threads. */ void HTTPRequest::WriteReply(int nStatus, const std::string& strReply) { assert(!replySent && req); if (m_interrupt) { WriteHeader("Connection", "close"); } // Send event to main http thread to send reply message struct evbuffer* evb = evhttp_request_get_output_buffer(req); assert(evb); evbuffer_add(evb, strReply.data(), strReply.size()); auto req_copy = req; HTTPEvent* ev = new HTTPEvent(eventBase, true, [req_copy, nStatus]{ evhttp_send_reply(req_copy, nStatus, nullptr, nullptr); // Re-enable reading from the socket. This is the second part of the libevent // workaround above. if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) { evhttp_connection* conn = evhttp_request_get_connection(req_copy); if (conn) { bufferevent* bev = evhttp_connection_get_bufferevent(conn); if (bev) { bufferevent_enable(bev, EV_READ | EV_WRITE); } } } }); ev->trigger(nullptr); replySent = true; req = nullptr; // transferred back to main thread } CService HTTPRequest::GetPeer() const { evhttp_connection* con = evhttp_request_get_connection(req); CService peer; if (con) { // evhttp retains ownership over returned address string const char* address = ""; uint16_t port = 0; #ifdef HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR evhttp_connection_get_peer(con, &address, &port); #else evhttp_connection_get_peer(con, (char**)&address, &port); #endif // HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR peer = MaybeFlipIPv6toCJDNS(LookupNumeric(address, port)); } return peer; } std::string HTTPRequest::GetURI() const { return evhttp_request_get_uri(req); } HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod() const { switch (evhttp_request_get_command(req)) { case EVHTTP_REQ_GET: return GET; case EVHTTP_REQ_POST: return POST; case EVHTTP_REQ_HEAD: return HEAD; case EVHTTP_REQ_PUT: return PUT; default: return UNKNOWN; } } std::optional<std::string> HTTPRequest::GetQueryParameter(const std::string& key) const { const char* uri{evhttp_request_get_uri(req)}; return GetQueryParameterFromUri(uri, key); } std::optional<std::string> GetQueryParameterFromUri(const char* uri, const std::string& key) { evhttp_uri* uri_parsed{evhttp_uri_parse(uri)}; if (!uri_parsed) { throw std::runtime_error("URI parsing failed, it likely contained RFC 3986 invalid characters"); } const char* query{evhttp_uri_get_query(uri_parsed)}; std::optional<std::string> result; if (query) { // Parse the query string into a key-value queue and iterate over it struct evkeyvalq params_q; evhttp_parse_query_str(query, &params_q); for (struct evkeyval* param{params_q.tqh_first}; param != nullptr; param = param->next.tqe_next) { if (param->key == key) { result = param->value; break; } } evhttp_clear_headers(&params_q); } evhttp_uri_free(uri_parsed); return result; } void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler) { LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch); LOCK(g_httppathhandlers_mutex); pathHandlers.emplace_back(prefix, exactMatch, handler); } void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch) { LOCK(g_httppathhandlers_mutex); std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin(); std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end(); for (; i != iend; ++i) if (i->prefix == prefix && i->exactMatch == exactMatch) break; if (i != iend) { LogPrint(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch); pathHandlers.erase(i); } }
0
bitcoin
bitcoin/src/logging.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_LOGGING_H #define BITCOIN_LOGGING_H #include <threadsafety.h> #include <tinyformat.h> #include <util/fs.h> #include <util/string.h> #include <atomic> #include <cstdint> #include <functional> #include <list> #include <mutex> #include <string> #include <unordered_map> #include <vector> static const bool DEFAULT_LOGTIMEMICROS = false; static const bool DEFAULT_LOGIPS = false; static const bool DEFAULT_LOGTIMESTAMPS = true; static const bool DEFAULT_LOGTHREADNAMES = false; static const bool DEFAULT_LOGSOURCELOCATIONS = false; extern const char * const DEFAULT_DEBUGLOGFILE; extern bool fLogIPs; struct LogCategory { std::string category; bool active; }; namespace BCLog { enum LogFlags : uint32_t { NONE = 0, NET = (1 << 0), TOR = (1 << 1), MEMPOOL = (1 << 2), HTTP = (1 << 3), BENCH = (1 << 4), ZMQ = (1 << 5), WALLETDB = (1 << 6), RPC = (1 << 7), ESTIMATEFEE = (1 << 8), ADDRMAN = (1 << 9), SELECTCOINS = (1 << 10), REINDEX = (1 << 11), CMPCTBLOCK = (1 << 12), RAND = (1 << 13), PRUNE = (1 << 14), PROXY = (1 << 15), MEMPOOLREJ = (1 << 16), LIBEVENT = (1 << 17), COINDB = (1 << 18), QT = (1 << 19), LEVELDB = (1 << 20), VALIDATION = (1 << 21), I2P = (1 << 22), IPC = (1 << 23), #ifdef DEBUG_LOCKCONTENTION LOCK = (1 << 24), #endif UTIL = (1 << 25), BLOCKSTORAGE = (1 << 26), TXRECONCILIATION = (1 << 27), SCAN = (1 << 28), TXPACKAGES = (1 << 29), ALL = ~(uint32_t)0, }; enum class Level { Trace = 0, // High-volume or detailed logging for development/debugging Debug, // Reasonably noisy logging, but still usable in production Info, // Default Warning, Error, None, // Internal use only }; constexpr auto DEFAULT_LOG_LEVEL{Level::Debug}; class Logger { private: mutable StdMutex m_cs; // Can not use Mutex from sync.h because in debug mode it would cause a deadlock when a potential deadlock was detected FILE* m_fileout GUARDED_BY(m_cs) = nullptr; std::list<std::string> m_msgs_before_open GUARDED_BY(m_cs); bool m_buffering GUARDED_BY(m_cs) = true; //!< Buffer messages before logging can be started. /** * m_started_new_line is a state variable that will suppress printing of * the timestamp when multiple calls are made that don't end in a * newline. */ std::atomic_bool m_started_new_line{true}; //! Category-specific log level. Overrides `m_log_level`. std::unordered_map<LogFlags, Level> m_category_log_levels GUARDED_BY(m_cs); //! If there is no category-specific log level, all logs with a severity //! level lower than `m_log_level` will be ignored. std::atomic<Level> m_log_level{DEFAULT_LOG_LEVEL}; /** Log categories bitfield. */ std::atomic<uint32_t> m_categories{0}; std::string LogTimestampStr(const std::string& str); /** Slots that connect to the print signal */ std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {}; public: bool m_print_to_console = false; bool m_print_to_file = false; bool m_log_timestamps = DEFAULT_LOGTIMESTAMPS; bool m_log_time_micros = DEFAULT_LOGTIMEMICROS; bool m_log_threadnames = DEFAULT_LOGTHREADNAMES; bool m_log_sourcelocations = DEFAULT_LOGSOURCELOCATIONS; fs::path m_file_path; std::atomic<bool> m_reopen_file{false}; /** Send a string to the log output */ void LogPrintStr(const std::string& str, const std::string& logging_function, const std::string& source_file, int source_line, BCLog::LogFlags category, BCLog::Level level); /** Returns whether logs will be written to any output */ bool Enabled() const { StdLockGuard scoped_lock(m_cs); return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty(); } /** Connect a slot to the print signal and return the connection */ std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun) { StdLockGuard scoped_lock(m_cs); m_print_callbacks.push_back(std::move(fun)); return --m_print_callbacks.end(); } /** Delete a connection */ void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it) { StdLockGuard scoped_lock(m_cs); m_print_callbacks.erase(it); } /** Start logging (and flush all buffered messages) */ bool StartLogging(); /** Only for testing */ void DisconnectTestLogger(); void ShrinkDebugFile(); std::unordered_map<LogFlags, Level> CategoryLevels() const { StdLockGuard scoped_lock(m_cs); return m_category_log_levels; } void SetCategoryLogLevel(const std::unordered_map<LogFlags, Level>& levels) { StdLockGuard scoped_lock(m_cs); m_category_log_levels = levels; } bool SetCategoryLogLevel(const std::string& category_str, const std::string& level_str); Level LogLevel() const { return m_log_level.load(); } void SetLogLevel(Level level) { m_log_level = level; } bool SetLogLevel(const std::string& level); uint32_t GetCategoryMask() const { return m_categories.load(); } void EnableCategory(LogFlags flag); bool EnableCategory(const std::string& str); void DisableCategory(LogFlags flag); bool DisableCategory(const std::string& str); bool WillLogCategory(LogFlags category) const; bool WillLogCategoryLevel(LogFlags category, Level level) const; /** Returns a vector of the log categories in alphabetical order. */ std::vector<LogCategory> LogCategoriesList() const; /** Returns a string with the log categories in alphabetical order. */ std::string LogCategoriesString() const { return Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; }); }; //! Returns a string with all user-selectable log levels. std::string LogLevelsString() const; //! Returns the string representation of a log level. std::string LogLevelToStr(BCLog::Level level) const; bool DefaultShrinkDebugFile() const; }; } // namespace BCLog BCLog::Logger& LogInstance(); /** Return true if log accepts specified category, at the specified level. */ static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level) { return LogInstance().WillLogCategoryLevel(category, level); } /** Return true if str parses as a log category and set the flag */ bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str); // Be conservative when using LogPrintf/error or other things which // unconditionally log to debug.log! It should not be the case that an inbound // peer can fill up a user's disk with debug.log entries. template <typename... Args> static inline void LogPrintf_(const std::string& logging_function, const std::string& source_file, const int source_line, const BCLog::LogFlags flag, const BCLog::Level level, const char* fmt, const Args&... args) { if (LogInstance().Enabled()) { std::string log_msg; try { log_msg = tfm::format(fmt, args...); } catch (tinyformat::format_error& fmterr) { /* Original format string will have newline so don't add one here */ log_msg = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + fmt; } LogInstance().LogPrintStr(log_msg, logging_function, source_file, source_line, flag, level); } } #define LogPrintLevel_(category, level, ...) LogPrintf_(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__) // Log unconditionally. #define LogPrintf(...) LogPrintLevel_(BCLog::LogFlags::NONE, BCLog::Level::None, __VA_ARGS__) // Log unconditionally, prefixing the output with the passed category name. #define LogPrintfCategory(category, ...) LogPrintLevel_(category, BCLog::Level::None, __VA_ARGS__) // Use a macro instead of a function for conditional logging to prevent // evaluating arguments when logging for the category is not enabled. // Log conditionally, prefixing the output with the passed category name. #define LogPrint(category, ...) \ do { \ if (LogAcceptCategory((category), BCLog::Level::Debug)) { \ LogPrintLevel_(category, BCLog::Level::None, __VA_ARGS__); \ } \ } while (0) // Log conditionally, prefixing the output with the passed category name and severity level. #define LogPrintLevel(category, level, ...) \ do { \ if (LogAcceptCategory((category), (level))) { \ LogPrintLevel_(category, level, __VA_ARGS__); \ } \ } while (0) template <typename... Args> bool error(const char* fmt, const Args&... args) { LogPrintf("ERROR: %s\n", tfm::format(fmt, args...)); return false; } #endif // BITCOIN_LOGGING_H
0
bitcoin
bitcoin/src/merkleblock.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2020 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 <merkleblock.h> #include <hash.h> #include <consensus/consensus.h> std::vector<unsigned char> BitsToBytes(const std::vector<bool>& bits) { std::vector<unsigned char> ret((bits.size() + 7) / 8); for (unsigned int p = 0; p < bits.size(); p++) { ret[p / 8] |= bits[p] << (p % 8); } return ret; } std::vector<bool> BytesToBits(const std::vector<unsigned char>& bytes) { std::vector<bool> ret(bytes.size() * 8); for (unsigned int p = 0; p < ret.size(); p++) { ret[p] = (bytes[p / 8] & (1 << (p % 8))) != 0; } return ret; } CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter* filter, const std::set<Txid>* txids) { header = block.GetBlockHeader(); std::vector<bool> vMatch; std::vector<uint256> vHashes; vMatch.reserve(block.vtx.size()); vHashes.reserve(block.vtx.size()); for (unsigned int i = 0; i < block.vtx.size(); i++) { const Txid& hash{block.vtx[i]->GetHash()}; if (txids && txids->count(hash)) { vMatch.push_back(true); } else if (filter && filter->IsRelevantAndUpdate(*block.vtx[i])) { vMatch.push_back(true); vMatchedTxn.emplace_back(i, hash); } else { vMatch.push_back(false); } vHashes.push_back(hash); } txn = CPartialMerkleTree(vHashes, vMatch); } uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) { //we can never have zero txs in a merkle block, we always need the coinbase tx //if we do not have this assert, we can hit a memory access violation when indexing into vTxid assert(vTxid.size() != 0); if (height == 0) { // hash at height 0 is the txids themselves return vTxid[pos]; } else { // calculate left hash uint256 left = CalcHash(height-1, pos*2, vTxid), right; // calculate right hash if not beyond the end of the array - copy left hash otherwise if (pos*2+1 < CalcTreeWidth(height-1)) right = CalcHash(height-1, pos*2+1, vTxid); else right = left; // combine subhashes return Hash(left, right); } } void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) { // determine whether this node is the parent of at least one matched txid bool fParentOfMatch = false; for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++) fParentOfMatch |= vMatch[p]; // store as flag bit vBits.push_back(fParentOfMatch); if (height==0 || !fParentOfMatch) { // if at height 0, or nothing interesting below, store hash and stop vHash.push_back(CalcHash(height, pos, vTxid)); } else { // otherwise, don't store any hash, but descend into the subtrees TraverseAndBuild(height-1, pos*2, vTxid, vMatch); if (pos*2+1 < CalcTreeWidth(height-1)) TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch); } } uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) { if (nBitsUsed >= vBits.size()) { // overflowed the bits array - failure fBad = true; return uint256(); } bool fParentOfMatch = vBits[nBitsUsed++]; if (height==0 || !fParentOfMatch) { // if at height 0, or nothing interesting below, use stored hash and do not descend if (nHashUsed >= vHash.size()) { // overflowed the hash array - failure fBad = true; return uint256(); } const uint256 &hash = vHash[nHashUsed++]; if (height==0 && fParentOfMatch) { // in case of height 0, we have a matched txid vMatch.push_back(hash); vnIndex.push_back(pos); } return hash; } else { // otherwise, descend into the subtrees to extract matched txids and hashes uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch, vnIndex), right; if (pos*2+1 < CalcTreeWidth(height-1)) { right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch, vnIndex); if (right == left) { // The left and right branches should never be identical, as the transaction // hashes covered by them must each be unique. fBad = true; } } else { right = left; } // and combine them before returning return Hash(left, right); } } CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) { // reset state vBits.clear(); vHash.clear(); // calculate height of tree int nHeight = 0; while (CalcTreeWidth(nHeight) > 1) nHeight++; // traverse the partial tree TraverseAndBuild(nHeight, 0, vTxid, vMatch); } CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {} uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) { vMatch.clear(); // An empty set will not work if (nTransactions == 0) return uint256(); // check for excessively high numbers of transactions if (nTransactions > MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT) return uint256(); // there can never be more hashes provided than one for every txid if (vHash.size() > nTransactions) return uint256(); // there must be at least one bit per node in the partial tree, and at least one node per hash if (vBits.size() < vHash.size()) return uint256(); // calculate height of tree int nHeight = 0; while (CalcTreeWidth(nHeight) > 1) nHeight++; // traverse the partial tree unsigned int nBitsUsed = 0, nHashUsed = 0; uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch, vnIndex); // verify that no problems occurred during the tree traversal if (fBad) return uint256(); // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence) if ((nBitsUsed+7)/8 != (vBits.size()+7)/8) return uint256(); // verify that all hashes were consumed if (nHashUsed != vHash.size()) return uint256(); return hashMerkleRoot; }
0
bitcoin
bitcoin/src/chainparamsbase.cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2021 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 <chainparamsbase.h> #include <common/args.h> #include <tinyformat.h> #include <util/chaintype.h> #include <assert.h> void SetupChainParamsBaseOptions(ArgsManager& argsman) { argsman.AddArg("-chain=<chain>", "Use the chain <chain> (default: main). Allowed values: main, test, signet, regtest", ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS); argsman.AddArg("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. " "This is intended for regression testing tools and app development. Equivalent to -chain=regtest.", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS); argsman.AddArg("-testactivationheight=name@height.", "Set the activation height of 'name' (segwit, bip34, dersig, cltv, csv). (regtest-only)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-testnet", "Use the test chain. Equivalent to -chain=test.", ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS); argsman.AddArg("-vbparams=deployment:start:end[:min_activation_height]", "Use given start/end times and min_activation_height for specified version bits deployment (regtest-only)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS); argsman.AddArg("-signet", "Use the signet chain. Equivalent to -chain=signet. Note that the network is defined by the -signetchallenge parameter", ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS); argsman.AddArg("-signetchallenge", "Blocks must satisfy the given script to be considered valid (only for signet networks; defaults to the global default signet test network challenge)", ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_NEGATION, OptionsCategory::CHAINPARAMS); argsman.AddArg("-signetseednode", "Specify a seed node for the signet network, in the hostname[:port] format, e.g. sig.net:1234 (may be used multiple times to specify multiple seed nodes; defaults to the global default signet test network seed node(s))", ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_NEGATION, OptionsCategory::CHAINPARAMS); } static std::unique_ptr<CBaseChainParams> globalChainBaseParams; const CBaseChainParams& BaseParams() { assert(globalChainBaseParams); return *globalChainBaseParams; } /** * Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have * been chosen arbitrarily to keep ranges of used ports tight. */ std::unique_ptr<CBaseChainParams> CreateBaseChainParams(const ChainType chain) { switch (chain) { case ChainType::MAIN: return std::make_unique<CBaseChainParams>("", 8332, 8334); case ChainType::TESTNET: return std::make_unique<CBaseChainParams>("testnet3", 18332, 18334); case ChainType::SIGNET: return std::make_unique<CBaseChainParams>("signet", 38332, 38334); case ChainType::REGTEST: return std::make_unique<CBaseChainParams>("regtest", 18443, 18445); } assert(false); } void SelectBaseParams(const ChainType chain) { globalChainBaseParams = CreateBaseChainParams(chain); gArgs.SelectConfigNetwork(ChainTypeToString(chain)); }
0
bitcoin
bitcoin/src/net_processing.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_NET_PROCESSING_H #define BITCOIN_NET_PROCESSING_H #include <net.h> #include <validationinterface.h> class AddrMan; class CChainParams; class CTxMemPool; class ChainstateManager; /** Whether transaction reconciliation protocol should be enabled by default. */ static constexpr bool DEFAULT_TXRECONCILIATION_ENABLE{false}; /** Default for -maxorphantx, maximum number of orphan transactions kept in memory */ static const uint32_t DEFAULT_MAX_ORPHAN_TRANSACTIONS{100}; /** Default number of non-mempool transactions to keep around for block reconstruction. Includes orphan, replaced, and rejected transactions. */ static const uint32_t DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN{100}; static const bool DEFAULT_PEERBLOOMFILTERS = false; static const bool DEFAULT_PEERBLOCKFILTERS = false; /** Threshold for marking a node to be discouraged, e.g. disconnected and added to the discouragement filter. */ static const int DISCOURAGEMENT_THRESHOLD{100}; /** Maximum number of outstanding CMPCTBLOCK requests for the same block. */ static const unsigned int MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK = 3; struct CNodeStateStats { int nSyncHeight = -1; int nCommonHeight = -1; int m_starting_height = -1; std::chrono::microseconds m_ping_wait; std::vector<int> vHeightInFlight; bool m_relay_txs; CAmount m_fee_filter_received; uint64_t m_addr_processed = 0; uint64_t m_addr_rate_limited = 0; bool m_addr_relay_enabled{false}; ServiceFlags their_services; int64_t presync_height{-1}; }; class PeerManager : public CValidationInterface, public NetEventsInterface { public: struct Options { //! Whether this node is running in -blocksonly mode bool ignore_incoming_txs{DEFAULT_BLOCKSONLY}; //! Whether transaction reconciliation protocol is enabled bool reconcile_txs{DEFAULT_TXRECONCILIATION_ENABLE}; //! Maximum number of orphan transactions kept in memory uint32_t max_orphan_txs{DEFAULT_MAX_ORPHAN_TRANSACTIONS}; //! Number of non-mempool transactions to keep around for block reconstruction. Includes //! orphan, replaced, and rejected transactions. uint32_t max_extra_txs{DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN}; //! Whether all P2P messages are captured to disk bool capture_messages{false}; //! Whether or not the internal RNG behaves deterministically (this is //! a test-only option). bool deterministic_rng{false}; }; static std::unique_ptr<PeerManager> make(CConnman& connman, AddrMan& addrman, BanMan* banman, ChainstateManager& chainman, CTxMemPool& pool, Options opts); virtual ~PeerManager() { } /** * Attempt to manually fetch block from a given peer. We must already have the header. * * @param[in] peer_id The peer id * @param[in] block_index The blockindex * @returns std::nullopt if a request was successfully made, otherwise an error message */ virtual std::optional<std::string> FetchBlock(NodeId peer_id, const CBlockIndex& block_index) = 0; /** Begin running background tasks, should only be called once */ virtual void StartScheduledTasks(CScheduler& scheduler) = 0; /** Get statistics from node state */ virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const = 0; /** Whether this node ignores txs received over p2p. */ virtual bool IgnoresIncomingTxs() = 0; /** Relay transaction to all peers. */ virtual void RelayTransaction(const uint256& txid, const uint256& wtxid) = 0; /** Send ping message to all peers */ virtual void SendPings() = 0; /** Set the best height */ virtual void SetBestHeight(int height) = 0; /* Public for unit testing. */ virtual void UnitTestMisbehaving(NodeId peer_id, int howmuch) = 0; /** * Evict extra outbound peers. If we think our tip may be stale, connect to an extra outbound. * Public for unit testing. */ virtual void CheckForStaleTipAndEvictPeers() = 0; /** Process a single message from a peer. Public for fuzz testing */ 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; /** 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; }; #endif // BITCOIN_NET_PROCESSING_H
0
bitcoin
bitcoin/src/httpserver.h
// Copyright (c) 2015-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_HTTPSERVER_H #define BITCOIN_HTTPSERVER_H #include <functional> #include <optional> #include <string> namespace util { class SignalInterrupt; } // namespace util static const int DEFAULT_HTTP_THREADS=4; static const int DEFAULT_HTTP_WORKQUEUE=16; static const int DEFAULT_HTTP_SERVER_TIMEOUT=30; struct evhttp_request; struct event_base; class CService; class HTTPRequest; /** Initialize HTTP server. * Call this before RegisterHTTPHandler or EventBase(). */ bool InitHTTPServer(const util::SignalInterrupt& interrupt); /** Start HTTP server. * This is separate from InitHTTPServer to give users race-condition-free time * to register their handlers between InitHTTPServer and StartHTTPServer. */ void StartHTTPServer(); /** Interrupt HTTP server threads */ void InterruptHTTPServer(); /** Stop HTTP server */ void StopHTTPServer(); /** Change logging level for libevent. */ void UpdateHTTPServerLogging(bool enable); /** Handler for requests to a certain HTTP path */ typedef std::function<bool(HTTPRequest* req, const std::string &)> HTTPRequestHandler; /** Register handler for prefix. * If multiple handlers match a prefix, the first-registered one will * be invoked. */ void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler); /** Unregister handler for prefix */ void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch); /** Return evhttp event base. This can be used by submodules to * queue timers or custom events. */ struct event_base* EventBase(); /** In-flight HTTP request. * Thin C++ wrapper around evhttp_request. */ class HTTPRequest { private: struct evhttp_request* req; const util::SignalInterrupt& m_interrupt; bool replySent; public: explicit HTTPRequest(struct evhttp_request* req, const util::SignalInterrupt& interrupt, bool replySent = false); ~HTTPRequest(); enum RequestMethod { UNKNOWN, GET, POST, HEAD, PUT }; /** Get requested URI. */ std::string GetURI() const; /** Get CService (address:ip) for the origin of the http request. */ CService GetPeer() const; /** Get request method. */ RequestMethod GetRequestMethod() const; /** Get the query parameter value from request uri for a specified key, or std::nullopt if the * key is not found. * * If the query string contains duplicate keys, the first value is returned. Many web frameworks * would instead parse this as an array of values, but this is not (yet) implemented as it is * currently not needed in any of the endpoints. * * @param[in] key represents the query parameter of which the value is returned */ std::optional<std::string> GetQueryParameter(const std::string& key) const; /** * Get the request header specified by hdr, or an empty string. * Return a pair (isPresent,string). */ std::pair<bool, std::string> GetHeader(const std::string& hdr) const; /** * Read request body. * * @note As this consumes the underlying buffer, call this only once. * Repeated calls will return an empty string. */ std::string ReadBody(); /** * Write output header. * * @note call this before calling WriteErrorReply or Reply. */ void WriteHeader(const std::string& hdr, const std::string& value); /** * Write HTTP reply. * nStatus is the HTTP status code to send. * strReply is the body of the reply. Keep it empty to send a standard message. * * @note Can be called only once. As this will give the request back to the * main thread, do not call any other HTTPRequest methods after calling this. */ void WriteReply(int nStatus, const std::string& strReply = ""); }; /** Get the query parameter value from request uri for a specified key, or std::nullopt if the key * is not found. * * If the query string contains duplicate keys, the first value is returned. Many web frameworks * would instead parse this as an array of values, but this is not (yet) implemented as it is * currently not needed in any of the endpoints. * * Helper function for HTTPRequest::GetQueryParameter. * * @param[in] uri is the entire request uri * @param[in] key represents the query parameter of which the value is returned */ std::optional<std::string> GetQueryParameterFromUri(const char* uri, const std::string& key); /** Event handler closure. */ class HTTPClosure { public: virtual void operator()() = 0; virtual ~HTTPClosure() {} }; /** Event class. This can be used either as a cross-thread trigger or as a timer. */ class HTTPEvent { public: /** Create a new event. * deleteWhenTriggered deletes this event object after the event is triggered (and the handler called) * handler is the handler to call when the event is triggered. */ HTTPEvent(struct event_base* base, bool deleteWhenTriggered, const std::function<void()>& handler); ~HTTPEvent(); /** Trigger the event. If tv is 0, trigger it immediately. Otherwise trigger it after * the given time has elapsed. */ void trigger(struct timeval* tv); bool deleteWhenTriggered; std::function<void()> handler; private: struct event* ev; }; #endif // BITCOIN_HTTPSERVER_H
0
bitcoin
bitcoin/src/txmempool.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 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 <txmempool.h> #include <chain.h> #include <coins.h> #include <common/system.h> #include <consensus/consensus.h> #include <consensus/tx_verify.h> #include <consensus/validation.h> #include <logging.h> #include <policy/policy.h> #include <policy/settings.h> #include <random.h> #include <reverse_iterator.h> #include <util/check.h> #include <util/moneystr.h> #include <util/overflow.h> #include <util/result.h> #include <util/time.h> #include <util/trace.h> #include <util/translation.h> #include <validationinterface.h> #include <cmath> #include <numeric> #include <optional> #include <string_view> #include <utility> bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp) { AssertLockHeld(cs_main); // If there are relative lock times then the maxInputBlock will be set // If there are no relative lock times, the LockPoints don't depend on the chain if (lp.maxInputBlock) { // Check whether active_chain is an extension of the block at which the LockPoints // calculation was valid. If not LockPoints are no longer valid if (!active_chain.Contains(lp.maxInputBlock)) { return false; } } // LockPoints still valid return true; } void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants, const std::set<uint256>& setExclude, std::set<uint256>& descendants_to_remove) { CTxMemPoolEntry::Children stageEntries, descendants; stageEntries = updateIt->GetMemPoolChildrenConst(); while (!stageEntries.empty()) { const CTxMemPoolEntry& descendant = *stageEntries.begin(); descendants.insert(descendant); stageEntries.erase(descendant); const CTxMemPoolEntry::Children& children = descendant.GetMemPoolChildrenConst(); for (const CTxMemPoolEntry& childEntry : children) { cacheMap::iterator cacheIt = cachedDescendants.find(mapTx.iterator_to(childEntry)); if (cacheIt != cachedDescendants.end()) { // We've already calculated this one, just add the entries for this set // but don't traverse again. for (txiter cacheEntry : cacheIt->second) { descendants.insert(*cacheEntry); } } else if (!descendants.count(childEntry)) { // Schedule for later processing stageEntries.insert(childEntry); } } } // descendants now contains all in-mempool descendants of updateIt. // Update and add to cached descendant map int32_t modifySize = 0; CAmount modifyFee = 0; int64_t modifyCount = 0; for (const CTxMemPoolEntry& descendant : descendants) { if (!setExclude.count(descendant.GetTx().GetHash())) { modifySize += descendant.GetTxSize(); modifyFee += descendant.GetModifiedFee(); modifyCount++; cachedDescendants[updateIt].insert(mapTx.iterator_to(descendant)); // Update ancestor state for each descendant mapTx.modify(mapTx.iterator_to(descendant), [=](CTxMemPoolEntry& e) { e.UpdateAncestorState(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCost()); }); // Don't directly remove the transaction here -- doing so would // invalidate iterators in cachedDescendants. Mark it for removal // by inserting into descendants_to_remove. if (descendant.GetCountWithAncestors() > uint64_t(m_limits.ancestor_count) || descendant.GetSizeWithAncestors() > m_limits.ancestor_size_vbytes) { descendants_to_remove.insert(descendant.GetTx().GetHash()); } } } mapTx.modify(updateIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); }); } void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256>& vHashesToUpdate) { AssertLockHeld(cs); // For each entry in vHashesToUpdate, store the set of in-mempool, but not // in-vHashesToUpdate transactions, so that we don't have to recalculate // descendants when we come across a previously seen entry. cacheMap mapMemPoolDescendantsToUpdate; // Use a set for lookups into vHashesToUpdate (these entries are already // accounted for in the state of their ancestors) std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end()); std::set<uint256> descendants_to_remove; // Iterate in reverse, so that whenever we are looking at a transaction // we are sure that all in-mempool descendants have already been processed. // This maximizes the benefit of the descendant cache and guarantees that // CTxMemPoolEntry::m_children will be updated, an assumption made in // UpdateForDescendants. for (const uint256 &hash : reverse_iterate(vHashesToUpdate)) { // calculate children from mapNextTx txiter it = mapTx.find(hash); if (it == mapTx.end()) { continue; } auto iter = mapNextTx.lower_bound(COutPoint(Txid::FromUint256(hash), 0)); // First calculate the children, and update CTxMemPoolEntry::m_children to // include them, and update their CTxMemPoolEntry::m_parents to include this tx. // we cache the in-mempool children to avoid duplicate updates { WITH_FRESH_EPOCH(m_epoch); for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) { const uint256 &childHash = iter->second->GetHash(); txiter childIter = mapTx.find(childHash); assert(childIter != mapTx.end()); // We can skip updating entries we've encountered before or that // are in the block (which are already accounted for). if (!visited(childIter) && !setAlreadyIncluded.count(childHash)) { UpdateChild(it, childIter, true); UpdateParent(childIter, it, true); } } } // release epoch guard for UpdateForDescendants UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded, descendants_to_remove); } for (const auto& txid : descendants_to_remove) { // This txid may have been removed already in a prior call to removeRecursive. // Therefore we ensure it is not yet removed already. if (const std::optional<txiter> txiter = GetIter(txid)) { removeRecursive((*txiter)->GetTx(), MemPoolRemovalReason::SIZELIMIT); } } } util::Result<CTxMemPool::setEntries> CTxMemPool::CalculateAncestorsAndCheckLimits( int64_t entry_size, size_t entry_count, CTxMemPoolEntry::Parents& staged_ancestors, const Limits& limits) const { int64_t totalSizeWithAncestors = entry_size; setEntries ancestors; while (!staged_ancestors.empty()) { const CTxMemPoolEntry& stage = staged_ancestors.begin()->get(); txiter stageit = mapTx.iterator_to(stage); ancestors.insert(stageit); staged_ancestors.erase(stage); totalSizeWithAncestors += stageit->GetTxSize(); if (stageit->GetSizeWithDescendants() + entry_size > limits.descendant_size_vbytes) { return util::Error{Untranslated(strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_size_vbytes))}; } else if (stageit->GetCountWithDescendants() + entry_count > static_cast<uint64_t>(limits.descendant_count)) { return util::Error{Untranslated(strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_count))}; } else if (totalSizeWithAncestors > limits.ancestor_size_vbytes) { return util::Error{Untranslated(strprintf("exceeds ancestor size limit [limit: %u]", limits.ancestor_size_vbytes))}; } const CTxMemPoolEntry::Parents& parents = stageit->GetMemPoolParentsConst(); for (const CTxMemPoolEntry& parent : parents) { txiter parent_it = mapTx.iterator_to(parent); // If this is a new ancestor, add it. if (ancestors.count(parent_it) == 0) { staged_ancestors.insert(parent); } if (staged_ancestors.size() + ancestors.size() + entry_count > static_cast<uint64_t>(limits.ancestor_count)) { return util::Error{Untranslated(strprintf("too many unconfirmed ancestors [limit: %u]", limits.ancestor_count))}; } } } return ancestors; } util::Result<void> CTxMemPool::CheckPackageLimits(const Package& package, const int64_t total_vsize) const { size_t pack_count = package.size(); // Package itself is busting mempool limits; should be rejected even if no staged_ancestors exist if (pack_count > static_cast<uint64_t>(m_limits.ancestor_count)) { return util::Error{Untranslated(strprintf("package count %u exceeds ancestor count limit [limit: %u]", pack_count, m_limits.ancestor_count))}; } else if (pack_count > static_cast<uint64_t>(m_limits.descendant_count)) { return util::Error{Untranslated(strprintf("package count %u exceeds descendant count limit [limit: %u]", pack_count, m_limits.descendant_count))}; } else if (total_vsize > m_limits.ancestor_size_vbytes) { return util::Error{Untranslated(strprintf("package size %u exceeds ancestor size limit [limit: %u]", total_vsize, m_limits.ancestor_size_vbytes))}; } else if (total_vsize > m_limits.descendant_size_vbytes) { return util::Error{Untranslated(strprintf("package size %u exceeds descendant size limit [limit: %u]", total_vsize, m_limits.descendant_size_vbytes))}; } CTxMemPoolEntry::Parents staged_ancestors; for (const auto& tx : package) { for (const auto& input : tx->vin) { std::optional<txiter> piter = GetIter(input.prevout.hash); if (piter) { staged_ancestors.insert(**piter); if (staged_ancestors.size() + package.size() > static_cast<uint64_t>(m_limits.ancestor_count)) { return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", m_limits.ancestor_count))}; } } } } // When multiple transactions are passed in, the ancestors and descendants of all transactions // considered together must be within limits even if they are not interdependent. This may be // stricter than the limits for each individual transaction. const auto ancestors{CalculateAncestorsAndCheckLimits(total_vsize, package.size(), staged_ancestors, m_limits)}; // It's possible to overestimate the ancestor/descendant totals. if (!ancestors.has_value()) return util::Error{Untranslated("possibly " + util::ErrorString(ancestors).original)}; return {}; } util::Result<CTxMemPool::setEntries> CTxMemPool::CalculateMemPoolAncestors( const CTxMemPoolEntry &entry, const Limits& limits, bool fSearchForParents /* = true */) const { CTxMemPoolEntry::Parents staged_ancestors; const CTransaction &tx = entry.GetTx(); if (fSearchForParents) { // Get parents of this transaction that are in the mempool // GetMemPoolParents() is only valid for entries in the mempool, so we // iterate mapTx to find parents. for (unsigned int i = 0; i < tx.vin.size(); i++) { std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash); if (piter) { staged_ancestors.insert(**piter); if (staged_ancestors.size() + 1 > static_cast<uint64_t>(limits.ancestor_count)) { return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", limits.ancestor_count))}; } } } } else { // If we're not searching for parents, we require this to already be an // entry in the mempool and use the entry's cached parents. txiter it = mapTx.iterator_to(entry); staged_ancestors = it->GetMemPoolParentsConst(); } return CalculateAncestorsAndCheckLimits(entry.GetTxSize(), /*entry_count=*/1, staged_ancestors, limits); } CTxMemPool::setEntries CTxMemPool::AssumeCalculateMemPoolAncestors( std::string_view calling_fn_name, const CTxMemPoolEntry &entry, const Limits& limits, bool fSearchForParents /* = true */) const { auto result{CalculateMemPoolAncestors(entry, limits, fSearchForParents)}; if (!Assume(result)) { LogPrintLevel(BCLog::MEMPOOL, BCLog::Level::Error, "%s: CalculateMemPoolAncestors failed unexpectedly, continuing with empty ancestor set (%s)\n", calling_fn_name, util::ErrorString(result).original); } return std::move(result).value_or(CTxMemPool::setEntries{}); } void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors) { const CTxMemPoolEntry::Parents& parents = it->GetMemPoolParentsConst(); // add or remove this tx as a child of each parent for (const CTxMemPoolEntry& parent : parents) { UpdateChild(mapTx.iterator_to(parent), it, add); } const int32_t updateCount = (add ? 1 : -1); const int32_t updateSize{updateCount * it->GetTxSize()}; const CAmount updateFee = updateCount * it->GetModifiedFee(); for (txiter ancestorIt : setAncestors) { mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(updateSize, updateFee, updateCount); }); } } void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) { int64_t updateCount = setAncestors.size(); int64_t updateSize = 0; CAmount updateFee = 0; int64_t updateSigOpsCost = 0; for (txiter ancestorIt : setAncestors) { updateSize += ancestorIt->GetTxSize(); updateFee += ancestorIt->GetModifiedFee(); updateSigOpsCost += ancestorIt->GetSigOpCost(); } mapTx.modify(it, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(updateSize, updateFee, updateCount, updateSigOpsCost); }); } void CTxMemPool::UpdateChildrenForRemoval(txiter it) { const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst(); for (const CTxMemPoolEntry& updateIt : children) { UpdateParent(mapTx.iterator_to(updateIt), it, false); } } void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants) { // For each entry, walk back all ancestors and decrement size associated with this // transaction if (updateDescendants) { // updateDescendants should be true whenever we're not recursively // removing a tx and all its descendants, eg when a transaction is // confirmed in a block. // Here we only update statistics and not data in CTxMemPool::Parents // and CTxMemPoolEntry::Children (which we need to preserve until we're // finished with all operations that need to traverse the mempool). for (txiter removeIt : entriesToRemove) { setEntries setDescendants; CalculateDescendants(removeIt, setDescendants); setDescendants.erase(removeIt); // don't update state for self int32_t modifySize = -removeIt->GetTxSize(); CAmount modifyFee = -removeIt->GetModifiedFee(); int modifySigOps = -removeIt->GetSigOpCost(); for (txiter dit : setDescendants) { mapTx.modify(dit, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(modifySize, modifyFee, -1, modifySigOps); }); } } } for (txiter removeIt : entriesToRemove) { const CTxMemPoolEntry &entry = *removeIt; // Since this is a tx that is already in the mempool, we can call CMPA // with fSearchForParents = false. If the mempool is in a consistent // state, then using true or false should both be correct, though false // 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 GetMemPoolParents()/GetMemPoolChildren() // 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 false, the in-mempool children aren't // linked to the in-block tx's until UpdateTransactionsFromBlock() is // called. // So if we're being called during a reorg, ie before // UpdateTransactionsFromBlock() has been called, then // GetMemPoolParents()/GetMemPoolChildren() will differ from the set of // mempool parents we'd calculate by searching, and it's important that // we use the cached notion of ancestor transactions as the set of // things to update for removal. auto ancestors{AssumeCalculateMemPoolAncestors(__func__, entry, Limits::NoLimits(), /*fSearchForParents=*/false)}; // Note that UpdateAncestorsOf severs the child links that point to // removeIt in the entries for the parents of removeIt. UpdateAncestorsOf(false, removeIt, ancestors); } // After updating all the ancestor sizes, we can now sever the link between each // transaction being removed and any mempool children (ie, update CTxMemPoolEntry::m_parents // for each direct child of a transaction being removed). for (txiter removeIt : entriesToRemove) { UpdateChildrenForRemoval(removeIt); } } void CTxMemPoolEntry::UpdateDescendantState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount) { nSizeWithDescendants += modifySize; assert(nSizeWithDescendants > 0); nModFeesWithDescendants = SaturatingAdd(nModFeesWithDescendants, modifyFee); m_count_with_descendants += modifyCount; assert(m_count_with_descendants > 0); } void CTxMemPoolEntry::UpdateAncestorState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps) { nSizeWithAncestors += modifySize; assert(nSizeWithAncestors > 0); nModFeesWithAncestors = SaturatingAdd(nModFeesWithAncestors, modifyFee); m_count_with_ancestors += modifyCount; assert(m_count_with_ancestors > 0); nSigOpCostWithAncestors += modifySigOps; assert(int(nSigOpCostWithAncestors) >= 0); } CTxMemPool::CTxMemPool(const Options& opts) : m_check_ratio{opts.check_ratio}, m_max_size_bytes{opts.max_size_bytes}, m_expiry{opts.expiry}, m_incremental_relay_feerate{opts.incremental_relay_feerate}, m_min_relay_feerate{opts.min_relay_feerate}, m_dust_relay_feerate{opts.dust_relay_feerate}, m_permit_bare_multisig{opts.permit_bare_multisig}, m_max_datacarrier_bytes{opts.max_datacarrier_bytes}, m_require_standard{opts.require_standard}, m_full_rbf{opts.full_rbf}, m_persist_v1_dat{opts.persist_v1_dat}, m_limits{opts.limits} { } bool CTxMemPool::isSpent(const COutPoint& outpoint) const { LOCK(cs); return mapNextTx.count(outpoint); } unsigned int CTxMemPool::GetTransactionsUpdated() const { return nTransactionsUpdated; } void CTxMemPool::AddTransactionsUpdated(unsigned int n) { nTransactionsUpdated += n; } void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry, setEntries &setAncestors) { // Add to memory pool without checking anything. // Used by AcceptToMemoryPool(), which DOES do // all the appropriate checks. indexed_transaction_set::iterator newit = mapTx.emplace(CTxMemPoolEntry::ExplicitCopy, entry).first; // Update transaction for any feeDelta created by PrioritiseTransaction CAmount delta{0}; ApplyDelta(entry.GetTx().GetHash(), delta); // The following call to UpdateModifiedFee assumes no previous fee modifications Assume(entry.GetFee() == entry.GetModifiedFee()); if (delta) { mapTx.modify(newit, [&delta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(delta); }); } // Update cachedInnerUsage to include contained transaction's usage. // (When we update the entry for in-mempool parents, memory usage will be // further updated.) cachedInnerUsage += entry.DynamicMemoryUsage(); const CTransaction& tx = newit->GetTx(); std::set<uint256> setParentTransactions; for (unsigned int i = 0; i < tx.vin.size(); i++) { mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx)); setParentTransactions.insert(tx.vin[i].prevout.hash); } // Don't bother worrying about child transactions of this one. // Normal case of a new transaction arriving is that there can't be any // children, because such children would be orphans. // An exception to that is if a transaction enters that used to be in a block. // In that case, our disconnect block logic will call UpdateTransactionsFromBlock // to clean up the mess we're leaving here. // Update ancestors with information about this tx for (const auto& pit : GetIterSet(setParentTransactions)) { UpdateParent(newit, pit, true); } UpdateAncestorsOf(true, newit, setAncestors); UpdateEntryForAncestors(newit, setAncestors); nTransactionsUpdated++; totalTxSize += entry.GetTxSize(); m_total_fee += entry.GetFee(); txns_randomized.emplace_back(newit->GetSharedTx()); newit->idx_randomized = txns_randomized.size() - 1; TRACE3(mempool, added, entry.GetTx().GetHash().data(), entry.GetTxSize(), entry.GetFee() ); } void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason) { // We increment mempool sequence value no matter removal reason // even if not directly reported below. uint64_t mempool_sequence = GetAndIncrementSequence(); if (reason != MemPoolRemovalReason::BLOCK) { // Notify clients that a transaction has been removed from the mempool // for any reason except being included in a block. Clients interested // in transactions included in blocks can subscribe to the BlockConnected // notification. GetMainSignals().TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence); } TRACE5(mempool, removed, it->GetTx().GetHash().data(), RemovalReasonToString(reason).c_str(), it->GetTxSize(), it->GetFee(), std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count() ); for (const CTxIn& txin : it->GetTx().vin) mapNextTx.erase(txin.prevout); RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */); if (txns_randomized.size() > 1) { // Update idx_randomized of the to-be-moved entry. Assert(GetEntry(txns_randomized.back()->GetHash()))->idx_randomized = it->idx_randomized; // Remove entry from txns_randomized by replacing it with the back and deleting the back. txns_randomized[it->idx_randomized] = std::move(txns_randomized.back()); txns_randomized.pop_back(); if (txns_randomized.size() * 2 < txns_randomized.capacity()) txns_randomized.shrink_to_fit(); } else txns_randomized.clear(); totalTxSize -= it->GetTxSize(); m_total_fee -= it->GetFee(); cachedInnerUsage -= it->DynamicMemoryUsage(); cachedInnerUsage -= memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst()); mapTx.erase(it); nTransactionsUpdated++; } // Calculates descendants of entry that are not already in setDescendants, and adds to // setDescendants. Assumes entryit is already a tx in the mempool and CTxMemPoolEntry::m_children // is correct for tx and all descendants. // Also assumes that if an entry is in setDescendants already, then all // in-mempool descendants of it are already in setDescendants as well, so that we // can save time by not iterating over those entries. void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const { setEntries stage; if (setDescendants.count(entryit) == 0) { stage.insert(entryit); } // Traverse down the children of entry, only adding children that are not // accounted for in setDescendants already (because those children have either // already been walked, or will be walked in this iteration). while (!stage.empty()) { txiter it = *stage.begin(); setDescendants.insert(it); stage.erase(it); const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst(); for (const CTxMemPoolEntry& child : children) { txiter childiter = mapTx.iterator_to(child); if (!setDescendants.count(childiter)) { stage.insert(childiter); } } } } void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason) { // Remove transaction from memory pool AssertLockHeld(cs); setEntries txToRemove; txiter origit = mapTx.find(origTx.GetHash()); if (origit != mapTx.end()) { txToRemove.insert(origit); } else { // When recursively removing but origTx isn't in the mempool // be sure to remove any children that are in the pool. This can // happen during chain re-orgs if origTx isn't re-accepted into // the mempool for any reason. for (unsigned int i = 0; i < origTx.vout.size(); i++) { auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i)); if (it == mapNextTx.end()) continue; txiter nextit = mapTx.find(it->second->GetHash()); assert(nextit != mapTx.end()); txToRemove.insert(nextit); } } setEntries setAllRemoves; for (txiter it : txToRemove) { CalculateDescendants(it, setAllRemoves); } RemoveStaged(setAllRemoves, false, reason); } void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature) { // Remove transactions spending a coinbase which are now immature and no-longer-final transactions AssertLockHeld(cs); AssertLockHeld(::cs_main); setEntries txToRemove; for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) { if (check_final_and_mature(it)) txToRemove.insert(it); } setEntries setAllRemoves; for (txiter it : txToRemove) { CalculateDescendants(it, setAllRemoves); } RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG); for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) { assert(TestLockPointValidity(chain, it->GetLockPoints())); } } void CTxMemPool::removeConflicts(const CTransaction &tx) { // Remove transactions which depend on inputs of tx, recursively AssertLockHeld(cs); for (const CTxIn &txin : tx.vin) { auto it = mapNextTx.find(txin.prevout); if (it != mapNextTx.end()) { const CTransaction &txConflict = *it->second; if (txConflict != tx) { ClearPrioritisation(txConflict.GetHash()); removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT); } } } } /** * Called when a block is connected. Removes from mempool. */ void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight) { AssertLockHeld(cs); std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block; txs_removed_for_block.reserve(vtx.size()); for (const auto& tx : vtx) { txiter it = mapTx.find(tx->GetHash()); if (it != mapTx.end()) { setEntries stage; stage.insert(it); txs_removed_for_block.emplace_back(*it); RemoveStaged(stage, true, MemPoolRemovalReason::BLOCK); } removeConflicts(*tx); ClearPrioritisation(tx->GetHash()); } GetMainSignals().MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight); lastRollingFeeUpdate = GetTime(); blockSinceLastRollingFeeBump = true; } void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const { if (m_check_ratio == 0) return; if (GetRand(m_check_ratio) >= 1) return; AssertLockHeld(::cs_main); LOCK(cs); LogPrint(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size()); uint64_t checkTotal = 0; CAmount check_total_fee{0}; uint64_t innerUsage = 0; uint64_t prev_ancestor_count{0}; CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip)); for (const auto& it : GetSortedDepthAndScore()) { checkTotal += it->GetTxSize(); check_total_fee += it->GetFee(); innerUsage += it->DynamicMemoryUsage(); const CTransaction& tx = it->GetTx(); innerUsage += memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst()); CTxMemPoolEntry::Parents setParentCheck; for (const CTxIn &txin : tx.vin) { // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's. indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash); if (it2 != mapTx.end()) { const CTransaction& tx2 = it2->GetTx(); assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull()); setParentCheck.insert(*it2); } // We are iterating through the mempool entries sorted in order by ancestor count. // All parents must have been checked before their children and their coins added to // the mempoolDuplicate coins cache. assert(mempoolDuplicate.HaveCoin(txin.prevout)); // Check whether its inputs are marked in mapNextTx. auto it3 = mapNextTx.find(txin.prevout); assert(it3 != mapNextTx.end()); assert(it3->first == &txin.prevout); assert(it3->second == &tx); } auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool { return a.GetTx().GetHash() == b.GetTx().GetHash(); }; assert(setParentCheck.size() == it->GetMemPoolParentsConst().size()); assert(std::equal(setParentCheck.begin(), setParentCheck.end(), it->GetMemPoolParentsConst().begin(), comp)); // Verify ancestor state is correct. auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())}; uint64_t nCountCheck = ancestors.size() + 1; int32_t nSizeCheck = it->GetTxSize(); CAmount nFeesCheck = it->GetModifiedFee(); int64_t nSigOpCheck = it->GetSigOpCost(); for (txiter ancestorIt : ancestors) { nSizeCheck += ancestorIt->GetTxSize(); nFeesCheck += ancestorIt->GetModifiedFee(); nSigOpCheck += ancestorIt->GetSigOpCost(); } assert(it->GetCountWithAncestors() == nCountCheck); assert(it->GetSizeWithAncestors() == nSizeCheck); assert(it->GetSigOpCostWithAncestors() == nSigOpCheck); assert(it->GetModFeesWithAncestors() == nFeesCheck); // Sanity check: we are walking in ascending ancestor count order. assert(prev_ancestor_count <= it->GetCountWithAncestors()); prev_ancestor_count = it->GetCountWithAncestors(); // Check children against mapNextTx CTxMemPoolEntry::Children setChildrenCheck; auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0)); int32_t child_sizes{0}; for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) { txiter childit = mapTx.find(iter->second->GetHash()); assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions if (setChildrenCheck.insert(*childit).second) { child_sizes += childit->GetTxSize(); } } assert(setChildrenCheck.size() == it->GetMemPoolChildrenConst().size()); assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), it->GetMemPoolChildrenConst().begin(), comp)); // Also check to make sure size is greater than sum with immediate children. // just a sanity check, not definitive that this calc is correct... assert(it->GetSizeWithDescendants() >= child_sizes + it->GetTxSize()); TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass CAmount txfee = 0; assert(!tx.IsCoinBase()); assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee)); for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout); AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max()); } for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) { uint256 hash = it->second->GetHash(); indexed_transaction_set::const_iterator it2 = mapTx.find(hash); const CTransaction& tx = it2->GetTx(); assert(it2 != mapTx.end()); assert(&tx == it->second); } assert(totalTxSize == checkTotal); assert(m_total_fee == check_total_fee); assert(innerUsage == cachedInnerUsage); } bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb, bool wtxid) { /* Return `true` if hasha should be considered sooner than hashb. Namely when: * a is not in the mempool, but b is * both are in the mempool and a has fewer ancestors than b * both are in the mempool and a has a higher score than b */ LOCK(cs); indexed_transaction_set::const_iterator j = wtxid ? get_iter_from_wtxid(hashb) : mapTx.find(hashb); if (j == mapTx.end()) return false; indexed_transaction_set::const_iterator i = wtxid ? get_iter_from_wtxid(hasha) : mapTx.find(hasha); if (i == mapTx.end()) return true; uint64_t counta = i->GetCountWithAncestors(); uint64_t countb = j->GetCountWithAncestors(); if (counta == countb) { return CompareTxMemPoolEntryByScore()(*i, *j); } return counta < countb; } namespace { class DepthAndScoreComparator { public: bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b) { uint64_t counta = a->GetCountWithAncestors(); uint64_t countb = b->GetCountWithAncestors(); if (counta == countb) { return CompareTxMemPoolEntryByScore()(*a, *b); } return counta < countb; } }; } // namespace std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const { std::vector<indexed_transaction_set::const_iterator> iters; AssertLockHeld(cs); iters.reserve(mapTx.size()); for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) { iters.push_back(mi); } std::sort(iters.begin(), iters.end(), DepthAndScoreComparator()); return iters; } void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) const { LOCK(cs); auto iters = GetSortedDepthAndScore(); vtxid.clear(); vtxid.reserve(mapTx.size()); for (auto it : iters) { vtxid.push_back(it->GetTx().GetHash()); } } static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) { return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), it->GetFee(), it->GetTxSize(), it->GetModifiedFee() - it->GetFee()}; } std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const { AssertLockHeld(cs); std::vector<CTxMemPoolEntryRef> ret; ret.reserve(mapTx.size()); for (const auto& it : GetSortedDepthAndScore()) { ret.emplace_back(*it); } return ret; } std::vector<TxMempoolInfo> CTxMemPool::infoAll() const { LOCK(cs); auto iters = GetSortedDepthAndScore(); std::vector<TxMempoolInfo> ret; ret.reserve(mapTx.size()); for (auto it : iters) { ret.push_back(GetInfo(it)); } return ret; } const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const { AssertLockHeld(cs); const auto i = mapTx.find(txid); return i == mapTx.end() ? nullptr : &(*i); } CTransactionRef CTxMemPool::get(const uint256& hash) const { LOCK(cs); indexed_transaction_set::const_iterator i = mapTx.find(hash); if (i == mapTx.end()) return nullptr; return i->GetSharedTx(); } TxMempoolInfo CTxMemPool::info(const GenTxid& gtxid) const { LOCK(cs); indexed_transaction_set::const_iterator i = (gtxid.IsWtxid() ? get_iter_from_wtxid(gtxid.GetHash()) : mapTx.find(gtxid.GetHash())); if (i == mapTx.end()) return TxMempoolInfo(); return GetInfo(i); } TxMempoolInfo CTxMemPool::info_for_relay(const GenTxid& gtxid, uint64_t last_sequence) const { LOCK(cs); indexed_transaction_set::const_iterator i = (gtxid.IsWtxid() ? get_iter_from_wtxid(gtxid.GetHash()) : mapTx.find(gtxid.GetHash())); if (i != mapTx.end() && i->GetSequence() < last_sequence) { return GetInfo(i); } else { return TxMempoolInfo(); } } void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta) { { LOCK(cs); CAmount &delta = mapDeltas[hash]; delta = SaturatingAdd(delta, nFeeDelta); txiter it = mapTx.find(hash); if (it != mapTx.end()) { mapTx.modify(it, [&nFeeDelta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(nFeeDelta); }); // Now update all ancestors' modified fees with descendants auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits(), /*fSearchForParents=*/false)}; for (txiter ancestorIt : ancestors) { mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e){ e.UpdateDescendantState(0, nFeeDelta, 0);}); } // Now update all descendants' modified fees with ancestors setEntries setDescendants; CalculateDescendants(it, setDescendants); setDescendants.erase(it); for (txiter descendantIt : setDescendants) { mapTx.modify(descendantIt, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(0, nFeeDelta, 0, 0); }); } ++nTransactionsUpdated; } if (delta == 0) { mapDeltas.erase(hash); LogPrintf("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : ""); } else { LogPrintf("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n", hash.ToString(), it == mapTx.end() ? "not " : "", FormatMoney(nFeeDelta), FormatMoney(delta)); } } } void CTxMemPool::ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const { AssertLockHeld(cs); std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash); if (pos == mapDeltas.end()) return; const CAmount &delta = pos->second; nFeeDelta += delta; } void CTxMemPool::ClearPrioritisation(const uint256& hash) { AssertLockHeld(cs); mapDeltas.erase(hash); } std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const { AssertLockNotHeld(cs); LOCK(cs); std::vector<delta_info> result; result.reserve(mapDeltas.size()); for (const auto& [txid, delta] : mapDeltas) { const auto iter{mapTx.find(txid)}; const bool in_mempool{iter != mapTx.end()}; std::optional<CAmount> modified_fee; if (in_mempool) modified_fee = iter->GetModifiedFee(); result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid}); } return result; } const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const { const auto it = mapNextTx.find(prevout); return it == mapNextTx.end() ? nullptr : it->second; } std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const uint256& txid) const { auto it = mapTx.find(txid); if (it != mapTx.end()) return it; return std::nullopt; } CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<uint256>& hashes) const { CTxMemPool::setEntries ret; for (const auto& h : hashes) { const auto mi = GetIter(h); if (mi) ret.insert(*mi); } return ret; } std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<uint256>& txids) const { AssertLockHeld(cs); std::vector<txiter> ret; ret.reserve(txids.size()); for (const auto& txid : txids) { const auto it{GetIter(txid)}; if (!it) return {}; ret.push_back(*it); } return ret; } bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const { for (unsigned int i = 0; i < tx.vin.size(); i++) if (exists(GenTxid::Txid(tx.vin[i].prevout.hash))) return false; return true; } CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { } bool CCoinsViewMemPool::GetCoin(const COutPoint &outpoint, Coin &coin) const { // Check to see if the inputs are made available by another tx in the package. // These Coins would not be available in the underlying CoinsView. if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) { coin = it->second; return true; } // If an entry in the mempool exists, always return that one, as it's guaranteed to never // conflict with the underlying cache, and it cannot have pruned entries (as it contains full) // transactions. First checking the underlying cache risks returning a pruned entry instead. CTransactionRef ptx = mempool.get(outpoint.hash); if (ptx) { if (outpoint.n < ptx->vout.size()) { coin = Coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false); m_non_base_coins.emplace(outpoint); return true; } else { return false; } } return base->GetCoin(outpoint, coin); } void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx) { for (unsigned int n = 0; n < tx->vout.size(); ++n) { m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false)); m_non_base_coins.emplace(tx->GetHash(), n); } } void CCoinsViewMemPool::Reset() { m_temp_added.clear(); m_non_base_coins.clear(); } size_t CTxMemPool::DynamicMemoryUsage() const { LOCK(cs); // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented. return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + cachedInnerUsage; } void CTxMemPool::RemoveUnbroadcastTx(const uint256& txid, const bool unchecked) { LOCK(cs); if (m_unbroadcast_txids.erase(txid)) { LogPrint(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : "")); } } void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) { AssertLockHeld(cs); UpdateForRemoveFromMempool(stage, updateDescendants); for (txiter it : stage) { removeUnchecked(it, reason); } } int CTxMemPool::Expire(std::chrono::seconds time) { AssertLockHeld(cs); indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin(); setEntries toremove; while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) { toremove.insert(mapTx.project<0>(it)); it++; } setEntries stage; for (txiter removeit : toremove) { CalculateDescendants(removeit, stage); } RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY); return stage.size(); } void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry) { auto ancestors{AssumeCalculateMemPoolAncestors(__func__, entry, Limits::NoLimits())}; return addUnchecked(entry, ancestors); } void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add) { AssertLockHeld(cs); CTxMemPoolEntry::Children s; if (add && entry->GetMemPoolChildren().insert(*child).second) { cachedInnerUsage += memusage::IncrementalDynamicUsage(s); } else if (!add && entry->GetMemPoolChildren().erase(*child)) { cachedInnerUsage -= memusage::IncrementalDynamicUsage(s); } } void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add) { AssertLockHeld(cs); CTxMemPoolEntry::Parents s; if (add && entry->GetMemPoolParents().insert(*parent).second) { cachedInnerUsage += memusage::IncrementalDynamicUsage(s); } else if (!add && entry->GetMemPoolParents().erase(*parent)) { cachedInnerUsage -= memusage::IncrementalDynamicUsage(s); } } CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const { LOCK(cs); if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0) return CFeeRate(llround(rollingMinimumFeeRate)); int64_t time = GetTime(); if (time > lastRollingFeeUpdate + 10) { double halflife = ROLLING_FEE_HALFLIFE; if (DynamicMemoryUsage() < sizelimit / 4) halflife /= 4; else if (DynamicMemoryUsage() < sizelimit / 2) halflife /= 2; rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife); lastRollingFeeUpdate = time; if (rollingMinimumFeeRate < (double)m_incremental_relay_feerate.GetFeePerK() / 2) { rollingMinimumFeeRate = 0; return CFeeRate(0); } } return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_incremental_relay_feerate); } void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) { AssertLockHeld(cs); if (rate.GetFeePerK() > rollingMinimumFeeRate) { rollingMinimumFeeRate = rate.GetFeePerK(); blockSinceLastRollingFeeBump = false; } } void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) { AssertLockHeld(cs); unsigned nTxnRemoved = 0; CFeeRate maxFeeRateRemoved(0); while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) { indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin(); // We set the new mempool min fee to the feerate of the removed set, plus the // "minimum reasonable fee rate" (ie some value under which we consider txn // to have 0 fee). This way, we don't allow txn to enter mempool with feerate // equal to txn which were removed with no block in between. CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants()); removed += m_incremental_relay_feerate; trackPackageRemoved(removed); maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed); setEntries stage; CalculateDescendants(mapTx.project<0>(it), stage); nTxnRemoved += stage.size(); std::vector<CTransaction> txn; if (pvNoSpendsRemaining) { txn.reserve(stage.size()); for (txiter iter : stage) txn.push_back(iter->GetTx()); } RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT); if (pvNoSpendsRemaining) { for (const CTransaction& tx : txn) { for (const CTxIn& txin : tx.vin) { if (exists(GenTxid::Txid(txin.prevout.hash))) continue; pvNoSpendsRemaining->push_back(txin.prevout); } } } } if (maxFeeRateRemoved > CFeeRate(0)) { LogPrint(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString()); } } uint64_t CTxMemPool::CalculateDescendantMaximum(txiter entry) const { // find parent with highest descendant count std::vector<txiter> candidates; setEntries counted; candidates.push_back(entry); uint64_t maximum = 0; while (candidates.size()) { txiter candidate = candidates.back(); candidates.pop_back(); if (!counted.insert(candidate).second) continue; const CTxMemPoolEntry::Parents& parents = candidate->GetMemPoolParentsConst(); if (parents.size() == 0) { maximum = std::max(maximum, candidate->GetCountWithDescendants()); } else { for (const CTxMemPoolEntry& i : parents) { candidates.push_back(mapTx.iterator_to(i)); } } } return maximum; } void CTxMemPool::GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* const ancestorsize, CAmount* const ancestorfees) const { LOCK(cs); auto it = mapTx.find(txid); ancestors = descendants = 0; if (it != mapTx.end()) { ancestors = it->GetCountWithAncestors(); if (ancestorsize) *ancestorsize = it->GetSizeWithAncestors(); if (ancestorfees) *ancestorfees = it->GetModFeesWithAncestors(); descendants = CalculateDescendantMaximum(it); } } bool CTxMemPool::GetLoadTried() const { LOCK(cs); return m_load_tried; } void CTxMemPool::SetLoadTried(bool load_tried) { LOCK(cs); m_load_tried = load_tried; } std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<uint256>& txids) const { AssertLockHeld(cs); std::vector<txiter> clustered_txs{GetIterVec(txids)}; // Use epoch: visiting an entry means we have added it to the clustered_txs vector. It does not // necessarily mean the entry has been processed. WITH_FRESH_EPOCH(m_epoch); for (const auto& it : clustered_txs) { visited(it); } // i = index of where the list of entries to process starts for (size_t i{0}; i < clustered_txs.size(); ++i) { // DoS protection: if there are 500 or more entries to process, just quit. if (clustered_txs.size() > 500) return {}; const txiter& tx_iter = clustered_txs.at(i); for (const auto& entries : {tx_iter->GetMemPoolParentsConst(), tx_iter->GetMemPoolChildrenConst()}) { for (const CTxMemPoolEntry& entry : entries) { const auto entry_it = mapTx.iterator_to(entry); if (!visited(entry_it)) { clustered_txs.push_back(entry_it); } } } } return clustered_txs; }
0
bitcoin
bitcoin/src/net.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <net.h> #include <addrdb.h> #include <addrman.h> #include <banman.h> #include <clientversion.h> #include <common/args.h> #include <compat/compat.h> #include <consensus/consensus.h> #include <crypto/sha256.h> #include <i2p.h> #include <logging.h> #include <memusage.h> #include <net_permissions.h> #include <netaddress.h> #include <netbase.h> #include <node/eviction.h> #include <node/interface_ui.h> #include <protocol.h> #include <random.h> #include <scheduler.h> #include <util/fs.h> #include <util/sock.h> #include <util/strencodings.h> #include <util/thread.h> #include <util/threadinterrupt.h> #include <util/trace.h> #include <util/translation.h> #include <util/vector.h> #ifdef WIN32 #include <string.h> #endif #if HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS #include <ifaddrs.h> #endif #include <algorithm> #include <array> #include <cstdint> #include <functional> #include <optional> #include <unordered_map> #include <math.h> /** Maximum number of block-relay-only anchor connections */ static constexpr size_t MAX_BLOCK_RELAY_ONLY_ANCHORS = 2; static_assert (MAX_BLOCK_RELAY_ONLY_ANCHORS <= static_cast<size_t>(MAX_BLOCK_RELAY_ONLY_CONNECTIONS), "MAX_BLOCK_RELAY_ONLY_ANCHORS must not exceed MAX_BLOCK_RELAY_ONLY_CONNECTIONS."); /** Anchor IP address database file name */ const char* const ANCHORS_DATABASE_FILENAME = "anchors.dat"; // How often to dump addresses to peers.dat static constexpr std::chrono::minutes DUMP_PEERS_INTERVAL{15}; /** Number of DNS seeds to query when the number of connections is low. */ static constexpr int DNSSEEDS_TO_QUERY_AT_ONCE = 3; /** How long to delay before querying DNS seeds * * If we have more than THRESHOLD entries in addrman, then it's likely * that we got those addresses from having previously connected to the P2P * network, and that we'll be able to successfully reconnect to the P2P * network via contacting one of them. So if that's the case, spend a * little longer trying to connect to known peers before querying the * DNS seeds. */ static constexpr std::chrono::seconds DNSSEEDS_DELAY_FEW_PEERS{11}; static constexpr std::chrono::minutes DNSSEEDS_DELAY_MANY_PEERS{5}; static constexpr int DNSSEEDS_DELAY_PEER_THRESHOLD = 1000; // "many" vs "few" peers /** The default timeframe for -maxuploadtarget. 1 day. */ static constexpr std::chrono::seconds MAX_UPLOAD_TIMEFRAME{60 * 60 * 24}; // A random time period (0 to 1 seconds) is added to feeler connections to prevent synchronization. static constexpr auto FEELER_SLEEP_WINDOW{1s}; /** Frequency to attempt extra connections to reachable networks we're not connected to yet **/ static constexpr auto EXTRA_NETWORK_PEER_INTERVAL{5min}; /** Used to pass flags to the Bind() function */ enum BindFlags { BF_NONE = 0, BF_REPORT_ERROR = (1U << 0), /** * Do not call AddLocal() for our special addresses, e.g., for incoming * Tor connections, to prevent gossiping them over the network. */ BF_DONT_ADVERTISE = (1U << 1), }; // The set of sockets cannot be modified while waiting // The sleep time needs to be small to avoid new sockets stalling static const uint64_t SELECT_TIMEOUT_MILLISECONDS = 50; const std::string NET_MESSAGE_TYPE_OTHER = "*other*"; static const uint64_t RANDOMIZER_ID_NETGROUP = 0x6c0edd8036ef4036ULL; // SHA256("netgroup")[0:8] static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE = 0xd93e69e2bbfa5735ULL; // SHA256("localhostnonce")[0:8] static const uint64_t RANDOMIZER_ID_ADDRCACHE = 0x1cf2e4ddd306dda9ULL; // SHA256("addrcache")[0:8] // // Global state variables // bool fDiscover = true; bool fListen = true; GlobalMutex g_maplocalhost_mutex; std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex); std::string strSubVersion; size_t CSerializedNetMsg::GetMemoryUsage() const noexcept { // Don't count the dynamic memory used for the m_type string, by assuming it fits in the // "small string" optimization area (which stores data inside the object itself, up to some // size; 15 bytes in modern libstdc++). return sizeof(*this) + memusage::DynamicUsage(data); } void CConnman::AddAddrFetch(const std::string& strDest) { LOCK(m_addr_fetches_mutex); m_addr_fetches.push_back(strDest); } uint16_t GetListenPort() { // If -bind= is provided with ":port" part, use that (first one if multiple are provided). for (const std::string& bind_arg : gArgs.GetArgs("-bind")) { constexpr uint16_t dummy_port = 0; const std::optional<CService> bind_addr{Lookup(bind_arg, dummy_port, /*fAllowLookup=*/false)}; if (bind_addr.has_value() && bind_addr->GetPort() != dummy_port) return bind_addr->GetPort(); } // Otherwise, if -whitebind= without NetPermissionFlags::NoBan is provided, use that // (-whitebind= is required to have ":port"). for (const std::string& whitebind_arg : gArgs.GetArgs("-whitebind")) { NetWhitebindPermissions whitebind; bilingual_str error; if (NetWhitebindPermissions::TryParse(whitebind_arg, whitebind, error)) { if (!NetPermissions::HasFlag(whitebind.m_flags, NetPermissionFlags::NoBan)) { return whitebind.m_service.GetPort(); } } } // Otherwise, if -port= is provided, use that. Otherwise use the default port. return static_cast<uint16_t>(gArgs.GetIntArg("-port", Params().GetDefaultPort())); } // Determine the "best" local address for a particular peer. [[nodiscard]] static std::optional<CService> GetLocal(const CNode& peer) { if (!fListen) return std::nullopt; std::optional<CService> addr; int nBestScore = -1; int nBestReachability = -1; { LOCK(g_maplocalhost_mutex); for (const auto& [local_addr, local_service_info] : mapLocalHost) { // For privacy reasons, don't advertise our privacy-network address // to other networks and don't advertise our other-network address // to privacy networks. if (local_addr.GetNetwork() != peer.ConnectedThroughNetwork() && (local_addr.IsPrivacyNet() || peer.IsConnectedThroughPrivacyNet())) { continue; } const int nScore{local_service_info.nScore}; const int nReachability{local_addr.GetReachabilityFrom(peer.addr)}; if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr.emplace(CService{local_addr, local_service_info.nPort}); nBestReachability = nReachability; nBestScore = nScore; } } } return addr; } //! Convert the serialized seeds into usable address objects. static std::vector<CAddress> ConvertSeeds(const std::vector<uint8_t> &vSeedsIn) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const auto one_week{7 * 24h}; std::vector<CAddress> vSeedsOut; FastRandomContext rng; DataStream underlying_stream{vSeedsIn}; ParamsStream s{CAddress::V2_NETWORK, underlying_stream}; while (!s.eof()) { CService endpoint; s >> endpoint; CAddress addr{endpoint, GetDesirableServiceFlags(NODE_NONE)}; addr.nTime = rng.rand_uniform_delay(Now<NodeSeconds>() - one_week, -one_week); LogPrint(BCLog::NET, "Added hardcoded seed: %s\n", addr.ToStringAddrPort()); vSeedsOut.push_back(addr); } return vSeedsOut; } // Determine the "best" local address for a particular peer. // If none, return the unroutable 0.0.0.0 but filled in with // the normal parameters, since the IP may be changed to a useful // one by discovery. CService GetLocalAddress(const CNode& peer) { return GetLocal(peer).value_or(CService{CNetAddr(), GetListenPort()}); } static int GetnScore(const CService& addr) { LOCK(g_maplocalhost_mutex); const auto it = mapLocalHost.find(addr); return (it != mapLocalHost.end()) ? it->second.nScore : 0; } // Is our peer's addrLocal potentially useful as an external IP source? [[nodiscard]] static bool IsPeerAddrLocalGood(CNode *pnode) { CService addrLocal = pnode->GetAddrLocal(); return fDiscover && pnode->addr.IsRoutable() && addrLocal.IsRoutable() && g_reachable_nets.Contains(addrLocal); } std::optional<CService> GetLocalAddrForPeer(CNode& node) { CService addrLocal{GetLocalAddress(node)}; if (gArgs.GetBoolArg("-addrmantest", false)) { // use IPv4 loopback during addrmantest addrLocal = CService(LookupNumeric("127.0.0.1", GetListenPort())); } // If discovery is enabled, sometimes give our peer the address it // tells us that it sees us as in case it has a better idea of our // address than we do. FastRandomContext rng; if (IsPeerAddrLocalGood(&node) && (!addrLocal.IsRoutable() || rng.randbits((GetnScore(addrLocal) > LOCAL_MANUAL) ? 3 : 1) == 0)) { if (node.IsInboundConn()) { // For inbound connections, assume both the address and the port // as seen from the peer. addrLocal = CService{node.GetAddrLocal()}; } else { // For outbound connections, assume just the address as seen from // the peer and leave the port in `addrLocal` as returned by // `GetLocalAddress()` above. The peer has no way to observe our // listening port when we have initiated the connection. addrLocal.SetIP(node.GetAddrLocal()); } } if (addrLocal.IsRoutable() || gArgs.GetBoolArg("-addrmantest", false)) { LogPrint(BCLog::NET, "Advertising address %s to peer=%d\n", addrLocal.ToStringAddrPort(), node.GetId()); return addrLocal; } // Address is unroutable. Don't advertise. return std::nullopt; } // learn a new local address bool AddLocal(const CService& addr_, int nScore) { CService addr{MaybeFlipIPv6toCJDNS(addr_)}; if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (!g_reachable_nets.Contains(addr)) return false; LogPrintf("AddLocal(%s,%i)\n", addr.ToStringAddrPort(), nScore); { LOCK(g_maplocalhost_mutex); const auto [it, is_newly_added] = mapLocalHost.emplace(addr, LocalServiceInfo()); LocalServiceInfo &info = it->second; if (is_newly_added || nScore >= info.nScore) { info.nScore = nScore + (is_newly_added ? 0 : 1); info.nPort = addr.GetPort(); } } return true; } bool AddLocal(const CNetAddr &addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } void RemoveLocal(const CService& addr) { LOCK(g_maplocalhost_mutex); LogPrintf("RemoveLocal(%s)\n", addr.ToStringAddrPort()); mapLocalHost.erase(addr); } /** vote for a local address */ bool SeenLocal(const CService& addr) { LOCK(g_maplocalhost_mutex); const auto it = mapLocalHost.find(addr); if (it == mapLocalHost.end()) return false; ++it->second.nScore; return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(g_maplocalhost_mutex); return mapLocalHost.count(addr) > 0; } CNode* CConnman::FindNode(const CNetAddr& ip) { LOCK(m_nodes_mutex); for (CNode* pnode : m_nodes) { if (static_cast<CNetAddr>(pnode->addr) == ip) { return pnode; } } return nullptr; } CNode* CConnman::FindNode(const std::string& addrName) { LOCK(m_nodes_mutex); for (CNode* pnode : m_nodes) { if (pnode->m_addr_name == addrName) { return pnode; } } return nullptr; } CNode* CConnman::FindNode(const CService& addr) { LOCK(m_nodes_mutex); for (CNode* pnode : m_nodes) { if (static_cast<CService>(pnode->addr) == addr) { return pnode; } } return nullptr; } bool CConnman::AlreadyConnectedToAddress(const CAddress& addr) { return FindNode(static_cast<CNetAddr>(addr)) || FindNode(addr.ToStringAddrPort()); } bool CConnman::CheckIncomingNonce(uint64_t nonce) { LOCK(m_nodes_mutex); for (const CNode* pnode : m_nodes) { if (!pnode->fSuccessfullyConnected && !pnode->IsInboundConn() && pnode->GetLocalNonce() == nonce) return false; } return true; } /** Get the bind address for a socket as CAddress */ static CAddress GetBindAddress(const Sock& sock) { CAddress addr_bind; struct sockaddr_storage sockaddr_bind; socklen_t sockaddr_bind_len = sizeof(sockaddr_bind); if (!sock.GetSockName((struct sockaddr*)&sockaddr_bind, &sockaddr_bind_len)) { addr_bind.SetSockAddr((const struct sockaddr*)&sockaddr_bind); } else { LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "getsockname failed\n"); } return addr_bind; } CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type, bool use_v2transport) { AssertLockNotHeld(m_unused_i2p_sessions_mutex); assert(conn_type != ConnectionType::INBOUND); if (pszDest == nullptr) { if (IsLocal(addrConnect)) return nullptr; // Look for an existing connection CNode* pnode = FindNode(static_cast<CService>(addrConnect)); if (pnode) { LogPrintf("Failed to open new connection, already connected\n"); return nullptr; } } LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "trying %s connection %s lastseen=%.1fhrs\n", use_v2transport ? "v2" : "v1", pszDest ? pszDest : addrConnect.ToStringAddrPort(), Ticks<HoursDouble>(pszDest ? 0h : Now<NodeSeconds>() - addrConnect.nTime)); // Resolve const uint16_t default_port{pszDest != nullptr ? GetDefaultPort(pszDest) : m_params.GetDefaultPort()}; if (pszDest) { std::vector<CService> resolved{Lookup(pszDest, default_port, fNameLookup && !HaveNameProxy(), 256)}; if (!resolved.empty()) { Shuffle(resolved.begin(), resolved.end(), FastRandomContext()); // If the connection is made by name, it can be the case that the name resolves to more than one address. // We don't want to connect any more of them if we are already connected to one for (const auto& r : resolved) { addrConnect = CAddress{MaybeFlipIPv6toCJDNS(r), NODE_NONE}; if (!addrConnect.IsValid()) { LogPrint(BCLog::NET, "Resolver returned invalid address %s for %s\n", addrConnect.ToStringAddrPort(), pszDest); return nullptr; } // It is possible that we already have a connection to the IP/port pszDest resolved to. // In that case, drop the connection that was just created. LOCK(m_nodes_mutex); CNode* pnode = FindNode(static_cast<CService>(addrConnect)); if (pnode) { LogPrintf("Not opening a connection to %s, already connected to %s\n", pszDest, addrConnect.ToStringAddrPort()); return nullptr; } } } } // Connect bool connected = false; std::unique_ptr<Sock> sock; Proxy proxy; CAddress addr_bind; assert(!addr_bind.IsValid()); std::unique_ptr<i2p::sam::Session> i2p_transient_session; if (addrConnect.IsValid()) { const bool use_proxy{GetProxy(addrConnect.GetNetwork(), proxy)}; bool proxyConnectionFailed = false; if (addrConnect.IsI2P() && use_proxy) { i2p::Connection conn; if (m_i2p_sam_session) { connected = m_i2p_sam_session->Connect(addrConnect, conn, proxyConnectionFailed); } else { { LOCK(m_unused_i2p_sessions_mutex); if (m_unused_i2p_sessions.empty()) { i2p_transient_session = std::make_unique<i2p::sam::Session>(proxy.proxy, &interruptNet); } else { i2p_transient_session.swap(m_unused_i2p_sessions.front()); m_unused_i2p_sessions.pop(); } } connected = i2p_transient_session->Connect(addrConnect, conn, proxyConnectionFailed); if (!connected) { LOCK(m_unused_i2p_sessions_mutex); if (m_unused_i2p_sessions.size() < MAX_UNUSED_I2P_SESSIONS_SIZE) { m_unused_i2p_sessions.emplace(i2p_transient_session.release()); } } } if (connected) { sock = std::move(conn.sock); addr_bind = CAddress{conn.me, NODE_NONE}; } } else if (use_proxy) { sock = CreateSock(proxy.proxy); if (!sock) { return nullptr; } connected = ConnectThroughProxy(proxy, addrConnect.ToStringAddr(), addrConnect.GetPort(), *sock, nConnectTimeout, proxyConnectionFailed); } else { // no proxy needed (none set for target network) sock = CreateSock(addrConnect); if (!sock) { return nullptr; } connected = ConnectSocketDirectly(addrConnect, *sock, nConnectTimeout, conn_type == ConnectionType::MANUAL); } if (!proxyConnectionFailed) { // If a connection to the node was attempted, and failure (if any) is not caused by a problem connecting to // the proxy, mark this as an attempt. addrman.Attempt(addrConnect, fCountFailure); } } else if (pszDest && GetNameProxy(proxy)) { sock = CreateSock(proxy.proxy); if (!sock) { return nullptr; } std::string host; uint16_t port{default_port}; SplitHostPort(std::string(pszDest), port, host); bool proxyConnectionFailed; connected = ConnectThroughProxy(proxy, host, port, *sock, nConnectTimeout, proxyConnectionFailed); } if (!connected) { return nullptr; } // Add node NodeId id = GetNewNodeId(); uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize(); if (!addr_bind.IsValid()) { addr_bind = GetBindAddress(*sock); } CNode* pnode = new CNode(id, std::move(sock), addrConnect, CalculateKeyedNetGroup(addrConnect), nonce, addr_bind, pszDest ? pszDest : "", conn_type, /*inbound_onion=*/false, CNodeOptions{ .i2p_sam_session = std::move(i2p_transient_session), .recv_flood_size = nReceiveFloodSize, .use_v2transport = use_v2transport, }); pnode->AddRef(); // We're making a new connection, harvest entropy from the time (and our peer count) RandAddEvent((uint32_t)id); return pnode; } void CNode::CloseSocketDisconnect() { fDisconnect = true; LOCK(m_sock_mutex); if (m_sock) { LogPrint(BCLog::NET, "disconnecting peer=%d\n", id); m_sock.reset(); } m_i2p_sam_session.reset(); } void CConnman::AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr) const { for (const auto& subnet : vWhitelistedRange) { if (subnet.m_subnet.Match(addr)) NetPermissions::AddFlag(flags, subnet.m_flags); } } CService CNode::GetAddrLocal() const { AssertLockNotHeld(m_addr_local_mutex); LOCK(m_addr_local_mutex); return addrLocal; } void CNode::SetAddrLocal(const CService& addrLocalIn) { AssertLockNotHeld(m_addr_local_mutex); LOCK(m_addr_local_mutex); if (addrLocal.IsValid()) { error("Addr local already set for node: %i. Refusing to change from %s to %s", id, addrLocal.ToStringAddrPort(), addrLocalIn.ToStringAddrPort()); } else { addrLocal = addrLocalIn; } } Network CNode::ConnectedThroughNetwork() const { return m_inbound_onion ? NET_ONION : addr.GetNetClass(); } bool CNode::IsConnectedThroughPrivacyNet() const { return m_inbound_onion || addr.IsPrivacyNet(); } #undef X #define X(name) stats.name = name void CNode::CopyStats(CNodeStats& stats) { stats.nodeid = this->GetId(); X(addr); X(addrBind); stats.m_network = ConnectedThroughNetwork(); X(m_last_send); X(m_last_recv); X(m_last_tx_time); X(m_last_block_time); X(m_connected); X(nTimeOffset); X(m_addr_name); X(nVersion); { LOCK(m_subver_mutex); X(cleanSubVer); } stats.fInbound = IsInboundConn(); X(m_bip152_highbandwidth_to); X(m_bip152_highbandwidth_from); { LOCK(cs_vSend); X(mapSendBytesPerMsgType); X(nSendBytes); } { LOCK(cs_vRecv); X(mapRecvBytesPerMsgType); X(nRecvBytes); Transport::Info info = m_transport->GetInfo(); stats.m_transport_type = info.transport_type; if (info.session_id) stats.m_session_id = HexStr(*info.session_id); } X(m_permission_flags); X(m_last_ping_time); X(m_min_ping_time); // Leave string empty if addrLocal invalid (not filled in yet) CService addrLocalUnlocked = GetAddrLocal(); stats.addrLocal = addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToStringAddrPort() : ""; X(m_conn_type); } #undef X bool CNode::ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete) { complete = false; const auto time = GetTime<std::chrono::microseconds>(); LOCK(cs_vRecv); m_last_recv = std::chrono::duration_cast<std::chrono::seconds>(time); nRecvBytes += msg_bytes.size(); while (msg_bytes.size() > 0) { // absorb network data if (!m_transport->ReceivedBytes(msg_bytes)) { // Serious transport problem, disconnect from the peer. return false; } if (m_transport->ReceivedMessageComplete()) { // decompose a transport agnostic CNetMessage from the deserializer bool reject_message{false}; CNetMessage msg = m_transport->GetReceivedMessage(time, reject_message); if (reject_message) { // Message deserialization failed. Drop the message but don't disconnect the peer. // store the size of the corrupt message mapRecvBytesPerMsgType.at(NET_MESSAGE_TYPE_OTHER) += msg.m_raw_message_size; continue; } // Store received bytes per message type. // To prevent a memory DOS, only allow known message types. auto i = mapRecvBytesPerMsgType.find(msg.m_type); if (i == mapRecvBytesPerMsgType.end()) { i = mapRecvBytesPerMsgType.find(NET_MESSAGE_TYPE_OTHER); } assert(i != mapRecvBytesPerMsgType.end()); i->second += msg.m_raw_message_size; // push the message to the process queue, vRecvMsg.push_back(std::move(msg)); complete = true; } } return true; } V1Transport::V1Transport(const NodeId node_id) noexcept : m_magic_bytes{Params().MessageStart()}, m_node_id{node_id} { LOCK(m_recv_mutex); Reset(); } Transport::Info V1Transport::GetInfo() const noexcept { return {.transport_type = TransportProtocolType::V1, .session_id = {}}; } int V1Transport::readHeader(Span<const uint8_t> msg_bytes) { AssertLockHeld(m_recv_mutex); // copy data to temporary parsing buffer unsigned int nRemaining = CMessageHeader::HEADER_SIZE - nHdrPos; unsigned int nCopy = std::min<unsigned int>(nRemaining, msg_bytes.size()); memcpy(&hdrbuf[nHdrPos], msg_bytes.data(), nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < CMessageHeader::HEADER_SIZE) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (const std::exception&) { LogPrint(BCLog::NET, "Header error: Unable to deserialize, peer=%d\n", m_node_id); return -1; } // Check start string, network magic if (hdr.pchMessageStart != m_magic_bytes) { LogPrint(BCLog::NET, "Header error: Wrong MessageStart %s received, peer=%d\n", HexStr(hdr.pchMessageStart), m_node_id); return -1; } // reject messages larger than MAX_SIZE or MAX_PROTOCOL_MESSAGE_LENGTH if (hdr.nMessageSize > MAX_SIZE || hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) { LogPrint(BCLog::NET, "Header error: Size too large (%s, %u bytes), peer=%d\n", SanitizeString(hdr.GetCommand()), hdr.nMessageSize, m_node_id); return -1; } // switch state to reading message data in_data = true; return nCopy; } int V1Transport::readData(Span<const uint8_t> msg_bytes) { AssertLockHeld(m_recv_mutex); unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min<unsigned int>(nRemaining, msg_bytes.size()); if (vRecv.size() < nDataPos + nCopy) { // Allocate up to 256 KiB ahead, but never more than the total message size. vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024)); } hasher.Write(msg_bytes.first(nCopy)); memcpy(&vRecv[nDataPos], msg_bytes.data(), nCopy); nDataPos += nCopy; return nCopy; } const uint256& V1Transport::GetMessageHash() const { AssertLockHeld(m_recv_mutex); assert(CompleteInternal()); if (data_hash.IsNull()) hasher.Finalize(data_hash); return data_hash; } CNetMessage V1Transport::GetReceivedMessage(const std::chrono::microseconds time, bool& reject_message) { AssertLockNotHeld(m_recv_mutex); // Initialize out parameter reject_message = false; // decompose a single CNetMessage from the TransportDeserializer LOCK(m_recv_mutex); CNetMessage msg(std::move(vRecv)); // store message type string, time, and sizes msg.m_type = hdr.GetCommand(); msg.m_time = time; msg.m_message_size = hdr.nMessageSize; msg.m_raw_message_size = hdr.nMessageSize + CMessageHeader::HEADER_SIZE; uint256 hash = GetMessageHash(); // We just received a message off the wire, harvest entropy from the time (and the message checksum) RandAddEvent(ReadLE32(hash.begin())); // Check checksum and header message type string if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0) { LogPrint(BCLog::NET, "Header error: Wrong checksum (%s, %u bytes), expected %s was %s, peer=%d\n", SanitizeString(msg.m_type), msg.m_message_size, HexStr(Span{hash}.first(CMessageHeader::CHECKSUM_SIZE)), HexStr(hdr.pchChecksum), m_node_id); reject_message = true; } else if (!hdr.IsCommandValid()) { LogPrint(BCLog::NET, "Header error: Invalid message type (%s, %u bytes), peer=%d\n", SanitizeString(hdr.GetCommand()), msg.m_message_size, m_node_id); reject_message = true; } // Always reset the network deserializer (prepare for the next message) Reset(); return msg; } bool V1Transport::SetMessageToSend(CSerializedNetMsg& msg) noexcept { AssertLockNotHeld(m_send_mutex); // Determine whether a new message can be set. LOCK(m_send_mutex); if (m_sending_header || m_bytes_sent < m_message_to_send.data.size()) return false; // create dbl-sha256 checksum uint256 hash = Hash(msg.data); // create header CMessageHeader hdr(m_magic_bytes, msg.m_type.c_str(), msg.data.size()); memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE); // serialize header m_header_to_send.clear(); VectorWriter{m_header_to_send, 0, hdr}; // update state m_message_to_send = std::move(msg); m_sending_header = true; m_bytes_sent = 0; return true; } Transport::BytesToSend V1Transport::GetBytesToSend(bool have_next_message) const noexcept { AssertLockNotHeld(m_send_mutex); LOCK(m_send_mutex); if (m_sending_header) { return {Span{m_header_to_send}.subspan(m_bytes_sent), // We have more to send after the header if the message has payload, or if there // is a next message after that. have_next_message || !m_message_to_send.data.empty(), m_message_to_send.m_type }; } else { return {Span{m_message_to_send.data}.subspan(m_bytes_sent), // We only have more to send after this message's payload if there is another // message. have_next_message, m_message_to_send.m_type }; } } void V1Transport::MarkBytesSent(size_t bytes_sent) noexcept { AssertLockNotHeld(m_send_mutex); LOCK(m_send_mutex); m_bytes_sent += bytes_sent; if (m_sending_header && m_bytes_sent == m_header_to_send.size()) { // We're done sending a message's header. Switch to sending its data bytes. m_sending_header = false; m_bytes_sent = 0; } else if (!m_sending_header && m_bytes_sent == m_message_to_send.data.size()) { // We're done sending a message's data. Wipe the data vector to reduce memory consumption. ClearShrink(m_message_to_send.data); m_bytes_sent = 0; } } size_t V1Transport::GetSendMemoryUsage() const noexcept { AssertLockNotHeld(m_send_mutex); LOCK(m_send_mutex); // Don't count sending-side fields besides m_message_to_send, as they're all small and bounded. return m_message_to_send.GetMemoryUsage(); } namespace { /** List of short messages as defined in BIP324, in order. * * Only message types that are actually implemented in this codebase need to be listed, as other * messages get ignored anyway - whether we know how to decode them or not. */ const std::array<std::string, 33> V2_MESSAGE_IDS = { "", // 12 bytes follow encoding the message type like in V1 NetMsgType::ADDR, NetMsgType::BLOCK, NetMsgType::BLOCKTXN, NetMsgType::CMPCTBLOCK, NetMsgType::FEEFILTER, NetMsgType::FILTERADD, NetMsgType::FILTERCLEAR, NetMsgType::FILTERLOAD, NetMsgType::GETBLOCKS, NetMsgType::GETBLOCKTXN, NetMsgType::GETDATA, NetMsgType::GETHEADERS, NetMsgType::HEADERS, NetMsgType::INV, NetMsgType::MEMPOOL, NetMsgType::MERKLEBLOCK, NetMsgType::NOTFOUND, NetMsgType::PING, NetMsgType::PONG, NetMsgType::SENDCMPCT, NetMsgType::TX, NetMsgType::GETCFILTERS, NetMsgType::CFILTER, NetMsgType::GETCFHEADERS, NetMsgType::CFHEADERS, NetMsgType::GETCFCHECKPT, NetMsgType::CFCHECKPT, NetMsgType::ADDRV2, // Unimplemented message types that are assigned in BIP324: "", "", "", "" }; class V2MessageMap { std::unordered_map<std::string, uint8_t> m_map; public: V2MessageMap() noexcept { for (size_t i = 1; i < std::size(V2_MESSAGE_IDS); ++i) { m_map.emplace(V2_MESSAGE_IDS[i], i); } } std::optional<uint8_t> operator()(const std::string& message_name) const noexcept { auto it = m_map.find(message_name); if (it == m_map.end()) return std::nullopt; return it->second; } }; const V2MessageMap V2_MESSAGE_MAP; CKey GenerateRandomKey() noexcept { CKey key; key.MakeNewKey(/*fCompressed=*/true); return key; } std::vector<uint8_t> GenerateRandomGarbage() noexcept { std::vector<uint8_t> ret; FastRandomContext rng; ret.resize(rng.randrange(V2Transport::MAX_GARBAGE_LEN + 1)); rng.fillrand(MakeWritableByteSpan(ret)); return ret; } } // namespace void V2Transport::StartSendingHandshake() noexcept { AssertLockHeld(m_send_mutex); Assume(m_send_state == SendState::AWAITING_KEY); Assume(m_send_buffer.empty()); // Initialize the send buffer with ellswift pubkey + provided garbage. m_send_buffer.resize(EllSwiftPubKey::size() + m_send_garbage.size()); std::copy(std::begin(m_cipher.GetOurPubKey()), std::end(m_cipher.GetOurPubKey()), MakeWritableByteSpan(m_send_buffer).begin()); std::copy(m_send_garbage.begin(), m_send_garbage.end(), m_send_buffer.begin() + EllSwiftPubKey::size()); // We cannot wipe m_send_garbage as it will still be used as AAD later in the handshake. } V2Transport::V2Transport(NodeId nodeid, bool initiating, const CKey& key, Span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept : m_cipher{key, ent32}, m_initiating{initiating}, m_nodeid{nodeid}, m_v1_fallback{nodeid}, m_recv_state{initiating ? RecvState::KEY : RecvState::KEY_MAYBE_V1}, m_send_garbage{std::move(garbage)}, m_send_state{initiating ? SendState::AWAITING_KEY : SendState::MAYBE_V1} { Assume(m_send_garbage.size() <= MAX_GARBAGE_LEN); // Start sending immediately if we're the initiator of the connection. if (initiating) { LOCK(m_send_mutex); StartSendingHandshake(); } } V2Transport::V2Transport(NodeId nodeid, bool initiating) noexcept : V2Transport{nodeid, initiating, GenerateRandomKey(), MakeByteSpan(GetRandHash()), GenerateRandomGarbage()} {} void V2Transport::SetReceiveState(RecvState recv_state) noexcept { AssertLockHeld(m_recv_mutex); // Enforce allowed state transitions. switch (m_recv_state) { case RecvState::KEY_MAYBE_V1: Assume(recv_state == RecvState::KEY || recv_state == RecvState::V1); break; case RecvState::KEY: Assume(recv_state == RecvState::GARB_GARBTERM); break; case RecvState::GARB_GARBTERM: Assume(recv_state == RecvState::VERSION); break; case RecvState::VERSION: Assume(recv_state == RecvState::APP); break; case RecvState::APP: Assume(recv_state == RecvState::APP_READY); break; case RecvState::APP_READY: Assume(recv_state == RecvState::APP); break; case RecvState::V1: Assume(false); // V1 state cannot be left break; } // Change state. m_recv_state = recv_state; } void V2Transport::SetSendState(SendState send_state) noexcept { AssertLockHeld(m_send_mutex); // Enforce allowed state transitions. switch (m_send_state) { case SendState::MAYBE_V1: Assume(send_state == SendState::V1 || send_state == SendState::AWAITING_KEY); break; case SendState::AWAITING_KEY: Assume(send_state == SendState::READY); break; case SendState::READY: case SendState::V1: Assume(false); // Final states break; } // Change state. m_send_state = send_state; } bool V2Transport::ReceivedMessageComplete() const noexcept { AssertLockNotHeld(m_recv_mutex); LOCK(m_recv_mutex); if (m_recv_state == RecvState::V1) return m_v1_fallback.ReceivedMessageComplete(); return m_recv_state == RecvState::APP_READY; } void V2Transport::ProcessReceivedMaybeV1Bytes() noexcept { AssertLockHeld(m_recv_mutex); AssertLockNotHeld(m_send_mutex); Assume(m_recv_state == RecvState::KEY_MAYBE_V1); // We still have to determine if this is a v1 or v2 connection. The bytes being received could // be the beginning of either a v1 packet (network magic + "version\x00\x00\x00\x00\x00"), or // of a v2 public key. BIP324 specifies that a mismatch with this 16-byte string should trigger // sending of the key. std::array<uint8_t, V1_PREFIX_LEN> v1_prefix = {0, 0, 0, 0, 'v', 'e', 'r', 's', 'i', 'o', 'n', 0, 0, 0, 0, 0}; std::copy(std::begin(Params().MessageStart()), std::end(Params().MessageStart()), v1_prefix.begin()); Assume(m_recv_buffer.size() <= v1_prefix.size()); if (!std::equal(m_recv_buffer.begin(), m_recv_buffer.end(), v1_prefix.begin())) { // Mismatch with v1 prefix, so we can assume a v2 connection. SetReceiveState(RecvState::KEY); // Convert to KEY state, leaving received bytes around. // Transition the sender to AWAITING_KEY state and start sending. LOCK(m_send_mutex); SetSendState(SendState::AWAITING_KEY); StartSendingHandshake(); } else if (m_recv_buffer.size() == v1_prefix.size()) { // Full match with the v1 prefix, so fall back to v1 behavior. LOCK(m_send_mutex); Span<const uint8_t> feedback{m_recv_buffer}; // Feed already received bytes to v1 transport. It should always accept these, because it's // less than the size of a v1 header, and these are the first bytes fed to m_v1_fallback. bool ret = m_v1_fallback.ReceivedBytes(feedback); Assume(feedback.empty()); Assume(ret); SetReceiveState(RecvState::V1); SetSendState(SendState::V1); // Reset v2 transport buffers to save memory. ClearShrink(m_recv_buffer); ClearShrink(m_send_buffer); } else { // We have not received enough to distinguish v1 from v2 yet. Wait until more bytes come. } } bool V2Transport::ProcessReceivedKeyBytes() noexcept { AssertLockHeld(m_recv_mutex); AssertLockNotHeld(m_send_mutex); Assume(m_recv_state == RecvState::KEY); Assume(m_recv_buffer.size() <= EllSwiftPubKey::size()); // As a special exception, if bytes 4-16 of the key on a responder connection match the // corresponding bytes of a V1 version message, but bytes 0-4 don't match the network magic // (if they did, we'd have switched to V1 state already), assume this is a peer from // another network, and disconnect them. They will almost certainly disconnect us too when // they receive our uniformly random key and garbage, but detecting this case specially // means we can log it. static constexpr std::array<uint8_t, 12> MATCH = {'v', 'e', 'r', 's', 'i', 'o', 'n', 0, 0, 0, 0, 0}; static constexpr size_t OFFSET = std::tuple_size_v<MessageStartChars>; if (!m_initiating && m_recv_buffer.size() >= OFFSET + MATCH.size()) { if (std::equal(MATCH.begin(), MATCH.end(), m_recv_buffer.begin() + OFFSET)) { LogPrint(BCLog::NET, "V2 transport error: V1 peer with wrong MessageStart %s\n", HexStr(Span(m_recv_buffer).first(OFFSET))); return false; } } if (m_recv_buffer.size() == EllSwiftPubKey::size()) { // Other side's key has been fully received, and can now be Diffie-Hellman combined with // our key to initialize the encryption ciphers. // Initialize the ciphers. EllSwiftPubKey ellswift(MakeByteSpan(m_recv_buffer)); LOCK(m_send_mutex); m_cipher.Initialize(ellswift, m_initiating); // Switch receiver state to GARB_GARBTERM. SetReceiveState(RecvState::GARB_GARBTERM); m_recv_buffer.clear(); // Switch sender state to READY. SetSendState(SendState::READY); // Append the garbage terminator to the send buffer. m_send_buffer.resize(m_send_buffer.size() + BIP324Cipher::GARBAGE_TERMINATOR_LEN); std::copy(m_cipher.GetSendGarbageTerminator().begin(), m_cipher.GetSendGarbageTerminator().end(), MakeWritableByteSpan(m_send_buffer).last(BIP324Cipher::GARBAGE_TERMINATOR_LEN).begin()); // Construct version packet in the send buffer, with the sent garbage data as AAD. m_send_buffer.resize(m_send_buffer.size() + BIP324Cipher::EXPANSION + VERSION_CONTENTS.size()); m_cipher.Encrypt( /*contents=*/VERSION_CONTENTS, /*aad=*/MakeByteSpan(m_send_garbage), /*ignore=*/false, /*output=*/MakeWritableByteSpan(m_send_buffer).last(BIP324Cipher::EXPANSION + VERSION_CONTENTS.size())); // We no longer need the garbage. ClearShrink(m_send_garbage); } else { // We still have to receive more key bytes. } return true; } bool V2Transport::ProcessReceivedGarbageBytes() noexcept { AssertLockHeld(m_recv_mutex); Assume(m_recv_state == RecvState::GARB_GARBTERM); Assume(m_recv_buffer.size() <= MAX_GARBAGE_LEN + BIP324Cipher::GARBAGE_TERMINATOR_LEN); if (m_recv_buffer.size() >= BIP324Cipher::GARBAGE_TERMINATOR_LEN) { if (MakeByteSpan(m_recv_buffer).last(BIP324Cipher::GARBAGE_TERMINATOR_LEN) == m_cipher.GetReceiveGarbageTerminator()) { // Garbage terminator received. Store garbage to authenticate it as AAD later. m_recv_aad = std::move(m_recv_buffer); m_recv_aad.resize(m_recv_aad.size() - BIP324Cipher::GARBAGE_TERMINATOR_LEN); m_recv_buffer.clear(); SetReceiveState(RecvState::VERSION); } else if (m_recv_buffer.size() == MAX_GARBAGE_LEN + BIP324Cipher::GARBAGE_TERMINATOR_LEN) { // We've reached the maximum length for garbage + garbage terminator, and the // terminator still does not match. Abort. LogPrint(BCLog::NET, "V2 transport error: missing garbage terminator, peer=%d\n", m_nodeid); return false; } else { // We still need to receive more garbage and/or garbage terminator bytes. } } else { // We have less than GARBAGE_TERMINATOR_LEN (16) bytes, so we certainly need to receive // more first. } return true; } bool V2Transport::ProcessReceivedPacketBytes() noexcept { AssertLockHeld(m_recv_mutex); Assume(m_recv_state == RecvState::VERSION || m_recv_state == RecvState::APP); // The maximum permitted contents length for a packet, consisting of: // - 0x00 byte: indicating long message type encoding // - 12 bytes of message type // - payload static constexpr size_t MAX_CONTENTS_LEN = 1 + CMessageHeader::COMMAND_SIZE + std::min<size_t>(MAX_SIZE, MAX_PROTOCOL_MESSAGE_LENGTH); if (m_recv_buffer.size() == BIP324Cipher::LENGTH_LEN) { // Length descriptor received. m_recv_len = m_cipher.DecryptLength(MakeByteSpan(m_recv_buffer)); if (m_recv_len > MAX_CONTENTS_LEN) { LogPrint(BCLog::NET, "V2 transport error: packet too large (%u bytes), peer=%d\n", m_recv_len, m_nodeid); return false; } } else if (m_recv_buffer.size() > BIP324Cipher::LENGTH_LEN && m_recv_buffer.size() == m_recv_len + BIP324Cipher::EXPANSION) { // Ciphertext received, decrypt it into m_recv_decode_buffer. // Note that it is impossible to reach this branch without hitting the branch above first, // as GetMaxBytesToProcess only allows up to LENGTH_LEN into the buffer before that point. m_recv_decode_buffer.resize(m_recv_len); bool ignore{false}; bool ret = m_cipher.Decrypt( /*input=*/MakeByteSpan(m_recv_buffer).subspan(BIP324Cipher::LENGTH_LEN), /*aad=*/MakeByteSpan(m_recv_aad), /*ignore=*/ignore, /*contents=*/MakeWritableByteSpan(m_recv_decode_buffer)); if (!ret) { LogPrint(BCLog::NET, "V2 transport error: packet decryption failure (%u bytes), peer=%d\n", m_recv_len, m_nodeid); return false; } // We have decrypted a valid packet with the AAD we expected, so clear the expected AAD. ClearShrink(m_recv_aad); // Feed the last 4 bytes of the Poly1305 authentication tag (and its timing) into our RNG. RandAddEvent(ReadLE32(m_recv_buffer.data() + m_recv_buffer.size() - 4)); // At this point we have a valid packet decrypted into m_recv_decode_buffer. If it's not a // decoy, which we simply ignore, use the current state to decide what to do with it. if (!ignore) { switch (m_recv_state) { case RecvState::VERSION: // Version message received; transition to application phase. The contents is // ignored, but can be used for future extensions. SetReceiveState(RecvState::APP); break; case RecvState::APP: // Application message decrypted correctly. It can be extracted using GetMessage(). SetReceiveState(RecvState::APP_READY); break; default: // Any other state is invalid (this function should not have been called). Assume(false); } } // Wipe the receive buffer where the next packet will be received into. ClearShrink(m_recv_buffer); // In all but APP_READY state, we can wipe the decoded contents. if (m_recv_state != RecvState::APP_READY) ClearShrink(m_recv_decode_buffer); } else { // We either have less than 3 bytes, so we don't know the packet's length yet, or more // than 3 bytes but less than the packet's full ciphertext. Wait until those arrive. } return true; } size_t V2Transport::GetMaxBytesToProcess() noexcept { AssertLockHeld(m_recv_mutex); switch (m_recv_state) { case RecvState::KEY_MAYBE_V1: // During the KEY_MAYBE_V1 state we do not allow more than the length of v1 prefix into the // receive buffer. Assume(m_recv_buffer.size() <= V1_PREFIX_LEN); // As long as we're not sure if this is a v1 or v2 connection, don't receive more than what // is strictly necessary to distinguish the two (16 bytes). If we permitted more than // the v1 header size (24 bytes), we may not be able to feed the already-received bytes // back into the m_v1_fallback V1 transport. return V1_PREFIX_LEN - m_recv_buffer.size(); case RecvState::KEY: // During the KEY state, we only allow the 64-byte key into the receive buffer. Assume(m_recv_buffer.size() <= EllSwiftPubKey::size()); // As long as we have not received the other side's public key, don't receive more than // that (64 bytes), as garbage follows, and locating the garbage terminator requires the // key exchange first. return EllSwiftPubKey::size() - m_recv_buffer.size(); case RecvState::GARB_GARBTERM: // Process garbage bytes one by one (because terminator may appear anywhere). return 1; case RecvState::VERSION: case RecvState::APP: // These three states all involve decoding a packet. Process the length descriptor first, // so that we know where the current packet ends (and we don't process bytes from the next // packet or decoy yet). Then, process the ciphertext bytes of the current packet. if (m_recv_buffer.size() < BIP324Cipher::LENGTH_LEN) { return BIP324Cipher::LENGTH_LEN - m_recv_buffer.size(); } else { // Note that BIP324Cipher::EXPANSION is the total difference between contents size // and encoded packet size, which includes the 3 bytes due to the packet length. // When transitioning from receiving the packet length to receiving its ciphertext, // the encrypted packet length is left in the receive buffer. return BIP324Cipher::EXPANSION + m_recv_len - m_recv_buffer.size(); } case RecvState::APP_READY: // No bytes can be processed until GetMessage() is called. return 0; case RecvState::V1: // Not allowed (must be dealt with by the caller). Assume(false); return 0; } Assume(false); // unreachable return 0; } bool V2Transport::ReceivedBytes(Span<const uint8_t>& msg_bytes) noexcept { AssertLockNotHeld(m_recv_mutex); /** How many bytes to allocate in the receive buffer at most above what is received so far. */ static constexpr size_t MAX_RESERVE_AHEAD = 256 * 1024; LOCK(m_recv_mutex); if (m_recv_state == RecvState::V1) return m_v1_fallback.ReceivedBytes(msg_bytes); // Process the provided bytes in msg_bytes in a loop. In each iteration a nonzero number of // bytes (decided by GetMaxBytesToProcess) are taken from the beginning om msg_bytes, and // appended to m_recv_buffer. Then, depending on the receiver state, one of the // ProcessReceived*Bytes functions is called to process the bytes in that buffer. while (!msg_bytes.empty()) { // Decide how many bytes to copy from msg_bytes to m_recv_buffer. size_t max_read = GetMaxBytesToProcess(); // Reserve space in the buffer if there is not enough. if (m_recv_buffer.size() + std::min(msg_bytes.size(), max_read) > m_recv_buffer.capacity()) { switch (m_recv_state) { case RecvState::KEY_MAYBE_V1: case RecvState::KEY: case RecvState::GARB_GARBTERM: // During the initial states (key/garbage), allocate once to fit the maximum (4111 // bytes). m_recv_buffer.reserve(MAX_GARBAGE_LEN + BIP324Cipher::GARBAGE_TERMINATOR_LEN); break; case RecvState::VERSION: case RecvState::APP: { // During states where a packet is being received, as much as is expected but never // more than MAX_RESERVE_AHEAD bytes in addition to what is received so far. // This means attackers that want to cause us to waste allocated memory are limited // to MAX_RESERVE_AHEAD above the largest allowed message contents size, and to // MAX_RESERVE_AHEAD more than they've actually sent us. size_t alloc_add = std::min(max_read, msg_bytes.size() + MAX_RESERVE_AHEAD); m_recv_buffer.reserve(m_recv_buffer.size() + alloc_add); break; } case RecvState::APP_READY: // The buffer is empty in this state. Assume(m_recv_buffer.empty()); break; case RecvState::V1: // Should have bailed out above. Assume(false); break; } } // Can't read more than provided input. max_read = std::min(msg_bytes.size(), max_read); // Copy data to buffer. m_recv_buffer.insert(m_recv_buffer.end(), UCharCast(msg_bytes.data()), UCharCast(msg_bytes.data() + max_read)); msg_bytes = msg_bytes.subspan(max_read); // Process data in the buffer. switch (m_recv_state) { case RecvState::KEY_MAYBE_V1: ProcessReceivedMaybeV1Bytes(); if (m_recv_state == RecvState::V1) return true; break; case RecvState::KEY: if (!ProcessReceivedKeyBytes()) return false; break; case RecvState::GARB_GARBTERM: if (!ProcessReceivedGarbageBytes()) return false; break; case RecvState::VERSION: case RecvState::APP: if (!ProcessReceivedPacketBytes()) return false; break; case RecvState::APP_READY: return true; case RecvState::V1: // We should have bailed out before. Assume(false); break; } // Make sure we have made progress before continuing. Assume(max_read > 0); } return true; } std::optional<std::string> V2Transport::GetMessageType(Span<const uint8_t>& contents) noexcept { if (contents.size() == 0) return std::nullopt; // Empty contents uint8_t first_byte = contents[0]; contents = contents.subspan(1); // Strip first byte. if (first_byte != 0) { // Short (1 byte) encoding. if (first_byte < std::size(V2_MESSAGE_IDS)) { // Valid short message id. return V2_MESSAGE_IDS[first_byte]; } else { // Unknown short message id. return std::nullopt; } } if (contents.size() < CMessageHeader::COMMAND_SIZE) { return std::nullopt; // Long encoding needs 12 message type bytes. } size_t msg_type_len{0}; while (msg_type_len < CMessageHeader::COMMAND_SIZE && contents[msg_type_len] != 0) { // Verify that message type bytes before the first 0x00 are in range. if (contents[msg_type_len] < ' ' || contents[msg_type_len] > 0x7F) { return {}; } ++msg_type_len; } std::string ret{reinterpret_cast<const char*>(contents.data()), msg_type_len}; while (msg_type_len < CMessageHeader::COMMAND_SIZE) { // Verify that message type bytes after the first 0x00 are also 0x00. if (contents[msg_type_len] != 0) return {}; ++msg_type_len; } // Strip message type bytes of contents. contents = contents.subspan(CMessageHeader::COMMAND_SIZE); return ret; } CNetMessage V2Transport::GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) noexcept { AssertLockNotHeld(m_recv_mutex); LOCK(m_recv_mutex); if (m_recv_state == RecvState::V1) return m_v1_fallback.GetReceivedMessage(time, reject_message); Assume(m_recv_state == RecvState::APP_READY); Span<const uint8_t> contents{m_recv_decode_buffer}; auto msg_type = GetMessageType(contents); CNetMessage msg{DataStream{}}; // Note that BIP324Cipher::EXPANSION also includes the length descriptor size. msg.m_raw_message_size = m_recv_decode_buffer.size() + BIP324Cipher::EXPANSION; if (msg_type) { reject_message = false; msg.m_type = std::move(*msg_type); msg.m_time = time; msg.m_message_size = contents.size(); msg.m_recv.resize(contents.size()); std::copy(contents.begin(), contents.end(), UCharCast(msg.m_recv.data())); } else { LogPrint(BCLog::NET, "V2 transport error: invalid message type (%u bytes contents), peer=%d\n", m_recv_decode_buffer.size(), m_nodeid); reject_message = true; } ClearShrink(m_recv_decode_buffer); SetReceiveState(RecvState::APP); return msg; } bool V2Transport::SetMessageToSend(CSerializedNetMsg& msg) noexcept { AssertLockNotHeld(m_send_mutex); LOCK(m_send_mutex); if (m_send_state == SendState::V1) return m_v1_fallback.SetMessageToSend(msg); // We only allow adding a new message to be sent when in the READY state (so the packet cipher // is available) and the send buffer is empty. This limits the number of messages in the send // buffer to just one, and leaves the responsibility for queueing them up to the caller. if (!(m_send_state == SendState::READY && m_send_buffer.empty())) return false; // Construct contents (encoding message type + payload). std::vector<uint8_t> contents; auto short_message_id = V2_MESSAGE_MAP(msg.m_type); if (short_message_id) { contents.resize(1 + msg.data.size()); contents[0] = *short_message_id; std::copy(msg.data.begin(), msg.data.end(), contents.begin() + 1); } else { // Initialize with zeroes, and then write the message type string starting at offset 1. // This means contents[0] and the unused positions in contents[1..13] remain 0x00. contents.resize(1 + CMessageHeader::COMMAND_SIZE + msg.data.size(), 0); std::copy(msg.m_type.begin(), msg.m_type.end(), contents.data() + 1); std::copy(msg.data.begin(), msg.data.end(), contents.begin() + 1 + CMessageHeader::COMMAND_SIZE); } // Construct ciphertext in send buffer. m_send_buffer.resize(contents.size() + BIP324Cipher::EXPANSION); m_cipher.Encrypt(MakeByteSpan(contents), {}, false, MakeWritableByteSpan(m_send_buffer)); m_send_type = msg.m_type; // Release memory ClearShrink(msg.data); return true; } Transport::BytesToSend V2Transport::GetBytesToSend(bool have_next_message) const noexcept { AssertLockNotHeld(m_send_mutex); LOCK(m_send_mutex); if (m_send_state == SendState::V1) return m_v1_fallback.GetBytesToSend(have_next_message); if (m_send_state == SendState::MAYBE_V1) Assume(m_send_buffer.empty()); Assume(m_send_pos <= m_send_buffer.size()); return { Span{m_send_buffer}.subspan(m_send_pos), // We only have more to send after the current m_send_buffer if there is a (next) // message to be sent, and we're capable of sending packets. */ have_next_message && m_send_state == SendState::READY, m_send_type }; } void V2Transport::MarkBytesSent(size_t bytes_sent) noexcept { AssertLockNotHeld(m_send_mutex); LOCK(m_send_mutex); if (m_send_state == SendState::V1) return m_v1_fallback.MarkBytesSent(bytes_sent); if (m_send_state == SendState::AWAITING_KEY && m_send_pos == 0 && bytes_sent > 0) { LogPrint(BCLog::NET, "start sending v2 handshake to peer=%d\n", m_nodeid); } m_send_pos += bytes_sent; Assume(m_send_pos <= m_send_buffer.size()); if (m_send_pos >= CMessageHeader::HEADER_SIZE) { m_sent_v1_header_worth = true; } // Wipe the buffer when everything is sent. if (m_send_pos == m_send_buffer.size()) { m_send_pos = 0; ClearShrink(m_send_buffer); } } bool V2Transport::ShouldReconnectV1() const noexcept { AssertLockNotHeld(m_send_mutex); AssertLockNotHeld(m_recv_mutex); // Only outgoing connections need reconnection. if (!m_initiating) return false; LOCK(m_recv_mutex); // We only reconnect in the very first state and when the receive buffer is empty. Together // these conditions imply nothing has been received so far. if (m_recv_state != RecvState::KEY) return false; if (!m_recv_buffer.empty()) return false; // Check if we've sent enough for the other side to disconnect us (if it was V1). LOCK(m_send_mutex); return m_sent_v1_header_worth; } size_t V2Transport::GetSendMemoryUsage() const noexcept { AssertLockNotHeld(m_send_mutex); LOCK(m_send_mutex); if (m_send_state == SendState::V1) return m_v1_fallback.GetSendMemoryUsage(); return sizeof(m_send_buffer) + memusage::DynamicUsage(m_send_buffer); } Transport::Info V2Transport::GetInfo() const noexcept { AssertLockNotHeld(m_recv_mutex); LOCK(m_recv_mutex); if (m_recv_state == RecvState::V1) return m_v1_fallback.GetInfo(); Transport::Info info; // Do not report v2 and session ID until the version packet has been received // and verified (confirming that the other side very likely has the same keys as us). if (m_recv_state != RecvState::KEY_MAYBE_V1 && m_recv_state != RecvState::KEY && m_recv_state != RecvState::GARB_GARBTERM && m_recv_state != RecvState::VERSION) { info.transport_type = TransportProtocolType::V2; info.session_id = uint256(MakeUCharSpan(m_cipher.GetSessionID())); } else { info.transport_type = TransportProtocolType::DETECTING; } return info; } std::pair<size_t, bool> CConnman::SocketSendData(CNode& node) const { auto it = node.vSendMsg.begin(); size_t nSentSize = 0; bool data_left{false}; //!< second return value (whether unsent data remains) std::optional<bool> expected_more; while (true) { if (it != node.vSendMsg.end()) { // If possible, move one message from the send queue to the transport. This fails when // there is an existing message still being sent, or (for v2 transports) when the // handshake has not yet completed. size_t memusage = it->GetMemoryUsage(); if (node.m_transport->SetMessageToSend(*it)) { // Update memory usage of send buffer (as *it will be deleted). node.m_send_memusage -= memusage; ++it; } } const auto& [data, more, msg_type] = node.m_transport->GetBytesToSend(it != node.vSendMsg.end()); // We rely on the 'more' value returned by GetBytesToSend to correctly predict whether more // bytes are still to be sent, to correctly set the MSG_MORE flag. As a sanity check, // verify that the previously returned 'more' was correct. if (expected_more.has_value()) Assume(!data.empty() == *expected_more); expected_more = more; data_left = !data.empty(); // will be overwritten on next loop if all of data gets sent int nBytes = 0; if (!data.empty()) { LOCK(node.m_sock_mutex); // There is no socket in case we've already disconnected, or in test cases without // real connections. In these cases, we bail out immediately and just leave things // in the send queue and transport. if (!node.m_sock) { break; } int flags = MSG_NOSIGNAL | MSG_DONTWAIT; #ifdef MSG_MORE if (more) { flags |= MSG_MORE; } #endif nBytes = node.m_sock->Send(reinterpret_cast<const char*>(data.data()), data.size(), flags); } if (nBytes > 0) { node.m_last_send = GetTime<std::chrono::seconds>(); node.nSendBytes += nBytes; // Notify transport that bytes have been processed. node.m_transport->MarkBytesSent(nBytes); // Update statistics per message type. if (!msg_type.empty()) { // don't report v2 handshake bytes for now node.AccountForSentBytes(msg_type, nBytes); } nSentSize += nBytes; if ((size_t)nBytes != data.size()) { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { LogPrint(BCLog::NET, "socket send error for peer=%d: %s\n", node.GetId(), NetworkErrorString(nErr)); node.CloseSocketDisconnect(); } } break; } } node.fPauseSend = node.m_send_memusage + node.m_transport->GetSendMemoryUsage() > nSendBufferMaxSize; if (it == node.vSendMsg.end()) { assert(node.m_send_memusage == 0); } node.vSendMsg.erase(node.vSendMsg.begin(), it); return {nSentSize, data_left}; } /** Try to find a connection to evict when the node is full. * Extreme care must be taken to avoid opening the node to attacker * triggered network partitioning. * The strategy used here is to protect a small number of peers * for each of several distinct characteristics which are difficult * to forge. In order to partition a node the attacker must be * simultaneously better at all of them than honest peers. */ bool CConnman::AttemptToEvictConnection() { std::vector<NodeEvictionCandidate> vEvictionCandidates; { LOCK(m_nodes_mutex); for (const CNode* node : m_nodes) { if (node->fDisconnect) continue; NodeEvictionCandidate candidate{ .id = node->GetId(), .m_connected = node->m_connected, .m_min_ping_time = node->m_min_ping_time, .m_last_block_time = node->m_last_block_time, .m_last_tx_time = node->m_last_tx_time, .fRelevantServices = node->m_has_all_wanted_services, .m_relay_txs = node->m_relays_txs.load(), .fBloomFilter = node->m_bloom_filter_loaded.load(), .nKeyedNetGroup = node->nKeyedNetGroup, .prefer_evict = node->m_prefer_evict, .m_is_local = node->addr.IsLocal(), .m_network = node->ConnectedThroughNetwork(), .m_noban = node->HasPermission(NetPermissionFlags::NoBan), .m_conn_type = node->m_conn_type, }; vEvictionCandidates.push_back(candidate); } } const std::optional<NodeId> node_id_to_evict = SelectNodeToEvict(std::move(vEvictionCandidates)); if (!node_id_to_evict) { return false; } LOCK(m_nodes_mutex); for (CNode* pnode : m_nodes) { if (pnode->GetId() == *node_id_to_evict) { LogPrint(BCLog::NET, "selected %s connection for eviction peer=%d; disconnecting\n", pnode->ConnectionTypeAsString(), pnode->GetId()); pnode->fDisconnect = true; return true; } } return false; } void CConnman::AcceptConnection(const ListenSocket& hListenSocket) { struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); auto sock = hListenSocket.sock->Accept((struct sockaddr*)&sockaddr, &len); CAddress addr; if (!sock) { const int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) { LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr)); } return; } if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) { LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "Unknown socket family\n"); } else { addr = CAddress{MaybeFlipIPv6toCJDNS(addr), NODE_NONE}; } const CAddress addr_bind{MaybeFlipIPv6toCJDNS(GetBindAddress(*sock)), NODE_NONE}; NetPermissionFlags permission_flags = NetPermissionFlags::None; hListenSocket.AddSocketPermissionFlags(permission_flags); CreateNodeFromAcceptedSocket(std::move(sock), permission_flags, addr_bind, addr); } void CConnman::CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock, NetPermissionFlags permission_flags, const CAddress& addr_bind, const CAddress& addr) { int nInbound = 0; AddWhitelistPermissionFlags(permission_flags, addr); if (NetPermissions::HasFlag(permission_flags, NetPermissionFlags::Implicit)) { NetPermissions::ClearFlag(permission_flags, NetPermissionFlags::Implicit); if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) NetPermissions::AddFlag(permission_flags, NetPermissionFlags::ForceRelay); if (gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)) NetPermissions::AddFlag(permission_flags, NetPermissionFlags::Relay); NetPermissions::AddFlag(permission_flags, NetPermissionFlags::Mempool); NetPermissions::AddFlag(permission_flags, NetPermissionFlags::NoBan); } { LOCK(m_nodes_mutex); for (const CNode* pnode : m_nodes) { if (pnode->IsInboundConn()) nInbound++; } } if (!fNetworkActive) { LogPrint(BCLog::NET, "connection from %s dropped: not accepting new connections\n", addr.ToStringAddrPort()); return; } if (!sock->IsSelectable()) { LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToStringAddrPort()); return; } // According to the internet TCP_NODELAY is not carried into accepted sockets // on all platforms. Set it again here just to be sure. const int on{1}; if (sock->SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) == SOCKET_ERROR) { LogPrint(BCLog::NET, "connection from %s: unable to set TCP_NODELAY, continuing anyway\n", addr.ToStringAddrPort()); } // Don't accept connections from banned peers. bool banned = m_banman && m_banman->IsBanned(addr); if (!NetPermissions::HasFlag(permission_flags, NetPermissionFlags::NoBan) && banned) { LogPrint(BCLog::NET, "connection from %s dropped (banned)\n", addr.ToStringAddrPort()); return; } // Only accept connections from discouraged peers if our inbound slots aren't (almost) full. bool discouraged = m_banman && m_banman->IsDiscouraged(addr); if (!NetPermissions::HasFlag(permission_flags, NetPermissionFlags::NoBan) && nInbound + 1 >= m_max_inbound && discouraged) { LogPrint(BCLog::NET, "connection from %s dropped (discouraged)\n", addr.ToStringAddrPort()); return; } if (nInbound >= m_max_inbound) { if (!AttemptToEvictConnection()) { // No connection to evict, disconnect the new connection LogPrint(BCLog::NET, "failed to find an eviction candidate - connection dropped (full)\n"); return; } } NodeId id = GetNewNodeId(); uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize(); ServiceFlags nodeServices = nLocalServices; if (NetPermissions::HasFlag(permission_flags, NetPermissionFlags::BloomFilter)) { nodeServices = static_cast<ServiceFlags>(nodeServices | NODE_BLOOM); } const bool inbound_onion = std::find(m_onion_binds.begin(), m_onion_binds.end(), addr_bind) != m_onion_binds.end(); // The V2Transport transparently falls back to V1 behavior when an incoming V1 connection is // detected, so use it whenever we signal NODE_P2P_V2. const bool use_v2transport(nodeServices & NODE_P2P_V2); CNode* pnode = new CNode(id, std::move(sock), addr, CalculateKeyedNetGroup(addr), nonce, addr_bind, /*addrNameIn=*/"", ConnectionType::INBOUND, inbound_onion, CNodeOptions{ .permission_flags = permission_flags, .prefer_evict = discouraged, .recv_flood_size = nReceiveFloodSize, .use_v2transport = use_v2transport, }); pnode->AddRef(); m_msgproc->InitializeNode(*pnode, nodeServices); LogPrint(BCLog::NET, "connection from %s accepted\n", addr.ToStringAddrPort()); { LOCK(m_nodes_mutex); m_nodes.push_back(pnode); } // We received a new connection, harvest entropy from the time (and our peer count) RandAddEvent((uint32_t)id); } bool CConnman::AddConnection(const std::string& address, ConnectionType conn_type) { AssertLockNotHeld(m_unused_i2p_sessions_mutex); std::optional<int> max_connections; switch (conn_type) { case ConnectionType::INBOUND: case ConnectionType::MANUAL: return false; case ConnectionType::OUTBOUND_FULL_RELAY: max_connections = m_max_outbound_full_relay; break; case ConnectionType::BLOCK_RELAY: max_connections = m_max_outbound_block_relay; break; // no limit for ADDR_FETCH because -seednode has no limit either case ConnectionType::ADDR_FETCH: break; // no limit for FEELER connections since they're short-lived case ConnectionType::FEELER: break; } // no default case, so the compiler can warn about missing cases // Count existing connections int existing_connections = WITH_LOCK(m_nodes_mutex, return std::count_if(m_nodes.begin(), m_nodes.end(), [conn_type](CNode* node) { return node->m_conn_type == conn_type; });); // Max connections of specified type already exist if (max_connections != std::nullopt && existing_connections >= max_connections) return false; // Max total outbound connections already exist CSemaphoreGrant grant(*semOutbound, true); if (!grant) return false; OpenNetworkConnection(CAddress(), false, std::move(grant), address.c_str(), conn_type, /*use_v2transport=*/false); return true; } void CConnman::DisconnectNodes() { AssertLockNotHeld(m_nodes_mutex); AssertLockNotHeld(m_reconnections_mutex); // Use a temporary variable to accumulate desired reconnections, so we don't need // m_reconnections_mutex while holding m_nodes_mutex. decltype(m_reconnections) reconnections_to_add; { LOCK(m_nodes_mutex); if (!fNetworkActive) { // Disconnect any connected nodes for (CNode* pnode : m_nodes) { if (!pnode->fDisconnect) { LogPrint(BCLog::NET, "Network not active, dropping peer=%d\n", pnode->GetId()); pnode->fDisconnect = true; } } } // Disconnect unused nodes std::vector<CNode*> nodes_copy = m_nodes; for (CNode* pnode : nodes_copy) { if (pnode->fDisconnect) { // remove from m_nodes m_nodes.erase(remove(m_nodes.begin(), m_nodes.end(), pnode), m_nodes.end()); // Add to reconnection list if appropriate. We don't reconnect right here, because // the creation of a connection is a blocking operation (up to several seconds), // and we don't want to hold up the socket handler thread for that long. if (pnode->m_transport->ShouldReconnectV1()) { reconnections_to_add.push_back({ .addr_connect = pnode->addr, .grant = std::move(pnode->grantOutbound), .destination = pnode->m_dest, .conn_type = pnode->m_conn_type, .use_v2transport = false}); LogPrint(BCLog::NET, "retrying with v1 transport protocol for peer=%d\n", pnode->GetId()); } // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); // update connection count by network if (pnode->IsManualOrFullOutboundConn()) --m_network_conn_counts[pnode->addr.GetNetwork()]; // hold in disconnected pool until all refs are released pnode->Release(); m_nodes_disconnected.push_back(pnode); } } } { // Delete disconnected nodes std::list<CNode*> nodes_disconnected_copy = m_nodes_disconnected; for (CNode* pnode : nodes_disconnected_copy) { // Destroy the object only after other threads have stopped using it. if (pnode->GetRefCount() <= 0) { m_nodes_disconnected.remove(pnode); DeleteNode(pnode); } } } { // Move entries from reconnections_to_add to m_reconnections. LOCK(m_reconnections_mutex); m_reconnections.splice(m_reconnections.end(), std::move(reconnections_to_add)); } } void CConnman::NotifyNumConnectionsChanged() { size_t nodes_size; { LOCK(m_nodes_mutex); nodes_size = m_nodes.size(); } if(nodes_size != nPrevNodeCount) { nPrevNodeCount = nodes_size; if (m_client_interface) { m_client_interface->NotifyNumConnectionsChanged(nodes_size); } } } bool CConnman::ShouldRunInactivityChecks(const CNode& node, std::chrono::seconds now) const { return node.m_connected + m_peer_connect_timeout < now; } bool CConnman::InactivityCheck(const CNode& node) const { // Tests that see disconnects after using mocktime can start nodes with a // large timeout. For example, -peertimeout=999999999. const auto now{GetTime<std::chrono::seconds>()}; const auto last_send{node.m_last_send.load()}; const auto last_recv{node.m_last_recv.load()}; if (!ShouldRunInactivityChecks(node, now)) return false; if (last_recv.count() == 0 || last_send.count() == 0) { LogPrint(BCLog::NET, "socket no message in first %i seconds, %d %d peer=%d\n", count_seconds(m_peer_connect_timeout), last_recv.count() != 0, last_send.count() != 0, node.GetId()); return true; } if (now > last_send + TIMEOUT_INTERVAL) { LogPrint(BCLog::NET, "socket sending timeout: %is peer=%d\n", count_seconds(now - last_send), node.GetId()); return true; } if (now > last_recv + TIMEOUT_INTERVAL) { LogPrint(BCLog::NET, "socket receive timeout: %is peer=%d\n", count_seconds(now - last_recv), node.GetId()); return true; } if (!node.fSuccessfullyConnected) { LogPrint(BCLog::NET, "version handshake timeout peer=%d\n", node.GetId()); return true; } return false; } Sock::EventsPerSock CConnman::GenerateWaitSockets(Span<CNode* const> nodes) { Sock::EventsPerSock events_per_sock; for (const ListenSocket& hListenSocket : vhListenSocket) { events_per_sock.emplace(hListenSocket.sock, Sock::Events{Sock::RECV}); } for (CNode* pnode : nodes) { bool select_recv = !pnode->fPauseRecv; bool select_send; { LOCK(pnode->cs_vSend); // Sending is possible if either there are bytes to send right now, or if there will be // once a potential message from vSendMsg is handed to the transport. GetBytesToSend // determines both of these in a single call. const auto& [to_send, more, _msg_type] = pnode->m_transport->GetBytesToSend(!pnode->vSendMsg.empty()); select_send = !to_send.empty() || more; } if (!select_recv && !select_send) continue; LOCK(pnode->m_sock_mutex); if (pnode->m_sock) { Sock::Event event = (select_send ? Sock::SEND : 0) | (select_recv ? Sock::RECV : 0); events_per_sock.emplace(pnode->m_sock, Sock::Events{event}); } } return events_per_sock; } void CConnman::SocketHandler() { AssertLockNotHeld(m_total_bytes_sent_mutex); Sock::EventsPerSock events_per_sock; { const NodesSnapshot snap{*this, /*shuffle=*/false}; const auto timeout = std::chrono::milliseconds(SELECT_TIMEOUT_MILLISECONDS); // Check for the readiness of the already connected sockets and the // listening sockets in one call ("readiness" as in poll(2) or // select(2)). If none are ready, wait for a short while and return // empty sets. events_per_sock = GenerateWaitSockets(snap.Nodes()); if (events_per_sock.empty() || !events_per_sock.begin()->first->WaitMany(timeout, events_per_sock)) { interruptNet.sleep_for(timeout); } // Service (send/receive) each of the already connected nodes. SocketHandlerConnected(snap.Nodes(), events_per_sock); } // Accept new connections from listening sockets. SocketHandlerListening(events_per_sock); } void CConnman::SocketHandlerConnected(const std::vector<CNode*>& nodes, const Sock::EventsPerSock& events_per_sock) { AssertLockNotHeld(m_total_bytes_sent_mutex); for (CNode* pnode : nodes) { if (interruptNet) return; // // Receive // bool recvSet = false; bool sendSet = false; bool errorSet = false; { LOCK(pnode->m_sock_mutex); if (!pnode->m_sock) { continue; } const auto it = events_per_sock.find(pnode->m_sock); if (it != events_per_sock.end()) { recvSet = it->second.occurred & Sock::RECV; sendSet = it->second.occurred & Sock::SEND; errorSet = it->second.occurred & Sock::ERR; } } if (sendSet) { // Send data auto [bytes_sent, data_left] = WITH_LOCK(pnode->cs_vSend, return SocketSendData(*pnode)); if (bytes_sent) { RecordBytesSent(bytes_sent); // If both receiving and (non-optimistic) sending were possible, we first attempt // sending. If that succeeds, but does not fully drain the send queue, do not // attempt to receive. This avoids needlessly queueing data if the remote peer // is slow at receiving data, by means of TCP flow control. We only do this when // sending actually succeeded to make sure progress is always made; otherwise a // deadlock would be possible when both sides have data to send, but neither is // receiving. if (data_left) recvSet = false; } } if (recvSet || errorSet) { // typical socket buffer is 8K-64K uint8_t pchBuf[0x10000]; int nBytes = 0; { LOCK(pnode->m_sock_mutex); if (!pnode->m_sock) { continue; } nBytes = pnode->m_sock->Recv(pchBuf, sizeof(pchBuf), MSG_DONTWAIT); } if (nBytes > 0) { bool notify = false; if (!pnode->ReceiveMsgBytes({pchBuf, (size_t)nBytes}, notify)) { pnode->CloseSocketDisconnect(); } RecordBytesRecv(nBytes); if (notify) { pnode->MarkReceivedMsgsForProcessing(); WakeMessageHandler(); } } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) { LogPrint(BCLog::NET, "socket closed for peer=%d\n", pnode->GetId()); } pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) { LogPrint(BCLog::NET, "socket recv error for peer=%d: %s\n", pnode->GetId(), NetworkErrorString(nErr)); } pnode->CloseSocketDisconnect(); } } } if (InactivityCheck(*pnode)) pnode->fDisconnect = true; } } void CConnman::SocketHandlerListening(const Sock::EventsPerSock& events_per_sock) { for (const ListenSocket& listen_socket : vhListenSocket) { if (interruptNet) { return; } const auto it = events_per_sock.find(listen_socket.sock); if (it != events_per_sock.end() && it->second.occurred & Sock::RECV) { AcceptConnection(listen_socket); } } } void CConnman::ThreadSocketHandler() { AssertLockNotHeld(m_total_bytes_sent_mutex); while (!interruptNet) { DisconnectNodes(); NotifyNumConnectionsChanged(); SocketHandler(); } } void CConnman::WakeMessageHandler() { { LOCK(mutexMsgProc); fMsgProcWake = true; } condMsgProc.notify_one(); } void CConnman::ThreadDNSAddressSeed() { FastRandomContext rng; std::vector<std::string> seeds = m_params.DNSSeeds(); Shuffle(seeds.begin(), seeds.end(), rng); int seeds_right_now = 0; // Number of seeds left before testing if we have enough connections int found = 0; if (gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED)) { // When -forcednsseed is provided, query all. seeds_right_now = seeds.size(); } else if (addrman.Size() == 0) { // If we have no known peers, query all. // This will occur on the first run, or if peers.dat has been // deleted. seeds_right_now = seeds.size(); } // goal: only query DNS seed if address need is acute // * If we have a reasonable number of peers in addrman, spend // some time trying them first. This improves user privacy by // creating fewer identifying DNS requests, reduces trust by // giving seeds less influence on the network topology, and // reduces traffic to the seeds. // * When querying DNS seeds query a few at once, this ensures // that we don't give DNS seeds the ability to eclipse nodes // that query them. // * If we continue having problems, eventually query all the // DNS seeds, and if that fails too, also try the fixed seeds. // (done in ThreadOpenConnections) const std::chrono::seconds seeds_wait_time = (addrman.Size() >= DNSSEEDS_DELAY_PEER_THRESHOLD ? DNSSEEDS_DELAY_MANY_PEERS : DNSSEEDS_DELAY_FEW_PEERS); for (const std::string& seed : seeds) { if (seeds_right_now == 0) { seeds_right_now += DNSSEEDS_TO_QUERY_AT_ONCE; if (addrman.Size() > 0) { LogPrintf("Waiting %d seconds before querying DNS seeds.\n", seeds_wait_time.count()); std::chrono::seconds to_wait = seeds_wait_time; while (to_wait.count() > 0) { // if sleeping for the MANY_PEERS interval, wake up // early to see if we have enough peers and can stop // this thread entirely freeing up its resources std::chrono::seconds w = std::min(DNSSEEDS_DELAY_FEW_PEERS, to_wait); if (!interruptNet.sleep_for(w)) return; to_wait -= w; int nRelevant = 0; { LOCK(m_nodes_mutex); for (const CNode* pnode : m_nodes) { if (pnode->fSuccessfullyConnected && pnode->IsFullOutboundConn()) ++nRelevant; } } if (nRelevant >= 2) { if (found > 0) { LogPrintf("%d addresses found from DNS seeds\n", found); LogPrintf("P2P peers available. Finished DNS seeding.\n"); } else { LogPrintf("P2P peers available. Skipped DNS seeding.\n"); } return; } } } } if (interruptNet) return; // hold off on querying seeds if P2P network deactivated if (!fNetworkActive) { LogPrintf("Waiting for network to be reactivated before querying DNS seeds.\n"); do { if (!interruptNet.sleep_for(std::chrono::seconds{1})) return; } while (!fNetworkActive); } LogPrintf("Loading addresses from DNS seed %s\n", seed); // If -proxy is in use, we make an ADDR_FETCH connection to the DNS resolved peer address // for the base dns seed domain in chainparams if (HaveNameProxy()) { AddAddrFetch(seed); } else { std::vector<CAddress> vAdd; ServiceFlags requiredServiceBits = GetDesirableServiceFlags(NODE_NONE); std::string host = strprintf("x%x.%s", requiredServiceBits, seed); CNetAddr resolveSource; if (!resolveSource.SetInternal(host)) { continue; } unsigned int nMaxIPs = 256; // Limits number of IPs learned from a DNS seed const auto addresses{LookupHost(host, nMaxIPs, true)}; if (!addresses.empty()) { for (const CNetAddr& ip : addresses) { CAddress addr = CAddress(CService(ip, m_params.GetDefaultPort()), requiredServiceBits); addr.nTime = rng.rand_uniform_delay(Now<NodeSeconds>() - 3 * 24h, -4 * 24h); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } addrman.Add(vAdd, resolveSource); } else { // If the seed does not support a subdomain with our desired service bits, // we make an ADDR_FETCH connection to the DNS resolved peer address for the // base dns seed domain in chainparams AddAddrFetch(seed); } } --seeds_right_now; } LogPrintf("%d addresses found from DNS seeds\n", found); } void CConnman::DumpAddresses() { const auto start{SteadyClock::now()}; DumpPeerAddresses(::gArgs, addrman); LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n", addrman.Size(), Ticks<std::chrono::milliseconds>(SteadyClock::now() - start)); } void CConnman::ProcessAddrFetch() { AssertLockNotHeld(m_unused_i2p_sessions_mutex); std::string strDest; { LOCK(m_addr_fetches_mutex); if (m_addr_fetches.empty()) return; strDest = m_addr_fetches.front(); m_addr_fetches.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, /*fTry=*/true); if (grant) { OpenNetworkConnection(addr, false, std::move(grant), strDest.c_str(), ConnectionType::ADDR_FETCH, /*use_v2transport=*/false); } } bool CConnman::GetTryNewOutboundPeer() const { return m_try_another_outbound_peer; } void CConnman::SetTryNewOutboundPeer(bool flag) { m_try_another_outbound_peer = flag; LogPrint(BCLog::NET, "setting try another outbound peer=%s\n", flag ? "true" : "false"); } void CConnman::StartExtraBlockRelayPeers() { LogPrint(BCLog::NET, "enabling extra block-relay-only peers\n"); m_start_extra_block_relay_peers = true; } // Return the number of peers we have over our outbound connection limit // Exclude peers that are marked for disconnect, or are going to be // disconnected soon (eg ADDR_FETCH and FEELER) // Also exclude peers that haven't finished initial connection handshake yet // (so that we don't decide we're over our desired connection limit, and then // evict some peer that has finished the handshake) int CConnman::GetExtraFullOutboundCount() const { int full_outbound_peers = 0; { LOCK(m_nodes_mutex); for (const CNode* pnode : m_nodes) { if (pnode->fSuccessfullyConnected && !pnode->fDisconnect && pnode->IsFullOutboundConn()) { ++full_outbound_peers; } } } return std::max(full_outbound_peers - m_max_outbound_full_relay, 0); } int CConnman::GetExtraBlockRelayCount() const { int block_relay_peers = 0; { LOCK(m_nodes_mutex); for (const CNode* pnode : m_nodes) { if (pnode->fSuccessfullyConnected && !pnode->fDisconnect && pnode->IsBlockOnlyConn()) { ++block_relay_peers; } } } return std::max(block_relay_peers - m_max_outbound_block_relay, 0); } std::unordered_set<Network> CConnman::GetReachableEmptyNetworks() const { std::unordered_set<Network> networks{}; for (int n = 0; n < NET_MAX; n++) { enum Network net = (enum Network)n; if (net == NET_UNROUTABLE || net == NET_INTERNAL) continue; if (g_reachable_nets.Contains(net) && addrman.Size(net, std::nullopt) == 0) { networks.insert(net); } } return networks; } bool CConnman::MultipleManualOrFullOutboundConns(Network net) const { AssertLockHeld(m_nodes_mutex); return m_network_conn_counts[net] > 1; } bool CConnman::MaybePickPreferredNetwork(std::optional<Network>& network) { std::array<Network, 5> nets{NET_IPV4, NET_IPV6, NET_ONION, NET_I2P, NET_CJDNS}; Shuffle(nets.begin(), nets.end(), FastRandomContext()); LOCK(m_nodes_mutex); for (const auto net : nets) { if (g_reachable_nets.Contains(net) && m_network_conn_counts[net] == 0 && addrman.Size(net) != 0) { network = net; return true; } } return false; } void CConnman::ThreadOpenConnections(const std::vector<std::string> connect) { AssertLockNotHeld(m_unused_i2p_sessions_mutex); AssertLockNotHeld(m_reconnections_mutex); FastRandomContext rng; // Connect to specific addresses if (!connect.empty()) { for (int64_t nLoop = 0;; nLoop++) { for (const std::string& strAddr : connect) { CAddress addr(CService(), NODE_NONE); OpenNetworkConnection(addr, false, {}, strAddr.c_str(), ConnectionType::MANUAL, /*use_v2transport=*/false); for (int i = 0; i < 10 && i < nLoop; i++) { if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) return; } } if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) return; } } // Initiate network connections auto start = GetTime<std::chrono::microseconds>(); // Minimum time before next feeler connection (in microseconds). auto next_feeler = GetExponentialRand(start, FEELER_INTERVAL); auto next_extra_block_relay = GetExponentialRand(start, EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL); auto next_extra_network_peer{GetExponentialRand(start, EXTRA_NETWORK_PEER_INTERVAL)}; const bool dnsseed = gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED); bool add_fixed_seeds = gArgs.GetBoolArg("-fixedseeds", DEFAULT_FIXEDSEEDS); const bool use_seednodes{gArgs.IsArgSet("-seednode")}; if (!add_fixed_seeds) { LogPrintf("Fixed seeds are disabled\n"); } while (!interruptNet) { ProcessAddrFetch(); if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) return; PerformReconnections(); CSemaphoreGrant grant(*semOutbound); if (interruptNet) return; const std::unordered_set<Network> fixed_seed_networks{GetReachableEmptyNetworks()}; if (add_fixed_seeds && !fixed_seed_networks.empty()) { // When the node starts with an empty peers.dat, there are a few other sources of peers before // we fallback on to fixed seeds: -dnsseed, -seednode, -addnode // If none of those are available, we fallback on to fixed seeds immediately, else we allow // 60 seconds for any of those sources to populate addrman. bool add_fixed_seeds_now = false; // It is cheapest to check if enough time has passed first. if (GetTime<std::chrono::seconds>() > start + std::chrono::minutes{1}) { add_fixed_seeds_now = true; LogPrintf("Adding fixed seeds as 60 seconds have passed and addrman is empty for at least one reachable network\n"); } // Perform cheap checks before locking a mutex. else if (!dnsseed && !use_seednodes) { LOCK(m_added_nodes_mutex); if (m_added_node_params.empty()) { add_fixed_seeds_now = true; LogPrintf("Adding fixed seeds as -dnsseed=0 (or IPv4/IPv6 connections are disabled via -onlynet) and neither -addnode nor -seednode are provided\n"); } } if (add_fixed_seeds_now) { std::vector<CAddress> seed_addrs{ConvertSeeds(m_params.FixedSeeds())}; // We will not make outgoing connections to peers that are unreachable // (e.g. because of -onlynet configuration). // Therefore, we do not add them to addrman in the first place. // In case previously unreachable networks become reachable // (e.g. in case of -onlynet changes by the user), fixed seeds will // be loaded only for networks for which we have no addresses. seed_addrs.erase(std::remove_if(seed_addrs.begin(), seed_addrs.end(), [&fixed_seed_networks](const CAddress& addr) { return fixed_seed_networks.count(addr.GetNetwork()) == 0; }), seed_addrs.end()); CNetAddr local; local.SetInternal("fixedseeds"); addrman.Add(seed_addrs, local); add_fixed_seeds = false; LogPrintf("Added %d fixed seeds from reachable networks.\n", seed_addrs.size()); } } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per ipv4/ipv6 network group (/16 for IPv4). int nOutboundFullRelay = 0; int nOutboundBlockRelay = 0; int outbound_privacy_network_peers = 0; std::set<std::vector<unsigned char>> outbound_ipv46_peer_netgroups; { LOCK(m_nodes_mutex); for (const CNode* pnode : m_nodes) { if (pnode->IsFullOutboundConn()) nOutboundFullRelay++; if (pnode->IsBlockOnlyConn()) nOutboundBlockRelay++; // Make sure our persistent outbound slots to ipv4/ipv6 peers belong to different netgroups. switch (pnode->m_conn_type) { // We currently don't take inbound connections into account. Since they are // free to make, an attacker could make them to prevent us from connecting to // certain peers. case ConnectionType::INBOUND: // Short-lived outbound connections should not affect how we select outbound // peers from addrman. case ConnectionType::ADDR_FETCH: case ConnectionType::FEELER: break; case ConnectionType::MANUAL: case ConnectionType::OUTBOUND_FULL_RELAY: case ConnectionType::BLOCK_RELAY: const CAddress address{pnode->addr}; if (address.IsTor() || address.IsI2P() || address.IsCJDNS()) { // Since our addrman-groups for these networks are // random, without relation to the route we // take to connect to these peers or to the // difficulty in obtaining addresses with diverse // groups, we don't worry about diversity with // respect to our addrman groups when connecting to // these networks. ++outbound_privacy_network_peers; } else { outbound_ipv46_peer_netgroups.insert(m_netgroupman.GetGroup(address)); } } // no default case, so the compiler can warn about missing cases } } ConnectionType conn_type = ConnectionType::OUTBOUND_FULL_RELAY; auto now = GetTime<std::chrono::microseconds>(); bool anchor = false; bool fFeeler = false; std::optional<Network> preferred_net; // Determine what type of connection to open. Opening // BLOCK_RELAY connections to addresses from anchors.dat gets the highest // priority. Then we open OUTBOUND_FULL_RELAY priority until we // meet our full-relay capacity. Then we open BLOCK_RELAY connection // until we hit our block-relay-only peer limit. // GetTryNewOutboundPeer() gets set when a stale tip is detected, so we // try opening an additional OUTBOUND_FULL_RELAY connection. If none of // these conditions are met, check to see if it's time to try an extra // block-relay-only peer (to confirm our tip is current, see below) or the next_feeler // timer to decide if we should open a FEELER. if (!m_anchors.empty() && (nOutboundBlockRelay < m_max_outbound_block_relay)) { conn_type = ConnectionType::BLOCK_RELAY; anchor = true; } else if (nOutboundFullRelay < m_max_outbound_full_relay) { // OUTBOUND_FULL_RELAY } else if (nOutboundBlockRelay < m_max_outbound_block_relay) { conn_type = ConnectionType::BLOCK_RELAY; } else if (GetTryNewOutboundPeer()) { // OUTBOUND_FULL_RELAY } else if (now > next_extra_block_relay && m_start_extra_block_relay_peers) { // Periodically connect to a peer (using regular outbound selection // methodology from addrman) and stay connected long enough to sync // headers, but not much else. // // Then disconnect the peer, if we haven't learned anything new. // // The idea is to make eclipse attacks very difficult to pull off, // because every few minutes we're finding a new peer to learn headers // from. // // This is similar to the logic for trying extra outbound (full-relay) // peers, except: // - we do this all the time on an exponential timer, rather than just when // our tip is stale // - we potentially disconnect our next-youngest block-relay-only peer, if our // newest block-relay-only peer delivers a block more recently. // See the eviction logic in net_processing.cpp. // // Because we can promote these connections to block-relay-only // connections, they do not get their own ConnectionType enum // (similar to how we deal with extra outbound peers). next_extra_block_relay = GetExponentialRand(now, EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL); conn_type = ConnectionType::BLOCK_RELAY; } else if (now > next_feeler) { next_feeler = GetExponentialRand(now, FEELER_INTERVAL); conn_type = ConnectionType::FEELER; fFeeler = true; } else if (nOutboundFullRelay == m_max_outbound_full_relay && m_max_outbound_full_relay == MAX_OUTBOUND_FULL_RELAY_CONNECTIONS && now > next_extra_network_peer && MaybePickPreferredNetwork(preferred_net)) { // Full outbound connection management: Attempt to get at least one // outbound peer from each reachable network by making extra connections // and then protecting "only" peers from a network during outbound eviction. // This is not attempted if the user changed -maxconnections to a value // so low that less than MAX_OUTBOUND_FULL_RELAY_CONNECTIONS are made, // to prevent interactions with otherwise protected outbound peers. next_extra_network_peer = GetExponentialRand(now, EXTRA_NETWORK_PEER_INTERVAL); } else { // skip to next iteration of while loop continue; } addrman.ResolveCollisions(); const auto current_time{NodeClock::now()}; int nTries = 0; while (!interruptNet) { if (anchor && !m_anchors.empty()) { const CAddress addr = m_anchors.back(); m_anchors.pop_back(); if (!addr.IsValid() || IsLocal(addr) || !g_reachable_nets.Contains(addr) || !HasAllDesirableServiceFlags(addr.nServices) || outbound_ipv46_peer_netgroups.count(m_netgroupman.GetGroup(addr))) continue; addrConnect = addr; LogPrint(BCLog::NET, "Trying to make an anchor connection to %s\n", addrConnect.ToStringAddrPort()); break; } // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; CAddress addr; NodeSeconds addr_last_try{0s}; if (fFeeler) { // First, try to get a tried table collision address. This returns // an empty (invalid) address if there are no collisions to try. std::tie(addr, addr_last_try) = addrman.SelectTriedCollision(); if (!addr.IsValid()) { // No tried table collisions. Select a new table address // for our feeler. std::tie(addr, addr_last_try) = addrman.Select(true); } else if (AlreadyConnectedToAddress(addr)) { // If test-before-evict logic would have us connect to a // peer that we're already connected to, just mark that // address as Good(). We won't be able to initiate the // connection anyway, so this avoids inadvertently evicting // a currently-connected peer. addrman.Good(addr); // Select a new table address for our feeler instead. std::tie(addr, addr_last_try) = addrman.Select(true); } } else { // Not a feeler // If preferred_net has a value set, pick an extra outbound // peer from that network. The eviction logic in net_processing // ensures that a peer from another network will be evicted. std::tie(addr, addr_last_try) = addrman.Select(false, preferred_net); } // Require outbound IPv4/IPv6 connections, other than feelers, to be to distinct network groups if (!fFeeler && outbound_ipv46_peer_netgroups.count(m_netgroupman.GetGroup(addr))) { continue; } // if we selected an invalid or local address, restart if (!addr.IsValid() || IsLocal(addr)) { break; } if (!g_reachable_nets.Contains(addr)) { continue; } // only consider very recently tried nodes after 30 failed attempts if (current_time - addr_last_try < 10min && nTries < 30) { continue; } // for non-feelers, require all the services we'll want, // for feelers, only require they be a full node (only because most // SPV clients don't have a good address DB available) if (!fFeeler && !HasAllDesirableServiceFlags(addr.nServices)) { continue; } else if (fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) { continue; } // Do not connect to bad ports, unless 50 invalid addresses have been selected already. if (nTries < 50 && (addr.IsIPv4() || addr.IsIPv6()) && IsBadPort(addr.GetPort())) { continue; } // Do not make automatic outbound connections to addnode peers, to // not use our limited outbound slots for them and to ensure // addnode connections benefit from their intended protections. if (AddedNodesContain(addr)) { LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "Not making automatic %s%s connection to %s peer selected for manual (addnode) connection%s\n", preferred_net.has_value() ? "network-specific " : "", ConnectionTypeAsString(conn_type), GetNetworkName(addr.GetNetwork()), fLogIPs ? strprintf(": %s", addr.ToStringAddrPort()) : ""); continue; } addrConnect = addr; break; } if (addrConnect.IsValid()) { if (fFeeler) { // Add small amount of random noise before connection to avoid synchronization. if (!interruptNet.sleep_for(rng.rand_uniform_duration<CThreadInterrupt::Clock>(FEELER_SLEEP_WINDOW))) { return; } LogPrint(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToStringAddrPort()); } if (preferred_net != std::nullopt) LogPrint(BCLog::NET, "Making network specific connection to %s on %s.\n", addrConnect.ToStringAddrPort(), GetNetworkName(preferred_net.value())); // Record addrman failure attempts when node has at least 2 persistent outbound connections to peers with // different netgroups in ipv4/ipv6 networks + all peers in Tor/I2P/CJDNS networks. // Don't record addrman failure attempts when node is offline. This can be identified since all local // network connections (if any) belong in the same netgroup, and the size of `outbound_ipv46_peer_netgroups` would only be 1. const bool count_failures{((int)outbound_ipv46_peer_netgroups.size() + outbound_privacy_network_peers) >= std::min(m_max_automatic_connections - 1, 2)}; // Use BIP324 transport when both us and them have NODE_V2_P2P set. const bool use_v2transport(addrConnect.nServices & GetLocalServices() & NODE_P2P_V2); OpenNetworkConnection(addrConnect, count_failures, std::move(grant), /*strDest=*/nullptr, conn_type, use_v2transport); } } } std::vector<CAddress> CConnman::GetCurrentBlockRelayOnlyConns() const { std::vector<CAddress> ret; LOCK(m_nodes_mutex); for (const CNode* pnode : m_nodes) { if (pnode->IsBlockOnlyConn()) { ret.push_back(pnode->addr); } } return ret; } std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo(bool include_connected) const { std::vector<AddedNodeInfo> ret; std::list<AddedNodeParams> lAddresses(0); { LOCK(m_added_nodes_mutex); ret.reserve(m_added_node_params.size()); std::copy(m_added_node_params.cbegin(), m_added_node_params.cend(), std::back_inserter(lAddresses)); } // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService std::map<CService, bool> mapConnected; std::map<std::string, std::pair<bool, CService>> mapConnectedByName; { LOCK(m_nodes_mutex); for (const CNode* pnode : m_nodes) { if (pnode->addr.IsValid()) { mapConnected[pnode->addr] = pnode->IsInboundConn(); } std::string addrName{pnode->m_addr_name}; if (!addrName.empty()) { mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->IsInboundConn(), static_cast<const CService&>(pnode->addr)); } } } for (const auto& addr : lAddresses) { CService service(LookupNumeric(addr.m_added_node, GetDefaultPort(addr.m_added_node))); AddedNodeInfo addedNode{addr, CService(), false, false}; if (service.IsValid()) { // strAddNode is an IP:port auto it = mapConnected.find(service); if (it != mapConnected.end()) { if (!include_connected) { continue; } addedNode.resolvedAddress = service; addedNode.fConnected = true; addedNode.fInbound = it->second; } } else { // strAddNode is a name auto it = mapConnectedByName.find(addr.m_added_node); if (it != mapConnectedByName.end()) { if (!include_connected) { continue; } addedNode.resolvedAddress = it->second.second; addedNode.fConnected = true; addedNode.fInbound = it->second.first; } } ret.emplace_back(std::move(addedNode)); } return ret; } void CConnman::ThreadOpenAddedConnections() { AssertLockNotHeld(m_unused_i2p_sessions_mutex); AssertLockNotHeld(m_reconnections_mutex); while (true) { CSemaphoreGrant grant(*semAddnode); std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo(/*include_connected=*/false); bool tried = false; for (const AddedNodeInfo& info : vInfo) { if (!grant) { // If we've used up our semaphore and need a new one, let's not wait here since while we are waiting // the addednodeinfo state might change. break; } tried = true; CAddress addr(CService(), NODE_NONE); OpenNetworkConnection(addr, false, std::move(grant), info.m_params.m_added_node.c_str(), ConnectionType::MANUAL, info.m_params.m_use_v2transport); if (!interruptNet.sleep_for(std::chrono::milliseconds(500))) return; grant = CSemaphoreGrant(*semAddnode, /*fTry=*/true); } // Retry every 60 seconds if a connection was attempted, otherwise two seconds if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2))) return; // See if any reconnections are desired. PerformReconnections(); } } // if successful, this moves the passed grant to the constructed node void CConnman::OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant&& grant_outbound, const char *pszDest, ConnectionType conn_type, bool use_v2transport) { AssertLockNotHeld(m_unused_i2p_sessions_mutex); assert(conn_type != ConnectionType::INBOUND); // // Initiate outbound network connection // if (interruptNet) { return; } if (!fNetworkActive) { return; } if (!pszDest) { bool banned_or_discouraged = m_banman && (m_banman->IsDiscouraged(addrConnect) || m_banman->IsBanned(addrConnect)); if (IsLocal(addrConnect) || banned_or_discouraged || AlreadyConnectedToAddress(addrConnect)) { return; } } else if (FindNode(std::string(pszDest))) return; CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure, conn_type, use_v2transport); if (!pnode) return; pnode->grantOutbound = std::move(grant_outbound); m_msgproc->InitializeNode(*pnode, nLocalServices); { LOCK(m_nodes_mutex); m_nodes.push_back(pnode); // update connection count by network if (pnode->IsManualOrFullOutboundConn()) ++m_network_conn_counts[pnode->addr.GetNetwork()]; } } Mutex NetEventsInterface::g_msgproc_mutex; void CConnman::ThreadMessageHandler() { LOCK(NetEventsInterface::g_msgproc_mutex); while (!flagInterruptMsgProc) { bool fMoreWork = false; { // Randomize the order in which we process messages from/to our peers. // This prevents attacks in which an attacker exploits having multiple // consecutive connections in the m_nodes list. const NodesSnapshot snap{*this, /*shuffle=*/true}; for (CNode* pnode : snap.Nodes()) { if (pnode->fDisconnect) continue; // Receive messages bool fMoreNodeWork = m_msgproc->ProcessMessages(pnode, flagInterruptMsgProc); fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend); if (flagInterruptMsgProc) return; // Send messages m_msgproc->SendMessages(pnode); if (flagInterruptMsgProc) return; } } WAIT_LOCK(mutexMsgProc, lock); if (!fMoreWork) { condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this]() EXCLUSIVE_LOCKS_REQUIRED(mutexMsgProc) { return fMsgProcWake; }); } fMsgProcWake = false; } } void CConnman::ThreadI2PAcceptIncoming() { static constexpr auto err_wait_begin = 1s; static constexpr auto err_wait_cap = 5min; auto err_wait = err_wait_begin; bool advertising_listen_addr = false; i2p::Connection conn; auto SleepOnFailure = [&]() { interruptNet.sleep_for(err_wait); if (err_wait < err_wait_cap) { err_wait += 1s; } }; while (!interruptNet) { if (!m_i2p_sam_session->Listen(conn)) { if (advertising_listen_addr && conn.me.IsValid()) { RemoveLocal(conn.me); advertising_listen_addr = false; } SleepOnFailure(); continue; } if (!advertising_listen_addr) { AddLocal(conn.me, LOCAL_MANUAL); advertising_listen_addr = true; } if (!m_i2p_sam_session->Accept(conn)) { SleepOnFailure(); continue; } CreateNodeFromAcceptedSocket(std::move(conn.sock), NetPermissionFlags::None, CAddress{conn.me, NODE_NONE}, CAddress{conn.peer, NODE_NONE}); err_wait = err_wait_begin; } } bool CConnman::BindListenPort(const CService& addrBind, bilingual_str& strError, NetPermissionFlags permissions) { int nOne = 1; // Create socket for listening for incoming connections struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf(Untranslated("Bind address family for %s not supported"), addrBind.ToStringAddrPort()); LogPrintLevel(BCLog::NET, BCLog::Level::Error, "%s\n", strError.original); return false; } std::unique_ptr<Sock> sock = CreateSock(addrBind); if (!sock) { strError = strprintf(Untranslated("Couldn't open socket for incoming connections (socket returned error %s)"), NetworkErrorString(WSAGetLastError())); LogPrintLevel(BCLog::NET, BCLog::Level::Error, "%s\n", strError.original); return false; } // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. if (sock->SetSockOpt(SOL_SOCKET, SO_REUSEADDR, (sockopt_arg_type)&nOne, sizeof(int)) == SOCKET_ERROR) { strError = strprintf(Untranslated("Error setting SO_REUSEADDR on socket: %s, continuing anyway"), NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError.original); } // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_V6ONLY, (sockopt_arg_type)&nOne, sizeof(int)) == SOCKET_ERROR) { strError = strprintf(Untranslated("Error setting IPV6_V6ONLY on socket: %s, continuing anyway"), NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError.original); } #endif #ifdef WIN32 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED; if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int)) == SOCKET_ERROR) { strError = strprintf(Untranslated("Error setting IPV6_PROTECTION_LEVEL on socket: %s, continuing anyway"), NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError.original); } #endif } if (sock->Bind(reinterpret_cast<struct sockaddr*>(&sockaddr), len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToStringAddrPort(), PACKAGE_NAME); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToStringAddrPort(), NetworkErrorString(nErr)); LogPrintLevel(BCLog::NET, BCLog::Level::Error, "%s\n", strError.original); return false; } LogPrintf("Bound to %s\n", addrBind.ToStringAddrPort()); // Listen for incoming connections if (sock->Listen(SOMAXCONN) == SOCKET_ERROR) { strError = strprintf(_("Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError())); LogPrintLevel(BCLog::NET, BCLog::Level::Error, "%s\n", strError.original); return false; } vhListenSocket.emplace_back(std::move(sock), permissions); return true; } void Discover() { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[256] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { const std::vector<CNetAddr> addresses{LookupHost(pszHostName, 0, true)}; for (const CNetAddr& addr : addresses) { if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToStringAddr()); } } #elif (HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS) // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next) { if (ifa->ifa_addr == nullptr) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToStringAddr()); } else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToStringAddr()); } } freeifaddrs(myaddrs); } #endif } void CConnman::SetNetworkActive(bool active) { LogPrintf("%s: %s\n", __func__, active); if (fNetworkActive == active) { return; } fNetworkActive = active; if (m_client_interface) { m_client_interface->NotifyNetworkActiveChanged(fNetworkActive); } } CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In, AddrMan& addrman_in, const NetGroupManager& netgroupman, const CChainParams& params, bool network_active) : addrman(addrman_in) , m_netgroupman{netgroupman} , nSeed0(nSeed0In) , nSeed1(nSeed1In) , m_params(params) { SetTryNewOutboundPeer(false); Options connOptions; Init(connOptions); SetNetworkActive(network_active); } NodeId CConnman::GetNewNodeId() { return nLastNodeId.fetch_add(1, std::memory_order_relaxed); } uint16_t CConnman::GetDefaultPort(Network net) const { return net == NET_I2P ? I2P_SAM31_PORT : m_params.GetDefaultPort(); } uint16_t CConnman::GetDefaultPort(const std::string& addr) const { CNetAddr a; return a.SetSpecial(addr) ? GetDefaultPort(a.GetNetwork()) : m_params.GetDefaultPort(); } bool CConnman::Bind(const CService& addr_, unsigned int flags, NetPermissionFlags permissions) { const CService addr{MaybeFlipIPv6toCJDNS(addr_)}; bilingual_str strError; if (!BindListenPort(addr, strError, permissions)) { if ((flags & BF_REPORT_ERROR) && m_client_interface) { m_client_interface->ThreadSafeMessageBox(strError, "", CClientUIInterface::MSG_ERROR); } return false; } if (addr.IsRoutable() && fDiscover && !(flags & BF_DONT_ADVERTISE) && !NetPermissions::HasFlag(permissions, NetPermissionFlags::NoBan)) { AddLocal(addr, LOCAL_BIND); } return true; } bool CConnman::InitBinds(const Options& options) { bool fBound = false; for (const auto& addrBind : options.vBinds) { fBound |= Bind(addrBind, BF_REPORT_ERROR, NetPermissionFlags::None); } for (const auto& addrBind : options.vWhiteBinds) { fBound |= Bind(addrBind.m_service, BF_REPORT_ERROR, addrBind.m_flags); } for (const auto& addr_bind : options.onion_binds) { fBound |= Bind(addr_bind, BF_DONT_ADVERTISE, NetPermissionFlags::None); } if (options.bind_on_any) { struct in_addr inaddr_any; inaddr_any.s_addr = htonl(INADDR_ANY); struct in6_addr inaddr6_any = IN6ADDR_ANY_INIT; fBound |= Bind(CService(inaddr6_any, GetListenPort()), BF_NONE, NetPermissionFlags::None); fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE, NetPermissionFlags::None); } return fBound; } bool CConnman::Start(CScheduler& scheduler, const Options& connOptions) { AssertLockNotHeld(m_total_bytes_sent_mutex); Init(connOptions); if (fListen && !InitBinds(connOptions)) { if (m_client_interface) { m_client_interface->ThreadSafeMessageBox( _("Failed to listen on any port. Use -listen=0 if you want this."), "", CClientUIInterface::MSG_ERROR); } return false; } Proxy i2p_sam; if (GetProxy(NET_I2P, i2p_sam) && connOptions.m_i2p_accept_incoming) { m_i2p_sam_session = std::make_unique<i2p::sam::Session>(gArgs.GetDataDirNet() / "i2p_private_key", i2p_sam.proxy, &interruptNet); } for (const auto& strDest : connOptions.vSeedNodes) { AddAddrFetch(strDest); } if (m_use_addrman_outgoing) { // Load addresses from anchors.dat m_anchors = ReadAnchors(gArgs.GetDataDirNet() / ANCHORS_DATABASE_FILENAME); if (m_anchors.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) { m_anchors.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS); } LogPrintf("%i block-relay-only anchors will be tried for connections.\n", m_anchors.size()); } if (m_client_interface) { m_client_interface->InitMessage(_("Starting network threads…").translated); } fAddressesInitialized = true; if (semOutbound == nullptr) { // initialize semaphore semOutbound = std::make_unique<CSemaphore>(std::min(m_max_automatic_outbound, m_max_automatic_connections)); } if (semAddnode == nullptr) { // initialize semaphore semAddnode = std::make_unique<CSemaphore>(m_max_addnode); } // // Start threads // assert(m_msgproc); interruptNet.reset(); flagInterruptMsgProc = false; { LOCK(mutexMsgProc); fMsgProcWake = false; } // Send and receive from sockets, accept connections threadSocketHandler = std::thread(&util::TraceThread, "net", [this] { ThreadSocketHandler(); }); if (!gArgs.GetBoolArg("-dnsseed", DEFAULT_DNSSEED)) LogPrintf("DNS seeding disabled\n"); else threadDNSAddressSeed = std::thread(&util::TraceThread, "dnsseed", [this] { ThreadDNSAddressSeed(); }); // Initiate manual connections threadOpenAddedConnections = std::thread(&util::TraceThread, "addcon", [this] { ThreadOpenAddedConnections(); }); if (connOptions.m_use_addrman_outgoing && !connOptions.m_specified_outgoing.empty()) { if (m_client_interface) { m_client_interface->ThreadSafeMessageBox( _("Cannot provide specific connections and have addrman find outgoing connections at the same time."), "", CClientUIInterface::MSG_ERROR); } return false; } if (connOptions.m_use_addrman_outgoing || !connOptions.m_specified_outgoing.empty()) { threadOpenConnections = std::thread( &util::TraceThread, "opencon", [this, connect = connOptions.m_specified_outgoing] { ThreadOpenConnections(connect); }); } // Process messages threadMessageHandler = std::thread(&util::TraceThread, "msghand", [this] { ThreadMessageHandler(); }); if (m_i2p_sam_session) { threadI2PAcceptIncoming = std::thread(&util::TraceThread, "i2paccept", [this] { ThreadI2PAcceptIncoming(); }); } // Dump network addresses scheduler.scheduleEvery([this] { DumpAddresses(); }, DUMP_PEERS_INTERVAL); // Run the ASMap Health check once and then schedule it to run every 24h. if (m_netgroupman.UsingASMap()) { ASMapHealthCheck(); scheduler.scheduleEvery([this] { ASMapHealthCheck(); }, ASMAP_HEALTH_CHECK_INTERVAL); } return true; } class CNetCleanup { public: CNetCleanup() = default; ~CNetCleanup() { #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } }; static CNetCleanup instance_of_cnetcleanup; void CConnman::Interrupt() { { LOCK(mutexMsgProc); flagInterruptMsgProc = true; } condMsgProc.notify_all(); interruptNet(); g_socks5_interrupt(); if (semOutbound) { for (int i=0; i<m_max_automatic_outbound; i++) { semOutbound->post(); } } if (semAddnode) { for (int i=0; i<m_max_addnode; i++) { semAddnode->post(); } } } void CConnman::StopThreads() { if (threadI2PAcceptIncoming.joinable()) { threadI2PAcceptIncoming.join(); } if (threadMessageHandler.joinable()) threadMessageHandler.join(); if (threadOpenConnections.joinable()) threadOpenConnections.join(); if (threadOpenAddedConnections.joinable()) threadOpenAddedConnections.join(); if (threadDNSAddressSeed.joinable()) threadDNSAddressSeed.join(); if (threadSocketHandler.joinable()) threadSocketHandler.join(); } void CConnman::StopNodes() { if (fAddressesInitialized) { DumpAddresses(); fAddressesInitialized = false; if (m_use_addrman_outgoing) { // Anchor connections are only dumped during clean shutdown. std::vector<CAddress> anchors_to_dump = GetCurrentBlockRelayOnlyConns(); if (anchors_to_dump.size() > MAX_BLOCK_RELAY_ONLY_ANCHORS) { anchors_to_dump.resize(MAX_BLOCK_RELAY_ONLY_ANCHORS); } DumpAnchors(gArgs.GetDataDirNet() / ANCHORS_DATABASE_FILENAME, anchors_to_dump); } } // Delete peer connections. std::vector<CNode*> nodes; WITH_LOCK(m_nodes_mutex, nodes.swap(m_nodes)); for (CNode* pnode : nodes) { pnode->CloseSocketDisconnect(); DeleteNode(pnode); } for (CNode* pnode : m_nodes_disconnected) { DeleteNode(pnode); } m_nodes_disconnected.clear(); vhListenSocket.clear(); semOutbound.reset(); semAddnode.reset(); } void CConnman::DeleteNode(CNode* pnode) { assert(pnode); m_msgproc->FinalizeNode(*pnode); delete pnode; } CConnman::~CConnman() { Interrupt(); Stop(); } std::vector<CAddress> CConnman::GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const { std::vector<CAddress> addresses = addrman.GetAddr(max_addresses, max_pct, network, filtered); if (m_banman) { addresses.erase(std::remove_if(addresses.begin(), addresses.end(), [this](const CAddress& addr){return m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr);}), addresses.end()); } return addresses; } std::vector<CAddress> CConnman::GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct) { auto local_socket_bytes = requestor.addrBind.GetAddrBytes(); uint64_t cache_id = GetDeterministicRandomizer(RANDOMIZER_ID_ADDRCACHE) .Write(requestor.ConnectedThroughNetwork()) .Write(local_socket_bytes) // For outbound connections, the port of the bound address is randomly // assigned by the OS and would therefore not be useful for seeding. .Write(requestor.IsInboundConn() ? requestor.addrBind.GetPort() : 0) .Finalize(); const auto current_time = GetTime<std::chrono::microseconds>(); auto r = m_addr_response_caches.emplace(cache_id, CachedAddrResponse{}); CachedAddrResponse& cache_entry = r.first->second; if (cache_entry.m_cache_entry_expiration < current_time) { // If emplace() added new one it has expiration 0. cache_entry.m_addrs_response_cache = GetAddresses(max_addresses, max_pct, /*network=*/std::nullopt); // Choosing a proper cache lifetime is a trade-off between the privacy leak minimization // and the usefulness of ADDR responses to honest users. // // Longer cache lifetime makes it more difficult for an attacker to scrape // enough AddrMan data to maliciously infer something useful. // By the time an attacker scraped enough AddrMan records, most of // the records should be old enough to not leak topology info by // e.g. analyzing real-time changes in timestamps. // // It takes only several hundred requests to scrape everything from an AddrMan containing 100,000 nodes, // so ~24 hours of cache lifetime indeed makes the data less inferable by the time // most of it could be scraped (considering that timestamps are updated via // ADDR self-announcements and when nodes communicate). // We also should be robust to those attacks which may not require scraping *full* victim's AddrMan // (because even several timestamps of the same handful of nodes may leak privacy). // // On the other hand, longer cache lifetime makes ADDR responses // outdated and less useful for an honest requestor, e.g. if most nodes // in the ADDR response are no longer active. // // However, the churn in the network is known to be rather low. Since we consider // nodes to be "terrible" (see IsTerrible()) if the timestamps are older than 30 days, // max. 24 hours of "penalty" due to cache shouldn't make any meaningful difference // in terms of the freshness of the response. cache_entry.m_cache_entry_expiration = current_time + std::chrono::hours(21) + GetRandMillis(std::chrono::hours(6)); } return cache_entry.m_addrs_response_cache; } bool CConnman::AddNode(const AddedNodeParams& add) { const CService resolved(LookupNumeric(add.m_added_node, GetDefaultPort(add.m_added_node))); const bool resolved_is_valid{resolved.IsValid()}; LOCK(m_added_nodes_mutex); for (const auto& it : m_added_node_params) { if (add.m_added_node == it.m_added_node || (resolved_is_valid && resolved == LookupNumeric(it.m_added_node, GetDefaultPort(it.m_added_node)))) return false; } m_added_node_params.push_back(add); return true; } bool CConnman::RemoveAddedNode(const std::string& strNode) { LOCK(m_added_nodes_mutex); for (auto it = m_added_node_params.begin(); it != m_added_node_params.end(); ++it) { if (strNode == it->m_added_node) { m_added_node_params.erase(it); return true; } } return false; } bool CConnman::AddedNodesContain(const CAddress& addr) const { AssertLockNotHeld(m_added_nodes_mutex); const std::string addr_str{addr.ToStringAddr()}; const std::string addr_port_str{addr.ToStringAddrPort()}; LOCK(m_added_nodes_mutex); return (m_added_node_params.size() < 24 // bound the query to a reasonable limit && std::any_of(m_added_node_params.cbegin(), m_added_node_params.cend(), [&](const auto& p) { return p.m_added_node == addr_str || p.m_added_node == addr_port_str; })); } size_t CConnman::GetNodeCount(ConnectionDirection flags) const { LOCK(m_nodes_mutex); if (flags == ConnectionDirection::Both) // Shortcut if we want total return m_nodes.size(); int nNum = 0; for (const auto& pnode : m_nodes) { if (flags & (pnode->IsInboundConn() ? ConnectionDirection::In : ConnectionDirection::Out)) { nNum++; } } return nNum; } uint32_t CConnman::GetMappedAS(const CNetAddr& addr) const { return m_netgroupman.GetMappedAS(addr); } void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats) const { vstats.clear(); LOCK(m_nodes_mutex); vstats.reserve(m_nodes.size()); for (CNode* pnode : m_nodes) { vstats.emplace_back(); pnode->CopyStats(vstats.back()); vstats.back().m_mapped_as = GetMappedAS(pnode->addr); } } bool CConnman::DisconnectNode(const std::string& strNode) { LOCK(m_nodes_mutex); if (CNode* pnode = FindNode(strNode)) { LogPrint(BCLog::NET, "disconnect by address%s matched peer=%d; disconnecting\n", (fLogIPs ? strprintf("=%s", strNode) : ""), pnode->GetId()); pnode->fDisconnect = true; return true; } return false; } bool CConnman::DisconnectNode(const CSubNet& subnet) { bool disconnected = false; LOCK(m_nodes_mutex); for (CNode* pnode : m_nodes) { if (subnet.Match(pnode->addr)) { LogPrint(BCLog::NET, "disconnect by subnet%s matched peer=%d; disconnecting\n", (fLogIPs ? strprintf("=%s", subnet.ToString()) : ""), pnode->GetId()); pnode->fDisconnect = true; disconnected = true; } } return disconnected; } bool CConnman::DisconnectNode(const CNetAddr& addr) { return DisconnectNode(CSubNet(addr)); } bool CConnman::DisconnectNode(NodeId id) { LOCK(m_nodes_mutex); for(CNode* pnode : m_nodes) { if (id == pnode->GetId()) { LogPrint(BCLog::NET, "disconnect by id peer=%d; disconnecting\n", pnode->GetId()); pnode->fDisconnect = true; return true; } } return false; } void CConnman::RecordBytesRecv(uint64_t bytes) { nTotalBytesRecv += bytes; } void CConnman::RecordBytesSent(uint64_t bytes) { AssertLockNotHeld(m_total_bytes_sent_mutex); LOCK(m_total_bytes_sent_mutex); nTotalBytesSent += bytes; const auto now = GetTime<std::chrono::seconds>(); if (nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME < now) { // timeframe expired, reset cycle nMaxOutboundCycleStartTime = now; nMaxOutboundTotalBytesSentInCycle = 0; } nMaxOutboundTotalBytesSentInCycle += bytes; } uint64_t CConnman::GetMaxOutboundTarget() const { AssertLockNotHeld(m_total_bytes_sent_mutex); LOCK(m_total_bytes_sent_mutex); return nMaxOutboundLimit; } std::chrono::seconds CConnman::GetMaxOutboundTimeframe() const { return MAX_UPLOAD_TIMEFRAME; } std::chrono::seconds CConnman::GetMaxOutboundTimeLeftInCycle() const { AssertLockNotHeld(m_total_bytes_sent_mutex); LOCK(m_total_bytes_sent_mutex); return GetMaxOutboundTimeLeftInCycle_(); } std::chrono::seconds CConnman::GetMaxOutboundTimeLeftInCycle_() const { AssertLockHeld(m_total_bytes_sent_mutex); if (nMaxOutboundLimit == 0) return 0s; if (nMaxOutboundCycleStartTime.count() == 0) return MAX_UPLOAD_TIMEFRAME; const std::chrono::seconds cycleEndTime = nMaxOutboundCycleStartTime + MAX_UPLOAD_TIMEFRAME; const auto now = GetTime<std::chrono::seconds>(); return (cycleEndTime < now) ? 0s : cycleEndTime - now; } bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit) const { AssertLockNotHeld(m_total_bytes_sent_mutex); LOCK(m_total_bytes_sent_mutex); if (nMaxOutboundLimit == 0) return false; if (historicalBlockServingLimit) { // keep a large enough buffer to at least relay each block once const std::chrono::seconds timeLeftInCycle = GetMaxOutboundTimeLeftInCycle_(); const uint64_t buffer = timeLeftInCycle / std::chrono::minutes{10} * MAX_BLOCK_SERIALIZED_SIZE; if (buffer >= nMaxOutboundLimit || nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer) return true; } else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) return true; return false; } uint64_t CConnman::GetOutboundTargetBytesLeft() const { AssertLockNotHeld(m_total_bytes_sent_mutex); LOCK(m_total_bytes_sent_mutex); if (nMaxOutboundLimit == 0) return 0; return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) ? 0 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle; } uint64_t CConnman::GetTotalBytesRecv() const { return nTotalBytesRecv; } uint64_t CConnman::GetTotalBytesSent() const { AssertLockNotHeld(m_total_bytes_sent_mutex); LOCK(m_total_bytes_sent_mutex); return nTotalBytesSent; } ServiceFlags CConnman::GetLocalServices() const { return nLocalServices; } static std::unique_ptr<Transport> MakeTransport(NodeId id, bool use_v2transport, bool inbound) noexcept { if (use_v2transport) { return std::make_unique<V2Transport>(id, /*initiating=*/!inbound); } else { return std::make_unique<V1Transport>(id); } } CNode::CNode(NodeId idIn, std::shared_ptr<Sock> sock, const CAddress& addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress& addrBindIn, const std::string& addrNameIn, ConnectionType conn_type_in, bool inbound_onion, CNodeOptions&& node_opts) : m_transport{MakeTransport(idIn, node_opts.use_v2transport, conn_type_in == ConnectionType::INBOUND)}, m_permission_flags{node_opts.permission_flags}, m_sock{sock}, m_connected{GetTime<std::chrono::seconds>()}, addr{addrIn}, addrBind{addrBindIn}, m_addr_name{addrNameIn.empty() ? addr.ToStringAddrPort() : addrNameIn}, m_dest(addrNameIn), m_inbound_onion{inbound_onion}, m_prefer_evict{node_opts.prefer_evict}, nKeyedNetGroup{nKeyedNetGroupIn}, m_conn_type{conn_type_in}, id{idIn}, nLocalHostNonce{nLocalHostNonceIn}, m_recv_flood_size{node_opts.recv_flood_size}, m_i2p_sam_session{std::move(node_opts.i2p_sam_session)} { if (inbound_onion) assert(conn_type_in == ConnectionType::INBOUND); for (const std::string &msg : getAllNetMessageTypes()) mapRecvBytesPerMsgType[msg] = 0; mapRecvBytesPerMsgType[NET_MESSAGE_TYPE_OTHER] = 0; if (fLogIPs) { LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", m_addr_name, id); } else { LogPrint(BCLog::NET, "Added connection peer=%d\n", id); } } void CNode::MarkReceivedMsgsForProcessing() { AssertLockNotHeld(m_msg_process_queue_mutex); size_t nSizeAdded = 0; for (const auto& msg : vRecvMsg) { // vRecvMsg contains only completed CNetMessage // the single possible partially deserialized message are held by TransportDeserializer nSizeAdded += msg.m_raw_message_size; } LOCK(m_msg_process_queue_mutex); m_msg_process_queue.splice(m_msg_process_queue.end(), vRecvMsg); m_msg_process_queue_size += nSizeAdded; fPauseRecv = m_msg_process_queue_size > m_recv_flood_size; } std::optional<std::pair<CNetMessage, bool>> CNode::PollMessage() { LOCK(m_msg_process_queue_mutex); if (m_msg_process_queue.empty()) return std::nullopt; std::list<CNetMessage> msgs; // Just take one message msgs.splice(msgs.begin(), m_msg_process_queue, m_msg_process_queue.begin()); m_msg_process_queue_size -= msgs.front().m_raw_message_size; fPauseRecv = m_msg_process_queue_size > m_recv_flood_size; return std::make_pair(std::move(msgs.front()), !m_msg_process_queue.empty()); } bool CConnman::NodeFullyConnected(const CNode* pnode) { return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect; } void CConnman::PushMessage(CNode* pnode, CSerializedNetMsg&& msg) { AssertLockNotHeld(m_total_bytes_sent_mutex); size_t nMessageSize = msg.data.size(); LogPrint(BCLog::NET, "sending %s (%d bytes) peer=%d\n", msg.m_type, nMessageSize, pnode->GetId()); if (gArgs.GetBoolArg("-capturemessages", false)) { CaptureMessage(pnode->addr, msg.m_type, msg.data, /*is_incoming=*/false); } TRACE6(net, outbound_message, pnode->GetId(), pnode->m_addr_name.c_str(), pnode->ConnectionTypeAsString().c_str(), msg.m_type.c_str(), msg.data.size(), msg.data.data() ); size_t nBytesSent = 0; { LOCK(pnode->cs_vSend); // Check if the transport still has unsent bytes, and indicate to it that we're about to // give it a message to send. const auto& [to_send, more, _msg_type] = pnode->m_transport->GetBytesToSend(/*have_next_message=*/true); const bool queue_was_empty{to_send.empty() && pnode->vSendMsg.empty()}; // Update memory usage of send buffer. pnode->m_send_memusage += msg.GetMemoryUsage(); if (pnode->m_send_memusage + pnode->m_transport->GetSendMemoryUsage() > nSendBufferMaxSize) pnode->fPauseSend = true; // Move message to vSendMsg queue. pnode->vSendMsg.push_back(std::move(msg)); // If there was nothing to send before, and there is now (predicted by the "more" value // returned by the GetBytesToSend call above), attempt "optimistic write": // because the poll/select loop may pause for SELECT_TIMEOUT_MILLISECONDS before actually // doing a send, try sending from the calling thread if the queue was empty before. // With a V1Transport, more will always be true here, because adding a message always // results in sendable bytes there, but with V2Transport this is not the case (it may // still be in the handshake). if (queue_was_empty && more) { std::tie(nBytesSent, std::ignore) = SocketSendData(*pnode); } } if (nBytesSent) RecordBytesSent(nBytesSent); } bool CConnman::ForNode(NodeId id, std::function<bool(CNode* pnode)> func) { CNode* found = nullptr; LOCK(m_nodes_mutex); for (auto&& pnode : m_nodes) { if(pnode->GetId() == id) { found = pnode; break; } } return found != nullptr && NodeFullyConnected(found) && func(found); } CSipHasher CConnman::GetDeterministicRandomizer(uint64_t id) const { return CSipHasher(nSeed0, nSeed1).Write(id); } uint64_t CConnman::CalculateKeyedNetGroup(const CAddress& address) const { std::vector<unsigned char> vchNetGroup(m_netgroupman.GetGroup(address)); return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP).Write(vchNetGroup).Finalize(); } void CConnman::PerformReconnections() { AssertLockNotHeld(m_reconnections_mutex); AssertLockNotHeld(m_unused_i2p_sessions_mutex); while (true) { // Move first element of m_reconnections to todo (avoiding an allocation inside the lock). decltype(m_reconnections) todo; { LOCK(m_reconnections_mutex); if (m_reconnections.empty()) break; todo.splice(todo.end(), m_reconnections, m_reconnections.begin()); } auto& item = *todo.begin(); OpenNetworkConnection(item.addr_connect, // We only reconnect if the first attempt to connect succeeded at // connection time, but then failed after the CNode object was // created. Since we already know connecting is possible, do not // count failure to reconnect. /*fCountFailure=*/false, std::move(item.grant), item.destination.empty() ? nullptr : item.destination.c_str(), item.conn_type, item.use_v2transport); } } void CConnman::ASMapHealthCheck() { const std::vector<CAddress> v4_addrs{GetAddresses(/*max_addresses=*/ 0, /*max_pct=*/ 0, Network::NET_IPV4, /*filtered=*/ false)}; const std::vector<CAddress> v6_addrs{GetAddresses(/*max_addresses=*/ 0, /*max_pct=*/ 0, Network::NET_IPV6, /*filtered=*/ false)}; std::vector<CNetAddr> clearnet_addrs; clearnet_addrs.reserve(v4_addrs.size() + v6_addrs.size()); std::transform(v4_addrs.begin(), v4_addrs.end(), std::back_inserter(clearnet_addrs), [](const CAddress& addr) { return static_cast<CNetAddr>(addr); }); std::transform(v6_addrs.begin(), v6_addrs.end(), std::back_inserter(clearnet_addrs), [](const CAddress& addr) { return static_cast<CNetAddr>(addr); }); m_netgroupman.ASMapHealthCheck(clearnet_addrs); } // Dump binary message to file, with timestamp. static void CaptureMessageToFile(const CAddress& addr, const std::string& msg_type, Span<const unsigned char> data, bool is_incoming) { // Note: This function captures the message at the time of processing, // not at socket receive/send time. // This ensures that the messages are always in order from an application // layer (processing) perspective. auto now = GetTime<std::chrono::microseconds>(); // Windows folder names cannot include a colon std::string clean_addr = addr.ToStringAddrPort(); std::replace(clean_addr.begin(), clean_addr.end(), ':', '_'); fs::path base_path = gArgs.GetDataDirNet() / "message_capture" / fs::u8path(clean_addr); fs::create_directories(base_path); fs::path path = base_path / (is_incoming ? "msgs_recv.dat" : "msgs_sent.dat"); AutoFile f{fsbridge::fopen(path, "ab")}; ser_writedata64(f, now.count()); f << Span{msg_type}; for (auto i = msg_type.length(); i < CMessageHeader::COMMAND_SIZE; ++i) { f << uint8_t{'\0'}; } uint32_t size = data.size(); ser_writedata32(f, size); f << data; } std::function<void(const CAddress& addr, const std::string& msg_type, Span<const unsigned char> data, bool is_incoming)> CaptureMessage = CaptureMessageToFile;
0
bitcoin
bitcoin/src/scheduler.cpp
// Copyright (c) 2015-2022 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 <scheduler.h> #include <sync.h> #include <util/time.h> #include <cassert> #include <functional> #include <utility> CScheduler::CScheduler() = default; CScheduler::~CScheduler() { assert(nThreadsServicingQueue == 0); if (stopWhenEmpty) assert(taskQueue.empty()); } void CScheduler::serviceQueue() { WAIT_LOCK(newTaskMutex, lock); ++nThreadsServicingQueue; // newTaskMutex is locked throughout this loop EXCEPT // when the thread is waiting or when the user's function // is called. while (!shouldStop()) { try { while (!shouldStop() && taskQueue.empty()) { // Wait until there is something to do. newTaskScheduled.wait(lock); } // Wait until either there is a new task, or until // the time of the first item on the queue: while (!shouldStop() && !taskQueue.empty()) { std::chrono::steady_clock::time_point timeToWaitFor = taskQueue.begin()->first; if (newTaskScheduled.wait_until(lock, timeToWaitFor) == std::cv_status::timeout) { break; // Exit loop after timeout, it means we reached the time of the event } } // If there are multiple threads, the queue can empty while we're waiting (another // thread may service the task we were waiting on). if (shouldStop() || taskQueue.empty()) continue; Function f = taskQueue.begin()->second; taskQueue.erase(taskQueue.begin()); { // Unlock before calling f, so it can reschedule itself or another task // without deadlocking: REVERSE_LOCK(lock); f(); } } catch (...) { --nThreadsServicingQueue; throw; } } --nThreadsServicingQueue; newTaskScheduled.notify_one(); } void CScheduler::schedule(CScheduler::Function f, std::chrono::steady_clock::time_point t) { { LOCK(newTaskMutex); taskQueue.insert(std::make_pair(t, f)); } newTaskScheduled.notify_one(); } void CScheduler::MockForward(std::chrono::seconds delta_seconds) { assert(delta_seconds > 0s && delta_seconds <= 1h); { LOCK(newTaskMutex); // use temp_queue to maintain updated schedule std::multimap<std::chrono::steady_clock::time_point, Function> temp_queue; for (const auto& element : taskQueue) { temp_queue.emplace_hint(temp_queue.cend(), element.first - delta_seconds, element.second); } // point taskQueue to temp_queue taskQueue = std::move(temp_queue); } // notify that the taskQueue needs to be processed newTaskScheduled.notify_one(); } static void Repeat(CScheduler& s, CScheduler::Function f, std::chrono::milliseconds delta) { f(); s.scheduleFromNow([=, &s] { Repeat(s, f, delta); }, delta); } void CScheduler::scheduleEvery(CScheduler::Function f, std::chrono::milliseconds delta) { scheduleFromNow([this, f, delta] { Repeat(*this, f, delta); }, delta); } size_t CScheduler::getQueueInfo(std::chrono::steady_clock::time_point& first, std::chrono::steady_clock::time_point& last) const { LOCK(newTaskMutex); size_t result = taskQueue.size(); if (!taskQueue.empty()) { first = taskQueue.begin()->first; last = taskQueue.rbegin()->first; } return result; } bool CScheduler::AreThreadsServicingQueue() const { LOCK(newTaskMutex); return nThreadsServicingQueue; } void SingleThreadedSchedulerClient::MaybeScheduleProcessQueue() { { LOCK(m_callbacks_mutex); // Try to avoid scheduling too many copies here, but if we // accidentally have two ProcessQueue's scheduled at once its // not a big deal. if (m_are_callbacks_running) return; if (m_callbacks_pending.empty()) return; } m_scheduler.schedule([this] { this->ProcessQueue(); }, std::chrono::steady_clock::now()); } void SingleThreadedSchedulerClient::ProcessQueue() { std::function<void()> callback; { LOCK(m_callbacks_mutex); if (m_are_callbacks_running) return; if (m_callbacks_pending.empty()) return; m_are_callbacks_running = true; callback = std::move(m_callbacks_pending.front()); m_callbacks_pending.pop_front(); } // RAII the setting of fCallbacksRunning and calling MaybeScheduleProcessQueue // to ensure both happen safely even if callback() throws. struct RAIICallbacksRunning { SingleThreadedSchedulerClient* instance; explicit RAIICallbacksRunning(SingleThreadedSchedulerClient* _instance) : instance(_instance) {} ~RAIICallbacksRunning() { { LOCK(instance->m_callbacks_mutex); instance->m_are_callbacks_running = false; } instance->MaybeScheduleProcessQueue(); } } raiicallbacksrunning(this); callback(); } void SingleThreadedSchedulerClient::AddToProcessQueue(std::function<void()> func) { { LOCK(m_callbacks_mutex); m_callbacks_pending.emplace_back(std::move(func)); } MaybeScheduleProcessQueue(); } void SingleThreadedSchedulerClient::EmptyQueue() { assert(!m_scheduler.AreThreadsServicingQueue()); bool should_continue = true; while (should_continue) { ProcessQueue(); LOCK(m_callbacks_mutex); should_continue = !m_callbacks_pending.empty(); } } size_t SingleThreadedSchedulerClient::CallbacksPending() { LOCK(m_callbacks_mutex); return m_callbacks_pending.size(); }
0
bitcoin
bitcoin/src/validationinterface.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_VALIDATIONINTERFACE_H #define BITCOIN_VALIDATIONINTERFACE_H #include <kernel/cs_main.h> #include <kernel/chain.h> #include <primitives/transaction.h> // CTransaction(Ref) #include <sync.h> #include <functional> #include <memory> class BlockValidationState; class CBlock; class CBlockIndex; struct CBlockLocator; class CValidationInterface; class CScheduler; enum class MemPoolRemovalReason; struct RemovedMempoolTransactionInfo; struct NewMempoolTransactionInfo; /** Register subscriber */ void RegisterValidationInterface(CValidationInterface* callbacks); /** Unregister subscriber. DEPRECATED. This is not safe to use when the RPC server or main message handler thread is running. */ void UnregisterValidationInterface(CValidationInterface* callbacks); /** Unregister all subscribers */ void UnregisterAllValidationInterfaces(); // Alternate registration functions that release a shared_ptr after the last // notification is sent. These are useful for race-free cleanup, since // unregistration is nonblocking and can return before the last notification is // processed. /** Register subscriber */ void RegisterSharedValidationInterface(std::shared_ptr<CValidationInterface> callbacks); /** Unregister subscriber */ void UnregisterSharedValidationInterface(std::shared_ptr<CValidationInterface> callbacks); /** * Pushes a function to callback onto the notification queue, guaranteeing any * callbacks generated prior to now are finished when the function is called. * * Be very careful blocking on func to be called if any locks are held - * validation interface clients may not be able to make progress as they often * wait for things like cs_main, so blocking until func is called with cs_main * will result in a deadlock (that DEBUG_LOCKORDER will miss). */ void CallFunctionInValidationInterfaceQueue(std::function<void ()> func); /** * This is a synonym for the following, which asserts certain locks are not * held: * std::promise<void> promise; * CallFunctionInValidationInterfaceQueue([&promise] { * promise.set_value(); * }); * promise.get_future().wait(); */ void SyncWithValidationInterfaceQueue() LOCKS_EXCLUDED(cs_main); /** * Implement this to subscribe to events generated in validation and mempool * * Each CValidationInterface() subscriber will receive event callbacks * in the order in which the events were generated by validation and mempool. * Furthermore, each ValidationInterface() subscriber may assume that * callbacks effectively run in a single thread with single-threaded * memory consistency. That is, for a given ValidationInterface() * instantiation, each callback will complete before the next one is * invoked. This means, for example when a block is connected that the * UpdatedBlockTip() callback may depend on an operation performed in * the BlockConnected() callback without worrying about explicit * synchronization. No ordering should be assumed across * ValidationInterface() subscribers. */ class CValidationInterface { protected: /** * Protected destructor so that instances can only be deleted by derived classes. * If that restriction is no longer desired, this should be made public and virtual. */ ~CValidationInterface() = default; /** * Notifies listeners when the block chain tip advances. * * When multiple blocks are connected at once, UpdatedBlockTip will be called on the final tip * but may not be called on every intermediate tip. If the latter behavior is desired, * subscribe to BlockConnected() instead. * * Called on a background thread. Only called for the active chainstate. */ virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {} /** * Notifies listeners of a transaction having been added to mempool. * * Called on a background thread. */ virtual void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t mempool_sequence) {} /** * Notifies listeners of a transaction leaving mempool. * * This notification fires for transactions that are removed from the * mempool for the following reasons: * * - EXPIRY (expired from mempool after -mempoolexpiry hours) * - SIZELIMIT (removed in size limiting if the mempool exceeds -maxmempool megabytes) * - REORG (removed during a reorg) * - CONFLICT (removed because it conflicts with in-block transaction) * - REPLACED (removed due to RBF replacement) * * This does not fire for transactions that are removed from the mempool * because they have been included in a block. Any client that is interested * in transactions removed from the mempool for inclusion in a block can learn * about those transactions from the MempoolTransactionsRemovedForBlock notification. * * Transactions that are removed from the mempool because they conflict * with a transaction in the new block will have * TransactionRemovedFromMempool events fired *before* the BlockConnected * event is fired. If multiple blocks are connected in one step, then the * ordering could be: * * - TransactionRemovedFromMempool(tx1 from block A) * - TransactionRemovedFromMempool(tx2 from block A) * - TransactionRemovedFromMempool(tx1 from block B) * - TransactionRemovedFromMempool(tx2 from block B) * - BlockConnected(A) * - BlockConnected(B) * * Called on a background thread. */ virtual void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) {} /* * Notifies listeners of transactions removed from the mempool as * as a result of new block being connected. * MempoolTransactionsRemovedForBlock will be fired before BlockConnected. * * Called on a background thread. */ virtual void MempoolTransactionsRemovedForBlock(const std::vector<RemovedMempoolTransactionInfo>& txs_removed_for_block, unsigned int nBlockHeight) {} /** * Notifies listeners of a block being connected. * Provides a vector of transactions evicted from the mempool as a result. * * Called on a background thread. */ virtual void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock> &block, const CBlockIndex *pindex) {} /** * Notifies listeners of a block being disconnected * Provides the block that was connected. * * Called on a background thread. Only called for the active chainstate, since * background chainstates should never disconnect blocks. */ virtual void BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex) {} /** * Notifies listeners of the new active block chain on-disk. * * Prior to this callback, any updates are not guaranteed to persist on disk * (ie clients need to handle shutdown/restart safety by being able to * understand when some updates were lost due to unclean shutdown). * * When this callback is invoked, the validation changes done by any prior * callback are guaranteed to exist on disk and survive a restart, including * an unclean shutdown. * * Provides a locator describing the best chain, which is likely useful for * storing current state on disk in client DBs. * * Called on a background thread. */ virtual void ChainStateFlushed(ChainstateRole role, const CBlockLocator &locator) {} /** * Notifies listeners of a block validation result. * If the provided BlockValidationState IsValid, the provided block * is guaranteed to be the current best block at the time the * callback was generated (not necessarily now). */ virtual void BlockChecked(const CBlock&, const BlockValidationState&) {} /** * Notifies listeners that a block which builds directly on our current tip * has been received and connected to the headers tree, though not validated yet. */ virtual void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& block) {}; friend class CMainSignals; friend class ValidationInterfaceTest; }; class MainSignalsImpl; class CMainSignals { private: std::unique_ptr<MainSignalsImpl> m_internals; friend void ::RegisterSharedValidationInterface(std::shared_ptr<CValidationInterface>); friend void ::UnregisterValidationInterface(CValidationInterface*); friend void ::UnregisterAllValidationInterfaces(); friend void ::CallFunctionInValidationInterfaceQueue(std::function<void ()> func); public: /** Register a CScheduler to give callbacks which should run in the background (may only be called once) */ void RegisterBackgroundSignalScheduler(CScheduler& scheduler); /** Unregister a CScheduler to give callbacks which should run in the background - these callbacks will now be dropped! */ void UnregisterBackgroundSignalScheduler(); /** Call any remaining callbacks on the calling thread */ void FlushBackgroundCallbacks(); size_t CallbacksPending(); void UpdatedBlockTip(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload); void TransactionAddedToMempool(const NewMempoolTransactionInfo&, uint64_t mempool_sequence); void TransactionRemovedFromMempool(const CTransactionRef&, MemPoolRemovalReason, uint64_t mempool_sequence); void MempoolTransactionsRemovedForBlock(const std::vector<RemovedMempoolTransactionInfo>&, unsigned int nBlockHeight); void BlockConnected(ChainstateRole, const std::shared_ptr<const CBlock> &, const CBlockIndex *pindex); void BlockDisconnected(const std::shared_ptr<const CBlock> &, const CBlockIndex* pindex); void ChainStateFlushed(ChainstateRole, const CBlockLocator &); void BlockChecked(const CBlock&, const BlockValidationState&); void NewPoWValidBlock(const CBlockIndex *, const std::shared_ptr<const CBlock>&); }; CMainSignals& GetMainSignals(); #endif // BITCOIN_VALIDATIONINTERFACE_H
0
bitcoin
bitcoin/src/compressor.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2021 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 <compressor.h> #include <pubkey.h> #include <script/script.h> /* * These check for scripts for which a special case with a shorter encoding is defined. * They are implemented separately from the CScript test, as these test for exact byte * sequence correspondences, and are more strict. For example, IsToPubKey also verifies * whether the public key is valid (as invalid ones cannot be represented in compressed * form). */ static bool IsToKeyID(const CScript& script, CKeyID &hash) { if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) { memcpy(&hash, &script[3], 20); return true; } return false; } static bool IsToScriptID(const CScript& script, CScriptID &hash) { if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20 && script[22] == OP_EQUAL) { memcpy(&hash, &script[2], 20); return true; } return false; } static bool IsToPubKey(const CScript& script, CPubKey &pubkey) { if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG && (script[1] == 0x02 || script[1] == 0x03)) { pubkey.Set(&script[1], &script[34]); return true; } if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG && script[1] == 0x04) { pubkey.Set(&script[1], &script[66]); return pubkey.IsFullyValid(); // if not fully valid, a case that would not be compressible } return false; } bool CompressScript(const CScript& script, CompressedScript& out) { CKeyID keyID; if (IsToKeyID(script, keyID)) { out.resize(21); out[0] = 0x00; memcpy(&out[1], &keyID, 20); return true; } CScriptID scriptID; if (IsToScriptID(script, scriptID)) { out.resize(21); out[0] = 0x01; memcpy(&out[1], &scriptID, 20); return true; } CPubKey pubkey; if (IsToPubKey(script, pubkey)) { out.resize(33); memcpy(&out[1], &pubkey[1], 32); if (pubkey[0] == 0x02 || pubkey[0] == 0x03) { out[0] = pubkey[0]; return true; } else if (pubkey[0] == 0x04) { out[0] = 0x04 | (pubkey[64] & 0x01); return true; } } return false; } unsigned int GetSpecialScriptSize(unsigned int nSize) { if (nSize == 0 || nSize == 1) return 20; if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5) return 32; return 0; } bool DecompressScript(CScript& script, unsigned int nSize, const CompressedScript& in) { switch(nSize) { case 0x00: script.resize(25); script[0] = OP_DUP; script[1] = OP_HASH160; script[2] = 20; memcpy(&script[3], in.data(), 20); script[23] = OP_EQUALVERIFY; script[24] = OP_CHECKSIG; return true; case 0x01: script.resize(23); script[0] = OP_HASH160; script[1] = 20; memcpy(&script[2], in.data(), 20); script[22] = OP_EQUAL; return true; case 0x02: case 0x03: script.resize(35); script[0] = 33; script[1] = nSize; memcpy(&script[2], in.data(), 32); script[34] = OP_CHECKSIG; return true; case 0x04: case 0x05: unsigned char vch[33] = {}; vch[0] = nSize - 2; memcpy(&vch[1], in.data(), 32); CPubKey pubkey{vch}; if (!pubkey.Decompress()) return false; assert(pubkey.size() == 65); script.resize(67); script[0] = 65; memcpy(&script[1], pubkey.begin(), 65); script[66] = OP_CHECKSIG; return true; } return false; } // Amount compression: // * If the amount is 0, output 0 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9) // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10) // * call the result n // * output 1 + 10*(9*n + d - 1) + e // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9 // (this is decodable, as d is in [1-9] and e is in [0-9]) uint64_t CompressAmount(uint64_t n) { if (n == 0) return 0; int e = 0; while (((n % 10) == 0) && e < 9) { n /= 10; e++; } if (e < 9) { int d = (n % 10); assert(d >= 1 && d <= 9); n /= 10; return 1 + (n*9 + d - 1)*10 + e; } else { return 1 + (n - 1)*10 + 9; } } uint64_t DecompressAmount(uint64_t x) { // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9 if (x == 0) return 0; x--; // x = 10*(9*n + d - 1) + e int e = x % 10; x /= 10; uint64_t n = 0; if (e < 9) { // x = 9*n + d - 1 int d = (x % 9) + 1; x /= 9; // x = n n = x*10 + d; } else { n = x+1; } while (e) { n *= 10; e--; } return n; }
0
bitcoin
bitcoin/src/arith_uint256.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 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 <arith_uint256.h> #include <uint256.h> #include <crypto/common.h> #include <cassert> template <unsigned int BITS> base_uint<BITS>& base_uint<BITS>::operator<<=(unsigned int shift) { base_uint<BITS> a(*this); for (int i = 0; i < WIDTH; i++) pn[i] = 0; int k = shift / 32; shift = shift % 32; for (int i = 0; i < WIDTH; i++) { if (i + k + 1 < WIDTH && shift != 0) pn[i + k + 1] |= (a.pn[i] >> (32 - shift)); if (i + k < WIDTH) pn[i + k] |= (a.pn[i] << shift); } return *this; } template <unsigned int BITS> base_uint<BITS>& base_uint<BITS>::operator>>=(unsigned int shift) { base_uint<BITS> a(*this); for (int i = 0; i < WIDTH; i++) pn[i] = 0; int k = shift / 32; shift = shift % 32; for (int i = 0; i < WIDTH; i++) { if (i - k - 1 >= 0 && shift != 0) pn[i - k - 1] |= (a.pn[i] << (32 - shift)); if (i - k >= 0) pn[i - k] |= (a.pn[i] >> shift); } return *this; } template <unsigned int BITS> base_uint<BITS>& base_uint<BITS>::operator*=(uint32_t b32) { uint64_t carry = 0; for (int i = 0; i < WIDTH; i++) { uint64_t n = carry + (uint64_t)b32 * pn[i]; pn[i] = n & 0xffffffff; carry = n >> 32; } return *this; } template <unsigned int BITS> base_uint<BITS>& base_uint<BITS>::operator*=(const base_uint& b) { base_uint<BITS> a; for (int j = 0; j < WIDTH; j++) { uint64_t carry = 0; for (int i = 0; i + j < WIDTH; i++) { uint64_t n = carry + a.pn[i + j] + (uint64_t)pn[j] * b.pn[i]; a.pn[i + j] = n & 0xffffffff; carry = n >> 32; } } *this = a; return *this; } template <unsigned int BITS> base_uint<BITS>& base_uint<BITS>::operator/=(const base_uint& b) { base_uint<BITS> div = b; // make a copy, so we can shift. base_uint<BITS> num = *this; // make a copy, so we can subtract. *this = 0; // the quotient. int num_bits = num.bits(); int div_bits = div.bits(); if (div_bits == 0) throw uint_error("Division by zero"); if (div_bits > num_bits) // the result is certainly 0. return *this; int shift = num_bits - div_bits; div <<= shift; // shift so that div and num align. while (shift >= 0) { if (num >= div) { num -= div; pn[shift / 32] |= (1U << (shift & 31)); // set a bit of the result. } div >>= 1; // shift back. shift--; } // num now contains the remainder of the division. return *this; } template <unsigned int BITS> int base_uint<BITS>::CompareTo(const base_uint<BITS>& b) const { for (int i = WIDTH - 1; i >= 0; i--) { if (pn[i] < b.pn[i]) return -1; if (pn[i] > b.pn[i]) return 1; } return 0; } template <unsigned int BITS> bool base_uint<BITS>::EqualTo(uint64_t b) const { for (int i = WIDTH - 1; i >= 2; i--) { if (pn[i]) return false; } if (pn[1] != (b >> 32)) return false; if (pn[0] != (b & 0xfffffffful)) return false; return true; } template <unsigned int BITS> double base_uint<BITS>::getdouble() const { double ret = 0.0; double fact = 1.0; for (int i = 0; i < WIDTH; i++) { ret += fact * pn[i]; fact *= 4294967296.0; } return ret; } template <unsigned int BITS> std::string base_uint<BITS>::GetHex() const { base_blob<BITS> b; for (int x = 0; x < this->WIDTH; ++x) { WriteLE32(b.begin() + x*4, this->pn[x]); } return b.GetHex(); } template <unsigned int BITS> std::string base_uint<BITS>::ToString() const { return GetHex(); } template <unsigned int BITS> unsigned int base_uint<BITS>::bits() const { for (int pos = WIDTH - 1; pos >= 0; pos--) { if (pn[pos]) { for (int nbits = 31; nbits > 0; nbits--) { if (pn[pos] & 1U << nbits) return 32 * pos + nbits + 1; } return 32 * pos + 1; } } return 0; } // Explicit instantiations for base_uint<256> template class base_uint<256>; // This implementation directly uses shifts instead of going // through an intermediate MPI representation. arith_uint256& arith_uint256::SetCompact(uint32_t nCompact, bool* pfNegative, bool* pfOverflow) { int nSize = nCompact >> 24; uint32_t nWord = nCompact & 0x007fffff; if (nSize <= 3) { nWord >>= 8 * (3 - nSize); *this = nWord; } else { *this = nWord; *this <<= 8 * (nSize - 3); } if (pfNegative) *pfNegative = nWord != 0 && (nCompact & 0x00800000) != 0; if (pfOverflow) *pfOverflow = nWord != 0 && ((nSize > 34) || (nWord > 0xff && nSize > 33) || (nWord > 0xffff && nSize > 32)); return *this; } uint32_t arith_uint256::GetCompact(bool fNegative) const { int nSize = (bits() + 7) / 8; uint32_t nCompact = 0; if (nSize <= 3) { nCompact = GetLow64() << 8 * (3 - nSize); } else { arith_uint256 bn = *this >> 8 * (nSize - 3); nCompact = bn.GetLow64(); } // The 0x00800000 bit denotes the sign. // Thus, if it is already set, divide the mantissa by 256 and increase the exponent. if (nCompact & 0x00800000) { nCompact >>= 8; nSize++; } assert((nCompact & ~0x007fffffU) == 0); assert(nSize < 256); nCompact |= nSize << 24; nCompact |= (fNegative && (nCompact & 0x007fffff) ? 0x00800000 : 0); return nCompact; } uint256 ArithToUint256(const arith_uint256 &a) { uint256 b; for(int x=0; x<a.WIDTH; ++x) WriteLE32(b.begin() + x*4, a.pn[x]); return b; } arith_uint256 UintToArith256(const uint256 &a) { arith_uint256 b; for(int x=0; x<b.WIDTH; ++x) b.pn[x] = ReadLE32(a.begin() + x*4); return b; }
0
bitcoin
bitcoin/src/key_io.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_KEY_IO_H #define BITCOIN_KEY_IO_H #include <addresstype.h> #include <chainparams.h> #include <key.h> #include <pubkey.h> #include <string> CKey DecodeSecret(const std::string& str); std::string EncodeSecret(const CKey& key); CExtKey DecodeExtKey(const std::string& str); std::string EncodeExtKey(const CExtKey& extkey); CExtPubKey DecodeExtPubKey(const std::string& str); std::string EncodeExtPubKey(const CExtPubKey& extpubkey); std::string EncodeDestination(const CTxDestination& dest); CTxDestination DecodeDestination(const std::string& str); CTxDestination DecodeDestination(const std::string& str, std::string& error_msg, std::vector<int>* error_locations = nullptr); bool IsValidDestinationString(const std::string& str); bool IsValidDestinationString(const std::string& str, const CChainParams& params); #endif // BITCOIN_KEY_IO_H
0
bitcoin
bitcoin/src/chainparamsbase.h
// Copyright (c) 2014-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CHAINPARAMSBASE_H #define BITCOIN_CHAINPARAMSBASE_H #include <util/chaintype.h> #include <memory> #include <string> class ArgsManager; /** * CBaseChainParams defines the base parameters (shared between bitcoin-cli and bitcoind) * of a given instance of the Bitcoin system. */ class CBaseChainParams { public: const std::string& DataDir() const { return strDataDir; } uint16_t RPCPort() const { return m_rpc_port; } uint16_t OnionServiceTargetPort() const { return m_onion_service_target_port; } CBaseChainParams() = delete; CBaseChainParams(const std::string& data_dir, uint16_t rpc_port, uint16_t onion_service_target_port) : m_rpc_port(rpc_port), m_onion_service_target_port(onion_service_target_port), strDataDir(data_dir) {} private: const uint16_t m_rpc_port; const uint16_t m_onion_service_target_port; std::string strDataDir; }; /** * Creates and returns a std::unique_ptr<CBaseChainParams> of the chosen chain. */ std::unique_ptr<CBaseChainParams> CreateBaseChainParams(const ChainType chain); /** *Set the arguments for chainparams */ void SetupChainParamsBaseOptions(ArgsManager& argsman); /** * Return the currently selected parameters. This won't change after app * startup, except for unit tests. */ const CBaseChainParams& BaseParams(); /** Sets the params returned by Params() to those for the given chain. */ void SelectBaseParams(const ChainType chain); #endif // BITCOIN_CHAINPARAMSBASE_H
0
bitcoin
bitcoin/src/pubkey.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Copyright (c) 2017 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_PUBKEY_H #define BITCOIN_PUBKEY_H #include <hash.h> #include <serialize.h> #include <span.h> #include <uint256.h> #include <cstring> #include <optional> #include <vector> const unsigned int BIP32_EXTKEY_SIZE = 74; const unsigned int BIP32_EXTKEY_WITH_VERSION_SIZE = 78; /** A reference to a CKey: the Hash160 of its serialized public key */ class CKeyID : public uint160 { public: CKeyID() : uint160() {} explicit CKeyID(const uint160& in) : uint160(in) {} }; typedef uint256 ChainCode; /** An encapsulated public key. */ class CPubKey { public: /** * secp256k1: */ static constexpr unsigned int SIZE = 65; static constexpr unsigned int COMPRESSED_SIZE = 33; static constexpr unsigned int SIGNATURE_SIZE = 72; static constexpr unsigned int COMPACT_SIGNATURE_SIZE = 65; /** * see www.keylength.com * script supports up to 75 for single byte push */ static_assert( SIZE >= COMPRESSED_SIZE, "COMPRESSED_SIZE is larger than SIZE"); private: /** * Just store the serialized data. * Its length can very cheaply be computed from the first byte. */ unsigned char vch[SIZE]; //! Compute the length of a pubkey with a given first byte. unsigned int static GetLen(unsigned char chHeader) { if (chHeader == 2 || chHeader == 3) return COMPRESSED_SIZE; if (chHeader == 4 || chHeader == 6 || chHeader == 7) return SIZE; return 0; } //! Set this key data to be invalid void Invalidate() { vch[0] = 0xFF; } public: bool static ValidSize(const std::vector<unsigned char> &vch) { return vch.size() > 0 && GetLen(vch[0]) == vch.size(); } //! Construct an invalid public key. CPubKey() { Invalidate(); } //! Initialize a public key using begin/end iterators to byte data. template <typename T> void Set(const T pbegin, const T pend) { int len = pend == pbegin ? 0 : GetLen(pbegin[0]); if (len && len == (pend - pbegin)) memcpy(vch, (unsigned char*)&pbegin[0], len); else Invalidate(); } //! Construct a public key using begin/end iterators to byte data. template <typename T> CPubKey(const T pbegin, const T pend) { Set(pbegin, pend); } //! Construct a public key from a byte vector. explicit CPubKey(Span<const uint8_t> _vch) { Set(_vch.begin(), _vch.end()); } //! 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]; } //! Comparator implementation. friend bool operator==(const CPubKey& a, const CPubKey& b) { return a.vch[0] == b.vch[0] && memcmp(a.vch, b.vch, a.size()) == 0; } friend bool operator!=(const CPubKey& a, const CPubKey& b) { return !(a == b); } friend bool operator<(const CPubKey& a, const CPubKey& b) { return a.vch[0] < b.vch[0] || (a.vch[0] == b.vch[0] && memcmp(a.vch, b.vch, a.size()) < 0); } friend bool operator>(const CPubKey& a, const CPubKey& b) { return a.vch[0] > b.vch[0] || (a.vch[0] == b.vch[0] && memcmp(a.vch, b.vch, a.size()) > 0); } //! Implement serialization, as if this was a byte vector. template <typename Stream> void Serialize(Stream& s) const { unsigned int len = size(); ::WriteCompactSize(s, len); s << Span{vch, len}; } template <typename Stream> void Unserialize(Stream& s) { const unsigned int len(::ReadCompactSize(s)); if (len <= SIZE) { s >> Span{vch, len}; if (len != size()) { Invalidate(); } } else { // invalid pubkey, skip available data s.ignore(len); Invalidate(); } } //! Get the KeyID of this public key (hash of its serialization) CKeyID GetID() const { return CKeyID(Hash160(Span{vch}.first(size()))); } //! Get the 256-bit hash of this public key. uint256 GetHash() const { return Hash(Span{vch}.first(size())); } /* * Check syntactic correctness. * * When setting a pubkey (Set()) or deserializing fails (its header bytes * don't match the length of the data), the size is set to 0. Thus, * by checking size, one can observe whether Set() or deserialization has * failed. * * This does not check for more than that. In particular, it does not verify * that the coordinates correspond to a point on the curve (see IsFullyValid() * for that instead). * * Note that this is consensus critical as CheckECDSASignature() calls it! */ bool IsValid() const { return size() > 0; } /** Check if a public key is a syntactically valid compressed or uncompressed key. */ bool IsValidNonHybrid() const noexcept { return size() > 0 && (vch[0] == 0x02 || vch[0] == 0x03 || vch[0] == 0x04); } //! fully validate whether this is a valid public key (more expensive than IsValid()) bool IsFullyValid() const; //! Check whether this is a compressed public key. bool IsCompressed() const { return size() == COMPRESSED_SIZE; } /** * Verify a DER signature (~72 bytes). * If this public key is not fully valid, the return value will be false. */ bool Verify(const uint256& hash, const std::vector<unsigned char>& vchSig) const; /** * Check whether a signature is normalized (lower-S). */ static bool CheckLowS(const std::vector<unsigned char>& vchSig); //! Recover a public key from a compact signature. bool RecoverCompact(const uint256& hash, const std::vector<unsigned char>& vchSig); //! Turn this public key into an uncompressed public key. bool Decompress(); //! Derive BIP32 child pubkey. [[nodiscard]] bool Derive(CPubKey& pubkeyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const; }; class XOnlyPubKey { private: uint256 m_keydata; public: /** Construct an empty x-only pubkey. */ XOnlyPubKey() = default; XOnlyPubKey(const XOnlyPubKey&) = default; XOnlyPubKey& operator=(const XOnlyPubKey&) = default; /** Determine if this pubkey is fully valid. This is true for approximately 50% of all * possible 32-byte arrays. If false, VerifySchnorr, CheckTapTweak and CreateTapTweak * will always fail. */ bool IsFullyValid() const; /** Test whether this is the 0 key (the result of default construction). This implies * !IsFullyValid(). */ bool IsNull() const { return m_keydata.IsNull(); } /** Construct an x-only pubkey from exactly 32 bytes. */ explicit XOnlyPubKey(Span<const unsigned char> bytes); /** Construct an x-only pubkey from a normal pubkey. */ explicit XOnlyPubKey(const CPubKey& pubkey) : XOnlyPubKey(Span{pubkey}.subspan(1, 32)) {} /** Verify a Schnorr signature against this public key. * * sigbytes must be exactly 64 bytes. */ bool VerifySchnorr(const uint256& msg, Span<const unsigned char> sigbytes) const; /** Compute the Taproot tweak as specified in BIP341, with *this as internal * key: * - if merkle_root == nullptr: H_TapTweak(xonly_pubkey) * - otherwise: H_TapTweak(xonly_pubkey || *merkle_root) * * Note that the behavior of this function with merkle_root != nullptr is * consensus critical. */ uint256 ComputeTapTweakHash(const uint256* merkle_root) const; /** Verify that this is a Taproot tweaked output point, against a specified internal key, * Merkle root, and parity. */ bool CheckTapTweak(const XOnlyPubKey& internal, const uint256& merkle_root, bool parity) const; /** Construct a Taproot tweaked output point with this point as internal key. */ std::optional<std::pair<XOnlyPubKey, bool>> CreateTapTweak(const uint256* merkle_root) const; /** Returns a list of CKeyIDs for the CPubKeys that could have been used to create this XOnlyPubKey. * This is needed for key lookups since keys are indexed by CKeyID. */ std::vector<CKeyID> GetKeyIDs() const; CPubKey GetEvenCorrespondingCPubKey() const; const unsigned char& operator[](int pos) const { return *(m_keydata.begin() + pos); } const unsigned char* data() const { return m_keydata.begin(); } static constexpr size_t size() { return decltype(m_keydata)::size(); } const unsigned char* begin() const { return m_keydata.begin(); } const unsigned char* end() const { return m_keydata.end(); } unsigned char* begin() { return m_keydata.begin(); } unsigned char* end() { return m_keydata.end(); } bool operator==(const XOnlyPubKey& other) const { return m_keydata == other.m_keydata; } bool operator!=(const XOnlyPubKey& other) const { return m_keydata != other.m_keydata; } bool operator<(const XOnlyPubKey& other) const { return m_keydata < other.m_keydata; } //! Implement serialization without length prefixes since it is a fixed length SERIALIZE_METHODS(XOnlyPubKey, obj) { READWRITE(obj.m_keydata); } }; /** An ElligatorSwift-encoded public key. */ struct EllSwiftPubKey { private: static constexpr size_t SIZE = 64; std::array<std::byte, SIZE> m_pubkey; public: /** Default constructor creates all-zero pubkey (which is valid). */ EllSwiftPubKey() noexcept = default; /** Construct a new ellswift public key from a given serialization. */ EllSwiftPubKey(Span<const std::byte> ellswift) noexcept; /** Decode to normal compressed CPubKey (for debugging purposes). */ CPubKey Decode() const; // Read-only access for serialization. const std::byte* data() const { return m_pubkey.data(); } static constexpr size_t size() { return SIZE; } auto begin() const { return m_pubkey.cbegin(); } auto end() const { return m_pubkey.cend(); } bool friend operator==(const EllSwiftPubKey& a, const EllSwiftPubKey& b) { return a.m_pubkey == b.m_pubkey; } bool friend operator!=(const EllSwiftPubKey& a, const EllSwiftPubKey& b) { return a.m_pubkey != b.m_pubkey; } }; struct CExtPubKey { unsigned char version[4]; unsigned char nDepth; unsigned char vchFingerprint[4]; unsigned int nChild; ChainCode chaincode; CPubKey pubkey; friend bool operator==(const CExtPubKey &a, const CExtPubKey &b) { return a.nDepth == b.nDepth && memcmp(a.vchFingerprint, b.vchFingerprint, sizeof(vchFingerprint)) == 0 && a.nChild == b.nChild && a.chaincode == b.chaincode && a.pubkey == b.pubkey; } friend bool operator!=(const CExtPubKey &a, const CExtPubKey &b) { return !(a == b); } friend bool operator<(const CExtPubKey &a, const CExtPubKey &b) { if (a.pubkey < b.pubkey) { return true; } else if (a.pubkey > b.pubkey) { return false; } return a.chaincode < b.chaincode; } void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const; void Decode(const unsigned char code[BIP32_EXTKEY_SIZE]); void EncodeWithVersion(unsigned char code[BIP32_EXTKEY_WITH_VERSION_SIZE]) const; void DecodeWithVersion(const unsigned char code[BIP32_EXTKEY_WITH_VERSION_SIZE]); [[nodiscard]] bool Derive(CExtPubKey& out, unsigned int nChild) const; }; #endif // BITCOIN_PUBKEY_H
0
bitcoin
bitcoin/src/headerssync.cpp
// Copyright (c) 2022 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 <headerssync.h> #include <logging.h> #include <pow.h> #include <timedata.h> #include <util/check.h> #include <util/vector.h> // The two constants below are computed using the simulation script in // contrib/devtools/headerssync-params.py. //! Store one header commitment per HEADER_COMMITMENT_PERIOD blocks. constexpr size_t HEADER_COMMITMENT_PERIOD{606}; //! Only feed headers to validation once this many headers on top have been //! received and validated against commitments. constexpr size_t REDOWNLOAD_BUFFER_SIZE{14441}; // 14441/606 = ~23.8 commitments // Our memory analysis assumes 48 bytes for a CompressedHeader (so we should // re-calculate parameters if we compress further) static_assert(sizeof(CompressedHeader) == 48); HeadersSyncState::HeadersSyncState(NodeId id, const Consensus::Params& consensus_params, const CBlockIndex* chain_start, const arith_uint256& minimum_required_work) : m_commit_offset(GetRand<unsigned>(HEADER_COMMITMENT_PERIOD)), m_id(id), m_consensus_params(consensus_params), m_chain_start(chain_start), m_minimum_required_work(minimum_required_work), m_current_chain_work(chain_start->nChainWork), m_last_header_received(m_chain_start->GetBlockHeader()), m_current_height(chain_start->nHeight) { // Estimate the number of blocks that could possibly exist on the peer's // chain *right now* using 6 blocks/second (fastest blockrate given the MTP // rule) times the number of seconds from the last allowed block until // today. This serves as a memory bound on how many commitments we might // store from this peer, and we can safely give up syncing if the peer // exceeds this bound, because it's not possible for a consensus-valid // chain to be longer than this (at the current time -- in the future we // could try again, if necessary, to sync a longer chain). m_max_commitments = 6*(Ticks<std::chrono::seconds>(GetAdjustedTime() - NodeSeconds{std::chrono::seconds{chain_start->GetMedianTimePast()}}) + MAX_FUTURE_BLOCK_TIME) / HEADER_COMMITMENT_PERIOD; LogPrint(BCLog::NET, "Initial headers sync started with peer=%d: height=%i, max_commitments=%i, min_work=%s\n", m_id, m_current_height, m_max_commitments, m_minimum_required_work.ToString()); } /** Free any memory in use, and mark this object as no longer usable. This is * required to guarantee that we won't reuse this object with the same * SaltedTxidHasher for another sync. */ void HeadersSyncState::Finalize() { Assume(m_download_state != State::FINAL); ClearShrink(m_header_commitments); m_last_header_received.SetNull(); ClearShrink(m_redownloaded_headers); m_redownload_buffer_last_hash.SetNull(); m_redownload_buffer_first_prev_hash.SetNull(); m_process_all_remaining_headers = false; m_current_height = 0; m_download_state = State::FINAL; } /** Process the next batch of headers received from our peer. * Validate and store commitments, and compare total chainwork to our target to * see if we can switch to REDOWNLOAD mode. */ HeadersSyncState::ProcessingResult HeadersSyncState::ProcessNextHeaders(const std::vector<CBlockHeader>& received_headers, const bool full_headers_message) { ProcessingResult ret; Assume(!received_headers.empty()); if (received_headers.empty()) return ret; Assume(m_download_state != State::FINAL); if (m_download_state == State::FINAL) return ret; if (m_download_state == State::PRESYNC) { // During PRESYNC, we minimally validate block headers and // occasionally add commitments to them, until we reach our work // threshold (at which point m_download_state is updated to REDOWNLOAD). ret.success = ValidateAndStoreHeadersCommitments(received_headers); if (ret.success) { if (full_headers_message || m_download_state == State::REDOWNLOAD) { // A full headers message means the peer may have more to give us; // also if we just switched to REDOWNLOAD then we need to re-request // headers from the beginning. ret.request_more = true; } else { Assume(m_download_state == State::PRESYNC); // If we're in PRESYNC and we get a non-full headers // message, then the peer's chain has ended and definitely doesn't // have enough work, so we can stop our sync. LogPrint(BCLog::NET, "Initial headers sync aborted with peer=%d: incomplete headers message at height=%i (presync phase)\n", m_id, m_current_height); } } } else if (m_download_state == State::REDOWNLOAD) { // During REDOWNLOAD, we compare our stored commitments to what we // receive, and add headers to our redownload buffer. When the buffer // gets big enough (meaning that we've checked enough commitments), // we'll return a batch of headers to the caller for processing. ret.success = true; for (const auto& hdr : received_headers) { if (!ValidateAndStoreRedownloadedHeader(hdr)) { // Something went wrong -- the peer gave us an unexpected chain. // We could consider looking at the reason for failure and // punishing the peer, but for now just give up on sync. ret.success = false; break; } } if (ret.success) { // Return any headers that are ready for acceptance. ret.pow_validated_headers = PopHeadersReadyForAcceptance(); // If we hit our target blockhash, then all remaining headers will be // returned and we can clear any leftover internal state. if (m_redownloaded_headers.empty() && m_process_all_remaining_headers) { LogPrint(BCLog::NET, "Initial headers sync complete with peer=%d: releasing all at height=%i (redownload phase)\n", m_id, m_redownload_buffer_last_height); } else if (full_headers_message) { // If the headers message is full, we need to request more. ret.request_more = true; } else { // For some reason our peer gave us a high-work chain, but is now // declining to serve us that full chain again. Give up. // Note that there's no more processing to be done with these // headers, so we can still return success. LogPrint(BCLog::NET, "Initial headers sync aborted with peer=%d: incomplete headers message at height=%i (redownload phase)\n", m_id, m_redownload_buffer_last_height); } } } if (!(ret.success && ret.request_more)) Finalize(); return ret; } bool HeadersSyncState::ValidateAndStoreHeadersCommitments(const std::vector<CBlockHeader>& headers) { // The caller should not give us an empty set of headers. Assume(headers.size() > 0); if (headers.size() == 0) return true; Assume(m_download_state == State::PRESYNC); if (m_download_state != State::PRESYNC) return false; if (headers[0].hashPrevBlock != m_last_header_received.GetHash()) { // Somehow our peer gave us a header that doesn't connect. // This might be benign -- perhaps our peer reorged away from the chain // they were on. Give up on this sync for now (likely we will start a // new sync with a new starting point). LogPrint(BCLog::NET, "Initial headers sync aborted with peer=%d: non-continuous headers at height=%i (presync phase)\n", m_id, m_current_height); return false; } // If it does connect, (minimally) validate and occasionally store // commitments. for (const auto& hdr : headers) { if (!ValidateAndProcessSingleHeader(hdr)) { return false; } } if (m_current_chain_work >= m_minimum_required_work) { m_redownloaded_headers.clear(); m_redownload_buffer_last_height = m_chain_start->nHeight; m_redownload_buffer_first_prev_hash = m_chain_start->GetBlockHash(); m_redownload_buffer_last_hash = m_chain_start->GetBlockHash(); m_redownload_chain_work = m_chain_start->nChainWork; m_download_state = State::REDOWNLOAD; LogPrint(BCLog::NET, "Initial headers sync transition with peer=%d: reached sufficient work at height=%i, redownloading from height=%i\n", m_id, m_current_height, m_redownload_buffer_last_height); } return true; } bool HeadersSyncState::ValidateAndProcessSingleHeader(const CBlockHeader& current) { Assume(m_download_state == State::PRESYNC); if (m_download_state != State::PRESYNC) return false; int next_height = m_current_height + 1; // Verify that the difficulty isn't growing too fast; an adversary with // limited hashing capability has a greater chance of producing a high // work chain if they compress the work into as few blocks as possible, // so don't let anyone give a chain that would violate the difficulty // adjustment maximum. if (!PermittedDifficultyTransition(m_consensus_params, next_height, m_last_header_received.nBits, current.nBits)) { LogPrint(BCLog::NET, "Initial headers sync aborted with peer=%d: invalid difficulty transition at height=%i (presync phase)\n", m_id, next_height); return false; } if (next_height % HEADER_COMMITMENT_PERIOD == m_commit_offset) { // Add a commitment. m_header_commitments.push_back(m_hasher(current.GetHash()) & 1); if (m_header_commitments.size() > m_max_commitments) { // The peer's chain is too long; give up. // It's possible the chain grew since we started the sync; so // potentially we could succeed in syncing the peer's chain if we // try again later. LogPrint(BCLog::NET, "Initial headers sync aborted with peer=%d: exceeded max commitments at height=%i (presync phase)\n", m_id, next_height); return false; } } m_current_chain_work += GetBlockProof(CBlockIndex(current)); m_last_header_received = current; m_current_height = next_height; return true; } bool HeadersSyncState::ValidateAndStoreRedownloadedHeader(const CBlockHeader& header) { Assume(m_download_state == State::REDOWNLOAD); if (m_download_state != State::REDOWNLOAD) return false; int64_t next_height = m_redownload_buffer_last_height + 1; // Ensure that we're working on a header that connects to the chain we're // downloading. if (header.hashPrevBlock != m_redownload_buffer_last_hash) { LogPrint(BCLog::NET, "Initial headers sync aborted with peer=%d: non-continuous headers at height=%i (redownload phase)\n", m_id, next_height); return false; } // Check that the difficulty adjustments are within our tolerance: uint32_t previous_nBits{0}; if (!m_redownloaded_headers.empty()) { previous_nBits = m_redownloaded_headers.back().nBits; } else { previous_nBits = m_chain_start->nBits; } if (!PermittedDifficultyTransition(m_consensus_params, next_height, previous_nBits, header.nBits)) { LogPrint(BCLog::NET, "Initial headers sync aborted with peer=%d: invalid difficulty transition at height=%i (redownload phase)\n", m_id, next_height); return false; } // Track work on the redownloaded chain m_redownload_chain_work += GetBlockProof(CBlockIndex(header)); if (m_redownload_chain_work >= m_minimum_required_work) { m_process_all_remaining_headers = true; } // If we're at a header for which we previously stored a commitment, verify // it is correct. Failure will result in aborting download. // Also, don't check commitments once we've gotten to our target blockhash; // it's possible our peer has extended its chain between our first sync and // our second, and we don't want to return failure after we've seen our // target blockhash just because we ran out of commitments. if (!m_process_all_remaining_headers && next_height % HEADER_COMMITMENT_PERIOD == m_commit_offset) { if (m_header_commitments.size() == 0) { LogPrint(BCLog::NET, "Initial headers sync aborted with peer=%d: commitment overrun at height=%i (redownload phase)\n", m_id, next_height); // Somehow our peer managed to feed us a different chain and // we've run out of commitments. return false; } bool commitment = m_hasher(header.GetHash()) & 1; bool expected_commitment = m_header_commitments.front(); m_header_commitments.pop_front(); if (commitment != expected_commitment) { LogPrint(BCLog::NET, "Initial headers sync aborted with peer=%d: commitment mismatch at height=%i (redownload phase)\n", m_id, next_height); return false; } } // Store this header for later processing. m_redownloaded_headers.emplace_back(header); m_redownload_buffer_last_height = next_height; m_redownload_buffer_last_hash = header.GetHash(); return true; } std::vector<CBlockHeader> HeadersSyncState::PopHeadersReadyForAcceptance() { std::vector<CBlockHeader> ret; Assume(m_download_state == State::REDOWNLOAD); if (m_download_state != State::REDOWNLOAD) return ret; while (m_redownloaded_headers.size() > REDOWNLOAD_BUFFER_SIZE || (m_redownloaded_headers.size() > 0 && m_process_all_remaining_headers)) { ret.emplace_back(m_redownloaded_headers.front().GetFullHeader(m_redownload_buffer_first_prev_hash)); m_redownloaded_headers.pop_front(); m_redownload_buffer_first_prev_hash = ret.back().GetHash(); } return ret; } CBlockLocator HeadersSyncState::NextHeadersRequestLocator() const { Assume(m_download_state != State::FINAL); if (m_download_state == State::FINAL) return {}; auto chain_start_locator = LocatorEntries(m_chain_start); std::vector<uint256> locator; if (m_download_state == State::PRESYNC) { // During pre-synchronization, we continue from the last header received. locator.push_back(m_last_header_received.GetHash()); } if (m_download_state == State::REDOWNLOAD) { // During redownload, we will download from the last received header that we stored. locator.push_back(m_redownload_buffer_last_hash); } locator.insert(locator.end(), chain_start_locator.begin(), chain_start_locator.end()); return CBlockLocator{std::move(locator)}; }
0
bitcoin
bitcoin/src/bitcoin-tx.cpp
// Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <chainparamsbase.h> #include <clientversion.h> #include <coins.h> #include <common/args.h> #include <common/system.h> #include <compat/compat.h> #include <consensus/amount.h> #include <consensus/consensus.h> #include <core_io.h> #include <key_io.h> #include <policy/policy.h> #include <primitives/transaction.h> #include <script/script.h> #include <script/sign.h> #include <script/signingprovider.h> #include <univalue.h> #include <util/exception.h> #include <util/fs.h> #include <util/moneystr.h> #include <util/rbf.h> #include <util/strencodings.h> #include <util/string.h> #include <util/translation.h> #include <cstdio> #include <functional> #include <memory> static bool fCreateBlank; static std::map<std::string,UniValue> registers; static const int CONTINUE_EXECUTION=-1; const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr; static void SetupBitcoinTxArgs(ArgsManager &argsman) { SetupHelpOptions(argsman); argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-create", "Create new, empty TX.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-json", "Select JSON output", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-txid", "Output only the hex-encoded transaction id of the resultant transaction.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); SetupChainParamsBaseOptions(argsman); argsman.AddArg("delin=N", "Delete input N from TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); argsman.AddArg("delout=N", "Delete output N from TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); argsman.AddArg("in=TXID:VOUT(:SEQUENCE_NUMBER)", "Add input to TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); argsman.AddArg("locktime=N", "Set TX lock time to N", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); argsman.AddArg("nversion=N", "Set TX version to N", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); argsman.AddArg("outaddr=VALUE:ADDRESS", "Add address-based output to TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); argsman.AddArg("outdata=[VALUE:]DATA", "Add data-based output to TX", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); argsman.AddArg("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", "Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS. " "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. " "Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); argsman.AddArg("outpubkey=VALUE:PUBKEY[:FLAGS]", "Add pay-to-pubkey output to TX. " "Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output. " "Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); argsman.AddArg("outscript=VALUE:SCRIPT[:FLAGS]", "Add raw script output to TX. " "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. " "Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); argsman.AddArg("replaceable(=N)", "Sets Replace-By-Fee (RBF) opt-in sequence number for input N. " "If N is not provided, the command attempts to opt-in all available inputs for RBF. " "If the transaction has no inputs, this option is ignored.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); argsman.AddArg("sign=SIGHASH-FLAGS", "Add zero or more signatures to transaction. " "This command requires JSON registers:" "prevtxs=JSON object, " "privatekeys=JSON object. " "See signrawtransactionwithkey docs for format of sighash flags, JSON objects.", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); argsman.AddArg("load=NAME:FILENAME", "Load JSON file FILENAME into register NAME", ArgsManager::ALLOW_ANY, OptionsCategory::REGISTER_COMMANDS); argsman.AddArg("set=NAME:JSON-STRING", "Set register NAME to given JSON-STRING", ArgsManager::ALLOW_ANY, OptionsCategory::REGISTER_COMMANDS); } // // This function returns either one of EXIT_ codes when it's expected to stop the process or // CONTINUE_EXECUTION when it's expected to continue further. // static int AppInitRawTx(int argc, char* argv[]) { SetupBitcoinTxArgs(gArgs); std::string error; if (!gArgs.ParseParameters(argc, argv, error)) { tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error); return EXIT_FAILURE; } // Check for chain settings (Params() calls are only valid after this clause) try { SelectParams(gArgs.GetChainType()); } catch (const std::exception& e) { tfm::format(std::cerr, "Error: %s\n", e.what()); return EXIT_FAILURE; } fCreateBlank = gArgs.GetBoolArg("-create", false); if (argc < 2 || HelpRequested(gArgs) || gArgs.IsArgSet("-version")) { // First part of help message is specific to this utility std::string strUsage = PACKAGE_NAME " bitcoin-tx utility version " + FormatFullVersion() + "\n"; if (gArgs.IsArgSet("-version")) { strUsage += FormatParagraph(LicenseInfo()); } else { strUsage += "\n" "Usage: bitcoin-tx [options] <hex-tx> [commands] Update hex-encoded bitcoin transaction\n" "or: bitcoin-tx [options] -create [commands] Create hex-encoded bitcoin transaction\n" "\n"; strUsage += gArgs.GetHelpMessage(); } tfm::format(std::cout, "%s", strUsage); if (argc < 2) { tfm::format(std::cerr, "Error: too few parameters\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } return CONTINUE_EXECUTION; } static void RegisterSetJson(const std::string& key, const std::string& rawJson) { UniValue val; if (!val.read(rawJson)) { std::string strErr = "Cannot parse JSON for key " + key; throw std::runtime_error(strErr); } registers[key] = val; } static void RegisterSet(const std::string& strInput) { // separate NAME:VALUE in string size_t pos = strInput.find(':'); if ((pos == std::string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) throw std::runtime_error("Register input requires NAME:VALUE"); std::string key = strInput.substr(0, pos); std::string valStr = strInput.substr(pos + 1, std::string::npos); RegisterSetJson(key, valStr); } static void RegisterLoad(const std::string& strInput) { // separate NAME:FILENAME in string size_t pos = strInput.find(':'); if ((pos == std::string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) throw std::runtime_error("Register load requires NAME:FILENAME"); std::string key = strInput.substr(0, pos); std::string filename = strInput.substr(pos + 1, std::string::npos); FILE *f = fsbridge::fopen(filename.c_str(), "r"); if (!f) { std::string strErr = "Cannot open file " + filename; throw std::runtime_error(strErr); } // load file chunks into one big buffer std::string valStr; while ((!feof(f)) && (!ferror(f))) { char buf[4096]; int bread = fread(buf, 1, sizeof(buf), f); if (bread <= 0) break; valStr.insert(valStr.size(), buf, bread); } int error = ferror(f); fclose(f); if (error) { std::string strErr = "Error reading file " + filename; throw std::runtime_error(strErr); } // evaluate as JSON buffer register RegisterSetJson(key, valStr); } static CAmount ExtractAndValidateValue(const std::string& strValue) { if (std::optional<CAmount> parsed = ParseMoney(strValue)) { return parsed.value(); } else { throw std::runtime_error("invalid TX output value"); } } static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal) { int64_t newVersion; if (!ParseInt64(cmdVal, &newVersion) || newVersion < 1 || newVersion > TX_MAX_STANDARD_VERSION) { throw std::runtime_error("Invalid TX version requested: '" + cmdVal + "'"); } tx.nVersion = (int) newVersion; } static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal) { int64_t newLocktime; if (!ParseInt64(cmdVal, &newLocktime) || newLocktime < 0LL || newLocktime > 0xffffffffLL) throw std::runtime_error("Invalid TX locktime requested: '" + cmdVal + "'"); tx.nLockTime = (unsigned int) newLocktime; } static void MutateTxRBFOptIn(CMutableTransaction& tx, const std::string& strInIdx) { // parse requested index int64_t inIdx = -1; if (strInIdx != "" && (!ParseInt64(strInIdx, &inIdx) || inIdx < 0 || inIdx >= static_cast<int64_t>(tx.vin.size()))) { throw std::runtime_error("Invalid TX input index '" + strInIdx + "'"); } // set the nSequence to MAX_INT - 2 (= RBF opt in flag) int cnt = 0; for (CTxIn& txin : tx.vin) { if (strInIdx == "" || cnt == inIdx) { if (txin.nSequence > MAX_BIP125_RBF_SEQUENCE) { txin.nSequence = MAX_BIP125_RBF_SEQUENCE; } } ++cnt; } } template <typename T> static T TrimAndParse(const std::string& int_str, const std::string& err) { const auto parsed{ToIntegral<T>(TrimStringView(int_str))}; if (!parsed.has_value()) { throw std::runtime_error(err + " '" + int_str + "'"); } return parsed.value(); } static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput) { std::vector<std::string> vStrInputParts = SplitString(strInput, ':'); // separate TXID:VOUT in string if (vStrInputParts.size()<2) throw std::runtime_error("TX input missing separator"); // extract and validate TXID uint256 txid; if (!ParseHashStr(vStrInputParts[0], txid)) { throw std::runtime_error("invalid TX input txid"); } static const unsigned int minTxOutSz = 9; static const unsigned int maxVout = MAX_BLOCK_WEIGHT / (WITNESS_SCALE_FACTOR * minTxOutSz); // extract and validate vout const std::string& strVout = vStrInputParts[1]; int64_t vout; if (!ParseInt64(strVout, &vout) || vout < 0 || vout > static_cast<int64_t>(maxVout)) throw std::runtime_error("invalid TX input vout '" + strVout + "'"); // extract the optional sequence number uint32_t nSequenceIn = CTxIn::SEQUENCE_FINAL; if (vStrInputParts.size() > 2) { nSequenceIn = TrimAndParse<uint32_t>(vStrInputParts.at(2), "invalid TX sequence id"); } // append to transaction input list CTxIn txin(Txid::FromUint256(txid), vout, CScript(), nSequenceIn); tx.vin.push_back(txin); } static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput) { // Separate into VALUE:ADDRESS std::vector<std::string> vStrInputParts = SplitString(strInput, ':'); if (vStrInputParts.size() != 2) throw std::runtime_error("TX output missing or too many separators"); // Extract and validate VALUE CAmount value = ExtractAndValidateValue(vStrInputParts[0]); // extract and validate ADDRESS std::string strAddr = vStrInputParts[1]; CTxDestination destination = DecodeDestination(strAddr); if (!IsValidDestination(destination)) { throw std::runtime_error("invalid TX output address"); } CScript scriptPubKey = GetScriptForDestination(destination); // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& strInput) { // Separate into VALUE:PUBKEY[:FLAGS] std::vector<std::string> vStrInputParts = SplitString(strInput, ':'); if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3) throw std::runtime_error("TX output missing or too many separators"); // Extract and validate VALUE CAmount value = ExtractAndValidateValue(vStrInputParts[0]); // Extract and validate PUBKEY CPubKey pubkey(ParseHex(vStrInputParts[1])); if (!pubkey.IsFullyValid()) throw std::runtime_error("invalid TX output pubkey"); CScript scriptPubKey = GetScriptForRawPubKey(pubkey); // Extract and validate FLAGS bool bSegWit = false; bool bScriptHash = false; if (vStrInputParts.size() == 3) { std::string flags = vStrInputParts[2]; bSegWit = (flags.find('W') != std::string::npos); bScriptHash = (flags.find('S') != std::string::npos); } if (bSegWit) { if (!pubkey.IsCompressed()) { throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs"); } // Build a P2WPKH script scriptPubKey = GetScriptForDestination(WitnessV0KeyHash(pubkey)); } if (bScriptHash) { // Get the ID for the script, and then construct a P2SH destination for it. scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey)); } // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput) { // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS] std::vector<std::string> vStrInputParts = SplitString(strInput, ':'); // Check that there are enough parameters if (vStrInputParts.size()<3) throw std::runtime_error("Not enough multisig parameters"); // Extract and validate VALUE CAmount value = ExtractAndValidateValue(vStrInputParts[0]); // Extract REQUIRED const uint32_t required{TrimAndParse<uint32_t>(vStrInputParts.at(1), "invalid multisig required number")}; // Extract NUMKEYS const uint32_t numkeys{TrimAndParse<uint32_t>(vStrInputParts.at(2), "invalid multisig total number")}; // Validate there are the correct number of pubkeys if (vStrInputParts.size() < numkeys + 3) throw std::runtime_error("incorrect number of multisig pubkeys"); if (required < 1 || required > MAX_PUBKEYS_PER_MULTISIG || numkeys < 1 || numkeys > MAX_PUBKEYS_PER_MULTISIG || numkeys < required) throw std::runtime_error("multisig parameter mismatch. Required " \ + ToString(required) + " of " + ToString(numkeys) + "signatures."); // extract and validate PUBKEYs std::vector<CPubKey> pubkeys; for(int pos = 1; pos <= int(numkeys); pos++) { CPubKey pubkey(ParseHex(vStrInputParts[pos + 2])); if (!pubkey.IsFullyValid()) throw std::runtime_error("invalid TX output pubkey"); pubkeys.push_back(pubkey); } // Extract FLAGS bool bSegWit = false; bool bScriptHash = false; if (vStrInputParts.size() == numkeys + 4) { std::string flags = vStrInputParts.back(); bSegWit = (flags.find('W') != std::string::npos); bScriptHash = (flags.find('S') != std::string::npos); } else if (vStrInputParts.size() > numkeys + 4) { // Validate that there were no more parameters passed throw std::runtime_error("Too many parameters"); } CScript scriptPubKey = GetScriptForMultisig(required, pubkeys); if (bSegWit) { for (const CPubKey& pubkey : pubkeys) { if (!pubkey.IsCompressed()) { throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs"); } } // Build a P2WSH with the multisig script scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(scriptPubKey)); } if (bScriptHash) { if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) { throw std::runtime_error(strprintf( "redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE)); } // Get the ID for the script, and then construct a P2SH destination for it. scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey)); } // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput) { CAmount value = 0; // separate [VALUE:]DATA in string size_t pos = strInput.find(':'); if (pos==0) throw std::runtime_error("TX output value not specified"); if (pos == std::string::npos) { pos = 0; } else { // Extract and validate VALUE value = ExtractAndValidateValue(strInput.substr(0, pos)); ++pos; } // extract and validate DATA const std::string strData{strInput.substr(pos, std::string::npos)}; if (!IsHex(strData)) throw std::runtime_error("invalid TX output data"); std::vector<unsigned char> data = ParseHex(strData); CTxOut txout(value, CScript() << OP_RETURN << data); tx.vout.push_back(txout); } static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput) { // separate VALUE:SCRIPT[:FLAGS] std::vector<std::string> vStrInputParts = SplitString(strInput, ':'); if (vStrInputParts.size() < 2) throw std::runtime_error("TX output missing separator"); // Extract and validate VALUE CAmount value = ExtractAndValidateValue(vStrInputParts[0]); // extract and validate script std::string strScript = vStrInputParts[1]; CScript scriptPubKey = ParseScript(strScript); // Extract FLAGS bool bSegWit = false; bool bScriptHash = false; if (vStrInputParts.size() == 3) { std::string flags = vStrInputParts.back(); bSegWit = (flags.find('W') != std::string::npos); bScriptHash = (flags.find('S') != std::string::npos); } if (scriptPubKey.size() > MAX_SCRIPT_SIZE) { throw std::runtime_error(strprintf( "script exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_SIZE)); } if (bSegWit) { scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(scriptPubKey)); } if (bScriptHash) { if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) { throw std::runtime_error(strprintf( "redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE)); } scriptPubKey = GetScriptForDestination(ScriptHash(scriptPubKey)); } // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx) { // parse requested deletion index int64_t inIdx; if (!ParseInt64(strInIdx, &inIdx) || inIdx < 0 || inIdx >= static_cast<int64_t>(tx.vin.size())) { throw std::runtime_error("Invalid TX input index '" + strInIdx + "'"); } // delete input from transaction tx.vin.erase(tx.vin.begin() + inIdx); } static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx) { // parse requested deletion index int64_t outIdx; if (!ParseInt64(strOutIdx, &outIdx) || outIdx < 0 || outIdx >= static_cast<int64_t>(tx.vout.size())) { throw std::runtime_error("Invalid TX output index '" + strOutIdx + "'"); } // delete output from transaction tx.vout.erase(tx.vout.begin() + outIdx); } static const unsigned int N_SIGHASH_OPTS = 7; static const struct { const char *flagStr; int flags; } sighashOptions[N_SIGHASH_OPTS] = { {"DEFAULT", SIGHASH_DEFAULT}, {"ALL", SIGHASH_ALL}, {"NONE", SIGHASH_NONE}, {"SINGLE", SIGHASH_SINGLE}, {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY}, {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY}, {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY}, }; static bool findSighashFlags(int& flags, const std::string& flagStr) { flags = 0; for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) { if (flagStr == sighashOptions[i].flagStr) { flags = sighashOptions[i].flags; return true; } } return false; } static CAmount AmountFromValue(const UniValue& value) { if (!value.isNum() && !value.isStr()) throw std::runtime_error("Amount is not a number or string"); CAmount amount; if (!ParseFixedPoint(value.getValStr(), 8, &amount)) throw std::runtime_error("Invalid amount"); if (!MoneyRange(amount)) throw std::runtime_error("Amount out of range"); return amount; } static std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName) { std::string strHex; if (v.isStr()) strHex = v.getValStr(); if (!IsHex(strHex)) throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')"); return ParseHex(strHex); } static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr) { int nHashType = SIGHASH_ALL; if (flagStr.size() > 0) if (!findSighashFlags(nHashType, flagStr)) throw std::runtime_error("unknown sighash flag/sign option"); // mergedTx will end up with all the signatures; it // starts as a clone of the raw tx: CMutableTransaction mergedTx{tx}; const CMutableTransaction txv{tx}; CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); if (!registers.count("privatekeys")) throw std::runtime_error("privatekeys register variable must be set."); FillableSigningProvider tempKeystore; UniValue keysObj = registers["privatekeys"]; for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) { if (!keysObj[kidx].isStr()) throw std::runtime_error("privatekey not a std::string"); CKey key = DecodeSecret(keysObj[kidx].getValStr()); if (!key.IsValid()) { throw std::runtime_error("privatekey not valid"); } tempKeystore.AddKey(key); } // Add previous txouts given in the RPC call: if (!registers.count("prevtxs")) throw std::runtime_error("prevtxs register variable must be set."); UniValue prevtxsObj = registers["prevtxs"]; { for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) { const UniValue& prevOut = prevtxsObj[previdx]; if (!prevOut.isObject()) throw std::runtime_error("expected prevtxs internal object"); std::map<std::string, UniValue::VType> types = { {"txid", UniValue::VSTR}, {"vout", UniValue::VNUM}, {"scriptPubKey", UniValue::VSTR}, }; if (!prevOut.checkObject(types)) throw std::runtime_error("prevtxs internal object typecheck fail"); uint256 txid; if (!ParseHashStr(prevOut["txid"].get_str(), txid)) { throw std::runtime_error("txid must be hexadecimal string (not '" + prevOut["txid"].get_str() + "')"); } const int nOut = prevOut["vout"].getInt<int>(); if (nOut < 0) throw std::runtime_error("vout cannot be negative"); COutPoint out(Txid::FromUint256(txid), nOut); std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); { const Coin& coin = view.AccessCoin(out); if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) { std::string err("Previous output scriptPubKey mismatch:\n"); err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+ ScriptToAsmStr(scriptPubKey); throw std::runtime_error(err); } Coin newcoin; newcoin.out.scriptPubKey = scriptPubKey; newcoin.out.nValue = MAX_MONEY; if (prevOut.exists("amount")) { newcoin.out.nValue = AmountFromValue(prevOut["amount"]); } newcoin.nHeight = 1; view.AddCoin(out, std::move(newcoin), true); } // if redeemScript given and private keys given, // add redeemScript to the tempKeystore so it can be signed: if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) && prevOut.exists("redeemScript")) { UniValue v = prevOut["redeemScript"]; std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript")); CScript redeemScript(rsData.begin(), rsData.end()); tempKeystore.AddCScript(redeemScript); } } } const FillableSigningProvider& keystore = tempKeystore; bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; const Coin& coin = view.AccessCoin(txin.prevout); if (coin.IsSpent()) { continue; } const CScript& prevPubKey = coin.out.scriptPubKey; const CAmount& amount = coin.out.nValue; SignatureData sigdata = DataFromTransaction(mergedTx, i, coin.out); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) ProduceSignature(keystore, MutableTransactionSignatureCreator(mergedTx, i, amount, nHashType), prevPubKey, sigdata); if (amount == MAX_MONEY && !sigdata.scriptWitness.IsNull()) { throw std::runtime_error(strprintf("Missing amount for CTxOut with scriptPubKey=%s", HexStr(prevPubKey))); } UpdateInput(txin, sigdata); } tx = mergedTx; } class Secp256k1Init { public: Secp256k1Init() { ECC_Start(); } ~Secp256k1Init() { ECC_Stop(); } }; static void MutateTx(CMutableTransaction& tx, const std::string& command, const std::string& commandVal) { std::unique_ptr<Secp256k1Init> ecc; if (command == "nversion") MutateTxVersion(tx, commandVal); else if (command == "locktime") MutateTxLocktime(tx, commandVal); else if (command == "replaceable") { MutateTxRBFOptIn(tx, commandVal); } else if (command == "delin") MutateTxDelInput(tx, commandVal); else if (command == "in") MutateTxAddInput(tx, commandVal); else if (command == "delout") MutateTxDelOutput(tx, commandVal); else if (command == "outaddr") MutateTxAddOutAddr(tx, commandVal); else if (command == "outpubkey") { ecc.reset(new Secp256k1Init()); MutateTxAddOutPubKey(tx, commandVal); } else if (command == "outmultisig") { ecc.reset(new Secp256k1Init()); MutateTxAddOutMultiSig(tx, commandVal); } else if (command == "outscript") MutateTxAddOutScript(tx, commandVal); else if (command == "outdata") MutateTxAddOutData(tx, commandVal); else if (command == "sign") { ecc.reset(new Secp256k1Init()); MutateTxSign(tx, commandVal); } else if (command == "load") RegisterLoad(commandVal); else if (command == "set") RegisterSet(commandVal); else throw std::runtime_error("unknown command"); } static void OutputTxJSON(const CTransaction& tx) { UniValue entry(UniValue::VOBJ); TxToUniv(tx, /*block_hash=*/uint256(), entry); std::string jsonOutput = entry.write(4); tfm::format(std::cout, "%s\n", jsonOutput); } static void OutputTxHash(const CTransaction& tx) { std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id) tfm::format(std::cout, "%s\n", strHexHash); } static void OutputTxHex(const CTransaction& tx) { std::string strHex = EncodeHexTx(tx); tfm::format(std::cout, "%s\n", strHex); } static void OutputTx(const CTransaction& tx) { if (gArgs.GetBoolArg("-json", false)) OutputTxJSON(tx); else if (gArgs.GetBoolArg("-txid", false)) OutputTxHash(tx); else OutputTxHex(tx); } static std::string readStdin() { char buf[4096]; std::string ret; while (!feof(stdin)) { size_t bread = fread(buf, 1, sizeof(buf), stdin); ret.append(buf, bread); if (bread < sizeof(buf)) break; } if (ferror(stdin)) throw std::runtime_error("error reading stdin"); return TrimString(ret); } static int CommandLineRawTx(int argc, char* argv[]) { std::string strPrint; int nRet = 0; try { // Skip switches; Permit common stdin convention "-" while (argc > 1 && IsSwitchChar(argv[1][0]) && (argv[1][1] != 0)) { argc--; argv++; } CMutableTransaction tx; int startArg; if (!fCreateBlank) { // require at least one param if (argc < 2) throw std::runtime_error("too few parameters"); // param: hex-encoded bitcoin transaction std::string strHexTx(argv[1]); if (strHexTx == "-") // "-" implies standard input strHexTx = readStdin(); if (!DecodeHexTx(tx, strHexTx, true)) throw std::runtime_error("invalid transaction encoding"); startArg = 2; } else startArg = 1; for (int i = startArg; i < argc; i++) { std::string arg = argv[i]; std::string key, value; size_t eqpos = arg.find('='); if (eqpos == std::string::npos) key = arg; else { key = arg.substr(0, eqpos); value = arg.substr(eqpos + 1); } MutateTx(tx, key, value); } OutputTx(CTransaction(tx)); } catch (const std::exception& e) { strPrint = std::string("error: ") + e.what(); nRet = EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "CommandLineRawTx()"); throw; } if (strPrint != "") { tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint); } return nRet; } MAIN_FUNCTION { SetupEnvironment(); try { int ret = AppInitRawTx(argc, argv); if (ret != CONTINUE_EXECUTION) return ret; } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInitRawTx()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "AppInitRawTx()"); return EXIT_FAILURE; } int ret = EXIT_FAILURE; try { ret = CommandLineRawTx(argc, argv); } catch (const std::exception& e) { PrintExceptionContinue(&e, "CommandLineRawTx()"); } catch (...) { PrintExceptionContinue(nullptr, "CommandLineRawTx()"); } return ret; }
0
bitcoin
bitcoin/src/mapport.h
// Copyright (c) 2011-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_MAPPORT_H #define BITCOIN_MAPPORT_H static constexpr bool DEFAULT_UPNP = false; static constexpr bool DEFAULT_NATPMP = false; enum MapPortProtoFlag : unsigned int { NONE = 0x00, UPNP = 0x01, NAT_PMP = 0x02, }; void StartMapPort(bool use_upnp, bool use_natpmp); void InterruptMapPort(); void StopMapPort(); #endif // BITCOIN_MAPPORT_H
0
bitcoin
bitcoin/src/Makefile.am
# Copyright (c) 2013-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # Pattern rule to print variables, e.g. make print-top_srcdir print-%: FORCE @echo '$*'='$($*)' DIST_SUBDIRS = secp256k1 AM_LDFLAGS = $(LIBTOOL_LDFLAGS) $(HARDENED_LDFLAGS) $(GPROF_LDFLAGS) $(SANITIZER_LDFLAGS) $(LTO_LDFLAGS) $(CORE_LDFLAGS) AM_CXXFLAGS = $(DEBUG_CXXFLAGS) $(HARDENED_CXXFLAGS) $(WARN_CXXFLAGS) $(NOWARN_CXXFLAGS) $(ERROR_CXXFLAGS) $(GPROF_CXXFLAGS) $(SANITIZER_CXXFLAGS) $(LTO_CXXFLAGS) $(CORE_CXXFLAGS) AM_CPPFLAGS = $(DEBUG_CPPFLAGS) $(HARDENED_CPPFLAGS) $(CORE_CPPFLAGS) AM_LIBTOOLFLAGS = --preserve-dup-deps PTHREAD_FLAGS = $(PTHREAD_CFLAGS) $(PTHREAD_LIBS) EXTRA_LIBRARIES = lib_LTLIBRARIES = noinst_LTLIBRARIES = bin_PROGRAMS = noinst_PROGRAMS = check_PROGRAMS = TESTS = BENCHMARKS = BITCOIN_INCLUDES=-I$(builddir) -I$(srcdir)/$(MINISKETCH_INCLUDE_DIR_INT) -I$(srcdir)/secp256k1/include -I$(srcdir)/$(UNIVALUE_INCLUDE_DIR_INT) LIBBITCOIN_NODE=libbitcoin_node.a LIBBITCOIN_COMMON=libbitcoin_common.a LIBBITCOIN_CONSENSUS=libbitcoin_consensus.a LIBBITCOIN_CLI=libbitcoin_cli.a LIBBITCOIN_UTIL=libbitcoin_util.a LIBBITCOIN_CRYPTO_BASE=crypto/libbitcoin_crypto_base.la LIBBITCOINQT=qt/libbitcoinqt.a LIBSECP256K1=secp256k1/libsecp256k1.la if ENABLE_ZMQ LIBBITCOIN_ZMQ=libbitcoin_zmq.a endif if BUILD_BITCOIN_LIBS LIBBITCOINCONSENSUS=libbitcoinconsensus.la endif if BUILD_BITCOIN_KERNEL_LIB LIBBITCOINKERNEL=libbitcoinkernel.la endif if ENABLE_WALLET LIBBITCOIN_WALLET=libbitcoin_wallet.a LIBBITCOIN_WALLET_TOOL=libbitcoin_wallet_tool.a endif LIBBITCOIN_CRYPTO = $(LIBBITCOIN_CRYPTO_BASE) if ENABLE_SSE41 LIBBITCOIN_CRYPTO_SSE41 = crypto/libbitcoin_crypto_sse41.la LIBBITCOIN_CRYPTO += $(LIBBITCOIN_CRYPTO_SSE41) endif if ENABLE_AVX2 LIBBITCOIN_CRYPTO_AVX2 = crypto/libbitcoin_crypto_avx2.la LIBBITCOIN_CRYPTO += $(LIBBITCOIN_CRYPTO_AVX2) endif if ENABLE_X86_SHANI LIBBITCOIN_CRYPTO_X86_SHANI = crypto/libbitcoin_crypto_x86_shani.la LIBBITCOIN_CRYPTO += $(LIBBITCOIN_CRYPTO_X86_SHANI) endif if ENABLE_ARM_SHANI LIBBITCOIN_CRYPTO_ARM_SHANI = crypto/libbitcoin_crypto_arm_shani.la LIBBITCOIN_CRYPTO += $(LIBBITCOIN_CRYPTO_ARM_SHANI) endif noinst_LTLIBRARIES += $(LIBBITCOIN_CRYPTO) $(LIBSECP256K1): $(wildcard secp256k1/src/*.h) $(wildcard secp256k1/src/*.c) $(wildcard secp256k1/include/*) $(AM_V_at)$(MAKE) $(AM_MAKEFLAGS) -C $(@D) $(@F) # Make is not made aware of per-object dependencies to avoid limiting building parallelization # But to build the less dependent modules first, we manually select their order here: EXTRA_LIBRARIES += \ $(LIBBITCOIN_UTIL) \ $(LIBBITCOIN_COMMON) \ $(LIBBITCOIN_CONSENSUS) \ $(LIBBITCOIN_NODE) \ $(LIBBITCOIN_CLI) \ $(LIBBITCOIN_IPC) \ $(LIBBITCOIN_WALLET) \ $(LIBBITCOIN_WALLET_TOOL) \ $(LIBBITCOIN_ZMQ) if BUILD_BITCOIND bin_PROGRAMS += bitcoind endif if BUILD_BITCOIN_NODE bin_PROGRAMS += bitcoin-node endif if BUILD_BITCOIN_CLI bin_PROGRAMS += bitcoin-cli endif if BUILD_BITCOIN_TX bin_PROGRAMS += bitcoin-tx endif if ENABLE_WALLET if BUILD_BITCOIN_WALLET bin_PROGRAMS += bitcoin-wallet endif endif if BUILD_BITCOIN_UTIL bin_PROGRAMS += bitcoin-util endif if BUILD_BITCOIN_CHAINSTATE bin_PROGRAMS += bitcoin-chainstate endif .PHONY: FORCE check-symbols check-security # bitcoin core # BITCOIN_CORE_H = \ addresstype.h \ addrdb.h \ addrman.h \ addrman_impl.h \ attributes.h \ banman.h \ base58.h \ bech32.h \ bip324.h \ blockencodings.h \ blockfilter.h \ chain.h \ chainparams.h \ chainparamsbase.h \ chainparamsseeds.h \ checkqueue.h \ clientversion.h \ coins.h \ common/args.h \ common/bloom.h \ common/init.h \ common/run_command.h \ common/url.h \ compat/assumptions.h \ compat/byteswap.h \ compat/compat.h \ compat/cpuid.h \ compat/endian.h \ common/settings.h \ common/system.h \ compressor.h \ consensus/consensus.h \ consensus/tx_check.h \ consensus/tx_verify.h \ core_io.h \ core_memusage.h \ cuckoocache.h \ dbwrapper.h \ deploymentinfo.h \ deploymentstatus.h \ external_signer.h \ flatfile.h \ headerssync.h \ httprpc.h \ httpserver.h \ i2p.h \ index/base.h \ index/blockfilterindex.h \ index/coinstatsindex.h \ index/disktxpos.h \ index/txindex.h \ indirectmap.h \ init.h \ init/common.h \ interfaces/chain.h \ interfaces/echo.h \ interfaces/handler.h \ interfaces/init.h \ interfaces/ipc.h \ interfaces/node.h \ interfaces/wallet.h \ kernel/blockmanager_opts.h \ kernel/chain.h \ kernel/chainparams.h \ kernel/chainstatemanager_opts.h \ kernel/checks.h \ kernel/coinstats.h \ kernel/context.h \ kernel/cs_main.h \ kernel/disconnected_transactions.h \ kernel/mempool_entry.h \ kernel/mempool_limits.h \ kernel/mempool_options.h \ kernel/mempool_persist.h \ kernel/mempool_removal_reason.h \ kernel/messagestartchars.h \ kernel/notifications_interface.h \ kernel/validation_cache_sizes.h \ key.h \ key_io.h \ logging.h \ logging/timer.h \ mapport.h \ memusage.h \ merkleblock.h \ net.h \ net_permissions.h \ net_processing.h \ net_types.h \ netaddress.h \ netbase.h \ netgroup.h \ netmessagemaker.h \ node/abort.h \ node/blockmanager_args.h \ node/blockstorage.h \ node/caches.h \ node/chainstate.h \ node/chainstatemanager_args.h \ node/coin.h \ node/coins_view_args.h \ node/connection_types.h \ node/context.h \ node/database_args.h \ node/eviction.h \ node/interface_ui.h \ node/kernel_notifications.h \ node/mempool_args.h \ node/mempool_persist_args.h \ node/miner.h \ node/mini_miner.h \ node/minisketchwrapper.h \ node/peerman_args.h \ node/protocol_version.h \ node/psbt.h \ node/transaction.h \ node/txreconciliation.h \ node/utxo_snapshot.h \ node/validation_cache_args.h \ noui.h \ outputtype.h \ policy/feerate.h \ policy/fees.h \ policy/fees_args.h \ policy/packages.h \ policy/policy.h \ policy/rbf.h \ policy/settings.h \ pow.h \ protocol.h \ psbt.h \ random.h \ randomenv.h \ rest.h \ reverse_iterator.h \ rpc/blockchain.h \ rpc/client.h \ rpc/mempool.h \ rpc/mining.h \ rpc/protocol.h \ rpc/rawtransaction_util.h \ rpc/register.h \ rpc/request.h \ rpc/server.h \ rpc/server_util.h \ rpc/util.h \ scheduler.h \ script/descriptor.h \ script/keyorigin.h \ script/miniscript.h \ script/sigcache.h \ script/sign.h \ script/signingprovider.h \ script/solver.h \ signet.h \ streams.h \ support/allocators/pool.h \ support/allocators/secure.h \ support/allocators/zeroafterfree.h \ support/cleanse.h \ support/events.h \ support/lockedpool.h \ sync.h \ threadsafety.h \ timedata.h \ torcontrol.h \ txdb.h \ txmempool.h \ txorphanage.h \ txrequest.h \ undo.h \ util/any.h \ util/asmap.h \ util/batchpriority.h \ util/bip32.h \ util/bitdeque.h \ util/bytevectorhash.h \ util/chaintype.h \ util/check.h \ util/epochguard.h \ util/error.h \ util/exception.h \ util/fastrange.h \ util/fees.h \ util/fs.h \ util/fs_helpers.h \ util/golombrice.h \ util/hash_type.h \ util/hasher.h \ util/insert.h \ util/macros.h \ util/message.h \ util/moneystr.h \ util/overflow.h \ util/overloaded.h \ util/rbf.h \ util/readwritefile.h \ util/result.h \ util/serfloat.h \ util/signalinterrupt.h \ util/sock.h \ util/spanparsing.h \ util/string.h \ util/syserror.h \ util/thread.h \ util/threadinterrupt.h \ util/threadnames.h \ util/time.h \ util/tokenpipe.h \ util/trace.h \ util/transaction_identifier.h \ util/translation.h \ util/types.h \ util/ui_change_type.h \ util/vector.h \ validation.h \ validationinterface.h \ versionbits.h \ wallet/bdb.h \ wallet/coincontrol.h \ wallet/coinselection.h \ wallet/context.h \ wallet/crypter.h \ wallet/db.h \ wallet/dump.h \ wallet/external_signer_scriptpubkeyman.h \ wallet/feebumper.h \ wallet/fees.h \ wallet/load.h \ wallet/receive.h \ wallet/rpc/util.h \ wallet/rpc/wallet.h \ wallet/salvage.h \ wallet/scriptpubkeyman.h \ wallet/spend.h \ wallet/sqlite.h \ wallet/transaction.h \ wallet/types.h \ wallet/wallet.h \ wallet/walletdb.h \ wallet/wallettool.h \ wallet/walletutil.h \ walletinitinterface.h \ warnings.h \ zmq/zmqabstractnotifier.h \ zmq/zmqnotificationinterface.h \ zmq/zmqpublishnotifier.h \ zmq/zmqrpc.h \ zmq/zmqutil.h obj/build.h: FORCE @$(MKDIR_P) $(builddir)/obj $(AM_V_GEN) $(top_srcdir)/share/genbuild.sh "$(abs_top_builddir)/src/obj/build.h" \ "$(abs_top_srcdir)" libbitcoin_util_a-clientversion.$(OBJEXT): obj/build.h # node # libbitcoin_node_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(LEVELDB_CPPFLAGS) $(BOOST_CPPFLAGS) $(MINIUPNPC_CPPFLAGS) $(NATPMP_CPPFLAGS) $(EVENT_CFLAGS) $(EVENT_PTHREADS_CFLAGS) libbitcoin_node_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libbitcoin_node_a_SOURCES = \ addrdb.cpp \ addrman.cpp \ banman.cpp \ bip324.cpp \ blockencodings.cpp \ blockfilter.cpp \ chain.cpp \ consensus/tx_verify.cpp \ dbwrapper.cpp \ deploymentstatus.cpp \ flatfile.cpp \ headerssync.cpp \ httprpc.cpp \ httpserver.cpp \ i2p.cpp \ index/base.cpp \ index/blockfilterindex.cpp \ index/coinstatsindex.cpp \ index/txindex.cpp \ init.cpp \ kernel/chain.cpp \ kernel/checks.cpp \ kernel/coinstats.cpp \ kernel/context.cpp \ kernel/cs_main.cpp \ kernel/disconnected_transactions.cpp \ kernel/mempool_persist.cpp \ kernel/mempool_removal_reason.cpp \ mapport.cpp \ net.cpp \ net_processing.cpp \ netgroup.cpp \ node/abort.cpp \ node/blockmanager_args.cpp \ node/blockstorage.cpp \ node/caches.cpp \ node/chainstate.cpp \ node/chainstatemanager_args.cpp \ node/coin.cpp \ node/coins_view_args.cpp \ node/connection_types.cpp \ node/context.cpp \ node/database_args.cpp \ node/eviction.cpp \ node/interface_ui.cpp \ node/interfaces.cpp \ node/kernel_notifications.cpp \ node/mempool_args.cpp \ node/mempool_persist_args.cpp \ node/miner.cpp \ node/mini_miner.cpp \ node/minisketchwrapper.cpp \ node/peerman_args.cpp \ node/psbt.cpp \ node/transaction.cpp \ node/txreconciliation.cpp \ node/utxo_snapshot.cpp \ node/validation_cache_args.cpp \ noui.cpp \ policy/fees.cpp \ policy/fees_args.cpp \ policy/packages.cpp \ policy/rbf.cpp \ policy/settings.cpp \ pow.cpp \ rest.cpp \ rpc/blockchain.cpp \ rpc/fees.cpp \ rpc/mempool.cpp \ rpc/mining.cpp \ rpc/net.cpp \ rpc/node.cpp \ rpc/output_script.cpp \ rpc/rawtransaction.cpp \ rpc/server.cpp \ rpc/server_util.cpp \ rpc/signmessage.cpp \ rpc/txoutproof.cpp \ script/sigcache.cpp \ signet.cpp \ timedata.cpp \ torcontrol.cpp \ txdb.cpp \ txmempool.cpp \ txorphanage.cpp \ txrequest.cpp \ validation.cpp \ validationinterface.cpp \ versionbits.cpp \ $(BITCOIN_CORE_H) if ENABLE_WALLET libbitcoin_node_a_SOURCES += wallet/init.cpp libbitcoin_node_a_CPPFLAGS += $(BDB_CPPFLAGS) endif if !ENABLE_WALLET libbitcoin_node_a_SOURCES += dummywallet.cpp endif # # zmq # if ENABLE_ZMQ libbitcoin_zmq_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(ZMQ_CFLAGS) libbitcoin_zmq_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libbitcoin_zmq_a_SOURCES = \ zmq/zmqabstractnotifier.cpp \ zmq/zmqnotificationinterface.cpp \ zmq/zmqpublishnotifier.cpp \ zmq/zmqrpc.cpp \ zmq/zmqutil.cpp endif # # wallet # libbitcoin_wallet_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BOOST_CPPFLAGS) $(BDB_CPPFLAGS) $(SQLITE_CFLAGS) libbitcoin_wallet_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libbitcoin_wallet_a_SOURCES = \ wallet/coincontrol.cpp \ wallet/context.cpp \ wallet/crypter.cpp \ wallet/db.cpp \ wallet/dump.cpp \ wallet/external_signer_scriptpubkeyman.cpp \ wallet/feebumper.cpp \ wallet/fees.cpp \ wallet/interfaces.cpp \ wallet/load.cpp \ wallet/receive.cpp \ wallet/rpc/addresses.cpp \ wallet/rpc/backup.cpp \ wallet/rpc/coins.cpp \ wallet/rpc/encrypt.cpp \ wallet/rpc/spend.cpp \ wallet/rpc/signmessage.cpp \ wallet/rpc/transactions.cpp \ wallet/rpc/util.cpp \ wallet/rpc/wallet.cpp \ wallet/scriptpubkeyman.cpp \ wallet/spend.cpp \ wallet/transaction.cpp \ wallet/wallet.cpp \ wallet/walletdb.cpp \ wallet/walletutil.cpp \ wallet/coinselection.cpp \ $(BITCOIN_CORE_H) if USE_SQLITE libbitcoin_wallet_a_SOURCES += wallet/sqlite.cpp endif if USE_BDB libbitcoin_wallet_a_SOURCES += wallet/bdb.cpp wallet/salvage.cpp endif # # wallet tool # libbitcoin_wallet_tool_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BOOST_CPPFLAGS) libbitcoin_wallet_tool_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libbitcoin_wallet_tool_a_SOURCES = \ wallet/wallettool.cpp \ $(BITCOIN_CORE_H) # # crypto # crypto_libbitcoin_crypto_base_la_CPPFLAGS = $(AM_CPPFLAGS) # Specify -static in both CXXFLAGS and LDFLAGS so libtool will only build a # static version of this library. We don't need a dynamic version, and a dynamic # version can't be used on windows anyway because the library doesn't currently # export DLL symbols. crypto_libbitcoin_crypto_base_la_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) -static crypto_libbitcoin_crypto_base_la_LDFLAGS = $(AM_LDFLAGS) -static crypto_libbitcoin_crypto_base_la_SOURCES = \ crypto/aes.cpp \ crypto/aes.h \ crypto/chacha20.h \ crypto/chacha20.cpp \ crypto/chacha20poly1305.h \ crypto/chacha20poly1305.cpp \ crypto/common.h \ crypto/hkdf_sha256_32.cpp \ crypto/hkdf_sha256_32.h \ crypto/hmac_sha256.cpp \ crypto/hmac_sha256.h \ crypto/hmac_sha512.cpp \ crypto/hmac_sha512.h \ crypto/poly1305.h \ crypto/poly1305.cpp \ crypto/muhash.h \ crypto/muhash.cpp \ crypto/ripemd160.cpp \ crypto/ripemd160.h \ crypto/sha1.cpp \ crypto/sha1.h \ crypto/sha256.cpp \ crypto/sha256.h \ crypto/sha3.cpp \ crypto/sha3.h \ crypto/sha512.cpp \ crypto/sha512.h \ crypto/siphash.cpp \ crypto/siphash.h if USE_ASM crypto_libbitcoin_crypto_base_la_SOURCES += crypto/sha256_sse4.cpp endif # See explanation for -static in crypto_libbitcoin_crypto_base_la's LDFLAGS and # CXXFLAGS above crypto_libbitcoin_crypto_sse41_la_LDFLAGS = $(AM_LDFLAGS) -static crypto_libbitcoin_crypto_sse41_la_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) -static crypto_libbitcoin_crypto_sse41_la_CPPFLAGS = $(AM_CPPFLAGS) crypto_libbitcoin_crypto_sse41_la_CXXFLAGS += $(SSE41_CXXFLAGS) crypto_libbitcoin_crypto_sse41_la_CPPFLAGS += -DENABLE_SSE41 crypto_libbitcoin_crypto_sse41_la_SOURCES = crypto/sha256_sse41.cpp # See explanation for -static in crypto_libbitcoin_crypto_base_la's LDFLAGS and # CXXFLAGS above crypto_libbitcoin_crypto_avx2_la_LDFLAGS = $(AM_LDFLAGS) -static crypto_libbitcoin_crypto_avx2_la_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) -static crypto_libbitcoin_crypto_avx2_la_CPPFLAGS = $(AM_CPPFLAGS) crypto_libbitcoin_crypto_avx2_la_CXXFLAGS += $(AVX2_CXXFLAGS) crypto_libbitcoin_crypto_avx2_la_CPPFLAGS += -DENABLE_AVX2 crypto_libbitcoin_crypto_avx2_la_SOURCES = crypto/sha256_avx2.cpp # See explanation for -static in crypto_libbitcoin_crypto_base_la's LDFLAGS and # CXXFLAGS above crypto_libbitcoin_crypto_x86_shani_la_LDFLAGS = $(AM_LDFLAGS) -static crypto_libbitcoin_crypto_x86_shani_la_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) -static crypto_libbitcoin_crypto_x86_shani_la_CPPFLAGS = $(AM_CPPFLAGS) crypto_libbitcoin_crypto_x86_shani_la_CXXFLAGS += $(X86_SHANI_CXXFLAGS) crypto_libbitcoin_crypto_x86_shani_la_CPPFLAGS += -DENABLE_X86_SHANI crypto_libbitcoin_crypto_x86_shani_la_SOURCES = crypto/sha256_x86_shani.cpp # See explanation for -static in crypto_libbitcoin_crypto_base_la's LDFLAGS and # CXXFLAGS above crypto_libbitcoin_crypto_arm_shani_la_LDFLAGS = $(AM_LDFLAGS) -static crypto_libbitcoin_crypto_arm_shani_la_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) -static crypto_libbitcoin_crypto_arm_shani_la_CPPFLAGS = $(AM_CPPFLAGS) crypto_libbitcoin_crypto_arm_shani_la_CXXFLAGS += $(ARM_SHANI_CXXFLAGS) crypto_libbitcoin_crypto_arm_shani_la_CPPFLAGS += -DENABLE_ARM_SHANI crypto_libbitcoin_crypto_arm_shani_la_SOURCES = crypto/sha256_arm_shani.cpp # # consensus # libbitcoin_consensus_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) libbitcoin_consensus_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libbitcoin_consensus_a_SOURCES = \ arith_uint256.cpp \ arith_uint256.h \ consensus/amount.h \ consensus/merkle.cpp \ consensus/merkle.h \ consensus/params.h \ consensus/tx_check.cpp \ consensus/validation.h \ hash.cpp \ hash.h \ prevector.h \ primitives/block.cpp \ primitives/block.h \ primitives/transaction.cpp \ primitives/transaction.h \ pubkey.cpp \ pubkey.h \ script/bitcoinconsensus.cpp \ script/interpreter.cpp \ script/interpreter.h \ script/script.cpp \ script/script.h \ script/script_error.cpp \ script/script_error.h \ serialize.h \ span.h \ tinyformat.h \ uint256.cpp \ uint256.h \ util/strencodings.cpp \ util/strencodings.h # # common # libbitcoin_common_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BOOST_CPPFLAGS) libbitcoin_common_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libbitcoin_common_a_SOURCES = \ addresstype.cpp \ base58.cpp \ bech32.cpp \ chainparams.cpp \ coins.cpp \ common/args.cpp \ common/bloom.cpp \ common/config.cpp \ common/init.cpp \ common/interfaces.cpp \ common/run_command.cpp \ common/settings.cpp \ common/system.cpp \ compressor.cpp \ core_read.cpp \ core_write.cpp \ deploymentinfo.cpp \ external_signer.cpp \ init/common.cpp \ kernel/chainparams.cpp \ key.cpp \ key_io.cpp \ merkleblock.cpp \ net_types.cpp \ netaddress.cpp \ netbase.cpp \ net_permissions.cpp \ outputtype.cpp \ policy/feerate.cpp \ policy/policy.cpp \ protocol.cpp \ psbt.cpp \ rpc/external_signer.cpp \ rpc/rawtransaction_util.cpp \ rpc/request.cpp \ rpc/util.cpp \ scheduler.cpp \ script/descriptor.cpp \ script/miniscript.cpp \ script/sign.cpp \ script/signingprovider.cpp \ script/solver.cpp \ warnings.cpp \ $(BITCOIN_CORE_H) if USE_LIBEVENT libbitcoin_common_a_CPPFLAGS += $(EVENT_CFLAGS) libbitcoin_common_a_SOURCES += common/url.cpp endif # # util # libbitcoin_util_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) libbitcoin_util_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libbitcoin_util_a_SOURCES = \ support/lockedpool.cpp \ chainparamsbase.cpp \ clientversion.cpp \ logging.cpp \ random.cpp \ randomenv.cpp \ streams.cpp \ support/cleanse.cpp \ sync.cpp \ util/asmap.cpp \ util/batchpriority.cpp \ util/bip32.cpp \ util/bytevectorhash.cpp \ util/chaintype.cpp \ util/check.cpp \ util/error.cpp \ util/exception.cpp \ util/fees.cpp \ util/fs.cpp \ util/fs_helpers.cpp \ util/hasher.cpp \ util/sock.cpp \ util/syserror.cpp \ util/message.cpp \ util/moneystr.cpp \ util/rbf.cpp \ util/readwritefile.cpp \ util/signalinterrupt.cpp \ util/thread.cpp \ util/threadinterrupt.cpp \ util/threadnames.cpp \ util/serfloat.cpp \ util/spanparsing.cpp \ util/strencodings.cpp \ util/string.cpp \ util/time.cpp \ util/tokenpipe.cpp \ $(BITCOIN_CORE_H) # # cli # libbitcoin_cli_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) libbitcoin_cli_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libbitcoin_cli_a_SOURCES = \ compat/stdin.h \ compat/stdin.cpp \ rpc/client.cpp \ $(BITCOIN_CORE_H) nodist_libbitcoin_util_a_SOURCES = $(srcdir)/obj/build.h # # bitcoind & bitcoin-node binaries # bitcoin_daemon_sources = bitcoind.cpp bitcoin_bin_cppflags = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) bitcoin_bin_cxxflags = $(AM_CXXFLAGS) $(PIE_FLAGS) bitcoin_bin_ldflags = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) $(PTHREAD_FLAGS) if TARGET_WINDOWS bitcoin_daemon_sources += bitcoind-res.rc endif bitcoin_bin_ldadd = \ $(LIBBITCOIN_WALLET) \ $(LIBBITCOIN_COMMON) \ $(LIBBITCOIN_UTIL) \ $(LIBUNIVALUE) \ $(LIBBITCOIN_ZMQ) \ $(LIBBITCOIN_CONSENSUS) \ $(LIBBITCOIN_CRYPTO) \ $(LIBLEVELDB) \ $(LIBMEMENV) \ $(LIBSECP256K1) bitcoin_bin_ldadd += $(BDB_LIBS) $(MINIUPNPC_LIBS) $(NATPMP_LIBS) $(EVENT_PTHREADS_LIBS) $(EVENT_LIBS) $(ZMQ_LIBS) $(SQLITE_LIBS) bitcoind_SOURCES = $(bitcoin_daemon_sources) init/bitcoind.cpp bitcoind_CPPFLAGS = $(bitcoin_bin_cppflags) bitcoind_CXXFLAGS = $(bitcoin_bin_cxxflags) bitcoind_LDFLAGS = $(bitcoin_bin_ldflags) bitcoind_LDADD = $(LIBBITCOIN_NODE) $(bitcoin_bin_ldadd) bitcoin_node_SOURCES = $(bitcoin_daemon_sources) init/bitcoin-node.cpp bitcoin_node_CPPFLAGS = $(bitcoin_bin_cppflags) bitcoin_node_CXXFLAGS = $(bitcoin_bin_cxxflags) bitcoin_node_LDFLAGS = $(bitcoin_bin_ldflags) bitcoin_node_LDADD = $(LIBBITCOIN_NODE) $(bitcoin_bin_ldadd) $(LIBBITCOIN_IPC) $(LIBMULTIPROCESS_LIBS) # bitcoin-cli binary # bitcoin_cli_SOURCES = bitcoin-cli.cpp bitcoin_cli_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(EVENT_CFLAGS) bitcoin_cli_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) bitcoin_cli_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) $(PTHREAD_FLAGS) if TARGET_WINDOWS bitcoin_cli_SOURCES += bitcoin-cli-res.rc endif bitcoin_cli_LDADD = \ $(LIBBITCOIN_CLI) \ $(LIBUNIVALUE) \ $(LIBBITCOIN_COMMON) \ $(LIBBITCOIN_UTIL) \ $(LIBBITCOIN_CRYPTO) bitcoin_cli_LDADD += $(EVENT_LIBS) # # bitcoin-tx binary # bitcoin_tx_SOURCES = bitcoin-tx.cpp bitcoin_tx_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) bitcoin_tx_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) bitcoin_tx_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) $(PTHREAD_FLAGS) if TARGET_WINDOWS bitcoin_tx_SOURCES += bitcoin-tx-res.rc endif bitcoin_tx_LDADD = \ $(LIBUNIVALUE) \ $(LIBBITCOIN_COMMON) \ $(LIBBITCOIN_UTIL) \ $(LIBBITCOIN_CONSENSUS) \ $(LIBBITCOIN_CRYPTO) \ $(LIBSECP256K1) # # bitcoin-wallet binary # bitcoin_wallet_SOURCES = bitcoin-wallet.cpp bitcoin_wallet_SOURCES += init/bitcoin-wallet.cpp bitcoin_wallet_CPPFLAGS = $(bitcoin_bin_cppflags) bitcoin_wallet_CXXFLAGS = $(bitcoin_bin_cxxflags) bitcoin_wallet_LDFLAGS = $(bitcoin_bin_ldflags) bitcoin_wallet_LDADD = \ $(LIBBITCOIN_WALLET_TOOL) \ $(LIBBITCOIN_WALLET) \ $(LIBBITCOIN_COMMON) \ $(LIBBITCOIN_UTIL) \ $(LIBUNIVALUE) \ $(LIBBITCOIN_CONSENSUS) \ $(LIBBITCOIN_CRYPTO) \ $(LIBSECP256K1) \ $(BDB_LIBS) \ $(SQLITE_LIBS) if TARGET_WINDOWS bitcoin_wallet_SOURCES += bitcoin-wallet-res.rc endif # # bitcoin-util binary # bitcoin_util_SOURCES = bitcoin-util.cpp bitcoin_util_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) bitcoin_util_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) bitcoin_util_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) $(PTHREAD_FLAGS) if TARGET_WINDOWS bitcoin_util_SOURCES += bitcoin-util-res.rc endif bitcoin_util_LDADD = \ $(LIBBITCOIN_COMMON) \ $(LIBBITCOIN_UTIL) \ $(LIBUNIVALUE) \ $(LIBBITCOIN_CONSENSUS) \ $(LIBBITCOIN_CRYPTO) \ $(LIBSECP256K1) # # bitcoin-chainstate binary # bitcoin_chainstate_SOURCES = bitcoin-chainstate.cpp bitcoin_chainstate_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BOOST_CPPFLAGS) bitcoin_chainstate_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) bitcoin_chainstate_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(PTHREAD_FLAGS) $(LIBTOOL_APP_LDFLAGS) -static bitcoin_chainstate_LDADD = $(LIBBITCOINKERNEL) # libtool is unable to calculate this indirect dependency, presumably because it's a subproject. # libsecp256k1 only needs to be linked in when libbitcoinkernel is static. bitcoin_chainstate_LDADD += $(LIBSECP256K1) # # bitcoinkernel library # if BUILD_BITCOIN_KERNEL_LIB lib_LTLIBRARIES += $(LIBBITCOINKERNEL) libbitcoinkernel_la_LDFLAGS = $(AM_LDFLAGS) -no-undefined $(RELDFLAGS) $(PTHREAD_FLAGS) libbitcoinkernel_la_LIBADD = $(LIBBITCOIN_CRYPTO) $(LIBLEVELDB) $(LIBMEMENV) $(LIBSECP256K1) libbitcoinkernel_la_CPPFLAGS = $(AM_CPPFLAGS) -I$(builddir)/obj -I$(srcdir)/secp256k1/include -DBUILD_BITCOIN_INTERNAL $(BOOST_CPPFLAGS) $(LEVELDB_CPPFLAGS) # libbitcoinkernel requires default symbol visibility, explicitly specify that # here so that things still work even when user configures with # --enable-reduce-exports # # Note this is a quick hack that will be removed as we incrementally define what # to export from the library. libbitcoinkernel_la_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) -fvisibility=default # TODO: libbitcoinkernel is a work in progress consensus engine library, as more # and more modules are decoupled from the consensus engine, this list will # shrink to only those which are absolutely necessary. libbitcoinkernel_la_SOURCES = \ kernel/bitcoinkernel.cpp \ arith_uint256.cpp \ chain.cpp \ clientversion.cpp \ coins.cpp \ compressor.cpp \ consensus/merkle.cpp \ consensus/tx_check.cpp \ consensus/tx_verify.cpp \ core_read.cpp \ dbwrapper.cpp \ deploymentinfo.cpp \ deploymentstatus.cpp \ flatfile.cpp \ hash.cpp \ kernel/chain.cpp \ kernel/checks.cpp \ kernel/chainparams.cpp \ kernel/coinstats.cpp \ kernel/context.cpp \ kernel/cs_main.cpp \ kernel/disconnected_transactions.cpp \ kernel/mempool_persist.cpp \ kernel/mempool_removal_reason.cpp \ key.cpp \ logging.cpp \ node/blockstorage.cpp \ node/chainstate.cpp \ node/utxo_snapshot.cpp \ policy/feerate.cpp \ policy/packages.cpp \ policy/policy.cpp \ policy/rbf.cpp \ policy/settings.cpp \ pow.cpp \ primitives/block.cpp \ primitives/transaction.cpp \ pubkey.cpp \ random.cpp \ randomenv.cpp \ scheduler.cpp \ script/interpreter.cpp \ script/script.cpp \ script/script_error.cpp \ script/sigcache.cpp \ script/solver.cpp \ signet.cpp \ streams.cpp \ support/cleanse.cpp \ support/lockedpool.cpp \ sync.cpp \ txdb.cpp \ txmempool.cpp \ uint256.cpp \ util/batchpriority.cpp \ util/chaintype.cpp \ util/check.cpp \ util/exception.cpp \ util/fs.cpp \ util/fs_helpers.cpp \ util/hasher.cpp \ util/moneystr.cpp \ util/rbf.cpp \ util/serfloat.cpp \ util/signalinterrupt.cpp \ util/strencodings.cpp \ util/string.cpp \ util/syserror.cpp \ util/thread.cpp \ util/threadnames.cpp \ util/time.cpp \ util/tokenpipe.cpp \ validation.cpp \ validationinterface.cpp \ versionbits.cpp \ warnings.cpp # Required for obj/build.h to be generated first. # More details: https://www.gnu.org/software/automake/manual/html_node/Built-Sources-Example.html libbitcoinkernel_la-clientversion.l$(OBJEXT): obj/build.h endif # BUILD_BITCOIN_KERNEL_LIB # # bitcoinconsensus library # if BUILD_BITCOIN_LIBS lib_LTLIBRARIES += $(LIBBITCOINCONSENSUS) include_HEADERS = script/bitcoinconsensus.h libbitcoinconsensus_la_SOURCES = support/cleanse.cpp $(crypto_libbitcoin_crypto_base_la_SOURCES) $(libbitcoin_consensus_a_SOURCES) libbitcoinconsensus_la_LDFLAGS = $(AM_LDFLAGS) -no-undefined $(RELDFLAGS) libbitcoinconsensus_la_LIBADD = $(LIBSECP256K1) libbitcoinconsensus_la_CPPFLAGS = $(AM_CPPFLAGS) -I$(builddir)/obj -I$(srcdir)/secp256k1/include -DBUILD_BITCOIN_INTERNAL libbitcoinconsensus_la_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) endif # CTAES_DIST = crypto/ctaes/bench.c CTAES_DIST += crypto/ctaes/ctaes.c CTAES_DIST += crypto/ctaes/ctaes.h CTAES_DIST += crypto/ctaes/README.md CTAES_DIST += crypto/ctaes/test.c CLEANFILES = $(EXTRA_LIBRARIES) CLEANFILES += *.gcda *.gcno CLEANFILES += compat/*.gcda compat/*.gcno CLEANFILES += consensus/*.gcda consensus/*.gcno CLEANFILES += crc32c/src/*.gcda crc32c/src/*.gcno CLEANFILES += crypto/*.gcda crypto/*.gcno CLEANFILES += index/*.gcda index/*.gcno CLEANFILES += interfaces/*.gcda interfaces/*.gcno CLEANFILES += node/*.gcda node/*.gcno CLEANFILES += policy/*.gcda policy/*.gcno CLEANFILES += primitives/*.gcda primitives/*.gcno CLEANFILES += rpc/*.gcda rpc/*.gcno CLEANFILES += script/*.gcda script/*.gcno CLEANFILES += support/*.gcda support/*.gcno CLEANFILES += univalue/*.gcda univalue/*.gcno CLEANFILES += util/*.gcda util/*.gcno CLEANFILES += wallet/*.gcda wallet/*.gcno CLEANFILES += wallet/test/*.gcda wallet/test/*.gcno CLEANFILES += zmq/*.gcda zmq/*.gcno CLEANFILES += obj/build.h EXTRA_DIST = $(CTAES_DIST) config/bitcoin-config.h: config/stamp-h1 @$(MAKE) -C $(top_builddir) $(subdir)/$(@) config/stamp-h1: $(top_srcdir)/$(subdir)/config/bitcoin-config.h.in $(top_builddir)/config.status $(AM_V_at)$(MAKE) -C $(top_builddir) $(subdir)/$(@) $(top_srcdir)/$(subdir)/config/bitcoin-config.h.in: $(am__configure_deps) $(AM_V_at)$(MAKE) -C $(top_srcdir) $(subdir)/config/bitcoin-config.h.in clean-local: -$(MAKE) -C secp256k1 clean -rm -f leveldb/*/*.gcda leveldb/*/*.gcno leveldb/helpers/memenv/*.gcda leveldb/helpers/memenv/*.gcno -rm -f config.h -rm -rf test/__pycache__ .rc.o: @test -f $(WINDRES) || (echo "windres $(WINDRES) not found, but is required to compile windows resource files"; exit 1) ## FIXME: How to get the appropriate modulename_CPPFLAGS in here? $(AM_V_GEN) $(WINDRES) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(CPPFLAGS) -DWINDRES_PREPROC -i $< -o $@ check-symbols: $(bin_PROGRAMS) @echo "Running symbol and dynamic library checks..." $(AM_V_at) $(PYTHON) $(top_srcdir)/contrib/devtools/symbol-check.py $(bin_PROGRAMS) check-security: $(bin_PROGRAMS) if HARDEN @echo "Checking binary security..." $(AM_V_at) $(PYTHON) $(top_srcdir)/contrib/devtools/security-check.py $(bin_PROGRAMS) endif libbitcoin_ipc_mpgen_input = \ ipc/capnp/echo.capnp \ ipc/capnp/init.capnp EXTRA_DIST += $(libbitcoin_ipc_mpgen_input) %.capnp: # Explicitly list dependencies on generated headers as described in # https://www.gnu.org/software/automake/manual/html_node/Built-Sources-Example.html#Recording-Dependencies-manually ipc/capnp/libbitcoin_ipc_a-protocol.$(OBJEXT): $(libbitcoin_ipc_mpgen_input:=.h) if BUILD_MULTIPROCESS LIBBITCOIN_IPC=libbitcoin_ipc.a libbitcoin_ipc_a_SOURCES = \ ipc/capnp/context.h \ ipc/capnp/init-types.h \ ipc/capnp/protocol.cpp \ ipc/capnp/protocol.h \ ipc/context.h \ ipc/exception.h \ ipc/interfaces.cpp \ ipc/process.cpp \ ipc/process.h \ ipc/protocol.h libbitcoin_ipc_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) libbitcoin_ipc_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) $(LIBMULTIPROCESS_CFLAGS) include $(MPGEN_PREFIX)/include/mpgen.mk libbitcoin_ipc_mpgen_output = \ $(libbitcoin_ipc_mpgen_input:=.c++) \ $(libbitcoin_ipc_mpgen_input:=.h) \ $(libbitcoin_ipc_mpgen_input:=.proxy-client.c++) \ $(libbitcoin_ipc_mpgen_input:=.proxy-server.c++) \ $(libbitcoin_ipc_mpgen_input:=.proxy-types.c++) \ $(libbitcoin_ipc_mpgen_input:=.proxy-types.h) \ $(libbitcoin_ipc_mpgen_input:=.proxy.h) nodist_libbitcoin_ipc_a_SOURCES = $(libbitcoin_ipc_mpgen_output) CLEANFILES += $(libbitcoin_ipc_mpgen_output) endif %.raw.h: %.raw @$(MKDIR_P) $(@D) $(AM_V_GEN) { \ echo "static unsigned const char $(*F)_raw[] = {" && \ $(HEXDUMP) -v -e '8/1 "0x%02x, "' -e '"\n"' $< | $(SED) -e 's/0x ,//g' && \ echo "};"; \ } > "$@.new" && mv -f "$@.new" "$@" include Makefile.minisketch.include include Makefile.crc32c.include include Makefile.leveldb.include include Makefile.test_util.include include Makefile.test_fuzz.include include Makefile.test.include if ENABLE_BENCH include Makefile.bench.include endif if ENABLE_QT include Makefile.qt.include endif if ENABLE_QT_TESTS include Makefile.qttest.include endif include Makefile.univalue.include
0
bitcoin
bitcoin/src/Makefile.bench.include
# Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. bin_PROGRAMS += bench/bench_bitcoin BENCH_SRCDIR = bench BENCH_BINARY = bench/bench_bitcoin$(EXEEXT) RAW_BENCH_FILES = \ bench/data/block413567.raw GENERATED_BENCH_FILES = $(RAW_BENCH_FILES:.raw=.raw.h) bench_bench_bitcoin_SOURCES = \ $(RAW_BENCH_FILES) \ bench/addrman.cpp \ bench/base58.cpp \ bench/bech32.cpp \ bench/bench.cpp \ bench/bench.h \ bench/bench_bitcoin.cpp \ bench/bip324_ecdh.cpp \ bench/block_assemble.cpp \ bench/ccoins_caching.cpp \ bench/chacha20.cpp \ bench/checkblock.cpp \ bench/checkqueue.cpp \ bench/crypto_hash.cpp \ bench/data.cpp \ bench/data.h \ bench/descriptors.cpp \ bench/disconnected_transactions.cpp \ bench/duplicate_inputs.cpp \ bench/ellswift.cpp \ bench/examples.cpp \ bench/gcs_filter.cpp \ bench/hashpadding.cpp \ bench/load_external.cpp \ bench/lockedpool.cpp \ bench/logging.cpp \ bench/mempool_eviction.cpp \ bench/mempool_stress.cpp \ bench/merkle_root.cpp \ bench/nanobench.cpp \ bench/nanobench.h \ bench/peer_eviction.cpp \ bench/poly1305.cpp \ bench/pool.cpp \ bench/prevector.cpp \ bench/rollingbloom.cpp \ bench/rpc_blockchain.cpp \ bench/rpc_mempool.cpp \ bench/streams_findbyte.cpp \ bench/strencodings.cpp \ bench/util_time.cpp \ bench/verify_script.cpp \ bench/xor.cpp nodist_bench_bench_bitcoin_SOURCES = $(GENERATED_BENCH_FILES) bench_bench_bitcoin_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BOOST_CPPFLAGS) $(EVENT_CFLAGS) $(EVENT_PTHREADS_CFLAGS) -I$(builddir)/bench/ bench_bench_bitcoin_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) bench_bench_bitcoin_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) $(PTHREAD_FLAGS) bench_bench_bitcoin_LDADD = \ $(LIBTEST_UTIL) \ $(LIBBITCOIN_NODE) \ $(LIBBITCOIN_WALLET) \ $(LIBBITCOIN_COMMON) \ $(LIBBITCOIN_UTIL) \ $(LIBBITCOIN_CONSENSUS) \ $(LIBBITCOIN_CRYPTO) \ $(LIBLEVELDB) \ $(LIBMEMENV) \ $(LIBSECP256K1) \ $(LIBUNIVALUE) \ $(EVENT_PTHREADS_LIBS) \ $(EVENT_LIBS) \ $(MINIUPNPC_LIBS) \ $(NATPMP_LIBS) if ENABLE_ZMQ bench_bench_bitcoin_LDADD += $(LIBBITCOIN_ZMQ) $(ZMQ_LIBS) endif if ENABLE_WALLET bench_bench_bitcoin_SOURCES += bench/coin_selection.cpp bench_bench_bitcoin_SOURCES += bench/wallet_balance.cpp bench_bench_bitcoin_SOURCES += bench/wallet_create.cpp bench_bench_bitcoin_SOURCES += bench/wallet_loading.cpp bench_bench_bitcoin_SOURCES += bench/wallet_create_tx.cpp bench_bench_bitcoin_LDADD += $(BDB_LIBS) $(SQLITE_LIBS) endif CLEAN_BITCOIN_BENCH = bench/*.gcda bench/*.gcno $(GENERATED_BENCH_FILES) CLEANFILES += $(CLEAN_BITCOIN_BENCH) bench/data.cpp: bench/data/block413567.raw.h bitcoin_bench: $(BENCH_BINARY) bench: $(BENCH_BINARY) FORCE $(BENCH_BINARY) bitcoin_bench_clean : FORCE rm -f $(CLEAN_BITCOIN_BENCH) $(bench_bench_bitcoin_OBJECTS) $(BENCH_BINARY)
0
bitcoin
bitcoin/src/core_memusage.h
// Copyright (c) 2015-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. #ifndef BITCOIN_CORE_MEMUSAGE_H #define BITCOIN_CORE_MEMUSAGE_H #include <primitives/transaction.h> #include <primitives/block.h> #include <memusage.h> static inline size_t RecursiveDynamicUsage(const CScript& script) { return memusage::DynamicUsage(script); } static inline size_t RecursiveDynamicUsage(const COutPoint& out) { return 0; } static inline size_t RecursiveDynamicUsage(const CTxIn& in) { size_t mem = RecursiveDynamicUsage(in.scriptSig) + RecursiveDynamicUsage(in.prevout) + memusage::DynamicUsage(in.scriptWitness.stack); for (std::vector<std::vector<unsigned char> >::const_iterator it = in.scriptWitness.stack.begin(); it != in.scriptWitness.stack.end(); it++) { mem += memusage::DynamicUsage(*it); } return mem; } static inline size_t RecursiveDynamicUsage(const CTxOut& out) { return RecursiveDynamicUsage(out.scriptPubKey); } static inline size_t RecursiveDynamicUsage(const CTransaction& tx) { size_t mem = memusage::DynamicUsage(tx.vin) + memusage::DynamicUsage(tx.vout); for (std::vector<CTxIn>::const_iterator it = tx.vin.begin(); it != tx.vin.end(); it++) { mem += RecursiveDynamicUsage(*it); } for (std::vector<CTxOut>::const_iterator it = tx.vout.begin(); it != tx.vout.end(); it++) { mem += RecursiveDynamicUsage(*it); } return mem; } static inline size_t RecursiveDynamicUsage(const CMutableTransaction& tx) { size_t mem = memusage::DynamicUsage(tx.vin) + memusage::DynamicUsage(tx.vout); for (std::vector<CTxIn>::const_iterator it = tx.vin.begin(); it != tx.vin.end(); it++) { mem += RecursiveDynamicUsage(*it); } for (std::vector<CTxOut>::const_iterator it = tx.vout.begin(); it != tx.vout.end(); it++) { mem += RecursiveDynamicUsage(*it); } return mem; } static inline size_t RecursiveDynamicUsage(const CBlock& block) { size_t mem = memusage::DynamicUsage(block.vtx); for (const auto& tx : block.vtx) { mem += memusage::DynamicUsage(tx) + RecursiveDynamicUsage(*tx); } return mem; } static inline size_t RecursiveDynamicUsage(const CBlockLocator& locator) { return memusage::DynamicUsage(locator.vHave); } template<typename X> static inline size_t RecursiveDynamicUsage(const std::shared_ptr<X>& p) { return p ? memusage::DynamicUsage(p) + RecursiveDynamicUsage(*p) : 0; } #endif // BITCOIN_CORE_MEMUSAGE_H
0
bitcoin
bitcoin/src/net_processing.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 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 <net_processing.h> #include <addrman.h> #include <banman.h> #include <blockencodings.h> #include <blockfilter.h> #include <chainparams.h> #include <consensus/amount.h> #include <consensus/validation.h> #include <deploymentstatus.h> #include <hash.h> #include <headerssync.h> #include <index/blockfilterindex.h> #include <kernel/chain.h> #include <kernel/mempool_entry.h> #include <logging.h> #include <merkleblock.h> #include <netbase.h> #include <netmessagemaker.h> #include <node/blockstorage.h> #include <node/txreconciliation.h> #include <policy/fees.h> #include <policy/policy.h> #include <policy/settings.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <random.h> #include <reverse_iterator.h> #include <scheduler.h> #include <streams.h> #include <sync.h> #include <timedata.h> #include <tinyformat.h> #include <txmempool.h> #include <txorphanage.h> #include <txrequest.h> #include <util/check.h> #include <util/strencodings.h> #include <util/trace.h> #include <validation.h> #include <algorithm> #include <atomic> #include <chrono> #include <future> #include <memory> #include <optional> #include <typeinfo> #include <utility> /** Headers download timeout. * Timeout = base + per_header * (expected number of headers) */ static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE = 15min; static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER = 1ms; /** How long to wait for a peer to respond to a getheaders request */ static constexpr auto HEADERS_RESPONSE_TIME{2min}; /** Protect at least this many outbound peers from disconnection due to slow/ * behind headers chain. */ static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT = 4; /** Timeout for (unprotected) outbound peers to sync to our chainwork */ static constexpr auto CHAIN_SYNC_TIMEOUT{20min}; /** How frequently to check for stale tips */ static constexpr auto STALE_CHECK_INTERVAL{10min}; /** How frequently to check for extra outbound peers and disconnect */ static constexpr auto EXTRA_PEER_CHECK_INTERVAL{45s}; /** Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict */ static constexpr auto MINIMUM_CONNECT_TIME{30s}; /** SHA256("main address relay")[0:8] */ static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; /// Age after which a stale block will no longer be served if requested as /// protection against fingerprinting. Set to one month, denominated in seconds. static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60; /// Age after which a block is considered historical for purposes of rate /// limiting block relay. Set to one week, denominated in seconds. static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60; /** Time between pings automatically sent out for latency probing and keepalive */ static constexpr auto PING_INTERVAL{2min}; /** The maximum number of entries in a locator */ static const unsigned int MAX_LOCATOR_SZ = 101; /** The maximum number of entries in an 'inv' protocol message */ static const unsigned int MAX_INV_SZ = 50000; /** Maximum number of in-flight transaction requests from a peer. It is not a hard limit, but the threshold at which * point the OVERLOADED_PEER_TX_DELAY kicks in. */ static constexpr int32_t MAX_PEER_TX_REQUEST_IN_FLIGHT = 100; /** Maximum number of transactions to consider for requesting, per peer. It provides a reasonable DoS limit to * per-peer memory usage spent on announcements, while covering peers continuously sending INVs at the maximum * rate (by our own policy, see INVENTORY_BROADCAST_PER_SECOND) for several minutes, while not receiving * the actual transaction (from any peer) in response to requests for them. */ static constexpr int32_t MAX_PEER_TX_ANNOUNCEMENTS = 5000; /** How long to delay requesting transactions via txids, if we have wtxid-relaying peers */ static constexpr auto TXID_RELAY_DELAY{2s}; /** How long to delay requesting transactions from non-preferred peers */ static constexpr auto NONPREF_PEER_TX_DELAY{2s}; /** How long to delay requesting transactions from overloaded peers (see MAX_PEER_TX_REQUEST_IN_FLIGHT). */ static constexpr auto OVERLOADED_PEER_TX_DELAY{2s}; /** How long to wait before downloading a transaction from an additional peer */ static constexpr auto GETDATA_TX_INTERVAL{60s}; /** Limit to avoid sending big packets. Not used in processing incoming GETDATA for compatibility */ static const unsigned int MAX_GETDATA_SZ = 1000; /** Number of blocks that can be requested at any given time from a single peer. */ static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16; /** Default time during which a peer must stall block download progress before being disconnected. * the actual timeout is increased temporarily if peers are disconnected for hitting the timeout */ static constexpr auto BLOCK_STALLING_TIMEOUT_DEFAULT{2s}; /** Maximum timeout for stalling block download. */ static constexpr auto BLOCK_STALLING_TIMEOUT_MAX{64s}; /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends * less than this number, we reached its tip. Changing this value is a protocol upgrade. */ static const unsigned int MAX_HEADERS_RESULTS = 2000; /** Maximum depth of blocks we're willing to serve as compact blocks to peers * when requested. For older blocks, a regular BLOCK response will be sent. */ static const int MAX_CMPCTBLOCK_DEPTH = 5; /** Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for. */ static const int MAX_BLOCKTXN_DEPTH = 10; /** Size of the "block download window": how far ahead of our current height do we fetch? * Larger windows tolerate larger download speed differences between peer, but increase the potential * degree of disordering of blocks on disk (which make reindexing and pruning harder). We'll probably * want to make this a per-peer adaptive value at some point. */ static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024; /** Block download timeout base, expressed in multiples of the block interval (i.e. 10 min) */ static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE = 1; /** Additional block download timeout per parallel downloading peer (i.e. 5 min) */ static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 0.5; /** Maximum number of headers to announce when relaying blocks with headers message.*/ static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8; /** Maximum number of unconnecting headers announcements before DoS score */ static const int MAX_NUM_UNCONNECTING_HEADERS_MSGS = 10; /** Minimum blocks required to signal NODE_NETWORK_LIMITED */ static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288; /** Average delay between local address broadcasts */ static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL{24h}; /** Average delay between peer address broadcasts */ static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL{30s}; /** Delay between rotating the peers we relay a particular address to */ static constexpr auto ROTATE_ADDR_RELAY_DEST_INTERVAL{24h}; /** Average delay between trickled inventory transmissions for inbound peers. * Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */ static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL{5s}; /** Average delay between trickled inventory transmissions for outbound peers. * Use a smaller delay as there is less privacy concern for them. * Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */ static constexpr auto OUTBOUND_INVENTORY_BROADCAST_INTERVAL{2s}; /** Maximum rate of inventory items to send per second. * Limits the impact of low-fee transaction floods. */ static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND = 7; /** Target number of tx inventory items to send per transmission. */ static constexpr unsigned int INVENTORY_BROADCAST_TARGET = INVENTORY_BROADCAST_PER_SECOND * count_seconds(INBOUND_INVENTORY_BROADCAST_INTERVAL); /** Maximum number of inventory items to send per transmission. */ static constexpr unsigned int INVENTORY_BROADCAST_MAX = 1000; static_assert(INVENTORY_BROADCAST_MAX >= INVENTORY_BROADCAST_TARGET, "INVENTORY_BROADCAST_MAX too low"); static_assert(INVENTORY_BROADCAST_MAX <= MAX_PEER_TX_ANNOUNCEMENTS, "INVENTORY_BROADCAST_MAX too high"); /** Average delay between feefilter broadcasts in seconds. */ static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL{10min}; /** Maximum feefilter broadcast delay after significant change. */ static constexpr auto MAX_FEEFILTER_CHANGE_DELAY{5min}; /** Maximum number of compact filters that may be requested with one getcfilters. See BIP 157. */ static constexpr uint32_t MAX_GETCFILTERS_SIZE = 1000; /** Maximum number of cf hashes that may be requested with one getcfheaders. See BIP 157. */ static constexpr uint32_t MAX_GETCFHEADERS_SIZE = 2000; /** the maximum percentage of addresses from our addrman to return in response to a getaddr message. */ static constexpr size_t MAX_PCT_ADDR_TO_SEND = 23; /** The maximum number of address records permitted in an ADDR message. */ static constexpr size_t MAX_ADDR_TO_SEND{1000}; /** The maximum rate of address records we're willing to process on average. Can be bypassed using * the NetPermissionFlags::Addr permission. */ static constexpr double MAX_ADDR_RATE_PER_SECOND{0.1}; /** The soft limit of the address processing token bucket (the regular MAX_ADDR_RATE_PER_SECOND * based increments won't go above this, but the MAX_ADDR_TO_SEND increment following GETADDR * is exempt from this limit). */ static constexpr size_t MAX_ADDR_PROCESSING_TOKEN_BUCKET{MAX_ADDR_TO_SEND}; /** The compactblocks version we support. See BIP 152. */ static constexpr uint64_t CMPCTBLOCKS_VERSION{2}; // Internal stuff namespace { /** Blocks that are in flight, and that are in the queue to be downloaded. */ struct QueuedBlock { /** BlockIndex. We must have this since we only request blocks when we've already validated the header. */ const CBlockIndex* pindex; /** Optional, used for CMPCTBLOCK downloads */ std::unique_ptr<PartiallyDownloadedBlock> partialBlock; }; /** * Data structure for an individual peer. This struct is not protected by * cs_main since it does not contain validation-critical data. * * Memory is owned by shared pointers and this object is destructed when * the refcount drops to zero. * * Mutexes inside this struct must not be held when locking m_peer_mutex. * * TODO: move most members from CNodeState to this structure. * TODO: move remaining application-layer data members from CNode to this structure. */ struct Peer { /** Same id as the CNode object for this peer */ const NodeId m_id{0}; /** Services we offered to this peer. * * This is supplied by CConnman during peer initialization. It's const * because there is no protocol defined for renegotiating services * initially offered to a peer. The set of local services we offer should * not change after initialization. * * An interesting example of this is NODE_NETWORK and initial block * download: a node which starts up from scratch doesn't have any blocks * to serve, but still advertises NODE_NETWORK because it will eventually * fulfill this role after IBD completes. P2P code is written in such a * way that it can gracefully handle peers who don't make good on their * service advertisements. */ const ServiceFlags m_our_services; /** Services this peer offered to us. */ std::atomic<ServiceFlags> m_their_services{NODE_NONE}; /** Protects misbehavior data members */ Mutex m_misbehavior_mutex; /** Accumulated misbehavior score for this peer */ int m_misbehavior_score GUARDED_BY(m_misbehavior_mutex){0}; /** Whether this peer should be disconnected and marked as discouraged (unless it has NetPermissionFlags::NoBan permission). */ bool m_should_discourage GUARDED_BY(m_misbehavior_mutex){false}; /** Protects block inventory data members */ Mutex m_block_inv_mutex; /** List of blocks that we'll announce via an `inv` message. * There is no final sorting before sending, as they are always sent * immediately and in the order requested. */ std::vector<uint256> m_blocks_for_inv_relay GUARDED_BY(m_block_inv_mutex); /** Unfiltered list of blocks that we'd like to announce via a `headers` * message. If we can't announce via a `headers` message, we'll fall back to * announcing via `inv`. */ std::vector<uint256> m_blocks_for_headers_relay GUARDED_BY(m_block_inv_mutex); /** The final block hash that we sent in an `inv` message to this peer. * When the peer requests this block, we send an `inv` message to trigger * the peer to request the next sequence of block hashes. * Most peers use headers-first syncing, which doesn't use this mechanism */ uint256 m_continuation_block GUARDED_BY(m_block_inv_mutex) {}; /** This peer's reported block height when we connected */ std::atomic<int> m_starting_height{-1}; /** The pong reply we're expecting, or 0 if no pong expected. */ std::atomic<uint64_t> m_ping_nonce_sent{0}; /** When the last ping was sent, or 0 if no ping was ever sent */ std::atomic<std::chrono::microseconds> m_ping_start{0us}; /** Whether a ping has been requested by the user */ std::atomic<bool> m_ping_queued{false}; /** Whether this peer relays txs via wtxid */ std::atomic<bool> m_wtxid_relay{false}; /** The feerate in the most recent BIP133 `feefilter` message sent to the peer. * It is *not* a p2p protocol violation for the peer to send us * transactions with a lower fee rate than this. See BIP133. */ CAmount m_fee_filter_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0}; /** Timestamp after which we will send the next BIP133 `feefilter` message * to the peer. */ std::chrono::microseconds m_next_send_feefilter GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0}; struct TxRelay { mutable RecursiveMutex m_bloom_filter_mutex; /** Whether we relay transactions to this peer. */ bool m_relay_txs GUARDED_BY(m_bloom_filter_mutex){false}; /** A bloom filter for which transactions to announce to the peer. See BIP37. */ std::unique_ptr<CBloomFilter> m_bloom_filter PT_GUARDED_BY(m_bloom_filter_mutex) GUARDED_BY(m_bloom_filter_mutex){nullptr}; mutable RecursiveMutex m_tx_inventory_mutex; /** A filter of all the (w)txids that the peer has announced to * us or we have announced to the peer. We use this to avoid announcing * the same (w)txid to a peer that already has the transaction. */ CRollingBloomFilter m_tx_inventory_known_filter GUARDED_BY(m_tx_inventory_mutex){50000, 0.000001}; /** Set of transaction ids we still have to announce (txid for * non-wtxid-relay peers, wtxid for wtxid-relay peers). We use the * mempool to sort transactions in dependency order before relay, so * this does not have to be sorted. */ std::set<uint256> m_tx_inventory_to_send GUARDED_BY(m_tx_inventory_mutex); /** Whether the peer has requested us to send our complete mempool. Only * permitted if the peer has NetPermissionFlags::Mempool or we advertise * NODE_BLOOM. See BIP35. */ bool m_send_mempool GUARDED_BY(m_tx_inventory_mutex){false}; /** The next time after which we will send an `inv` message containing * transaction announcements to this peer. */ std::chrono::microseconds m_next_inv_send_time GUARDED_BY(m_tx_inventory_mutex){0}; /** The mempool sequence num at which we sent the last `inv` message to this peer. * Can relay txs with lower sequence numbers than this (see CTxMempool::info_for_relay). */ uint64_t m_last_inv_sequence GUARDED_BY(NetEventsInterface::g_msgproc_mutex){1}; /** Minimum fee rate with which to filter transaction announcements to this node. See BIP133. */ std::atomic<CAmount> m_fee_filter_received{0}; }; /* Initializes a TxRelay struct for this peer. Can be called at most once for a peer. */ TxRelay* SetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex) { LOCK(m_tx_relay_mutex); Assume(!m_tx_relay); m_tx_relay = std::make_unique<Peer::TxRelay>(); return m_tx_relay.get(); }; TxRelay* GetTxRelay() EXCLUSIVE_LOCKS_REQUIRED(!m_tx_relay_mutex) { return WITH_LOCK(m_tx_relay_mutex, return m_tx_relay.get()); }; /** A vector of addresses to send to the peer, limited to MAX_ADDR_TO_SEND. */ std::vector<CAddress> m_addrs_to_send GUARDED_BY(NetEventsInterface::g_msgproc_mutex); /** Probabilistic filter to track recent addr messages relayed with this * peer. Used to avoid relaying redundant addresses to this peer. * * We initialize this filter for outbound peers (other than * block-relay-only connections) or when an inbound peer sends us an * address related message (ADDR, ADDRV2, GETADDR). * * Presence of this filter must correlate with m_addr_relay_enabled. **/ std::unique_ptr<CRollingBloomFilter> m_addr_known GUARDED_BY(NetEventsInterface::g_msgproc_mutex); /** Whether we are participating in address relay with this connection. * * We set this bool to true for outbound peers (other than * block-relay-only connections), or when an inbound peer sends us an * address related message (ADDR, ADDRV2, GETADDR). * * We use this bool to decide whether a peer is eligible for gossiping * addr messages. This avoids relaying to peers that are unlikely to * forward them, effectively blackholing self announcements. Reasons * peers might support addr relay on the link include that they connected * to us as a block-relay-only peer or they are a light client. * * This field must correlate with whether m_addr_known has been * initialized.*/ std::atomic_bool m_addr_relay_enabled{false}; /** Whether a getaddr request to this peer is outstanding. */ bool m_getaddr_sent GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false}; /** Guards address sending timers. */ mutable Mutex m_addr_send_times_mutex; /** Time point to send the next ADDR message to this peer. */ std::chrono::microseconds m_next_addr_send GUARDED_BY(m_addr_send_times_mutex){0}; /** Time point to possibly re-announce our local address to this peer. */ std::chrono::microseconds m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){0}; /** Whether the peer has signaled support for receiving ADDRv2 (BIP155) * messages, indicating a preference to receive ADDRv2 instead of ADDR ones. */ std::atomic_bool m_wants_addrv2{false}; /** Whether this peer has already sent us a getaddr message. */ bool m_getaddr_recvd GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false}; /** Number of addresses that can be processed from this peer. Start at 1 to * permit self-announcement. */ double m_addr_token_bucket GUARDED_BY(NetEventsInterface::g_msgproc_mutex){1.0}; /** When m_addr_token_bucket was last updated */ std::chrono::microseconds m_addr_token_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){GetTime<std::chrono::microseconds>()}; /** Total number of addresses that were dropped due to rate limiting. */ std::atomic<uint64_t> m_addr_rate_limited{0}; /** Total number of addresses that were processed (excludes rate-limited ones). */ std::atomic<uint64_t> m_addr_processed{0}; /** Whether we've sent this peer a getheaders in response to an inv prior to initial-headers-sync completing */ bool m_inv_triggered_getheaders_before_sync GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false}; /** Protects m_getdata_requests **/ Mutex m_getdata_requests_mutex; /** Work queue of items requested by this peer **/ std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex); /** Time of the last getheaders message to this peer */ NodeClock::time_point m_last_getheaders_timestamp GUARDED_BY(NetEventsInterface::g_msgproc_mutex){}; /** Protects m_headers_sync **/ Mutex m_headers_sync_mutex; /** Headers-sync state for this peer (eg for initial sync, or syncing large * reorgs) **/ std::unique_ptr<HeadersSyncState> m_headers_sync PT_GUARDED_BY(m_headers_sync_mutex) GUARDED_BY(m_headers_sync_mutex) {}; /** Whether we've sent our peer a sendheaders message. **/ std::atomic<bool> m_sent_sendheaders{false}; /** Length of current-streak of unconnecting headers announcements */ int m_num_unconnecting_headers_msgs GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0}; /** When to potentially disconnect peer for stalling headers download */ std::chrono::microseconds m_headers_sync_timeout GUARDED_BY(NetEventsInterface::g_msgproc_mutex){0us}; /** Whether this peer wants invs or headers (when possible) for block announcements */ bool m_prefers_headers GUARDED_BY(NetEventsInterface::g_msgproc_mutex){false}; explicit Peer(NodeId id, ServiceFlags our_services) : m_id{id} , m_our_services{our_services} {} private: mutable Mutex m_tx_relay_mutex; /** Transaction relay data. May be a nullptr. */ std::unique_ptr<TxRelay> m_tx_relay GUARDED_BY(m_tx_relay_mutex); }; using PeerRef = std::shared_ptr<Peer>; /** * Maintain validation-specific state about nodes, protected by cs_main, instead * by CNode's own locks. This simplifies asynchronous operation, where * processing of incoming data is done after the ProcessMessage call returns, * and we're no longer holding the node's locks. */ struct CNodeState { //! The best known block we know this peer has announced. const CBlockIndex* pindexBestKnownBlock{nullptr}; //! The hash of the last unknown block this peer has announced. uint256 hashLastUnknownBlock{}; //! The last full block we both have. const CBlockIndex* pindexLastCommonBlock{nullptr}; //! The best header we have sent our peer. const CBlockIndex* pindexBestHeaderSent{nullptr}; //! Whether we've started headers synchronization with this peer. bool fSyncStarted{false}; //! Since when we're stalling block download progress (in microseconds), or 0. std::chrono::microseconds m_stalling_since{0us}; std::list<QueuedBlock> vBlocksInFlight; //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty. std::chrono::microseconds m_downloading_since{0us}; //! Whether we consider this a preferred download peer. bool fPreferredDownload{false}; /** Whether this peer wants invs or cmpctblocks (when possible) for block announcements. */ bool m_requested_hb_cmpctblocks{false}; /** Whether this peer will send us cmpctblocks if we request them. */ bool m_provides_cmpctblocks{false}; /** State used to enforce CHAIN_SYNC_TIMEOUT and EXTRA_PEER_CHECK_INTERVAL logic. * * Both are only in effect for outbound, non-manual, non-protected connections. * Any peer protected (m_protect = true) is not chosen for eviction. A peer is * marked as protected if all of these are true: * - its connection type is IsBlockOnlyConn() == false * - it gave us a valid connecting header * - we haven't reached MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT yet * - its chain tip has at least as much work as ours * * CHAIN_SYNC_TIMEOUT: if a peer's best known block has less work than our tip, * set a timeout CHAIN_SYNC_TIMEOUT in the future: * - If at timeout their best known block now has more work than our tip * when the timeout was set, then either reset the timeout or clear it * (after comparing against our current tip's work) * - If at timeout their best known block still has less work than our * tip did when the timeout was set, then send a getheaders message, * and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future. * If their best known block is still behind when that new timeout is * reached, disconnect. * * EXTRA_PEER_CHECK_INTERVAL: after each interval, if we have too many outbound peers, * drop the outbound one that least recently announced us a new block. */ struct ChainSyncTimeoutState { //! A timeout used for checking whether our peer has sufficiently synced std::chrono::seconds m_timeout{0s}; //! A header with the work we require on our peer's chain const CBlockIndex* m_work_header{nullptr}; //! After timeout is reached, set to true after sending getheaders bool m_sent_getheaders{false}; //! Whether this peer is protected from disconnection due to a bad/slow chain bool m_protect{false}; }; ChainSyncTimeoutState m_chain_sync; //! Time of last new block announcement int64_t m_last_block_announcement{0}; //! Whether this peer is an inbound connection const bool m_is_inbound; CNodeState(bool is_inbound) : m_is_inbound(is_inbound) {} }; class PeerManagerImpl final : public PeerManager { public: PeerManagerImpl(CConnman& connman, AddrMan& addrman, BanMan* banman, ChainstateManager& chainman, CTxMemPool& pool, Options opts); /** Overridden from CValidationInterface. */ void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexConnected) override EXCLUSIVE_LOCKS_REQUIRED(!m_recent_confirmed_transactions_mutex); void BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex) override EXCLUSIVE_LOCKS_REQUIRED(!m_recent_confirmed_transactions_mutex); void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); void BlockChecked(const CBlock& block, const BlockValidationState& state) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) override EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex); /** Implement NetEventsInterface */ void InitializeNode(CNode& node, ServiceFlags our_services) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); void FinalizeNode(const CNode& node) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex); bool ProcessMessages(CNode* pfrom, std::atomic<bool>& interrupt) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_recent_confirmed_transactions_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex, g_msgproc_mutex); bool SendMessages(CNode* pto) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_recent_confirmed_transactions_mutex, !m_most_recent_block_mutex, g_msgproc_mutex); /** Implement PeerManager */ void StartScheduledTasks(CScheduler& scheduler) override; void CheckForStaleTipAndEvictPeers() override; std::optional<std::string> FetchBlock(NodeId peer_id, const CBlockIndex& block_index) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); bool IgnoresIncomingTxs() override { return m_opts.ignore_incoming_txs; } void SendPings() override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); void RelayTransaction(const uint256& txid, const uint256& wtxid) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); void SetBestHeight(int height) override { m_best_height = height; }; void UnitTestMisbehaving(NodeId peer_id, int howmuch) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex) { Misbehaving(*Assert(GetPeerRef(peer_id)), howmuch, ""); }; void ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv, const std::chrono::microseconds time_received, const std::atomic<bool>& interruptMsgProc) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_recent_confirmed_transactions_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex, g_msgproc_mutex); void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) override; private: /** Consider evicting an outbound peer based on the amount of time they've been behind our tip */ void ConsiderEviction(CNode& pto, Peer& peer, std::chrono::seconds time_in_seconds) EXCLUSIVE_LOCKS_REQUIRED(cs_main, g_msgproc_mutex); /** If we have extra outbound peers, try to disconnect the one with the oldest block announcement */ void EvictExtraOutboundPeers(std::chrono::seconds now) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Retrieve unbroadcast transactions from the mempool and reattempt sending to peers */ void ReattemptInitialBroadcast(CScheduler& scheduler) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); /** Get a shared pointer to the Peer object. * May return an empty shared_ptr if the Peer object can't be found. */ PeerRef GetPeerRef(NodeId id) const EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); /** Get a shared pointer to the Peer object and remove it from m_peer_map. * May return an empty shared_ptr if the Peer object can't be found. */ PeerRef RemovePeer(NodeId id) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); /** * Increment peer's misbehavior score. If the new value >= DISCOURAGEMENT_THRESHOLD, mark the node * to be discouraged, meaning the peer might be disconnected and added to the discouragement filter. */ void Misbehaving(Peer& peer, int howmuch, const std::string& message); /** * Potentially mark a node discouraged based on the contents of a BlockValidationState object * * @param[in] via_compact_block this bool is passed in because net_processing should * punish peers differently depending on whether the data was provided in a compact * block message or not. If the compact block had a valid header, but contained invalid * txs, the peer should not be punished. See BIP 152. * * @return Returns true if the peer was punished (probably disconnected) */ bool MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state, bool via_compact_block, const std::string& message = "") EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); /** * Potentially disconnect and discourage a node based on the contents of a TxValidationState object * * @return Returns true if the peer was punished (probably disconnected) */ bool MaybePunishNodeForTx(NodeId nodeid, const TxValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex); /** Maybe disconnect a peer and discourage future connections from its address. * * @param[in] pnode The node to check. * @param[in] peer The peer object to check. * @return True if the peer was marked for disconnection in this function */ bool MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer); /** * Reconsider orphan transactions after a parent has been accepted to the mempool. * * @peer[in] peer The peer whose orphan transactions we will reconsider. Generally only * one orphan will be reconsidered on each call of this function. If an * accepted orphan has orphaned children, those will need to be * reconsidered, creating more work, possibly for other peers. * @return True if meaningful work was done (an orphan was accepted/rejected). * If no meaningful work was done, then the work set for this peer * will be empty. */ bool ProcessOrphanTx(Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex); /** Process a single headers message from a peer. * * @param[in] pfrom CNode of the peer * @param[in] peer The peer sending us the headers * @param[in] headers The headers received. Note that this may be modified within ProcessHeadersMessage. * @param[in] via_compact_block Whether this header came in via compact block handling. */ void ProcessHeadersMessage(CNode& pfrom, Peer& peer, std::vector<CBlockHeader>&& headers, bool via_compact_block) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex, g_msgproc_mutex); /** Various helpers for headers processing, invoked by ProcessHeadersMessage() */ /** Return true if headers are continuous and have valid proof-of-work (DoS points assigned on failure) */ bool CheckHeadersPoW(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams, Peer& peer); /** Calculate an anti-DoS work threshold for headers chains */ arith_uint256 GetAntiDoSWorkThreshold(); /** Deal with state tracking and headers sync for peers that send the * occasional non-connecting header (this can happen due to BIP 130 headers * announcements for blocks interacting with the 2hr (MAX_FUTURE_BLOCK_TIME) rule). */ void HandleFewUnconnectingHeaders(CNode& pfrom, Peer& peer, const std::vector<CBlockHeader>& headers) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); /** Return true if the headers connect to each other, false otherwise */ bool CheckHeadersAreContinuous(const std::vector<CBlockHeader>& headers) const; /** Try to continue a low-work headers sync that has already begun. * Assumes the caller has already verified the headers connect, and has * checked that each header satisfies the proof-of-work target included in * the header. * @param[in] peer The peer we're syncing with. * @param[in] pfrom CNode of the peer * @param[in,out] headers The headers to be processed. * @return True if the passed in headers were successfully processed * as the continuation of a low-work headers sync in progress; * false otherwise. * If false, the passed in headers will be returned back to * the caller. * If true, the returned headers may be empty, indicating * there is no more work for the caller to do; or the headers * may be populated with entries that have passed anti-DoS * checks (and therefore may be validated for block index * acceptance by the caller). */ bool IsContinuationOfLowWorkHeadersSync(Peer& peer, CNode& pfrom, std::vector<CBlockHeader>& headers) EXCLUSIVE_LOCKS_REQUIRED(peer.m_headers_sync_mutex, !m_headers_presync_mutex, g_msgproc_mutex); /** Check work on a headers chain to be processed, and if insufficient, * initiate our anti-DoS headers sync mechanism. * * @param[in] peer The peer whose headers we're processing. * @param[in] pfrom CNode of the peer * @param[in] chain_start_header Where these headers connect in our index. * @param[in,out] headers The headers to be processed. * * @return True if chain was low work (headers will be empty after * calling); false otherwise. */ bool TryLowWorkHeadersSync(Peer& peer, CNode& pfrom, const CBlockIndex* chain_start_header, std::vector<CBlockHeader>& headers) EXCLUSIVE_LOCKS_REQUIRED(!peer.m_headers_sync_mutex, !m_peer_mutex, !m_headers_presync_mutex, g_msgproc_mutex); /** Return true if the given header is an ancestor of * m_chainman.m_best_header or our current tip */ bool IsAncestorOfBestHeaderOrTip(const CBlockIndex* header) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Request further headers from this peer with a given locator. * We don't issue a getheaders message if we have a recent one outstanding. * This returns true if a getheaders is actually sent, and false otherwise. */ bool MaybeSendGetHeaders(CNode& pfrom, const CBlockLocator& locator, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); /** Potentially fetch blocks from this peer upon receipt of a new headers tip */ void HeadersDirectFetchBlocks(CNode& pfrom, const Peer& peer, const CBlockIndex& last_header); /** Update peer state based on received headers message */ void UpdatePeerStateForReceivedHeaders(CNode& pfrom, Peer& peer, const CBlockIndex& last_header, bool received_new_header, bool may_have_more_headers) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); void SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req); /** Register with TxRequestTracker that an INV has been received from a * peer. The announcement parameters are decided in PeerManager and then * passed to TxRequestTracker. */ void AddTxAnnouncement(const CNode& node, const GenTxid& gtxid, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); /** Send a message to a peer */ void PushMessage(CNode& node, CSerializedNetMsg&& msg) const { m_connman.PushMessage(&node, std::move(msg)); } template <typename... Args> void MakeAndPushMessage(CNode& node, std::string msg_type, Args&&... args) const { m_connman.PushMessage(&node, NetMsg::Make(std::move(msg_type), std::forward<Args>(args)...)); } /** Send a version message to a peer */ void PushNodeVersion(CNode& pnode, const Peer& peer); /** Send a ping message every PING_INTERVAL or if requested via RPC. May * mark the peer to be disconnected if a ping has timed out. * We use mockable time for ping timeouts, so setmocktime may cause pings * to time out. */ void MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now); /** Send `addr` messages on a regular schedule. */ void MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); /** Send a single `sendheaders` message, after we have completed headers sync with a peer. */ void MaybeSendSendHeaders(CNode& node, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); /** Relay (gossip) an address to a few randomly chosen nodes. * * @param[in] originator The id of the peer that sent us the address. We don't want to relay it back. * @param[in] addr Address to relay. * @param[in] fReachable Whether the address' network is reachable. We relay unreachable * addresses less. */ void RelayAddress(NodeId originator, const CAddress& addr, bool fReachable) EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, g_msgproc_mutex); /** Send `feefilter` message. */ void MaybeSendFeefilter(CNode& node, Peer& peer, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); FastRandomContext m_rng GUARDED_BY(NetEventsInterface::g_msgproc_mutex); FeeFilterRounder m_fee_filter_rounder GUARDED_BY(NetEventsInterface::g_msgproc_mutex); const CChainParams& m_chainparams; CConnman& m_connman; AddrMan& m_addrman; /** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */ BanMan* const m_banman; ChainstateManager& m_chainman; CTxMemPool& m_mempool; TxRequestTracker m_txrequest GUARDED_BY(::cs_main); std::unique_ptr<TxReconciliationTracker> m_txreconciliation; /** The height of the best chain */ std::atomic<int> m_best_height{-1}; /** Next time to check for stale tip */ std::chrono::seconds m_stale_tip_check_time GUARDED_BY(cs_main){0s}; const Options m_opts; bool RejectIncomingTxs(const CNode& peer) const; /** Whether we've completed initial sync yet, for determining when to turn * on extra block-relay-only peers. */ bool m_initial_sync_finished GUARDED_BY(cs_main){false}; /** Protects m_peer_map. This mutex must not be locked while holding a lock * on any of the mutexes inside a Peer object. */ mutable Mutex m_peer_mutex; /** * Map of all Peer objects, keyed by peer id. This map is protected * by the m_peer_mutex. Once a shared pointer reference is * taken, the lock may be released. Individual fields are protected by * their own locks. */ std::map<NodeId, PeerRef> m_peer_map GUARDED_BY(m_peer_mutex); /** Map maintaining per-node state. */ std::map<NodeId, CNodeState> m_node_states GUARDED_BY(cs_main); /** Get a pointer to a const CNodeState, used when not mutating the CNodeState object. */ const CNodeState* State(NodeId pnode) const EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Get a pointer to a mutable CNodeState. */ CNodeState* State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main); uint32_t GetFetchFlags(const Peer& peer) const; std::atomic<std::chrono::microseconds> m_next_inv_to_inbounds{0us}; /** Number of nodes with fSyncStarted. */ int nSyncStarted GUARDED_BY(cs_main) = 0; /** Hash of the last block we received via INV */ uint256 m_last_block_inv_triggering_headers_sync GUARDED_BY(g_msgproc_mutex){}; /** * Sources of received blocks, saved to be able punish them when processing * happens afterwards. * Set mapBlockSource[hash].second to false if the node should not be * punished if the block is invalid. */ std::map<uint256, std::pair<NodeId, bool>> mapBlockSource GUARDED_BY(cs_main); /** Number of peers with wtxid relay. */ std::atomic<int> m_wtxid_relay_peers{0}; /** Number of outbound peers with m_chain_sync.m_protect. */ int m_outbound_peers_with_protect_from_disconnect GUARDED_BY(cs_main) = 0; /** Number of preferable block download peers. */ int m_num_preferred_download_peers GUARDED_BY(cs_main){0}; /** Stalling timeout for blocks in IBD */ std::atomic<std::chrono::seconds> m_block_stalling_timeout{BLOCK_STALLING_TIMEOUT_DEFAULT}; bool AlreadyHaveTx(const GenTxid& gtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_main, !m_recent_confirmed_transactions_mutex); /** * Filter for transactions that were recently rejected by the mempool. * These are not rerequested until the chain tip changes, at which point * the entire filter is reset. * * Without this filter we'd be re-requesting txs from each of our peers, * increasing bandwidth consumption considerably. For instance, with 100 * peers, half of which relay a tx we don't accept, that might be a 50x * bandwidth increase. A flooding attacker attempting to roll-over the * filter using minimum-sized, 60byte, transactions might manage to send * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a * two minute window to send invs to us. * * Decreasing the false positive rate is fairly cheap, so we pick one in a * million to make it highly unlikely for users to have issues with this * filter. * * We typically only add wtxids to this filter. For non-segwit * transactions, the txid == wtxid, so this only prevents us from * re-downloading non-segwit transactions when communicating with * non-wtxidrelay peers -- which is important for avoiding malleation * attacks that could otherwise interfere with transaction relay from * non-wtxidrelay peers. For communicating with wtxidrelay peers, having * the reject filter store wtxids is exactly what we want to avoid * redownload of a rejected transaction. * * In cases where we can tell that a segwit transaction will fail * validation no matter the witness, we may add the txid of such * transaction to the filter as well. This can be helpful when * communicating with txid-relay peers or if we were to otherwise fetch a * transaction via txid (eg in our orphan handling). * * Memory used: 1.3 MB */ CRollingBloomFilter m_recent_rejects GUARDED_BY(::cs_main){120'000, 0.000'001}; uint256 hashRecentRejectsChainTip GUARDED_BY(cs_main); /* * Filter for transactions that have been recently confirmed. * We use this to avoid requesting transactions that have already been * confirnmed. * * Blocks don't typically have more than 4000 transactions, so this should * be at least six blocks (~1 hr) worth of transactions that we can store, * inserting both a txid and wtxid for every observed transaction. * If the number of transactions appearing in a block goes up, or if we are * seeing getdata requests more than an hour after initial announcement, we * can increase this number. * The false positive rate of 1/1M should come out to less than 1 * transaction per day that would be inadvertently ignored (which is the * same probability that we have in the reject filter). */ Mutex m_recent_confirmed_transactions_mutex; CRollingBloomFilter m_recent_confirmed_transactions GUARDED_BY(m_recent_confirmed_transactions_mutex){48'000, 0.000'001}; /** * For sending `inv`s to inbound peers, we use a single (exponentially * distributed) timer for all peers. If we used a separate timer for each * peer, a spy node could make multiple inbound connections to us to * accurately determine when we received the transaction (and potentially * determine the transaction's origin). */ std::chrono::microseconds NextInvToInbounds(std::chrono::microseconds now, std::chrono::seconds average_interval); // All of the following cache a recent block, and are protected by m_most_recent_block_mutex Mutex m_most_recent_block_mutex; std::shared_ptr<const CBlock> m_most_recent_block GUARDED_BY(m_most_recent_block_mutex); std::shared_ptr<const CBlockHeaderAndShortTxIDs> m_most_recent_compact_block GUARDED_BY(m_most_recent_block_mutex); uint256 m_most_recent_block_hash GUARDED_BY(m_most_recent_block_mutex); std::unique_ptr<const std::map<uint256, CTransactionRef>> m_most_recent_block_txs GUARDED_BY(m_most_recent_block_mutex); // Data about the low-work headers synchronization, aggregated from all peers' HeadersSyncStates. /** Mutex guarding the other m_headers_presync_* variables. */ Mutex m_headers_presync_mutex; /** A type to represent statistics about a peer's low-work headers sync. * * - The first field is the total verified amount of work in that synchronization. * - The second is: * - nullopt: the sync is in REDOWNLOAD phase (phase 2). * - {height, timestamp}: the sync has the specified tip height and block timestamp (phase 1). */ using HeadersPresyncStats = std::pair<arith_uint256, std::optional<std::pair<int64_t, uint32_t>>>; /** Statistics for all peers in low-work headers sync. */ std::map<NodeId, HeadersPresyncStats> m_headers_presync_stats GUARDED_BY(m_headers_presync_mutex) {}; /** The peer with the most-work entry in m_headers_presync_stats. */ NodeId m_headers_presync_bestpeer GUARDED_BY(m_headers_presync_mutex) {-1}; /** The m_headers_presync_stats improved, and needs signalling. */ std::atomic_bool m_headers_presync_should_signal{false}; /** Height of the highest block announced using BIP 152 high-bandwidth mode. */ int m_highest_fast_announce GUARDED_BY(::cs_main){0}; /** Have we requested this block from a peer */ bool IsBlockRequested(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Have we requested this block from an outbound peer */ bool IsBlockRequestedFromOutbound(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Remove this block from our tracked requested blocks. Called if: * - the block has been received from a peer * - the request for the block has timed out * If "from_peer" is specified, then only remove the block if it is in * flight from that peer (to avoid one peer's network traffic from * affecting another's state). */ void RemoveBlockRequest(const uint256& hash, std::optional<NodeId> from_peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /* Mark a block as in flight * Returns false, still setting pit, if the block was already in flight from the same peer * pit will only be valid as long as the same cs_main lock is being held */ bool BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main); bool TipMayBeStale() EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has * at most count entries. */ void FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Request blocks for the background chainstate, if one is in use. */ void TryDownloadingHistoricalBlocks(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, const CBlockIndex* from_tip, const CBlockIndex* target_block) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** * \brief Find next blocks to download from a peer after a starting block. * * \param vBlocks Vector of blocks to download which will be appended to. * \param peer Peer which blocks will be downloaded from. * \param state Pointer to the state of the peer. * \param pindexWalk Pointer to the starting block to add to vBlocks. * \param count Maximum number of blocks to allow in vBlocks. No more * blocks will be added if it reaches this size. * \param nWindowEnd Maximum height of blocks to allow in vBlocks. No * blocks will be added above this height. * \param activeChain Optional pointer to a chain to compare against. If * provided, any next blocks which are already contained * in this chain will not be appended to vBlocks, but * instead will be used to update the * state->pindexLastCommonBlock pointer. * \param nodeStaller Optional pointer to a NodeId variable that will receive * the ID of another peer that might be causing this peer * to stall. This is set to the ID of the peer which * first requested the first in-flight block in the * download window. It is only set if vBlocks is empty at * the end of this function call and if increasing * nWindowEnd by 1 would cause it to be non-empty (which * indicates the download might be stalled because every * block in the window is in flight and no other peer is * trying to download the next block). */ void FindNextBlocks(std::vector<const CBlockIndex*>& vBlocks, const Peer& peer, CNodeState *state, const CBlockIndex *pindexWalk, unsigned int count, int nWindowEnd, const CChain* activeChain=nullptr, NodeId* nodeStaller=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /* Multimap used to preserve insertion order */ typedef std::multimap<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator>> BlockDownloadMap; BlockDownloadMap mapBlocksInFlight GUARDED_BY(cs_main); /** When our tip was last updated. */ std::atomic<std::chrono::seconds> m_last_tip_update{0s}; /** Determine whether or not a peer can request a transaction, and return it (or nullptr if not found or not allowed). */ CTransactionRef FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid) EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, NetEventsInterface::g_msgproc_mutex); void ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc) EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, peer.m_getdata_requests_mutex, NetEventsInterface::g_msgproc_mutex) LOCKS_EXCLUDED(::cs_main); /** Process a new block. Perform any post-processing housekeeping */ void ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked); /** Process compact block txns */ void ProcessCompactBlockTxns(CNode& pfrom, Peer& peer, const BlockTransactions& block_transactions) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex, !m_most_recent_block_mutex); /** * When a peer sends us a valid block, instruct it to announce blocks to us * using CMPCTBLOCK if possible by adding its nodeid to the end of * lNodesAnnouncingHeaderAndIDs, and keeping that list under a certain size by * removing the first element if necessary. */ void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Stack of nodes which we have set to announce using compact blocks */ std::list<NodeId> lNodesAnnouncingHeaderAndIDs GUARDED_BY(cs_main); /** Number of peers from which we're downloading blocks. */ int m_peers_downloading_from GUARDED_BY(cs_main) = 0; /** Storage for orphan information */ TxOrphanage m_orphanage; void AddToCompactExtraTransactions(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); /** Orphan/conflicted/etc transactions that are kept for compact block reconstruction. * The last -blockreconstructionextratxn/DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN of * these are kept in a ring buffer */ std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(g_msgproc_mutex); /** Offset into vExtraTxnForCompact to insert the next tx */ size_t vExtraTxnForCompactIt GUARDED_BY(g_msgproc_mutex) = 0; /** Check whether the last unknown block a peer advertised is not yet known. */ void ProcessBlockAvailability(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Update tracking information about which blocks a peer is assumed to have. */ void UpdateBlockAvailability(NodeId nodeid, const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); bool CanDirectFetch() EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** * To prevent fingerprinting attacks, only send blocks/headers outside of * the active chain if they are no more than a month older (both in time, * and in best equivalent proof of work) than the best header chain we know * about and we fully-validated them at some point. */ bool BlockRequestAllowed(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main); bool AlreadyHaveBlock(const uint256& block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); void ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex); /** * Validation logic for compact filters request handling. * * May disconnect from the peer in the case of a bad request. * * @param[in] node The node that we received the request from * @param[in] peer The peer that we received the request from * @param[in] filter_type The filter type the request is for. Must be basic filters. * @param[in] start_height The start height for the request * @param[in] stop_hash The stop_hash for the request * @param[in] max_height_diff The maximum number of items permitted to request, as specified in BIP 157 * @param[out] stop_index The CBlockIndex for the stop_hash block, if the request can be serviced. * @param[out] filter_index The filter index, if the request can be serviced. * @return True if the request can be serviced. */ bool PrepareBlockFilterRequest(CNode& node, Peer& peer, BlockFilterType filter_type, uint32_t start_height, const uint256& stop_hash, uint32_t max_height_diff, const CBlockIndex*& stop_index, BlockFilterIndex*& filter_index); /** * Handle a cfilters request. * * May disconnect from the peer in the case of a bad request. * * @param[in] node The node that we received the request from * @param[in] peer The peer that we received the request from * @param[in] vRecv The raw message received */ void ProcessGetCFilters(CNode& node, Peer& peer, DataStream& vRecv); /** * Handle a cfheaders request. * * May disconnect from the peer in the case of a bad request. * * @param[in] node The node that we received the request from * @param[in] peer The peer that we received the request from * @param[in] vRecv The raw message received */ void ProcessGetCFHeaders(CNode& node, Peer& peer, DataStream& vRecv); /** * Handle a getcfcheckpt request. * * May disconnect from the peer in the case of a bad request. * * @param[in] node The node that we received the request from * @param[in] peer The peer that we received the request from * @param[in] vRecv The raw message received */ void ProcessGetCFCheckPt(CNode& node, Peer& peer, DataStream& vRecv); /** Checks if address relay is permitted with peer. If needed, initializes * the m_addr_known bloom filter and sets m_addr_relay_enabled to true. * * @return True if address relay is enabled with peer * False if address relay is disallowed */ bool SetupAddressRelay(const CNode& node, Peer& peer) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); void AddAddressKnown(Peer& peer, const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); void PushAddress(Peer& peer, const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex); }; const CNodeState* PeerManagerImpl::State(NodeId pnode) const EXCLUSIVE_LOCKS_REQUIRED(cs_main) { std::map<NodeId, CNodeState>::const_iterator it = m_node_states.find(pnode); if (it == m_node_states.end()) return nullptr; return &it->second; } CNodeState* PeerManagerImpl::State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return const_cast<CNodeState*>(std::as_const(*this).State(pnode)); } /** * Whether the peer supports the address. For example, a peer that does not * implement BIP155 cannot receive Tor v3 addresses because it requires * ADDRv2 (BIP155) encoding. */ static bool IsAddrCompatible(const Peer& peer, const CAddress& addr) { return peer.m_wants_addrv2 || addr.IsAddrV1Compatible(); } void PeerManagerImpl::AddAddressKnown(Peer& peer, const CAddress& addr) { assert(peer.m_addr_known); peer.m_addr_known->insert(addr.GetKey()); } void PeerManagerImpl::PushAddress(Peer& peer, const CAddress& addr) { // Known checking here is only to save space from duplicates. // Before sending, we'll filter it again for known addresses that were // added after addresses were pushed. assert(peer.m_addr_known); if (addr.IsValid() && !peer.m_addr_known->contains(addr.GetKey()) && IsAddrCompatible(peer, addr)) { if (peer.m_addrs_to_send.size() >= MAX_ADDR_TO_SEND) { peer.m_addrs_to_send[m_rng.randrange(peer.m_addrs_to_send.size())] = addr; } else { peer.m_addrs_to_send.push_back(addr); } } } static void AddKnownTx(Peer& peer, const uint256& hash) { auto tx_relay = peer.GetTxRelay(); if (!tx_relay) return; LOCK(tx_relay->m_tx_inventory_mutex); tx_relay->m_tx_inventory_known_filter.insert(hash); } /** Whether this peer can serve us blocks. */ static bool CanServeBlocks(const Peer& peer) { return peer.m_their_services & (NODE_NETWORK|NODE_NETWORK_LIMITED); } /** Whether this peer can only serve limited recent blocks (e.g. because * it prunes old blocks) */ static bool IsLimitedPeer(const Peer& peer) { return (!(peer.m_their_services & NODE_NETWORK) && (peer.m_their_services & NODE_NETWORK_LIMITED)); } /** Whether this peer can serve us witness data */ static bool CanServeWitnesses(const Peer& peer) { return peer.m_their_services & NODE_WITNESS; } std::chrono::microseconds PeerManagerImpl::NextInvToInbounds(std::chrono::microseconds now, std::chrono::seconds average_interval) { if (m_next_inv_to_inbounds.load() < now) { // If this function were called from multiple threads simultaneously // it would possible that both update the next send variable, and return a different result to their caller. // This is not possible in practice as only the net processing thread invokes this function. m_next_inv_to_inbounds = GetExponentialRand(now, average_interval); } return m_next_inv_to_inbounds; } bool PeerManagerImpl::IsBlockRequested(const uint256& hash) { return mapBlocksInFlight.count(hash); } bool PeerManagerImpl::IsBlockRequestedFromOutbound(const uint256& hash) { for (auto range = mapBlocksInFlight.equal_range(hash); range.first != range.second; range.first++) { auto [nodeid, block_it] = range.first->second; CNodeState& nodestate = *Assert(State(nodeid)); if (!nodestate.m_is_inbound) return true; } return false; } void PeerManagerImpl::RemoveBlockRequest(const uint256& hash, std::optional<NodeId> from_peer) { auto range = mapBlocksInFlight.equal_range(hash); if (range.first == range.second) { // Block was not requested from any peer return; } // We should not have requested too many of this block Assume(mapBlocksInFlight.count(hash) <= MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK); while (range.first != range.second) { auto [node_id, list_it] = range.first->second; if (from_peer && *from_peer != node_id) { range.first++; continue; } CNodeState& state = *Assert(State(node_id)); if (state.vBlocksInFlight.begin() == list_it) { // First block on the queue was received, update the start download time for the next one state.m_downloading_since = std::max(state.m_downloading_since, GetTime<std::chrono::microseconds>()); } state.vBlocksInFlight.erase(list_it); if (state.vBlocksInFlight.empty()) { // Last validated block on the queue for this peer was received. m_peers_downloading_from--; } state.m_stalling_since = 0us; range.first = mapBlocksInFlight.erase(range.first); } } bool PeerManagerImpl::BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit) { const uint256& hash{block.GetBlockHash()}; CNodeState *state = State(nodeid); assert(state != nullptr); Assume(mapBlocksInFlight.count(hash) <= MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK); // Short-circuit most stuff in case it is from the same node for (auto range = mapBlocksInFlight.equal_range(hash); range.first != range.second; range.first++) { if (range.first->second.first == nodeid) { if (pit) { *pit = &range.first->second.second; } return false; } } // Make sure it's not being fetched already from same peer. RemoveBlockRequest(hash, nodeid); std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), {&block, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&m_mempool) : nullptr)}); if (state->vBlocksInFlight.size() == 1) { // We're starting a block download (batch) from this peer. state->m_downloading_since = GetTime<std::chrono::microseconds>(); m_peers_downloading_from++; } auto itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))); if (pit) { *pit = &itInFlight->second.second; } return true; } void PeerManagerImpl::MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid) { AssertLockHeld(cs_main); // When in -blocksonly mode, never request high-bandwidth mode from peers. Our // mempool will not contain the transactions necessary to reconstruct the // compact block. if (m_opts.ignore_incoming_txs) return; CNodeState* nodestate = State(nodeid); if (!nodestate || !nodestate->m_provides_cmpctblocks) { // Don't request compact blocks if the peer has not signalled support return; } int num_outbound_hb_peers = 0; for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) { if (*it == nodeid) { lNodesAnnouncingHeaderAndIDs.erase(it); lNodesAnnouncingHeaderAndIDs.push_back(nodeid); return; } CNodeState *state = State(*it); if (state != nullptr && !state->m_is_inbound) ++num_outbound_hb_peers; } if (nodestate->m_is_inbound) { // If we're adding an inbound HB peer, make sure we're not removing // our last outbound HB peer in the process. if (lNodesAnnouncingHeaderAndIDs.size() >= 3 && num_outbound_hb_peers == 1) { CNodeState *remove_node = State(lNodesAnnouncingHeaderAndIDs.front()); if (remove_node != nullptr && !remove_node->m_is_inbound) { // Put the HB outbound peer in the second slot, so that it // doesn't get removed. std::swap(lNodesAnnouncingHeaderAndIDs.front(), *std::next(lNodesAnnouncingHeaderAndIDs.begin())); } } } m_connman.ForNode(nodeid, [this](CNode* pfrom) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { AssertLockHeld(::cs_main); if (lNodesAnnouncingHeaderAndIDs.size() >= 3) { // As per BIP152, we only get 3 of our peers to announce // blocks using compact encodings. m_connman.ForNode(lNodesAnnouncingHeaderAndIDs.front(), [this](CNode* pnodeStop){ MakeAndPushMessage(*pnodeStop, NetMsgType::SENDCMPCT, /*high_bandwidth=*/false, /*version=*/CMPCTBLOCKS_VERSION); // save BIP152 bandwidth state: we select peer to be low-bandwidth pnodeStop->m_bip152_highbandwidth_to = false; return true; }); lNodesAnnouncingHeaderAndIDs.pop_front(); } MakeAndPushMessage(*pfrom, NetMsgType::SENDCMPCT, /*high_bandwidth=*/true, /*version=*/CMPCTBLOCKS_VERSION); // save BIP152 bandwidth state: we select peer to be high-bandwidth pfrom->m_bip152_highbandwidth_to = true; lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId()); return true; }); } bool PeerManagerImpl::TipMayBeStale() { AssertLockHeld(cs_main); const Consensus::Params& consensusParams = m_chainparams.GetConsensus(); if (m_last_tip_update.load() == 0s) { m_last_tip_update = GetTime<std::chrono::seconds>(); } return m_last_tip_update.load() < GetTime<std::chrono::seconds>() - std::chrono::seconds{consensusParams.nPowTargetSpacing * 3} && mapBlocksInFlight.empty(); } bool PeerManagerImpl::CanDirectFetch() { return m_chainman.ActiveChain().Tip()->Time() > GetAdjustedTime() - m_chainparams.GetConsensus().PowTargetSpacing() * 20; } static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight)) return true; if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight)) return true; return false; } void PeerManagerImpl::ProcessBlockAvailability(NodeId nodeid) { CNodeState *state = State(nodeid); assert(state != nullptr); if (!state->hashLastUnknownBlock.IsNull()) { const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(state->hashLastUnknownBlock); if (pindex && pindex->nChainWork > 0) { if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) { state->pindexBestKnownBlock = pindex; } state->hashLastUnknownBlock.SetNull(); } } } void PeerManagerImpl::UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) { CNodeState *state = State(nodeid); assert(state != nullptr); ProcessBlockAvailability(nodeid); const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash); if (pindex && pindex->nChainWork > 0) { // An actually better block was announced. if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) { state->pindexBestKnownBlock = pindex; } } else { // An unknown block was announced; just assume that the latest one is the best one. state->hashLastUnknownBlock = hash; } } // Logic for calculating which blocks to download from a given peer, given our current tip. void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller) { if (count == 0) return; vBlocks.reserve(vBlocks.size() + count); CNodeState *state = State(peer.m_id); assert(state != nullptr); // Make sure pindexBestKnownBlock is up to date, we'll need it. ProcessBlockAvailability(peer.m_id); if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < m_chainman.ActiveChain().Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < m_chainman.MinimumChainWork()) { // This peer has nothing interesting. return; } if (state->pindexLastCommonBlock == nullptr) { // Bootstrap quickly by guessing a parent of our best tip is the forking point. // Guessing wrong in either direction is not a problem. state->pindexLastCommonBlock = m_chainman.ActiveChain()[std::min(state->pindexBestKnownBlock->nHeight, m_chainman.ActiveChain().Height())]; } // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor // of its current tip anymore. Go back enough to fix that. state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock); if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) return; const CBlockIndex *pindexWalk = state->pindexLastCommonBlock; // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to // download that next block if the window were 1 larger. int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW; FindNextBlocks(vBlocks, peer, state, pindexWalk, count, nWindowEnd, &m_chainman.ActiveChain(), &nodeStaller); } void PeerManagerImpl::TryDownloadingHistoricalBlocks(const Peer& peer, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, const CBlockIndex *from_tip, const CBlockIndex* target_block) { Assert(from_tip); Assert(target_block); if (vBlocks.size() >= count) { return; } vBlocks.reserve(count); CNodeState *state = Assert(State(peer.m_id)); if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->GetAncestor(target_block->nHeight) != target_block) { // This peer can't provide us the complete series of blocks leading up to the // assumeutxo snapshot base. // // Presumably this peer's chain has less work than our ActiveChain()'s tip, or else we // will eventually crash when we try to reorg to it. Let other logic // deal with whether we disconnect this peer. // // TODO at some point in the future, we might choose to request what blocks // this peer does have from the historical chain, despite it not having a // complete history beneath the snapshot base. return; } FindNextBlocks(vBlocks, peer, state, from_tip, count, std::min<int>(from_tip->nHeight + BLOCK_DOWNLOAD_WINDOW, target_block->nHeight)); } void PeerManagerImpl::FindNextBlocks(std::vector<const CBlockIndex*>& vBlocks, const Peer& peer, CNodeState *state, const CBlockIndex *pindexWalk, unsigned int count, int nWindowEnd, const CChain* activeChain, NodeId* nodeStaller) { std::vector<const CBlockIndex*> vToFetch; int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1); NodeId waitingfor = -1; while (pindexWalk->nHeight < nMaxHeight) { // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive // as iterating over ~100 CBlockIndex* entries anyway. int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128)); vToFetch.resize(nToFetch); pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch); vToFetch[nToFetch - 1] = pindexWalk; for (unsigned int i = nToFetch - 1; i > 0; i--) { vToFetch[i - 1] = vToFetch[i]->pprev; } // Iterate over those blocks in vToFetch (in forward direction), adding the ones that // are not yet downloaded and not in flight to vBlocks. In the meantime, update // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's // already part of our chain (and therefore don't need it even if pruned). for (const CBlockIndex* pindex : vToFetch) { if (!pindex->IsValid(BLOCK_VALID_TREE)) { // We consider the chain that this peer is on invalid. return; } if (!CanServeWitnesses(peer) && DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) { // We wouldn't download this block or its descendants from this peer. return; } if (pindex->nStatus & BLOCK_HAVE_DATA || (activeChain && activeChain->Contains(pindex))) { if (activeChain && pindex->HaveNumChainTxs()) state->pindexLastCommonBlock = pindex; } else if (!IsBlockRequested(pindex->GetBlockHash())) { // The block is not already downloaded, and not yet in flight. if (pindex->nHeight > nWindowEnd) { // We reached the end of the window. if (vBlocks.size() == 0 && waitingfor != peer.m_id) { // We aren't able to fetch anything, but we would be if the download window was one larger. if (nodeStaller) *nodeStaller = waitingfor; } return; } vBlocks.push_back(pindex); if (vBlocks.size() == count) { return; } } else if (waitingfor == -1) { // This is the first already-in-flight block. waitingfor = mapBlocksInFlight.lower_bound(pindex->GetBlockHash())->second.first; } } } } } // namespace void PeerManagerImpl::PushNodeVersion(CNode& pnode, const Peer& peer) { uint64_t my_services{peer.m_our_services}; const int64_t nTime{count_seconds(GetTime<std::chrono::seconds>())}; uint64_t nonce = pnode.GetLocalNonce(); const int nNodeStartingHeight{m_best_height}; NodeId nodeid = pnode.GetId(); CAddress addr = pnode.addr; CService addr_you = addr.IsRoutable() && !IsProxy(addr) && addr.IsAddrV1Compatible() ? addr : CService(); uint64_t your_services{addr.nServices}; const bool tx_relay{!RejectIncomingTxs(pnode)}; MakeAndPushMessage(pnode, NetMsgType::VERSION, PROTOCOL_VERSION, my_services, nTime, your_services, CNetAddr::V1(addr_you), // Together the pre-version-31402 serialization of CAddress "addrYou" (without nTime) my_services, CNetAddr::V1(CService{}), // Together the pre-version-31402 serialization of CAddress "addrMe" (without nTime) nonce, strSubVersion, nNodeStartingHeight, tx_relay); if (fLogIPs) { LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, them=%s, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addr_you.ToStringAddrPort(), tx_relay, nodeid); } else { LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, tx_relay, nodeid); } } void PeerManagerImpl::AddTxAnnouncement(const CNode& node, const GenTxid& gtxid, std::chrono::microseconds current_time) { AssertLockHeld(::cs_main); // For m_txrequest NodeId nodeid = node.GetId(); if (!node.HasPermission(NetPermissionFlags::Relay) && m_txrequest.Count(nodeid) >= MAX_PEER_TX_ANNOUNCEMENTS) { // Too many queued announcements from this peer return; } const CNodeState* state = State(nodeid); // Decide the TxRequestTracker parameters for this announcement: // - "preferred": if fPreferredDownload is set (= outbound, or NetPermissionFlags::NoBan permission) // - "reqtime": current time plus delays for: // - NONPREF_PEER_TX_DELAY for announcements from non-preferred connections // - TXID_RELAY_DELAY for txid announcements while wtxid peers are available // - OVERLOADED_PEER_TX_DELAY for announcements from peers which have at least // MAX_PEER_TX_REQUEST_IN_FLIGHT requests in flight (and don't have NetPermissionFlags::Relay). auto delay{0us}; const bool preferred = state->fPreferredDownload; if (!preferred) delay += NONPREF_PEER_TX_DELAY; if (!gtxid.IsWtxid() && m_wtxid_relay_peers > 0) delay += TXID_RELAY_DELAY; const bool overloaded = !node.HasPermission(NetPermissionFlags::Relay) && m_txrequest.CountInFlight(nodeid) >= MAX_PEER_TX_REQUEST_IN_FLIGHT; if (overloaded) delay += OVERLOADED_PEER_TX_DELAY; m_txrequest.ReceivedInv(nodeid, gtxid, preferred, current_time + delay); } void PeerManagerImpl::UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) { LOCK(cs_main); CNodeState *state = State(node); if (state) state->m_last_block_announcement = time_in_seconds; } void PeerManagerImpl::InitializeNode(CNode& node, ServiceFlags our_services) { NodeId nodeid = node.GetId(); { LOCK(cs_main); m_node_states.emplace_hint(m_node_states.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(node.IsInboundConn())); assert(m_txrequest.Count(nodeid) == 0); } PeerRef peer = std::make_shared<Peer>(nodeid, our_services); { LOCK(m_peer_mutex); m_peer_map.emplace_hint(m_peer_map.end(), nodeid, peer); } if (!node.IsInboundConn()) { PushNodeVersion(node, *peer); } } void PeerManagerImpl::ReattemptInitialBroadcast(CScheduler& scheduler) { std::set<uint256> unbroadcast_txids = m_mempool.GetUnbroadcastTxs(); for (const auto& txid : unbroadcast_txids) { CTransactionRef tx = m_mempool.get(txid); if (tx != nullptr) { RelayTransaction(txid, tx->GetWitnessHash()); } else { m_mempool.RemoveUnbroadcastTx(txid, true); } } // Schedule next run for 10-15 minutes in the future. // We add randomness on every cycle to avoid the possibility of P2P fingerprinting. const std::chrono::milliseconds delta = 10min + GetRandMillis(5min); scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta); } void PeerManagerImpl::FinalizeNode(const CNode& node) { NodeId nodeid = node.GetId(); int misbehavior{0}; { LOCK(cs_main); { // We remove the PeerRef from g_peer_map here, but we don't always // destruct the Peer. Sometimes another thread is still holding a // PeerRef, so the refcount is >= 1. Be careful not to do any // processing here that assumes Peer won't be changed before it's // destructed. PeerRef peer = RemovePeer(nodeid); assert(peer != nullptr); misbehavior = WITH_LOCK(peer->m_misbehavior_mutex, return peer->m_misbehavior_score); m_wtxid_relay_peers -= peer->m_wtxid_relay; assert(m_wtxid_relay_peers >= 0); } CNodeState *state = State(nodeid); assert(state != nullptr); if (state->fSyncStarted) nSyncStarted--; for (const QueuedBlock& entry : state->vBlocksInFlight) { auto range = mapBlocksInFlight.equal_range(entry.pindex->GetBlockHash()); while (range.first != range.second) { auto [node_id, list_it] = range.first->second; if (node_id != nodeid) { range.first++; } else { range.first = mapBlocksInFlight.erase(range.first); } } } m_orphanage.EraseForPeer(nodeid); m_txrequest.DisconnectedPeer(nodeid); if (m_txreconciliation) m_txreconciliation->ForgetPeer(nodeid); m_num_preferred_download_peers -= state->fPreferredDownload; m_peers_downloading_from -= (!state->vBlocksInFlight.empty()); assert(m_peers_downloading_from >= 0); m_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect; assert(m_outbound_peers_with_protect_from_disconnect >= 0); m_node_states.erase(nodeid); if (m_node_states.empty()) { // Do a consistency check after the last peer is removed. assert(mapBlocksInFlight.empty()); assert(m_num_preferred_download_peers == 0); assert(m_peers_downloading_from == 0); assert(m_outbound_peers_with_protect_from_disconnect == 0); assert(m_wtxid_relay_peers == 0); assert(m_txrequest.Size() == 0); assert(m_orphanage.Size() == 0); } } // cs_main if (node.fSuccessfullyConnected && misbehavior == 0 && !node.IsBlockOnlyConn() && !node.IsInboundConn()) { // Only change visible addrman state for full outbound peers. We don't // call Connected() for feeler connections since they don't have // fSuccessfullyConnected set. m_addrman.Connected(node.addr); } { LOCK(m_headers_presync_mutex); m_headers_presync_stats.erase(nodeid); } LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid); } PeerRef PeerManagerImpl::GetPeerRef(NodeId id) const { LOCK(m_peer_mutex); auto it = m_peer_map.find(id); return it != m_peer_map.end() ? it->second : nullptr; } PeerRef PeerManagerImpl::RemovePeer(NodeId id) { PeerRef ret; LOCK(m_peer_mutex); auto it = m_peer_map.find(id); if (it != m_peer_map.end()) { ret = std::move(it->second); m_peer_map.erase(it); } return ret; } bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const { { LOCK(cs_main); const CNodeState* state = State(nodeid); if (state == nullptr) return false; stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1; stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1; for (const QueuedBlock& queue : state->vBlocksInFlight) { if (queue.pindex) stats.vHeightInFlight.push_back(queue.pindex->nHeight); } } PeerRef peer = GetPeerRef(nodeid); if (peer == nullptr) return false; stats.their_services = peer->m_their_services; stats.m_starting_height = peer->m_starting_height; // It is common for nodes with good ping times to suddenly become lagged, // due to a new block arriving or other large transfer. // Merely reporting pingtime might fool the caller into thinking the node was still responsive, // since pingtime does not update until the ping is complete, which might take a while. // So, if a ping is taking an unusually long time in flight, // the caller can immediately detect that this is happening. auto ping_wait{0us}; if ((0 != peer->m_ping_nonce_sent) && (0 != peer->m_ping_start.load().count())) { ping_wait = GetTime<std::chrono::microseconds>() - peer->m_ping_start.load(); } if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { stats.m_relay_txs = WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs); stats.m_fee_filter_received = tx_relay->m_fee_filter_received.load(); } else { stats.m_relay_txs = false; stats.m_fee_filter_received = 0; } stats.m_ping_wait = ping_wait; stats.m_addr_processed = peer->m_addr_processed.load(); stats.m_addr_rate_limited = peer->m_addr_rate_limited.load(); stats.m_addr_relay_enabled = peer->m_addr_relay_enabled.load(); { LOCK(peer->m_headers_sync_mutex); if (peer->m_headers_sync) { stats.presync_height = peer->m_headers_sync->GetPresyncHeight(); } } return true; } void PeerManagerImpl::AddToCompactExtraTransactions(const CTransactionRef& tx) { if (m_opts.max_extra_txs <= 0) return; if (!vExtraTxnForCompact.size()) vExtraTxnForCompact.resize(m_opts.max_extra_txs); vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx); vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % m_opts.max_extra_txs; } void PeerManagerImpl::Misbehaving(Peer& peer, int howmuch, const std::string& message) { assert(howmuch > 0); LOCK(peer.m_misbehavior_mutex); const int score_before{peer.m_misbehavior_score}; peer.m_misbehavior_score += howmuch; const int score_now{peer.m_misbehavior_score}; const std::string message_prefixed = message.empty() ? "" : (": " + message); std::string warning; if (score_now >= DISCOURAGEMENT_THRESHOLD && score_before < DISCOURAGEMENT_THRESHOLD) { warning = " DISCOURAGE THRESHOLD EXCEEDED"; peer.m_should_discourage = true; } LogPrint(BCLog::NET, "Misbehaving: peer=%d (%d -> %d)%s%s\n", peer.m_id, score_before, score_now, warning, message_prefixed); } bool PeerManagerImpl::MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state, bool via_compact_block, const std::string& message) { PeerRef peer{GetPeerRef(nodeid)}; switch (state.GetResult()) { case BlockValidationResult::BLOCK_RESULT_UNSET: break; case BlockValidationResult::BLOCK_HEADER_LOW_WORK: // We didn't try to process the block because the header chain may have // too little work. break; // The node is providing invalid data: case BlockValidationResult::BLOCK_CONSENSUS: case BlockValidationResult::BLOCK_MUTATED: if (!via_compact_block) { if (peer) Misbehaving(*peer, 100, message); return true; } break; case BlockValidationResult::BLOCK_CACHED_INVALID: { LOCK(cs_main); CNodeState *node_state = State(nodeid); if (node_state == nullptr) { break; } // Discourage outbound (but not inbound) peers if on an invalid chain. // Exempt HB compact block peers. Manual connections are always protected from discouragement. if (!via_compact_block && !node_state->m_is_inbound) { if (peer) Misbehaving(*peer, 100, message); return true; } break; } case BlockValidationResult::BLOCK_INVALID_HEADER: case BlockValidationResult::BLOCK_CHECKPOINT: case BlockValidationResult::BLOCK_INVALID_PREV: if (peer) Misbehaving(*peer, 100, message); return true; // Conflicting (but not necessarily invalid) data or different policy: case BlockValidationResult::BLOCK_MISSING_PREV: // TODO: Handle this much more gracefully (10 DoS points is super arbitrary) if (peer) Misbehaving(*peer, 10, message); return true; case BlockValidationResult::BLOCK_RECENT_CONSENSUS_CHANGE: case BlockValidationResult::BLOCK_TIME_FUTURE: break; } if (message != "") { LogPrint(BCLog::NET, "peer=%d: %s\n", nodeid, message); } return false; } bool PeerManagerImpl::MaybePunishNodeForTx(NodeId nodeid, const TxValidationState& state) { PeerRef peer{GetPeerRef(nodeid)}; switch (state.GetResult()) { case TxValidationResult::TX_RESULT_UNSET: break; // The node is providing invalid data: case TxValidationResult::TX_CONSENSUS: if (peer) Misbehaving(*peer, 100, ""); return true; // Conflicting (but not necessarily invalid) data or different policy: case TxValidationResult::TX_RECENT_CONSENSUS_CHANGE: case TxValidationResult::TX_INPUTS_NOT_STANDARD: case TxValidationResult::TX_NOT_STANDARD: case TxValidationResult::TX_MISSING_INPUTS: case TxValidationResult::TX_PREMATURE_SPEND: case TxValidationResult::TX_WITNESS_MUTATED: case TxValidationResult::TX_WITNESS_STRIPPED: case TxValidationResult::TX_CONFLICT: case TxValidationResult::TX_MEMPOOL_POLICY: case TxValidationResult::TX_NO_MEMPOOL: case TxValidationResult::TX_RECONSIDERABLE: case TxValidationResult::TX_UNKNOWN: break; } return false; } bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex) { AssertLockHeld(cs_main); if (m_chainman.ActiveChain().Contains(pindex)) return true; return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (m_chainman.m_best_header != nullptr) && (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) && (GetBlockProofEquivalentTime(*m_chainman.m_best_header, *pindex, *m_chainman.m_best_header, m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT); } std::optional<std::string> PeerManagerImpl::FetchBlock(NodeId peer_id, const CBlockIndex& block_index) { if (m_chainman.m_blockman.LoadingBlocks()) return "Loading blocks ..."; // Ensure this peer exists and hasn't been disconnected PeerRef peer = GetPeerRef(peer_id); if (peer == nullptr) return "Peer does not exist"; // Ignore pre-segwit peers if (!CanServeWitnesses(*peer)) return "Pre-SegWit peer"; LOCK(cs_main); // Forget about all prior requests RemoveBlockRequest(block_index.GetBlockHash(), std::nullopt); // Mark block as in-flight if (!BlockRequested(peer_id, block_index)) return "Already requested from this peer"; // Construct message to request the block const uint256& hash{block_index.GetBlockHash()}; std::vector<CInv> invs{CInv(MSG_BLOCK | MSG_WITNESS_FLAG, hash)}; // Send block request message to the peer bool success = m_connman.ForNode(peer_id, [this, &invs](CNode* node) { this->MakeAndPushMessage(*node, NetMsgType::GETDATA, invs); return true; }); if (!success) return "Peer not fully connected"; LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n", hash.ToString(), peer_id); return std::nullopt; } std::unique_ptr<PeerManager> PeerManager::make(CConnman& connman, AddrMan& addrman, BanMan* banman, ChainstateManager& chainman, CTxMemPool& pool, Options opts) { return std::make_unique<PeerManagerImpl>(connman, addrman, banman, chainman, pool, opts); } PeerManagerImpl::PeerManagerImpl(CConnman& connman, AddrMan& addrman, BanMan* banman, ChainstateManager& chainman, CTxMemPool& pool, Options opts) : m_rng{opts.deterministic_rng}, m_fee_filter_rounder{CFeeRate{DEFAULT_MIN_RELAY_TX_FEE}, m_rng}, m_chainparams(chainman.GetParams()), m_connman(connman), m_addrman(addrman), m_banman(banman), m_chainman(chainman), m_mempool(pool), m_opts{opts} { // While Erlay support is incomplete, it must be enabled explicitly via -txreconciliation. // This argument can go away after Erlay support is complete. if (opts.reconcile_txs) { m_txreconciliation = std::make_unique<TxReconciliationTracker>(TXRECONCILIATION_VERSION); } } void PeerManagerImpl::StartScheduledTasks(CScheduler& scheduler) { // Stale tip checking and peer eviction are on two different timers, but we // don't want them to get out of sync due to drift in the scheduler, so we // combine them in one function and schedule at the quicker (peer-eviction) // timer. static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer"); scheduler.scheduleEvery([this] { this->CheckForStaleTipAndEvictPeers(); }, std::chrono::seconds{EXTRA_PEER_CHECK_INTERVAL}); // schedule next run for 10-15 minutes in the future const std::chrono::milliseconds delta = 10min + GetRandMillis(5min); scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta); } /** * Evict orphan txn pool entries based on a newly connected * block, remember the recently confirmed transactions, and delete tracked * announcements for them. Also save the time of the last tip update and * possibly reduce dynamic block stalling timeout. */ void PeerManagerImpl::BlockConnected( ChainstateRole role, const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex) { // Update this for all chainstate roles so that we don't mistakenly see peers // helping us do background IBD as having a stale tip. m_last_tip_update = GetTime<std::chrono::seconds>(); // In case the dynamic timeout was doubled once or more, reduce it slowly back to its default value auto stalling_timeout = m_block_stalling_timeout.load(); Assume(stalling_timeout >= BLOCK_STALLING_TIMEOUT_DEFAULT); if (stalling_timeout != BLOCK_STALLING_TIMEOUT_DEFAULT) { const auto new_timeout = std::max(std::chrono::duration_cast<std::chrono::seconds>(stalling_timeout * 0.85), BLOCK_STALLING_TIMEOUT_DEFAULT); if (m_block_stalling_timeout.compare_exchange_strong(stalling_timeout, new_timeout)) { LogPrint(BCLog::NET, "Decreased stalling timeout to %d seconds\n", count_seconds(new_timeout)); } } // The following task can be skipped since we don't maintain a mempool for // the ibd/background chainstate. if (role == ChainstateRole::BACKGROUND) { return; } m_orphanage.EraseForBlock(*pblock); { LOCK(m_recent_confirmed_transactions_mutex); for (const auto& ptx : pblock->vtx) { m_recent_confirmed_transactions.insert(ptx->GetHash().ToUint256()); if (ptx->HasWitness()) { m_recent_confirmed_transactions.insert(ptx->GetWitnessHash().ToUint256()); } } } { LOCK(cs_main); for (const auto& ptx : pblock->vtx) { m_txrequest.ForgetTxHash(ptx->GetHash()); m_txrequest.ForgetTxHash(ptx->GetWitnessHash()); } } } void PeerManagerImpl::BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex) { // To avoid relay problems with transactions that were previously // confirmed, clear our filter of recently confirmed transactions whenever // there's a reorg. // This means that in a 1-block reorg (where 1 block is disconnected and // then another block reconnected), our filter will drop to having only one // block's worth of transactions in it, but that should be fine, since // presumably the most common case of relaying a confirmed transaction // should be just after a new block containing it is found. LOCK(m_recent_confirmed_transactions_mutex); m_recent_confirmed_transactions.reset(); } /** * Maintain state about the best-seen block and fast-announce a compact block * to compatible peers. */ void PeerManagerImpl::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) { auto pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs>(*pblock); LOCK(cs_main); if (pindex->nHeight <= m_highest_fast_announce) return; m_highest_fast_announce = pindex->nHeight; if (!DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) return; uint256 hashBlock(pblock->GetHash()); const std::shared_future<CSerializedNetMsg> lazy_ser{ std::async(std::launch::deferred, [&] { return NetMsg::Make(NetMsgType::CMPCTBLOCK, *pcmpctblock); })}; { auto most_recent_block_txs = std::make_unique<std::map<uint256, CTransactionRef>>(); for (const auto& tx : pblock->vtx) { most_recent_block_txs->emplace(tx->GetHash(), tx); most_recent_block_txs->emplace(tx->GetWitnessHash(), tx); } LOCK(m_most_recent_block_mutex); m_most_recent_block_hash = hashBlock; m_most_recent_block = pblock; m_most_recent_compact_block = pcmpctblock; m_most_recent_block_txs = std::move(most_recent_block_txs); } m_connman.ForEachNode([this, pindex, &lazy_ser, &hashBlock](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { AssertLockHeld(::cs_main); if (pnode->GetCommonVersion() < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect) return; ProcessBlockAvailability(pnode->GetId()); CNodeState &state = *State(pnode->GetId()); // If the peer has, or we announced to them the previous block already, // but we don't think they have this one, go ahead and announce it if (state.m_requested_hb_cmpctblocks && !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) { LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerManager::NewPoWValidBlock", hashBlock.ToString(), pnode->GetId()); const CSerializedNetMsg& ser_cmpctblock{lazy_ser.get()}; PushMessage(*pnode, ser_cmpctblock.Copy()); state.pindexBestHeaderSent = pindex; } }); } /** * Update our best height and announce any block hashes which weren't previously * in m_chainman.ActiveChain() to our peers. */ void PeerManagerImpl::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) { SetBestHeight(pindexNew->nHeight); SetServiceFlagsIBDCache(!fInitialDownload); // Don't relay inventory during initial block download. if (fInitialDownload) return; // Find the hashes of all blocks that weren't previously in the best chain. std::vector<uint256> vHashes; const CBlockIndex *pindexToAnnounce = pindexNew; while (pindexToAnnounce != pindexFork) { vHashes.push_back(pindexToAnnounce->GetBlockHash()); pindexToAnnounce = pindexToAnnounce->pprev; if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) { // Limit announcements in case of a huge reorganization. // Rely on the peer's synchronization mechanism in that case. break; } } { LOCK(m_peer_mutex); for (auto& it : m_peer_map) { Peer& peer = *it.second; LOCK(peer.m_block_inv_mutex); for (const uint256& hash : reverse_iterate(vHashes)) { peer.m_blocks_for_headers_relay.push_back(hash); } } } m_connman.WakeMessageHandler(); } /** * Handle invalid block rejection and consequent peer discouragement, maintain which * peers announce compact blocks. */ void PeerManagerImpl::BlockChecked(const CBlock& block, const BlockValidationState& state) { LOCK(cs_main); const uint256 hash(block.GetHash()); std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash); // If the block failed validation, we know where it came from and we're still connected // to that peer, maybe punish. if (state.IsInvalid() && it != mapBlockSource.end() && State(it->second.first)) { MaybePunishNodeForBlock(/*nodeid=*/ it->second.first, state, /*via_compact_block=*/ !it->second.second); } // Check that: // 1. The block is valid // 2. We're not in initial block download // 3. This is currently the best block we're aware of. We haven't updated // the tip yet so we have no way to check this directly here. Instead we // just check that there are currently no other blocks in flight. else if (state.IsValid() && !m_chainman.IsInitialBlockDownload() && mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) { if (it != mapBlockSource.end()) { MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first); } } if (it != mapBlockSource.end()) mapBlockSource.erase(it); } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool PeerManagerImpl::AlreadyHaveTx(const GenTxid& gtxid) { if (m_chainman.ActiveChain().Tip()->GetBlockHash() != hashRecentRejectsChainTip) { // If the chain tip has changed previously rejected transactions // might be now valid, e.g. due to a nLockTime'd tx becoming valid, // or a double-spend. Reset the rejects filter and give those // txs a second chance. hashRecentRejectsChainTip = m_chainman.ActiveChain().Tip()->GetBlockHash(); m_recent_rejects.reset(); } const uint256& hash = gtxid.GetHash(); if (m_orphanage.HaveTx(gtxid)) return true; { LOCK(m_recent_confirmed_transactions_mutex); if (m_recent_confirmed_transactions.contains(hash)) return true; } return m_recent_rejects.contains(hash) || m_mempool.exists(gtxid); } bool PeerManagerImpl::AlreadyHaveBlock(const uint256& block_hash) { return m_chainman.m_blockman.LookupBlockIndex(block_hash) != nullptr; } void PeerManagerImpl::SendPings() { LOCK(m_peer_mutex); for(auto& it : m_peer_map) it.second->m_ping_queued = true; } void PeerManagerImpl::RelayTransaction(const uint256& txid, const uint256& wtxid) { LOCK(m_peer_mutex); for(auto& it : m_peer_map) { Peer& peer = *it.second; auto tx_relay = peer.GetTxRelay(); if (!tx_relay) continue; LOCK(tx_relay->m_tx_inventory_mutex); // Only queue transactions for announcement once the version handshake // is completed. The time of arrival for these transactions is // otherwise at risk of leaking to a spy, if the spy is able to // distinguish transactions received during the handshake from the rest // in the announcement. if (tx_relay->m_next_inv_send_time == 0s) continue; const uint256& hash{peer.m_wtxid_relay ? wtxid : txid}; if (!tx_relay->m_tx_inventory_known_filter.contains(hash)) { tx_relay->m_tx_inventory_to_send.insert(hash); } }; } void PeerManagerImpl::RelayAddress(NodeId originator, const CAddress& addr, bool fReachable) { // We choose the same nodes within a given 24h window (if the list of connected // nodes does not change) and we don't relay to nodes that already know an // address. So within 24h we will likely relay a given address once. This is to // prevent a peer from unjustly giving their address better propagation by sending // it to us repeatedly. if (!fReachable && !addr.IsRelayable()) return; // Relay to a limited number of other nodes // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the m_addr_knowns of the chosen nodes prevent repeats const uint64_t hash_addr{CServiceHash(0, 0)(addr)}; const auto current_time{GetTime<std::chrono::seconds>()}; // Adding address hash makes exact rotation time different per address, while preserving periodicity. const uint64_t time_addr{(static_cast<uint64_t>(count_seconds(current_time)) + hash_addr) / count_seconds(ROTATE_ADDR_RELAY_DEST_INTERVAL)}; const CSipHasher hasher{m_connman.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY) .Write(hash_addr) .Write(time_addr)}; // Relay reachable addresses to 2 peers. Unreachable addresses are relayed randomly to 1 or 2 peers. unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1; std::array<std::pair<uint64_t, Peer*>, 2> best{{{0, nullptr}, {0, nullptr}}}; assert(nRelayNodes <= best.size()); LOCK(m_peer_mutex); for (auto& [id, peer] : m_peer_map) { if (peer->m_addr_relay_enabled && id != originator && IsAddrCompatible(*peer, addr)) { uint64_t hashKey = CSipHasher(hasher).Write(id).Finalize(); for (unsigned int i = 0; i < nRelayNodes; i++) { if (hashKey > best[i].first) { std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1); best[i] = std::make_pair(hashKey, peer.get()); break; } } } }; for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) { PushAddress(*best[i].second, addr); } } void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv) { std::shared_ptr<const CBlock> a_recent_block; std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block; { LOCK(m_most_recent_block_mutex); a_recent_block = m_most_recent_block; a_recent_compact_block = m_most_recent_compact_block; } bool need_activate_chain = false; { LOCK(cs_main); const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash); if (pindex) { if (pindex->HaveNumChainTxs() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) && pindex->IsValid(BLOCK_VALID_TREE)) { // If we have the block and all of its parents, but have not yet validated it, // we might be in the middle of connecting it (ie in the unlock of cs_main // before ActivateBestChain but after AcceptBlock). // In this case, we need to run ActivateBestChain prior to checking the relay // conditions below. need_activate_chain = true; } } } // release cs_main before calling ActivateBestChain if (need_activate_chain) { BlockValidationState state; if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) { LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString()); } } LOCK(cs_main); const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash); if (!pindex) { return; } if (!BlockRequestAllowed(pindex)) { LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom.GetId()); return; } // disconnect node in case we have reached the outbound limit for serving historical blocks if (m_connman.OutboundTargetReached(true) && (((m_chainman.m_best_header != nullptr) && (m_chainman.m_best_header->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.IsMsgFilteredBlk()) && !pfrom.HasPermission(NetPermissionFlags::Download) // nodes with the download permission may exceed target ) { LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom.GetId()); pfrom.fDisconnect = true; return; } // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold if (!pfrom.HasPermission(NetPermissionFlags::NoBan) && ( (((peer.m_our_services & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((peer.m_our_services & NODE_NETWORK) != NODE_NETWORK) && (m_chainman.ActiveChain().Tip()->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) ) )) { LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold, disconnect peer=%d\n", pfrom.GetId()); //disconnect node and prevent it from stalling (would otherwise wait for the missing block) pfrom.fDisconnect = true; return; } // Pruned nodes may have deleted the block, so check whether // it's available before trying to send. if (!(pindex->nStatus & BLOCK_HAVE_DATA)) { return; } std::shared_ptr<const CBlock> pblock; if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) { pblock = a_recent_block; } else if (inv.IsMsgWitnessBlk()) { // Fast-path: in this case it is possible to serve the block directly from disk, // as the network format matches the format on disk std::vector<uint8_t> block_data; if (!m_chainman.m_blockman.ReadRawBlockFromDisk(block_data, pindex->GetBlockPos())) { assert(!"cannot load block from disk"); } MakeAndPushMessage(pfrom, NetMsgType::BLOCK, Span{block_data}); // Don't set pblock as we've sent the block } else { // Send block from disk std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>(); if (!m_chainman.m_blockman.ReadBlockFromDisk(*pblockRead, *pindex)) { assert(!"cannot load block from disk"); } pblock = pblockRead; } if (pblock) { if (inv.IsMsgBlk()) { MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_NO_WITNESS(*pblock)); } else if (inv.IsMsgWitnessBlk()) { MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_WITH_WITNESS(*pblock)); } else if (inv.IsMsgFilteredBlk()) { bool sendMerkleBlock = false; CMerkleBlock merkleBlock; if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) { LOCK(tx_relay->m_bloom_filter_mutex); if (tx_relay->m_bloom_filter) { sendMerkleBlock = true; merkleBlock = CMerkleBlock(*pblock, *tx_relay->m_bloom_filter); } } if (sendMerkleBlock) { MakeAndPushMessage(pfrom, NetMsgType::MERKLEBLOCK, merkleBlock); // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see // This avoids hurting performance by pointlessly requiring a round-trip // Note that there is currently no way for a node to request any single transactions we didn't send here - // they must either disconnect and retry or request the full block. // Thus, the protocol spec specified allows for us to provide duplicate txn here, // however we MUST always provide at least what the remote peer needs typedef std::pair<unsigned int, uint256> PairType; for (PairType& pair : merkleBlock.vMatchedTxn) MakeAndPushMessage(pfrom, NetMsgType::TX, TX_NO_WITNESS(*pblock->vtx[pair.first])); } // else // no response } else if (inv.IsMsgCmpctBlk()) { // If a peer is asking for old blocks, we're almost guaranteed // they won't have a useful mempool to match against a compact block, // and we don't feel like constructing the object for them, so // instead we respond with the full, non-compact block. if (CanDirectFetch() && pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_CMPCTBLOCK_DEPTH) { if (a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) { MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, *a_recent_compact_block); } else { CBlockHeaderAndShortTxIDs cmpctblock{*pblock}; MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, cmpctblock); } } else { MakeAndPushMessage(pfrom, NetMsgType::BLOCK, TX_WITH_WITNESS(*pblock)); } } } { LOCK(peer.m_block_inv_mutex); // Trigger the peer node to send a getblocks request for the next batch of inventory if (inv.hash == peer.m_continuation_block) { // Send immediately. This must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. std::vector<CInv> vInv; vInv.emplace_back(MSG_BLOCK, m_chainman.ActiveChain().Tip()->GetBlockHash()); MakeAndPushMessage(pfrom, NetMsgType::INV, vInv); peer.m_continuation_block.SetNull(); } } } CTransactionRef PeerManagerImpl::FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid) { // If a tx was in the mempool prior to the last INV for this peer, permit the request. auto txinfo = m_mempool.info_for_relay(gtxid, tx_relay.m_last_inv_sequence); if (txinfo.tx) { return std::move(txinfo.tx); } // Or it might be from the most recent block { LOCK(m_most_recent_block_mutex); if (m_most_recent_block_txs != nullptr) { auto it = m_most_recent_block_txs->find(gtxid.GetHash()); if (it != m_most_recent_block_txs->end()) return it->second; } } return {}; } void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc) { AssertLockNotHeld(cs_main); auto tx_relay = peer.GetTxRelay(); std::deque<CInv>::iterator it = peer.m_getdata_requests.begin(); std::vector<CInv> vNotFound; // Process as many TX items from the front of the getdata queue as // possible, since they're common and it's efficient to batch process // them. while (it != peer.m_getdata_requests.end() && it->IsGenTxMsg()) { if (interruptMsgProc) return; // The send buffer provides backpressure. If there's no space in // the buffer, pause processing until the next call. if (pfrom.fPauseSend) break; const CInv &inv = *it++; if (tx_relay == nullptr) { // Ignore GETDATA requests for transactions from block-relay-only // peers and peers that asked us not to announce transactions. continue; } CTransactionRef tx = FindTxForGetData(*tx_relay, ToGenTxid(inv)); if (tx) { // WTX and WITNESS_TX imply we serialize with witness const auto maybe_with_witness = (inv.IsMsgTx() ? TX_NO_WITNESS : TX_WITH_WITNESS); MakeAndPushMessage(pfrom, NetMsgType::TX, maybe_with_witness(*tx)); m_mempool.RemoveUnbroadcastTx(tx->GetHash()); } else { vNotFound.push_back(inv); } } // Only process one BLOCK item per call, since they're uncommon and can be // expensive to process. if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) { const CInv &inv = *it++; if (inv.IsGenBlkMsg()) { ProcessGetBlockData(pfrom, peer, inv); } // else: If the first item on the queue is an unknown type, we erase it // and continue processing the queue on the next call. } peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it); if (!vNotFound.empty()) { // Let the peer know that we didn't find what it asked for, so it doesn't // have to wait around forever. // SPV clients care about this message: it's needed when they are // recursively walking the dependencies of relevant unconfirmed // transactions. SPV clients want to do that because they want to know // about (and store and rebroadcast and risk analyze) the dependencies // of transactions relevant to them, without having to download the // entire memory pool. // Also, other nodes can use these messages to automatically request a // transaction from some other peer that announced it, and stop // waiting for us to respond. // In normal operation, we often send NOTFOUND messages for parents of // transactions that we relay; if a peer is missing a parent, they may // assume we have them and request the parents from us. MakeAndPushMessage(pfrom, NetMsgType::NOTFOUND, vNotFound); } } uint32_t PeerManagerImpl::GetFetchFlags(const Peer& peer) const { uint32_t nFetchFlags = 0; if (CanServeWitnesses(peer)) { nFetchFlags |= MSG_WITNESS_FLAG; } return nFetchFlags; } void PeerManagerImpl::SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req) { BlockTransactions resp(req); for (size_t i = 0; i < req.indexes.size(); i++) { if (req.indexes[i] >= block.vtx.size()) { Misbehaving(peer, 100, "getblocktxn with out-of-bounds tx indices"); return; } resp.txn[i] = block.vtx[req.indexes[i]]; } MakeAndPushMessage(pfrom, NetMsgType::BLOCKTXN, resp); } bool PeerManagerImpl::CheckHeadersPoW(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams, Peer& peer) { // Do these headers have proof-of-work matching what's claimed? if (!HasValidProofOfWork(headers, consensusParams)) { Misbehaving(peer, 100, "header with invalid proof of work"); return false; } // Are these headers connected to each other? if (!CheckHeadersAreContinuous(headers)) { Misbehaving(peer, 20, "non-continuous headers sequence"); return false; } return true; } arith_uint256 PeerManagerImpl::GetAntiDoSWorkThreshold() { arith_uint256 near_chaintip_work = 0; LOCK(cs_main); if (m_chainman.ActiveChain().Tip() != nullptr) { const CBlockIndex *tip = m_chainman.ActiveChain().Tip(); // Use a 144 block buffer, so that we'll accept headers that fork from // near our tip. near_chaintip_work = tip->nChainWork - std::min<arith_uint256>(144*GetBlockProof(*tip), tip->nChainWork); } return std::max(near_chaintip_work, m_chainman.MinimumChainWork()); } /** * Special handling for unconnecting headers that might be part of a block * announcement. * * We'll send a getheaders message in response to try to connect the chain. * * The peer can send up to MAX_NUM_UNCONNECTING_HEADERS_MSGS in a row that * don't connect before given DoS points. * * Once a headers message is received that is valid and does connect, * m_num_unconnecting_headers_msgs gets reset back to 0. */ void PeerManagerImpl::HandleFewUnconnectingHeaders(CNode& pfrom, Peer& peer, const std::vector<CBlockHeader>& headers) { peer.m_num_unconnecting_headers_msgs++; // Try to fill in the missing headers. const CBlockIndex* best_header{WITH_LOCK(cs_main, return m_chainman.m_best_header)}; if (MaybeSendGetHeaders(pfrom, GetLocator(best_header), peer)) { LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, m_num_unconnecting_headers_msgs=%d)\n", headers[0].GetHash().ToString(), headers[0].hashPrevBlock.ToString(), best_header->nHeight, pfrom.GetId(), peer.m_num_unconnecting_headers_msgs); } // Set hashLastUnknownBlock for this peer, so that if we // eventually get the headers - even from a different peer - // we can use this peer to download. WITH_LOCK(cs_main, UpdateBlockAvailability(pfrom.GetId(), headers.back().GetHash())); // The peer may just be broken, so periodically assign DoS points if this // condition persists. if (peer.m_num_unconnecting_headers_msgs % MAX_NUM_UNCONNECTING_HEADERS_MSGS == 0) { Misbehaving(peer, 20, strprintf("%d non-connecting headers", peer.m_num_unconnecting_headers_msgs)); } } bool PeerManagerImpl::CheckHeadersAreContinuous(const std::vector<CBlockHeader>& headers) const { uint256 hashLastBlock; for (const CBlockHeader& header : headers) { if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) { return false; } hashLastBlock = header.GetHash(); } return true; } bool PeerManagerImpl::IsContinuationOfLowWorkHeadersSync(Peer& peer, CNode& pfrom, std::vector<CBlockHeader>& headers) { if (peer.m_headers_sync) { auto result = peer.m_headers_sync->ProcessNextHeaders(headers, headers.size() == MAX_HEADERS_RESULTS); if (result.request_more) { auto locator = peer.m_headers_sync->NextHeadersRequestLocator(); // If we were instructed to ask for a locator, it should not be empty. Assume(!locator.vHave.empty()); if (!locator.vHave.empty()) { // It should be impossible for the getheaders request to fail, // because we should have cleared the last getheaders timestamp // when processing the headers that triggered this call. But // it may be possible to bypass this via compactblock // processing, so check the result before logging just to be // safe. bool sent_getheaders = MaybeSendGetHeaders(pfrom, locator, peer); if (sent_getheaders) { LogPrint(BCLog::NET, "more getheaders (from %s) to peer=%d\n", locator.vHave.front().ToString(), pfrom.GetId()); } else { LogPrint(BCLog::NET, "error sending next getheaders (from %s) to continue sync with peer=%d\n", locator.vHave.front().ToString(), pfrom.GetId()); } } } if (peer.m_headers_sync->GetState() == HeadersSyncState::State::FINAL) { peer.m_headers_sync.reset(nullptr); // Delete this peer's entry in m_headers_presync_stats. // If this is m_headers_presync_bestpeer, it will be replaced later // by the next peer that triggers the else{} branch below. LOCK(m_headers_presync_mutex); m_headers_presync_stats.erase(pfrom.GetId()); } else { // Build statistics for this peer's sync. HeadersPresyncStats stats; stats.first = peer.m_headers_sync->GetPresyncWork(); if (peer.m_headers_sync->GetState() == HeadersSyncState::State::PRESYNC) { stats.second = {peer.m_headers_sync->GetPresyncHeight(), peer.m_headers_sync->GetPresyncTime()}; } // Update statistics in stats. LOCK(m_headers_presync_mutex); m_headers_presync_stats[pfrom.GetId()] = stats; auto best_it = m_headers_presync_stats.find(m_headers_presync_bestpeer); bool best_updated = false; if (best_it == m_headers_presync_stats.end()) { // If the cached best peer is outdated, iterate over all remaining ones (including // newly updated one) to find the best one. NodeId peer_best{-1}; const HeadersPresyncStats* stat_best{nullptr}; for (const auto& [peer, stat] : m_headers_presync_stats) { if (!stat_best || stat > *stat_best) { peer_best = peer; stat_best = &stat; } } m_headers_presync_bestpeer = peer_best; best_updated = (peer_best == pfrom.GetId()); } else if (best_it->first == pfrom.GetId() || stats > best_it->second) { // pfrom was and remains the best peer, or pfrom just became best. m_headers_presync_bestpeer = pfrom.GetId(); best_updated = true; } if (best_updated && stats.second.has_value()) { // If the best peer updated, and it is in its first phase, signal. m_headers_presync_should_signal = true; } } if (result.success) { // We only overwrite the headers passed in if processing was // successful. headers.swap(result.pow_validated_headers); } return result.success; } // Either we didn't have a sync in progress, or something went wrong // processing these headers, or we are returning headers to the caller to // process. return false; } bool PeerManagerImpl::TryLowWorkHeadersSync(Peer& peer, CNode& pfrom, const CBlockIndex* chain_start_header, std::vector<CBlockHeader>& headers) { // Calculate the total work on this chain. arith_uint256 total_work = chain_start_header->nChainWork + CalculateHeadersWork(headers); // Our dynamic anti-DoS threshold (minimum work required on a headers chain // before we'll store it) arith_uint256 minimum_chain_work = GetAntiDoSWorkThreshold(); // Avoid DoS via low-difficulty-headers by only processing if the headers // are part of a chain with sufficient work. if (total_work < minimum_chain_work) { // Only try to sync with this peer if their headers message was full; // otherwise they don't have more headers after this so no point in // trying to sync their too-little-work chain. if (headers.size() == MAX_HEADERS_RESULTS) { // Note: we could advance to the last header in this set that is // known to us, rather than starting at the first header (which we // may already have); however this is unlikely to matter much since // ProcessHeadersMessage() already handles the case where all // headers in a received message are already known and are // ancestors of m_best_header or chainActive.Tip(), by skipping // this logic in that case. So even if the first header in this set // of headers is known, some header in this set must be new, so // advancing to the first unknown header would be a small effect. LOCK(peer.m_headers_sync_mutex); peer.m_headers_sync.reset(new HeadersSyncState(peer.m_id, m_chainparams.GetConsensus(), chain_start_header, minimum_chain_work)); // Now a HeadersSyncState object for tracking this synchronization // is created, process the headers using it as normal. Failures are // handled inside of IsContinuationOfLowWorkHeadersSync. (void)IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers); } else { LogPrint(BCLog::NET, "Ignoring low-work chain (height=%u) from peer=%d\n", chain_start_header->nHeight + headers.size(), pfrom.GetId()); } // The peer has not yet given us a chain that meets our work threshold, // so we want to prevent further processing of the headers in any case. headers = {}; return true; } return false; } bool PeerManagerImpl::IsAncestorOfBestHeaderOrTip(const CBlockIndex* header) { if (header == nullptr) { return false; } else if (m_chainman.m_best_header != nullptr && header == m_chainman.m_best_header->GetAncestor(header->nHeight)) { return true; } else if (m_chainman.ActiveChain().Contains(header)) { return true; } return false; } bool PeerManagerImpl::MaybeSendGetHeaders(CNode& pfrom, const CBlockLocator& locator, Peer& peer) { const auto current_time = NodeClock::now(); // Only allow a new getheaders message to go out if we don't have a recent // one already in-flight if (current_time - peer.m_last_getheaders_timestamp > HEADERS_RESPONSE_TIME) { MakeAndPushMessage(pfrom, NetMsgType::GETHEADERS, locator, uint256()); peer.m_last_getheaders_timestamp = current_time; return true; } return false; } /* * Given a new headers tip ending in last_header, potentially request blocks towards that tip. * We require that the given tip have at least as much work as our tip, and for * our current tip to be "close to synced" (see CanDirectFetch()). */ void PeerManagerImpl::HeadersDirectFetchBlocks(CNode& pfrom, const Peer& peer, const CBlockIndex& last_header) { LOCK(cs_main); CNodeState *nodestate = State(pfrom.GetId()); if (CanDirectFetch() && last_header.IsValid(BLOCK_VALID_TREE) && m_chainman.ActiveChain().Tip()->nChainWork <= last_header.nChainWork) { std::vector<const CBlockIndex*> vToFetch; const CBlockIndex* pindexWalk{&last_header}; // Calculate all the blocks we'd need to switch to last_header, up to a limit. while (pindexWalk && !m_chainman.ActiveChain().Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) && !IsBlockRequested(pindexWalk->GetBlockHash()) && (!DeploymentActiveAt(*pindexWalk, m_chainman, Consensus::DEPLOYMENT_SEGWIT) || CanServeWitnesses(peer))) { // We don't have this block, and it's not yet in flight. vToFetch.push_back(pindexWalk); } pindexWalk = pindexWalk->pprev; } // If pindexWalk still isn't on our main chain, we're looking at a // very large reorg at a time we think we're close to caught up to // the main chain -- this shouldn't really happen. Bail out on the // direct fetch and rely on parallel download instead. if (!m_chainman.ActiveChain().Contains(pindexWalk)) { LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n", last_header.GetBlockHash().ToString(), last_header.nHeight); } else { std::vector<CInv> vGetData; // Download as much as possible, from earliest to latest. for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) { if (nodestate->vBlocksInFlight.size() >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { // Can't download any more from this peer break; } uint32_t nFetchFlags = GetFetchFlags(peer); vGetData.emplace_back(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()); BlockRequested(pfrom.GetId(), *pindex); LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n", pindex->GetBlockHash().ToString(), pfrom.GetId()); } if (vGetData.size() > 1) { LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n", last_header.GetBlockHash().ToString(), last_header.nHeight); } if (vGetData.size() > 0) { if (!m_opts.ignore_incoming_txs && nodestate->m_provides_cmpctblocks && vGetData.size() == 1 && mapBlocksInFlight.size() == 1 && last_header.pprev->IsValid(BLOCK_VALID_CHAIN)) { // In any case, we want to download using a compact block, not a regular one vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash); } MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vGetData); } } } } /** * Given receipt of headers from a peer ending in last_header, along with * whether that header was new and whether the headers message was full, * update the state we keep for the peer. */ void PeerManagerImpl::UpdatePeerStateForReceivedHeaders(CNode& pfrom, Peer& peer, const CBlockIndex& last_header, bool received_new_header, bool may_have_more_headers) { if (peer.m_num_unconnecting_headers_msgs > 0) { LogPrint(BCLog::NET, "peer=%d: resetting m_num_unconnecting_headers_msgs (%d -> 0)\n", pfrom.GetId(), peer.m_num_unconnecting_headers_msgs); } peer.m_num_unconnecting_headers_msgs = 0; LOCK(cs_main); CNodeState *nodestate = State(pfrom.GetId()); UpdateBlockAvailability(pfrom.GetId(), last_header.GetBlockHash()); // From here, pindexBestKnownBlock should be guaranteed to be non-null, // because it is set in UpdateBlockAvailability. Some nullptr checks // are still present, however, as belt-and-suspenders. if (received_new_header && last_header.nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) { nodestate->m_last_block_announcement = GetTime(); } // If we're in IBD, we want outbound peers that will serve us a useful // chain. Disconnect peers that are on chains with insufficient work. if (m_chainman.IsInitialBlockDownload() && !may_have_more_headers) { // If the peer has no more headers to give us, then we know we have // their tip. if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < m_chainman.MinimumChainWork()) { // This peer has too little work on their headers chain to help // us sync -- disconnect if it is an outbound disconnection // candidate. // Note: We compare their tip to the minimum chain work (rather than // m_chainman.ActiveChain().Tip()) because we won't start block download // until we have a headers chain that has at least // the minimum chain work, even if a peer has a chain past our tip, // as an anti-DoS measure. if (pfrom.IsOutboundOrBlockRelayConn()) { LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom.GetId()); pfrom.fDisconnect = true; } } } // If this is an outbound full-relay peer, check to see if we should protect // it from the bad/lagging chain logic. // Note that outbound block-relay peers are excluded from this protection, and // thus always subject to eviction under the bad/lagging chain logic. // See ChainSyncTimeoutState. if (!pfrom.fDisconnect && pfrom.IsFullOutboundConn() && nodestate->pindexBestKnownBlock != nullptr) { if (m_outbound_peers_with_protect_from_disconnect < MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT && nodestate->pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork && !nodestate->m_chain_sync.m_protect) { LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom.GetId()); nodestate->m_chain_sync.m_protect = true; ++m_outbound_peers_with_protect_from_disconnect; } } } void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, Peer& peer, std::vector<CBlockHeader>&& headers, bool via_compact_block) { size_t nCount = headers.size(); if (nCount == 0) { // Nothing interesting. Stop asking this peers for more headers. // If we were in the middle of headers sync, receiving an empty headers // message suggests that the peer suddenly has nothing to give us // (perhaps it reorged to our chain). Clear download state for this peer. LOCK(peer.m_headers_sync_mutex); if (peer.m_headers_sync) { peer.m_headers_sync.reset(nullptr); LOCK(m_headers_presync_mutex); m_headers_presync_stats.erase(pfrom.GetId()); } return; } // Before we do any processing, make sure these pass basic sanity checks. // We'll rely on headers having valid proof-of-work further down, as an // anti-DoS criteria (note: this check is required before passing any // headers into HeadersSyncState). if (!CheckHeadersPoW(headers, m_chainparams.GetConsensus(), peer)) { // Misbehaving() calls are handled within CheckHeadersPoW(), so we can // just return. (Note that even if a header is announced via compact // block, the header itself should be valid, so this type of error can // always be punished.) return; } const CBlockIndex *pindexLast = nullptr; // We'll set already_validated_work to true if these headers are // successfully processed as part of a low-work headers sync in progress // (either in PRESYNC or REDOWNLOAD phase). // If true, this will mean that any headers returned to us (ie during // REDOWNLOAD) can be validated without further anti-DoS checks. bool already_validated_work = false; // If we're in the middle of headers sync, let it do its magic. bool have_headers_sync = false; { LOCK(peer.m_headers_sync_mutex); already_validated_work = IsContinuationOfLowWorkHeadersSync(peer, pfrom, headers); // The headers we passed in may have been: // - untouched, perhaps if no headers-sync was in progress, or some // failure occurred // - erased, such as if the headers were successfully processed and no // additional headers processing needs to take place (such as if we // are still in PRESYNC) // - replaced with headers that are now ready for validation, such as // during the REDOWNLOAD phase of a low-work headers sync. // So just check whether we still have headers that we need to process, // or not. if (headers.empty()) { return; } have_headers_sync = !!peer.m_headers_sync; } // Do these headers connect to something in our block index? const CBlockIndex *chain_start_header{WITH_LOCK(::cs_main, return m_chainman.m_blockman.LookupBlockIndex(headers[0].hashPrevBlock))}; bool headers_connect_blockindex{chain_start_header != nullptr}; if (!headers_connect_blockindex) { if (nCount <= MAX_BLOCKS_TO_ANNOUNCE) { // If this looks like it could be a BIP 130 block announcement, use // special logic for handling headers that don't connect, as this // could be benign. HandleFewUnconnectingHeaders(pfrom, peer, headers); } else { Misbehaving(peer, 10, "invalid header received"); } return; } // If the headers we received are already in memory and an ancestor of // m_best_header or our tip, skip anti-DoS checks. These headers will not // use any more memory (and we are not leaking information that could be // used to fingerprint us). const CBlockIndex *last_received_header{nullptr}; { LOCK(cs_main); last_received_header = m_chainman.m_blockman.LookupBlockIndex(headers.back().GetHash()); if (IsAncestorOfBestHeaderOrTip(last_received_header)) { already_validated_work = true; } } // If our peer has NetPermissionFlags::NoBan privileges, then bypass our // anti-DoS logic (this saves bandwidth when we connect to a trusted peer // on startup). if (pfrom.HasPermission(NetPermissionFlags::NoBan)) { already_validated_work = true; } // At this point, the headers connect to something in our block index. // Do anti-DoS checks to determine if we should process or store for later // processing. if (!already_validated_work && TryLowWorkHeadersSync(peer, pfrom, chain_start_header, headers)) { // If we successfully started a low-work headers sync, then there // should be no headers to process any further. Assume(headers.empty()); return; } // At this point, we have a set of headers with sufficient work on them // which can be processed. // If we don't have the last header, then this peer will have given us // something new (if these headers are valid). bool received_new_header{last_received_header == nullptr}; // Now process all the headers. BlockValidationState state; if (!m_chainman.ProcessNewBlockHeaders(headers, /*min_pow_checked=*/true, state, &pindexLast)) { if (state.IsInvalid()) { MaybePunishNodeForBlock(pfrom.GetId(), state, via_compact_block, "invalid header received"); return; } } assert(pindexLast); // Consider fetching more headers if we are not using our headers-sync mechanism. if (nCount == MAX_HEADERS_RESULTS && !have_headers_sync) { // Headers message had its maximum size; the peer may have more headers. if (MaybeSendGetHeaders(pfrom, GetLocator(pindexLast), peer)) { LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom.GetId(), peer.m_starting_height); } } UpdatePeerStateForReceivedHeaders(pfrom, peer, *pindexLast, received_new_header, nCount == MAX_HEADERS_RESULTS); // Consider immediately downloading blocks. HeadersDirectFetchBlocks(pfrom, peer, *pindexLast); return; } bool PeerManagerImpl::ProcessOrphanTx(Peer& peer) { AssertLockHeld(g_msgproc_mutex); LOCK(cs_main); CTransactionRef porphanTx = nullptr; while (CTransactionRef porphanTx = m_orphanage.GetTxToReconsider(peer.m_id)) { const MempoolAcceptResult result = m_chainman.ProcessTransaction(porphanTx); const TxValidationState& state = result.m_state; const Txid& orphanHash = porphanTx->GetHash(); const Wtxid& orphan_wtxid = porphanTx->GetWitnessHash(); if (result.m_result_type == MempoolAcceptResult::ResultType::VALID) { LogPrint(BCLog::TXPACKAGES, " accepted orphan tx %s (wtxid=%s)\n", orphanHash.ToString(), orphan_wtxid.ToString()); LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (wtxid=%s) (poolsz %u txn, %u kB)\n", peer.m_id, orphanHash.ToString(), orphan_wtxid.ToString(), m_mempool.size(), m_mempool.DynamicMemoryUsage() / 1000); RelayTransaction(orphanHash, porphanTx->GetWitnessHash()); m_orphanage.AddChildrenToWorkSet(*porphanTx); m_orphanage.EraseTx(orphanHash); for (const CTransactionRef& removedTx : result.m_replaced_transactions.value()) { AddToCompactExtraTransactions(removedTx); } return true; } else if (state.GetResult() != TxValidationResult::TX_MISSING_INPUTS) { if (state.IsInvalid()) { LogPrint(BCLog::TXPACKAGES, " invalid orphan tx %s (wtxid=%s) from peer=%d. %s\n", orphanHash.ToString(), orphan_wtxid.ToString(), peer.m_id, state.ToString()); LogPrint(BCLog::MEMPOOLREJ, "%s (wtxid=%s) from peer=%d was not accepted: %s\n", orphanHash.ToString(), orphan_wtxid.ToString(), peer.m_id, state.ToString()); // Maybe punish peer that gave us an invalid orphan tx MaybePunishNodeForTx(peer.m_id, state); } // Has inputs but not accepted to mempool // Probably non-standard or insufficient fee LogPrint(BCLog::TXPACKAGES, " removed orphan tx %s (wtxid=%s)\n", orphanHash.ToString(), orphan_wtxid.ToString()); if (state.GetResult() != TxValidationResult::TX_WITNESS_STRIPPED) { // We can add the wtxid of this transaction to our reject filter. // Do not add txids of witness transactions or witness-stripped // transactions to the filter, as they can have been malleated; // adding such txids to the reject filter would potentially // interfere with relay of valid transactions from peers that // do not support wtxid-based relay. See // https://github.com/bitcoin/bitcoin/issues/8279 for details. // We can remove this restriction (and always add wtxids to // the filter even for witness stripped transactions) once // wtxid-based relay is broadly deployed. // See also comments in https://github.com/bitcoin/bitcoin/pull/18044#discussion_r443419034 // for concerns around weakening security of unupgraded nodes // if we start doing this too early. m_recent_rejects.insert(porphanTx->GetWitnessHash().ToUint256()); // If the transaction failed for TX_INPUTS_NOT_STANDARD, // then we know that the witness was irrelevant to the policy // failure, since this check depends only on the txid // (the scriptPubKey being spent is covered by the txid). // Add the txid to the reject filter to prevent repeated // processing of this transaction in the event that child // transactions are later received (resulting in // parent-fetching by txid via the orphan-handling logic). if (state.GetResult() == TxValidationResult::TX_INPUTS_NOT_STANDARD && porphanTx->HasWitness()) { // We only add the txid if it differs from the wtxid, to // avoid wasting entries in the rolling bloom filter. m_recent_rejects.insert(porphanTx->GetHash().ToUint256()); } } m_orphanage.EraseTx(orphanHash); return true; } } return false; } bool PeerManagerImpl::PrepareBlockFilterRequest(CNode& node, Peer& peer, BlockFilterType filter_type, uint32_t start_height, const uint256& stop_hash, uint32_t max_height_diff, const CBlockIndex*& stop_index, BlockFilterIndex*& filter_index) { const bool supported_filter_type = (filter_type == BlockFilterType::BASIC && (peer.m_our_services & NODE_COMPACT_FILTERS)); if (!supported_filter_type) { LogPrint(BCLog::NET, "peer %d requested unsupported block filter type: %d\n", node.GetId(), static_cast<uint8_t>(filter_type)); node.fDisconnect = true; return false; } { LOCK(cs_main); stop_index = m_chainman.m_blockman.LookupBlockIndex(stop_hash); // Check that the stop block exists and the peer would be allowed to fetch it. if (!stop_index || !BlockRequestAllowed(stop_index)) { LogPrint(BCLog::NET, "peer %d requested invalid block hash: %s\n", node.GetId(), stop_hash.ToString()); node.fDisconnect = true; return false; } } uint32_t stop_height = stop_index->nHeight; if (start_height > stop_height) { LogPrint(BCLog::NET, "peer %d sent invalid getcfilters/getcfheaders with " "start height %d and stop height %d\n", node.GetId(), start_height, stop_height); node.fDisconnect = true; return false; } if (stop_height - start_height >= max_height_diff) { LogPrint(BCLog::NET, "peer %d requested too many cfilters/cfheaders: %d / %d\n", node.GetId(), stop_height - start_height + 1, max_height_diff); node.fDisconnect = true; return false; } filter_index = GetBlockFilterIndex(filter_type); if (!filter_index) { LogPrint(BCLog::NET, "Filter index for supported type %s not found\n", BlockFilterTypeName(filter_type)); return false; } return true; } void PeerManagerImpl::ProcessGetCFilters(CNode& node, Peer& peer, DataStream& vRecv) { uint8_t filter_type_ser; uint32_t start_height; uint256 stop_hash; vRecv >> filter_type_ser >> start_height >> stop_hash; const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser); const CBlockIndex* stop_index; BlockFilterIndex* filter_index; if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash, MAX_GETCFILTERS_SIZE, stop_index, filter_index)) { return; } std::vector<BlockFilter> filters; if (!filter_index->LookupFilterRange(start_height, stop_index, filters)) { LogPrint(BCLog::NET, "Failed to find block filter in index: filter_type=%s, start_height=%d, stop_hash=%s\n", BlockFilterTypeName(filter_type), start_height, stop_hash.ToString()); return; } for (const auto& filter : filters) { MakeAndPushMessage(node, NetMsgType::CFILTER, filter); } } void PeerManagerImpl::ProcessGetCFHeaders(CNode& node, Peer& peer, DataStream& vRecv) { uint8_t filter_type_ser; uint32_t start_height; uint256 stop_hash; vRecv >> filter_type_ser >> start_height >> stop_hash; const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser); const CBlockIndex* stop_index; BlockFilterIndex* filter_index; if (!PrepareBlockFilterRequest(node, peer, filter_type, start_height, stop_hash, MAX_GETCFHEADERS_SIZE, stop_index, filter_index)) { return; } uint256 prev_header; if (start_height > 0) { const CBlockIndex* const prev_block = stop_index->GetAncestor(static_cast<int>(start_height - 1)); if (!filter_index->LookupFilterHeader(prev_block, prev_header)) { LogPrint(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n", BlockFilterTypeName(filter_type), prev_block->GetBlockHash().ToString()); return; } } std::vector<uint256> filter_hashes; if (!filter_index->LookupFilterHashRange(start_height, stop_index, filter_hashes)) { LogPrint(BCLog::NET, "Failed to find block filter hashes in index: filter_type=%s, start_height=%d, stop_hash=%s\n", BlockFilterTypeName(filter_type), start_height, stop_hash.ToString()); return; } MakeAndPushMessage(node, NetMsgType::CFHEADERS, filter_type_ser, stop_index->GetBlockHash(), prev_header, filter_hashes); } void PeerManagerImpl::ProcessGetCFCheckPt(CNode& node, Peer& peer, DataStream& vRecv) { uint8_t filter_type_ser; uint256 stop_hash; vRecv >> filter_type_ser >> stop_hash; const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser); const CBlockIndex* stop_index; BlockFilterIndex* filter_index; if (!PrepareBlockFilterRequest(node, peer, filter_type, /*start_height=*/0, stop_hash, /*max_height_diff=*/std::numeric_limits<uint32_t>::max(), stop_index, filter_index)) { return; } std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL); // Populate headers. const CBlockIndex* block_index = stop_index; for (int i = headers.size() - 1; i >= 0; i--) { int height = (i + 1) * CFCHECKPT_INTERVAL; block_index = block_index->GetAncestor(height); if (!filter_index->LookupFilterHeader(block_index, headers[i])) { LogPrint(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n", BlockFilterTypeName(filter_type), block_index->GetBlockHash().ToString()); return; } } MakeAndPushMessage(node, NetMsgType::CFCHECKPT, filter_type_ser, stop_index->GetBlockHash(), headers); } void PeerManagerImpl::ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked) { bool new_block{false}; m_chainman.ProcessNewBlock(block, force_processing, min_pow_checked, &new_block); if (new_block) { node.m_last_block_time = GetTime<std::chrono::seconds>(); // In case this block came from a different peer than we requested // from, we can erase the block request now anyway (as we just stored // this block to disk). LOCK(cs_main); RemoveBlockRequest(block->GetHash(), std::nullopt); } else { LOCK(cs_main); mapBlockSource.erase(block->GetHash()); } } void PeerManagerImpl::ProcessCompactBlockTxns(CNode& pfrom, Peer& peer, const BlockTransactions& block_transactions) { std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); bool fBlockRead{false}; { LOCK(cs_main); auto range_flight = mapBlocksInFlight.equal_range(block_transactions.blockhash); size_t already_in_flight = std::distance(range_flight.first, range_flight.second); bool requested_block_from_this_peer{false}; // Multimap ensures ordering of outstanding requests. It's either empty or first in line. bool first_in_flight = already_in_flight == 0 || (range_flight.first->second.first == pfrom.GetId()); while (range_flight.first != range_flight.second) { auto [node_id, block_it] = range_flight.first->second; if (node_id == pfrom.GetId() && block_it->partialBlock) { requested_block_from_this_peer = true; break; } range_flight.first++; } if (!requested_block_from_this_peer) { LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom.GetId()); return; } PartiallyDownloadedBlock& partialBlock = *range_flight.first->second.second->partialBlock; ReadStatus status = partialBlock.FillBlock(*pblock, block_transactions.txn); if (status == READ_STATUS_INVALID) { RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); // Reset in-flight state in case Misbehaving does not result in a disconnect Misbehaving(peer, 100, "invalid compact block/non-matching block transactions"); return; } else if (status == READ_STATUS_FAILED) { if (first_in_flight) { // Might have collided, fall back to getdata now :( std::vector<CInv> invs; invs.emplace_back(MSG_BLOCK | GetFetchFlags(peer), block_transactions.blockhash); MakeAndPushMessage(pfrom, NetMsgType::GETDATA, invs); } else { RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); LogPrint(BCLog::NET, "Peer %d sent us a compact block but it failed to reconstruct, waiting on first download to complete\n", pfrom.GetId()); return; } } else { // Block is either okay, or possibly we received // READ_STATUS_CHECKBLOCK_FAILED. // Note that CheckBlock can only fail for one of a few reasons: // 1. bad-proof-of-work (impossible here, because we've already // accepted the header) // 2. merkleroot doesn't match the transactions given (already // caught in FillBlock with READ_STATUS_FAILED, so // impossible here) // 3. the block is otherwise invalid (eg invalid coinbase, // block is too big, too many legacy sigops, etc). // So if CheckBlock failed, #3 is the only possibility. // Under BIP 152, we don't discourage the peer unless proof of work is // invalid (we don't require all the stateless checks to have // been run). This is handled below, so just treat this as // though the block was successfully read, and rely on the // handling in ProcessNewBlock to ensure the block index is // updated, etc. RemoveBlockRequest(block_transactions.blockhash, pfrom.GetId()); // it is now an empty pointer fBlockRead = true; // mapBlockSource is used for potentially punishing peers and // updating which peers send us compact blocks, so the race // between here and cs_main in ProcessNewBlock is fine. // BIP 152 permits peers to relay compact blocks after validating // the header only; we should not punish peers if the block turns // out to be invalid. mapBlockSource.emplace(block_transactions.blockhash, std::make_pair(pfrom.GetId(), false)); } } // Don't hold cs_main when we call into ProcessNewBlock if (fBlockRead) { // Since we requested this block (it was in mapBlocksInFlight), force it to be processed, // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc) // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent // disk-space attacks), but this should be safe due to the // protections in the compact block handler -- see related comment // in compact block optimistic reconstruction handling. ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true); } return; } void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type, DataStream& vRecv, const std::chrono::microseconds time_received, const std::atomic<bool>& interruptMsgProc) { AssertLockHeld(g_msgproc_mutex); LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(msg_type), vRecv.size(), pfrom.GetId()); PeerRef peer = GetPeerRef(pfrom.GetId()); if (peer == nullptr) return; if (msg_type == NetMsgType::VERSION) { if (pfrom.nVersion != 0) { LogPrint(BCLog::NET, "redundant version message from peer=%d\n", pfrom.GetId()); return; } int64_t nTime; CService addrMe; uint64_t nNonce = 1; ServiceFlags nServices; int nVersion; std::string cleanSubVer; int starting_height = -1; bool fRelay = true; vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime; if (nTime < 0) { nTime = 0; } vRecv.ignore(8); // Ignore the addrMe service bits sent by the peer vRecv >> CNetAddr::V1(addrMe); if (!pfrom.IsInboundConn()) { m_addrman.SetServices(pfrom.addr, nServices); } if (pfrom.ExpectServicesFromConn() && !HasAllDesirableServiceFlags(nServices)) { LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom.GetId(), nServices, GetDesirableServiceFlags(nServices)); pfrom.fDisconnect = true; return; } if (nVersion < MIN_PEER_PROTO_VERSION) { // disconnect from peers older than this proto version LogPrint(BCLog::NET, "peer=%d using obsolete version %i; disconnecting\n", pfrom.GetId(), nVersion); pfrom.fDisconnect = true; return; } if (!vRecv.empty()) { // The version message includes information about the sending node which we don't use: // - 8 bytes (service bits) // - 16 bytes (ipv6 address) // - 2 bytes (port) vRecv.ignore(26); vRecv >> nNonce; } if (!vRecv.empty()) { std::string strSubVer; vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH); cleanSubVer = SanitizeString(strSubVer); } if (!vRecv.empty()) { vRecv >> starting_height; } if (!vRecv.empty()) vRecv >> fRelay; // Disconnect if we connected to ourself if (pfrom.IsInboundConn() && !m_connman.CheckIncomingNonce(nNonce)) { LogPrintf("connected to self at %s, disconnecting\n", pfrom.addr.ToStringAddrPort()); pfrom.fDisconnect = true; return; } if (pfrom.IsInboundConn() && addrMe.IsRoutable()) { SeenLocal(addrMe); } // Inbound peers send us their version message when they connect. // We send our version message in response. if (pfrom.IsInboundConn()) { PushNodeVersion(pfrom, *peer); } // Change version const int greatest_common_version = std::min(nVersion, PROTOCOL_VERSION); pfrom.SetCommonVersion(greatest_common_version); pfrom.nVersion = nVersion; if (greatest_common_version >= WTXID_RELAY_VERSION) { MakeAndPushMessage(pfrom, NetMsgType::WTXIDRELAY); } // Signal ADDRv2 support (BIP155). if (greatest_common_version >= 70016) { // BIP155 defines addrv2 and sendaddrv2 for all protocol versions, but some // implementations reject messages they don't know. As a courtesy, don't send // it to nodes with a version before 70016, as no software is known to support // BIP155 that doesn't announce at least that protocol version number. MakeAndPushMessage(pfrom, NetMsgType::SENDADDRV2); } pfrom.m_has_all_wanted_services = HasAllDesirableServiceFlags(nServices); peer->m_their_services = nServices; pfrom.SetAddrLocal(addrMe); { LOCK(pfrom.m_subver_mutex); pfrom.cleanSubVer = cleanSubVer; } peer->m_starting_height = starting_height; // Only initialize the Peer::TxRelay m_relay_txs data structure if: // - this isn't an outbound block-relay-only connection, and // - this isn't an outbound feeler connection, and // - fRelay=true (the peer wishes to receive transaction announcements) // or we're offering NODE_BLOOM to this peer. NODE_BLOOM means that // the peer may turn on transaction relay later. if (!pfrom.IsBlockOnlyConn() && !pfrom.IsFeelerConn() && (fRelay || (peer->m_our_services & NODE_BLOOM))) { auto* const tx_relay = peer->SetTxRelay(); { LOCK(tx_relay->m_bloom_filter_mutex); tx_relay->m_relay_txs = fRelay; // set to true after we get the first filter* message } if (fRelay) pfrom.m_relays_txs = true; } if (greatest_common_version >= WTXID_RELAY_VERSION && m_txreconciliation) { // Per BIP-330, we announce txreconciliation support if: // - protocol version per the peer's VERSION message supports WTXID_RELAY; // - transaction relay is supported per the peer's VERSION message // - this is not a block-relay-only connection and not a feeler // - this is not an addr fetch connection; // - we are not in -blocksonly mode. const auto* tx_relay = peer->GetTxRelay(); if (tx_relay && WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs) && !pfrom.IsAddrFetchConn() && !m_opts.ignore_incoming_txs) { const uint64_t recon_salt = m_txreconciliation->PreRegisterPeer(pfrom.GetId()); MakeAndPushMessage(pfrom, NetMsgType::SENDTXRCNCL, TXRECONCILIATION_VERSION, recon_salt); } } MakeAndPushMessage(pfrom, NetMsgType::VERACK); // Potentially mark this peer as a preferred download peer. { LOCK(cs_main); CNodeState* state = State(pfrom.GetId()); state->fPreferredDownload = (!pfrom.IsInboundConn() || pfrom.HasPermission(NetPermissionFlags::NoBan)) && !pfrom.IsAddrFetchConn() && CanServeBlocks(*peer); m_num_preferred_download_peers += state->fPreferredDownload; } // Attempt to initialize address relay for outbound peers and use result // to decide whether to send GETADDR, so that we don't send it to // inbound or outbound block-relay-only peers. bool send_getaddr{false}; if (!pfrom.IsInboundConn()) { send_getaddr = SetupAddressRelay(pfrom, *peer); } if (send_getaddr) { // Do a one-time address fetch to help populate/update our addrman. // If we're starting up for the first time, our addrman may be pretty // empty, so this mechanism is important to help us connect to the network. // We skip this for block-relay-only peers. We want to avoid // potentially leaking addr information and we do not want to // indicate to the peer that we will participate in addr relay. MakeAndPushMessage(pfrom, NetMsgType::GETADDR); peer->m_getaddr_sent = true; // When requesting a getaddr, accept an additional MAX_ADDR_TO_SEND addresses in response // (bypassing the MAX_ADDR_PROCESSING_TOKEN_BUCKET limit). peer->m_addr_token_bucket += MAX_ADDR_TO_SEND; } if (!pfrom.IsInboundConn()) { // For non-inbound connections, we update the addrman to record // connection success so that addrman will have an up-to-date // notion of which peers are online and available. // // While we strive to not leak information about block-relay-only // connections via the addrman, not moving an address to the tried // table is also potentially detrimental because new-table entries // are subject to eviction in the event of addrman collisions. We // mitigate the information-leak by never calling // AddrMan::Connected() on block-relay-only peers; see // FinalizeNode(). // // This moves an address from New to Tried table in Addrman, // resolves tried-table collisions, etc. m_addrman.Good(pfrom.addr); } std::string remoteAddr; if (fLogIPs) remoteAddr = ", peeraddr=" + pfrom.addr.ToStringAddrPort(); const auto mapped_as{m_connman.GetMappedAS(pfrom.addr)}; LogPrint(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, txrelay=%d, peer=%d%s%s\n", cleanSubVer, pfrom.nVersion, peer->m_starting_height, addrMe.ToStringAddrPort(), fRelay, pfrom.GetId(), remoteAddr, (mapped_as ? strprintf(", mapped_as=%d", mapped_as) : "")); int64_t nTimeOffset = nTime - GetTime(); pfrom.nTimeOffset = nTimeOffset; if (!pfrom.IsInboundConn()) { // Don't use timedata samples from inbound peers to make it // harder for others to tamper with our adjusted time. AddTimeData(pfrom.addr, nTimeOffset); } // If the peer is old enough to have the old alert system, send it the final alert. if (greatest_common_version <= 70012) { const auto finalAlert{ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50")}; MakeAndPushMessage(pfrom, "alert", Span{finalAlert}); } // Feeler connections exist only to verify if address is online. if (pfrom.IsFeelerConn()) { LogPrint(BCLog::NET, "feeler connection completed peer=%d; disconnecting\n", pfrom.GetId()); pfrom.fDisconnect = true; } return; } if (pfrom.nVersion == 0) { // Must have a version message before anything else LogPrint(BCLog::NET, "non-version message before version handshake. Message \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId()); return; } if (msg_type == NetMsgType::VERACK) { if (pfrom.fSuccessfullyConnected) { LogPrint(BCLog::NET, "ignoring redundant verack message from peer=%d\n", pfrom.GetId()); return; } // Log successful connections unconditionally for outbound, but not for inbound as those // can be triggered by an attacker at high rate. if (!pfrom.IsInboundConn() || LogAcceptCategory(BCLog::NET, BCLog::Level::Debug)) { const auto mapped_as{m_connman.GetMappedAS(pfrom.addr)}; LogPrintf("New %s %s peer connected: version: %d, blocks=%d, peer=%d%s%s\n", pfrom.ConnectionTypeAsString(), TransportTypeAsString(pfrom.m_transport->GetInfo().transport_type), pfrom.nVersion.load(), peer->m_starting_height, pfrom.GetId(), (fLogIPs ? strprintf(", peeraddr=%s", pfrom.addr.ToStringAddrPort()) : ""), (mapped_as ? strprintf(", mapped_as=%d", mapped_as) : "")); } if (pfrom.GetCommonVersion() >= SHORT_IDS_BLOCKS_VERSION) { // Tell our peer we are willing to provide version 2 cmpctblocks. // However, we do not request new block announcements using // cmpctblock messages. // We send this to non-NODE NETWORK peers as well, because // they may wish to request compact blocks from us MakeAndPushMessage(pfrom, NetMsgType::SENDCMPCT, /*high_bandwidth=*/false, /*version=*/CMPCTBLOCKS_VERSION); } if (m_txreconciliation) { if (!peer->m_wtxid_relay || !m_txreconciliation->IsPeerRegistered(pfrom.GetId())) { // We could have optimistically pre-registered/registered the peer. In that case, // we should forget about the reconciliation state here if this wasn't followed // by WTXIDRELAY (since WTXIDRELAY can't be announced later). m_txreconciliation->ForgetPeer(pfrom.GetId()); } } if (auto tx_relay = peer->GetTxRelay()) { // `TxRelay::m_tx_inventory_to_send` must be empty before the // version handshake is completed as // `TxRelay::m_next_inv_send_time` is first initialised in // `SendMessages` after the verack is received. Any transactions // received during the version handshake would otherwise // immediately be advertised without random delay, potentially // leaking the time of arrival to a spy. Assume(WITH_LOCK( tx_relay->m_tx_inventory_mutex, return tx_relay->m_tx_inventory_to_send.empty() && tx_relay->m_next_inv_send_time == 0s)); } pfrom.fSuccessfullyConnected = true; return; } if (msg_type == NetMsgType::SENDHEADERS) { peer->m_prefers_headers = true; return; } if (msg_type == NetMsgType::SENDCMPCT) { bool sendcmpct_hb{false}; uint64_t sendcmpct_version{0}; vRecv >> sendcmpct_hb >> sendcmpct_version; // Only support compact block relay with witnesses if (sendcmpct_version != CMPCTBLOCKS_VERSION) return; LOCK(cs_main); CNodeState* nodestate = State(pfrom.GetId()); nodestate->m_provides_cmpctblocks = true; nodestate->m_requested_hb_cmpctblocks = sendcmpct_hb; // save whether peer selects us as BIP152 high-bandwidth peer // (receiving sendcmpct(1) signals high-bandwidth, sendcmpct(0) low-bandwidth) pfrom.m_bip152_highbandwidth_from = sendcmpct_hb; return; } // BIP339 defines feature negotiation of wtxidrelay, which must happen between // VERSION and VERACK to avoid relay problems from switching after a connection is up. if (msg_type == NetMsgType::WTXIDRELAY) { if (pfrom.fSuccessfullyConnected) { // Disconnect peers that send a wtxidrelay message after VERACK. LogPrint(BCLog::NET, "wtxidrelay received after verack from peer=%d; disconnecting\n", pfrom.GetId()); pfrom.fDisconnect = true; return; } if (pfrom.GetCommonVersion() >= WTXID_RELAY_VERSION) { if (!peer->m_wtxid_relay) { peer->m_wtxid_relay = true; m_wtxid_relay_peers++; } else { LogPrint(BCLog::NET, "ignoring duplicate wtxidrelay from peer=%d\n", pfrom.GetId()); } } else { LogPrint(BCLog::NET, "ignoring wtxidrelay due to old common version=%d from peer=%d\n", pfrom.GetCommonVersion(), pfrom.GetId()); } return; } // BIP155 defines feature negotiation of addrv2 and sendaddrv2, which must happen // between VERSION and VERACK. if (msg_type == NetMsgType::SENDADDRV2) { if (pfrom.fSuccessfullyConnected) { // Disconnect peers that send a SENDADDRV2 message after VERACK. LogPrint(BCLog::NET, "sendaddrv2 received after verack from peer=%d; disconnecting\n", pfrom.GetId()); pfrom.fDisconnect = true; return; } peer->m_wants_addrv2 = true; return; } // Received from a peer demonstrating readiness to announce transactions via reconciliations. // This feature negotiation must happen between VERSION and VERACK to avoid relay problems // from switching announcement protocols after the connection is up. if (msg_type == NetMsgType::SENDTXRCNCL) { if (!m_txreconciliation) { LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "sendtxrcncl from peer=%d ignored, as our node does not have txreconciliation enabled\n", pfrom.GetId()); return; } if (pfrom.fSuccessfullyConnected) { LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "sendtxrcncl received after verack from peer=%d; disconnecting\n", pfrom.GetId()); pfrom.fDisconnect = true; return; } // Peer must not offer us reconciliations if we specified no tx relay support in VERSION. if (RejectIncomingTxs(pfrom)) { LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "sendtxrcncl received from peer=%d to which we indicated no tx relay; disconnecting\n", pfrom.GetId()); pfrom.fDisconnect = true; return; } // Peer must not offer us reconciliations if they specified no tx relay support in VERSION. // This flag might also be false in other cases, but the RejectIncomingTxs check above // eliminates them, so that this flag fully represents what we are looking for. const auto* tx_relay = peer->GetTxRelay(); if (!tx_relay || !WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs)) { LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "sendtxrcncl received from peer=%d which indicated no tx relay to us; disconnecting\n", pfrom.GetId()); pfrom.fDisconnect = true; return; } uint32_t peer_txreconcl_version; uint64_t remote_salt; vRecv >> peer_txreconcl_version >> remote_salt; const ReconciliationRegisterResult result = m_txreconciliation->RegisterPeer(pfrom.GetId(), pfrom.IsInboundConn(), peer_txreconcl_version, remote_salt); switch (result) { case ReconciliationRegisterResult::NOT_FOUND: LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "Ignore unexpected txreconciliation signal from peer=%d\n", pfrom.GetId()); break; case ReconciliationRegisterResult::SUCCESS: break; case ReconciliationRegisterResult::ALREADY_REGISTERED: LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "txreconciliation protocol violation from peer=%d (sendtxrcncl received from already registered peer); disconnecting\n", pfrom.GetId()); pfrom.fDisconnect = true; return; case ReconciliationRegisterResult::PROTOCOL_VIOLATION: LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "txreconciliation protocol violation from peer=%d; disconnecting\n", pfrom.GetId()); pfrom.fDisconnect = true; return; } return; } if (!pfrom.fSuccessfullyConnected) { LogPrint(BCLog::NET, "Unsupported message \"%s\" prior to verack from peer=%d\n", SanitizeString(msg_type), pfrom.GetId()); return; } if (msg_type == NetMsgType::ADDR || msg_type == NetMsgType::ADDRV2) { const auto ser_params{ msg_type == NetMsgType::ADDRV2 ? // Set V2 param so that the CNetAddr and CAddress // unserialize methods know that an address in v2 format is coming. CAddress::V2_NETWORK : CAddress::V1_NETWORK, }; std::vector<CAddress> vAddr; vRecv >> ser_params(vAddr); if (!SetupAddressRelay(pfrom, *peer)) { LogPrint(BCLog::NET, "ignoring %s message from %s peer=%d\n", msg_type, pfrom.ConnectionTypeAsString(), pfrom.GetId()); return; } if (vAddr.size() > MAX_ADDR_TO_SEND) { Misbehaving(*peer, 20, strprintf("%s message size = %u", msg_type, vAddr.size())); return; } // Store the new addresses std::vector<CAddress> vAddrOk; const auto current_a_time{Now<NodeSeconds>()}; // Update/increment addr rate limiting bucket. const auto current_time{GetTime<std::chrono::microseconds>()}; if (peer->m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) { // Don't increment bucket if it's already full const auto time_diff = std::max(current_time - peer->m_addr_token_timestamp, 0us); const double increment = Ticks<SecondsDouble>(time_diff) * MAX_ADDR_RATE_PER_SECOND; peer->m_addr_token_bucket = std::min<double>(peer->m_addr_token_bucket + increment, MAX_ADDR_PROCESSING_TOKEN_BUCKET); } peer->m_addr_token_timestamp = current_time; const bool rate_limited = !pfrom.HasPermission(NetPermissionFlags::Addr); uint64_t num_proc = 0; uint64_t num_rate_limit = 0; Shuffle(vAddr.begin(), vAddr.end(), m_rng); for (CAddress& addr : vAddr) { if (interruptMsgProc) return; // Apply rate limiting. if (peer->m_addr_token_bucket < 1.0) { if (rate_limited) { ++num_rate_limit; continue; } } else { peer->m_addr_token_bucket -= 1.0; } // We only bother storing full nodes, though this may include // things which we would not make an outbound connection to, in // part because we may make feeler connections to them. if (!MayHaveUsefulAddressDB(addr.nServices) && !HasAllDesirableServiceFlags(addr.nServices)) continue; if (addr.nTime <= NodeSeconds{100000000s} || addr.nTime > current_a_time + 10min) { addr.nTime = current_a_time - 5 * 24h; } AddAddressKnown(*peer, addr); if (m_banman && (m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr))) { // Do not process banned/discouraged addresses beyond remembering we received them continue; } ++num_proc; const bool reachable{g_reachable_nets.Contains(addr)}; if (addr.nTime > current_a_time - 10min && !peer->m_getaddr_sent && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes RelayAddress(pfrom.GetId(), addr, reachable); } // Do not store addresses outside our network if (reachable) { vAddrOk.push_back(addr); } } peer->m_addr_processed += num_proc; peer->m_addr_rate_limited += num_rate_limit; LogPrint(BCLog::NET, "Received addr: %u addresses (%u processed, %u rate-limited) from peer=%d\n", vAddr.size(), num_proc, num_rate_limit, pfrom.GetId()); m_addrman.Add(vAddrOk, pfrom.addr, 2h); if (vAddr.size() < 1000) peer->m_getaddr_sent = false; // AddrFetch: Require multiple addresses to avoid disconnecting on self-announcements if (pfrom.IsAddrFetchConn() && vAddr.size() > 1) { LogPrint(BCLog::NET, "addrfetch connection completed peer=%d; disconnecting\n", pfrom.GetId()); pfrom.fDisconnect = true; } return; } if (msg_type == NetMsgType::INV) { std::vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { Misbehaving(*peer, 20, strprintf("inv message size = %u", vInv.size())); return; } const bool reject_tx_invs{RejectIncomingTxs(pfrom)}; LOCK(cs_main); const auto current_time{GetTime<std::chrono::microseconds>()}; uint256* best_block{nullptr}; for (CInv& inv : vInv) { if (interruptMsgProc) return; // Ignore INVs that don't match wtxidrelay setting. // Note that orphan parent fetching always uses MSG_TX GETDATAs regardless of the wtxidrelay setting. // This is fine as no INV messages are involved in that process. if (peer->m_wtxid_relay) { if (inv.IsMsgTx()) continue; } else { if (inv.IsMsgWtx()) continue; } if (inv.IsMsgBlk()) { const bool fAlreadyHave = AlreadyHaveBlock(inv.hash); LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId()); UpdateBlockAvailability(pfrom.GetId(), inv.hash); if (!fAlreadyHave && !m_chainman.m_blockman.LoadingBlocks() && !IsBlockRequested(inv.hash)) { // Headers-first is the primary method of announcement on // the network. If a node fell back to sending blocks by // inv, it may be for a re-org, or because we haven't // completed initial headers sync. The final block hash // provided should be the highest, so send a getheaders and // then fetch the blocks we need to catch up. best_block = &inv.hash; } } else if (inv.IsGenTxMsg()) { if (reject_tx_invs) { LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol, disconnecting peer=%d\n", inv.hash.ToString(), pfrom.GetId()); pfrom.fDisconnect = true; return; } const GenTxid gtxid = ToGenTxid(inv); const bool fAlreadyHave = AlreadyHaveTx(gtxid); LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId()); AddKnownTx(*peer, inv.hash); if (!fAlreadyHave && !m_chainman.IsInitialBlockDownload()) { AddTxAnnouncement(pfrom, gtxid, current_time); } } else { LogPrint(BCLog::NET, "Unknown inv type \"%s\" received from peer=%d\n", inv.ToString(), pfrom.GetId()); } } if (best_block != nullptr) { // If we haven't started initial headers-sync with this peer, then // consider sending a getheaders now. On initial startup, there's a // reliability vs bandwidth tradeoff, where we are only trying to do // initial headers sync with one peer at a time, with a long // timeout (at which point, if the sync hasn't completed, we will // disconnect the peer and then choose another). In the meantime, // as new blocks are found, we are willing to add one new peer per // block to sync with as well, to sync quicker in the case where // our initial peer is unresponsive (but less bandwidth than we'd // use if we turned on sync with all peers). CNodeState& state{*Assert(State(pfrom.GetId()))}; if (state.fSyncStarted || (!peer->m_inv_triggered_getheaders_before_sync && *best_block != m_last_block_inv_triggering_headers_sync)) { if (MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), *peer)) { LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", m_chainman.m_best_header->nHeight, best_block->ToString(), pfrom.GetId()); } if (!state.fSyncStarted) { peer->m_inv_triggered_getheaders_before_sync = true; // Update the last block hash that triggered a new headers // sync, so that we don't turn on headers sync with more // than 1 new peer every new block. m_last_block_inv_triggering_headers_sync = *best_block; } } } return; } if (msg_type == NetMsgType::GETDATA) { std::vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { Misbehaving(*peer, 20, strprintf("getdata message size = %u", vInv.size())); return; } LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom.GetId()); if (vInv.size() > 0) { LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom.GetId()); } { LOCK(peer->m_getdata_requests_mutex); peer->m_getdata_requests.insert(peer->m_getdata_requests.end(), vInv.begin(), vInv.end()); ProcessGetData(pfrom, *peer, interruptMsgProc); } return; } if (msg_type == NetMsgType::GETBLOCKS) { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; if (locator.vHave.size() > MAX_LOCATOR_SZ) { LogPrint(BCLog::NET, "getblocks locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId()); pfrom.fDisconnect = true; return; } // We might have announced the currently-being-connected tip using a // compact block, which resulted in the peer sending a getblocks // request, which we would otherwise respond to without the new block. // To avoid this situation we simply verify that we are on our best // known chain now. This is super overkill, but we handle it better // for getheaders requests, and there are no known nodes which support // compact blocks but still use getblocks to request blocks. { std::shared_ptr<const CBlock> a_recent_block; { LOCK(m_most_recent_block_mutex); a_recent_block = m_most_recent_block; } BlockValidationState state; if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) { LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString()); } } LOCK(cs_main); // Find the last block the caller has in the main chain const CBlockIndex* pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator); // Send the rest of the chain if (pindex) pindex = m_chainman.ActiveChain().Next(pindex); int nLimit = 500; LogPrint(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom.GetId()); for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex)) { if (pindex->GetBlockHash() == hashStop) { LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); break; } // If pruning, don't inv blocks unless we have on disk and are likely to still have // for some reasonable time window (1 hour) that block relay might require. const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / m_chainparams.GetConsensus().nPowTargetSpacing; if (m_chainman.m_blockman.IsPruneMode() && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight - nPrunedBlocksLikelyToHave)) { LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); break; } WITH_LOCK(peer->m_block_inv_mutex, peer->m_blocks_for_inv_relay.push_back(pindex->GetBlockHash())); if (--nLimit <= 0) { // When this block is requested, we'll send an inv that'll // trigger the peer to getblocks the next batch of inventory. LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); WITH_LOCK(peer->m_block_inv_mutex, {peer->m_continuation_block = pindex->GetBlockHash();}); break; } } return; } if (msg_type == NetMsgType::GETBLOCKTXN) { BlockTransactionsRequest req; vRecv >> req; std::shared_ptr<const CBlock> recent_block; { LOCK(m_most_recent_block_mutex); if (m_most_recent_block_hash == req.blockhash) recent_block = m_most_recent_block; // Unlock m_most_recent_block_mutex to avoid cs_main lock inversion } if (recent_block) { SendBlockTransactions(pfrom, *peer, *recent_block, req); return; } { LOCK(cs_main); const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(req.blockhash); if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) { LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have\n", pfrom.GetId()); return; } if (pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_BLOCKTXN_DEPTH) { CBlock block; const bool ret{m_chainman.m_blockman.ReadBlockFromDisk(block, *pindex)}; assert(ret); SendBlockTransactions(pfrom, *peer, block, req); return; } } // If an older block is requested (should never happen in practice, // but can happen in tests) send a block response instead of a // blocktxn response. Sending a full block response instead of a // small blocktxn response is preferable in the case where a peer // might maliciously send lots of getblocktxn requests to trigger // expensive disk reads, because it will require the peer to // actually receive all the data read from disk over the network. LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep\n", pfrom.GetId(), MAX_BLOCKTXN_DEPTH); CInv inv{MSG_WITNESS_BLOCK, req.blockhash}; WITH_LOCK(peer->m_getdata_requests_mutex, peer->m_getdata_requests.push_back(inv)); // The message processing loop will go around again (without pausing) and we'll respond then return; } if (msg_type == NetMsgType::GETHEADERS) { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; if (locator.vHave.size() > MAX_LOCATOR_SZ) { LogPrint(BCLog::NET, "getheaders locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId()); pfrom.fDisconnect = true; return; } if (m_chainman.m_blockman.LoadingBlocks()) { LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d while importing/reindexing\n", pfrom.GetId()); return; } LOCK(cs_main); // Note that if we were to be on a chain that forks from the checkpointed // chain, then serving those headers to a peer that has seen the // checkpointed chain would cause that peer to disconnect us. Requiring // that our chainwork exceed the minimum chain work is a protection against // being fed a bogus chain when we started up for the first time and // getting partitioned off the honest network for serving that chain to // others. if (m_chainman.ActiveTip() == nullptr || (m_chainman.ActiveTip()->nChainWork < m_chainman.MinimumChainWork() && !pfrom.HasPermission(NetPermissionFlags::Download))) { LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because active chain has too little work; sending empty response\n", pfrom.GetId()); // Just respond with an empty headers message, to tell the peer to // go away but not treat us as unresponsive. MakeAndPushMessage(pfrom, NetMsgType::HEADERS, std::vector<CBlockHeader>()); return; } CNodeState *nodestate = State(pfrom.GetId()); const CBlockIndex* pindex = nullptr; if (locator.IsNull()) { // If locator is null, return the hashStop block pindex = m_chainman.m_blockman.LookupBlockIndex(hashStop); if (!pindex) { return; } if (!BlockRequestAllowed(pindex)) { LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom.GetId()); return; } } else { // Find the last block the caller has in the main chain pindex = m_chainman.ActiveChainstate().FindForkInGlobalIndex(locator); if (pindex) pindex = m_chainman.ActiveChain().Next(pindex); } // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end std::vector<CBlock> vHeaders; int nLimit = MAX_HEADERS_RESULTS; LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom.GetId()); for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex)) { vHeaders.emplace_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } // pindex can be nullptr either if we sent m_chainman.ActiveChain().Tip() OR // if our peer has m_chainman.ActiveChain().Tip() (and thus we are sending an empty // headers message). In both cases it's safe to update // pindexBestHeaderSent to be our tip. // // It is important that we simply reset the BestHeaderSent value here, // and not max(BestHeaderSent, newHeaderSent). We might have announced // the currently-being-connected tip using a compact block, which // resulted in the peer sending a headers request, which we respond to // without the new block. By resetting the BestHeaderSent, we ensure we // will re-announce the new block via headers (or compact blocks again) // in the SendMessages logic. nodestate->pindexBestHeaderSent = pindex ? pindex : m_chainman.ActiveChain().Tip(); MakeAndPushMessage(pfrom, NetMsgType::HEADERS, TX_WITH_WITNESS(vHeaders)); return; } if (msg_type == NetMsgType::TX) { if (RejectIncomingTxs(pfrom)) { LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom.GetId()); pfrom.fDisconnect = true; return; } // Stop processing the transaction early if we are still in IBD since we don't // have enough information to validate it yet. Sending unsolicited transactions // is not considered a protocol violation, so don't punish the peer. if (m_chainman.IsInitialBlockDownload()) return; CTransactionRef ptx; vRecv >> TX_WITH_WITNESS(ptx); const CTransaction& tx = *ptx; const uint256& txid = ptx->GetHash(); const uint256& wtxid = ptx->GetWitnessHash(); const uint256& hash = peer->m_wtxid_relay ? wtxid : txid; AddKnownTx(*peer, hash); LOCK(cs_main); m_txrequest.ReceivedResponse(pfrom.GetId(), txid); if (tx.HasWitness()) m_txrequest.ReceivedResponse(pfrom.GetId(), wtxid); // We do the AlreadyHaveTx() check using wtxid, rather than txid - in the // absence of witness malleation, this is strictly better, because the // recent rejects filter may contain the wtxid but rarely contains // the txid of a segwit transaction that has been rejected. // In the presence of witness malleation, it's possible that by only // doing the check with wtxid, we could overlook a transaction which // was confirmed with a different witness, or exists in our mempool // with a different witness, but this has limited downside: // mempool validation does its own lookup of whether we have the txid // already; and an adversary can already relay us old transactions // (older than our recency filter) if trying to DoS us, without any need // for witness malleation. if (AlreadyHaveTx(GenTxid::Wtxid(wtxid))) { if (pfrom.HasPermission(NetPermissionFlags::ForceRelay)) { // Always relay transactions received from peers with forcerelay // permission, even if they were already in the mempool, allowing // the node to function as a gateway for nodes hidden behind it. if (!m_mempool.exists(GenTxid::Txid(tx.GetHash()))) { LogPrintf("Not relaying non-mempool transaction %s (wtxid=%s) from forcerelay peer=%d\n", tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), pfrom.GetId()); } else { LogPrintf("Force relaying tx %s (wtxid=%s) from peer=%d\n", tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), pfrom.GetId()); RelayTransaction(tx.GetHash(), tx.GetWitnessHash()); } } // If a tx is detected by m_recent_rejects it is ignored. Because we haven't // submitted the tx to our mempool, we won't have computed a DoS // score for it or determined exactly why we consider it invalid. // // This means we won't penalize any peer subsequently relaying a DoSy // tx (even if we penalized the first peer who gave it to us) because // we have to account for m_recent_rejects showing false positives. In // other words, we shouldn't penalize a peer if we aren't *sure* they // submitted a DoSy tx. // // Note that m_recent_rejects doesn't just record DoSy or invalid // transactions, but any tx not accepted by the mempool, which may be // due to node policy (vs. consensus). So we can't blanket penalize a // peer simply for relaying a tx that our m_recent_rejects has caught, // regardless of false positives. return; } const MempoolAcceptResult result = m_chainman.ProcessTransaction(ptx); const TxValidationState& state = result.m_state; if (result.m_result_type == MempoolAcceptResult::ResultType::VALID) { // As this version of the transaction was acceptable, we can forget about any // requests for it. m_txrequest.ForgetTxHash(tx.GetHash()); m_txrequest.ForgetTxHash(tx.GetWitnessHash()); RelayTransaction(tx.GetHash(), tx.GetWitnessHash()); m_orphanage.AddChildrenToWorkSet(tx); pfrom.m_last_tx_time = GetTime<std::chrono::seconds>(); LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (wtxid=%s) (poolsz %u txn, %u kB)\n", pfrom.GetId(), tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), m_mempool.size(), m_mempool.DynamicMemoryUsage() / 1000); for (const CTransactionRef& removedTx : result.m_replaced_transactions.value()) { AddToCompactExtraTransactions(removedTx); } } else if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS) { bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected // Deduplicate parent txids, so that we don't have to loop over // the same parent txid more than once down below. std::vector<uint256> unique_parents; unique_parents.reserve(tx.vin.size()); for (const CTxIn& txin : tx.vin) { // We start with all parents, and then remove duplicates below. unique_parents.push_back(txin.prevout.hash); } std::sort(unique_parents.begin(), unique_parents.end()); unique_parents.erase(std::unique(unique_parents.begin(), unique_parents.end()), unique_parents.end()); for (const uint256& parent_txid : unique_parents) { if (m_recent_rejects.contains(parent_txid)) { fRejectedParents = true; break; } } if (!fRejectedParents) { const auto current_time{GetTime<std::chrono::microseconds>()}; for (const uint256& parent_txid : unique_parents) { // Here, we only have the txid (and not wtxid) of the // inputs, so we only request in txid mode, even for // wtxidrelay peers. // Eventually we should replace this with an improved // protocol for getting all unconfirmed parents. const auto gtxid{GenTxid::Txid(parent_txid)}; AddKnownTx(*peer, parent_txid); if (!AlreadyHaveTx(gtxid)) AddTxAnnouncement(pfrom, gtxid, current_time); } if (m_orphanage.AddTx(ptx, pfrom.GetId())) { AddToCompactExtraTransactions(ptx); } // Once added to the orphan pool, a tx is considered AlreadyHave, and we shouldn't request it anymore. m_txrequest.ForgetTxHash(tx.GetHash()); m_txrequest.ForgetTxHash(tx.GetWitnessHash()); // DoS prevention: do not allow m_orphanage to grow unbounded (see CVE-2012-3789) m_orphanage.LimitOrphans(m_opts.max_orphan_txs, m_rng); } else { LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s (wtxid=%s)\n", tx.GetHash().ToString(), tx.GetWitnessHash().ToString()); // We will continue to reject this tx since it has rejected // parents so avoid re-requesting it from other peers. // Here we add both the txid and the wtxid, as we know that // regardless of what witness is provided, we will not accept // this, so we don't need to allow for redownload of this txid // from any of our non-wtxidrelay peers. m_recent_rejects.insert(tx.GetHash().ToUint256()); m_recent_rejects.insert(tx.GetWitnessHash().ToUint256()); m_txrequest.ForgetTxHash(tx.GetHash()); m_txrequest.ForgetTxHash(tx.GetWitnessHash()); } } else { if (state.GetResult() != TxValidationResult::TX_WITNESS_STRIPPED) { // We can add the wtxid of this transaction to our reject filter. // Do not add txids of witness transactions or witness-stripped // transactions to the filter, as they can have been malleated; // adding such txids to the reject filter would potentially // interfere with relay of valid transactions from peers that // do not support wtxid-based relay. See // https://github.com/bitcoin/bitcoin/issues/8279 for details. // We can remove this restriction (and always add wtxids to // the filter even for witness stripped transactions) once // wtxid-based relay is broadly deployed. // See also comments in https://github.com/bitcoin/bitcoin/pull/18044#discussion_r443419034 // for concerns around weakening security of unupgraded nodes // if we start doing this too early. m_recent_rejects.insert(tx.GetWitnessHash().ToUint256()); m_txrequest.ForgetTxHash(tx.GetWitnessHash()); // If the transaction failed for TX_INPUTS_NOT_STANDARD, // then we know that the witness was irrelevant to the policy // failure, since this check depends only on the txid // (the scriptPubKey being spent is covered by the txid). // Add the txid to the reject filter to prevent repeated // processing of this transaction in the event that child // transactions are later received (resulting in // parent-fetching by txid via the orphan-handling logic). if (state.GetResult() == TxValidationResult::TX_INPUTS_NOT_STANDARD && tx.HasWitness()) { m_recent_rejects.insert(tx.GetHash().ToUint256()); m_txrequest.ForgetTxHash(tx.GetHash()); } if (RecursiveDynamicUsage(*ptx) < 100000) { AddToCompactExtraTransactions(ptx); } } } if (state.IsInvalid()) { LogPrint(BCLog::MEMPOOLREJ, "%s (wtxid=%s) from peer=%d was not accepted: %s\n", tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), pfrom.GetId(), state.ToString()); MaybePunishNodeForTx(pfrom.GetId(), state); } return; } if (msg_type == NetMsgType::CMPCTBLOCK) { // Ignore cmpctblock received while importing if (m_chainman.m_blockman.LoadingBlocks()) { LogPrint(BCLog::NET, "Unexpected cmpctblock message received from peer %d\n", pfrom.GetId()); return; } CBlockHeaderAndShortTxIDs cmpctblock; vRecv >> cmpctblock; bool received_new_header = false; const auto blockhash = cmpctblock.header.GetHash(); { LOCK(cs_main); const CBlockIndex* prev_block = m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock); if (!prev_block) { // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers if (!m_chainman.IsInitialBlockDownload()) { MaybeSendGetHeaders(pfrom, GetLocator(m_chainman.m_best_header), *peer); } return; } else if (prev_block->nChainWork + CalculateHeadersWork({cmpctblock.header}) < GetAntiDoSWorkThreshold()) { // If we get a low-work header in a compact block, we can ignore it. LogPrint(BCLog::NET, "Ignoring low-work compact block from peer %d\n", pfrom.GetId()); return; } if (!m_chainman.m_blockman.LookupBlockIndex(blockhash)) { received_new_header = true; } } const CBlockIndex *pindex = nullptr; BlockValidationState state; if (!m_chainman.ProcessNewBlockHeaders({cmpctblock.header}, /*min_pow_checked=*/true, state, &pindex)) { if (state.IsInvalid()) { MaybePunishNodeForBlock(pfrom.GetId(), state, /*via_compact_block=*/true, "invalid header via cmpctblock"); return; } } if (received_new_header) { LogPrintfCategory(BCLog::NET, "Saw new cmpctblock header hash=%s peer=%d\n", blockhash.ToString(), pfrom.GetId()); } bool fProcessBLOCKTXN = false; // If we end up treating this as a plain headers message, call that as well // without cs_main. bool fRevertToHeaderProcessing = false; // Keep a CBlock for "optimistic" compactblock reconstructions (see // below) std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); bool fBlockReconstructed = false; { LOCK(cs_main); // If AcceptBlockHeader returned true, it set pindex assert(pindex); UpdateBlockAvailability(pfrom.GetId(), pindex->GetBlockHash()); CNodeState *nodestate = State(pfrom.GetId()); // If this was a new header with more work than our tip, update the // peer's last block announcement time if (received_new_header && pindex->nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) { nodestate->m_last_block_announcement = GetTime(); } if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here return; auto range_flight = mapBlocksInFlight.equal_range(pindex->GetBlockHash()); size_t already_in_flight = std::distance(range_flight.first, range_flight.second); bool requested_block_from_this_peer{false}; // Multimap ensures ordering of outstanding requests. It's either empty or first in line. bool first_in_flight = already_in_flight == 0 || (range_flight.first->second.first == pfrom.GetId()); while (range_flight.first != range_flight.second) { if (range_flight.first->second.first == pfrom.GetId()) { requested_block_from_this_peer = true; break; } range_flight.first++; } if (pindex->nChainWork <= m_chainman.ActiveChain().Tip()->nChainWork || // We know something better pindex->nTx != 0) { // We had this block at some point, but pruned it if (requested_block_from_this_peer) { // We requested this block for some reason, but our mempool will probably be useless // so we just grab the block via normal getdata std::vector<CInv> vInv(1); vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash); MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv); } return; } // If we're not close to tip yet, give up and let parallel block fetch work its magic if (!already_in_flight && !CanDirectFetch()) { return; } // We want to be a bit conservative just to be extra careful about DoS // possibilities in compact block processing... if (pindex->nHeight <= m_chainman.ActiveChain().Height() + 2) { if ((already_in_flight < MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK && nodestate->vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) || requested_block_from_this_peer) { std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr; if (!BlockRequested(pfrom.GetId(), *pindex, &queuedBlockIt)) { if (!(*queuedBlockIt)->partialBlock) (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&m_mempool)); else { // The block was already in flight using compact blocks from the same peer LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n"); return; } } PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock; ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact); if (status == READ_STATUS_INVALID) { RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId()); // Reset in-flight state in case Misbehaving does not result in a disconnect Misbehaving(*peer, 100, "invalid compact block"); return; } else if (status == READ_STATUS_FAILED) { if (first_in_flight) { // Duplicate txindexes, the block is now in-flight, so just request it std::vector<CInv> vInv(1); vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash); MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv); } else { // Give up for this peer and wait for other peer(s) RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId()); } return; } BlockTransactionsRequest req; for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) { if (!partialBlock.IsTxAvailable(i)) req.indexes.push_back(i); } if (req.indexes.empty()) { fProcessBLOCKTXN = true; } else if (first_in_flight) { // We will try to round-trip any compact blocks we get on failure, // as long as it's first... req.blockhash = pindex->GetBlockHash(); MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req); } else if (pfrom.m_bip152_highbandwidth_to && (!pfrom.IsInboundConn() || IsBlockRequestedFromOutbound(blockhash) || already_in_flight < MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK - 1)) { // ... or it's a hb relay peer and: // - peer is outbound, or // - we already have an outbound attempt in flight(so we'll take what we can get), or // - it's not the final parallel download slot (which we may reserve for first outbound) req.blockhash = pindex->GetBlockHash(); MakeAndPushMessage(pfrom, NetMsgType::GETBLOCKTXN, req); } else { // Give up for this peer and wait for other peer(s) RemoveBlockRequest(pindex->GetBlockHash(), pfrom.GetId()); } } else { // This block is either already in flight from a different // peer, or this peer has too many blocks outstanding to // download from. // Optimistically try to reconstruct anyway since we might be // able to without any round trips. PartiallyDownloadedBlock tempBlock(&m_mempool); ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact); if (status != READ_STATUS_OK) { // TODO: don't ignore failures return; } std::vector<CTransactionRef> dummy; status = tempBlock.FillBlock(*pblock, dummy); if (status == READ_STATUS_OK) { fBlockReconstructed = true; } } } else { if (requested_block_from_this_peer) { // We requested this block, but its far into the future, so our // mempool will probably be useless - request the block normally std::vector<CInv> vInv(1); vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), blockhash); MakeAndPushMessage(pfrom, NetMsgType::GETDATA, vInv); return; } else { // If this was an announce-cmpctblock, we want the same treatment as a header message fRevertToHeaderProcessing = true; } } } // cs_main if (fProcessBLOCKTXN) { BlockTransactions txn; txn.blockhash = blockhash; return ProcessCompactBlockTxns(pfrom, *peer, txn); } if (fRevertToHeaderProcessing) { // Headers received from HB compact block peers are permitted to be // relayed before full validation (see BIP 152), so we don't want to disconnect // the peer if the header turns out to be for an invalid block. // Note that if a peer tries to build on an invalid chain, that // will be detected and the peer will be disconnected/discouraged. return ProcessHeadersMessage(pfrom, *peer, {cmpctblock.header}, /*via_compact_block=*/true); } if (fBlockReconstructed) { // If we got here, we were able to optimistically reconstruct a // block that is in flight from some other peer. { LOCK(cs_main); mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom.GetId(), false)); } // Setting force_processing to true means that we bypass some of // our anti-DoS protections in AcceptBlock, which filters // unrequested blocks that might be trying to waste our resources // (eg disk space). Because we only try to reconstruct blocks when // we're close to caught up (via the CanDirectFetch() requirement // above, combined with the behavior of not requesting blocks until // we have a chain with at least the minimum chain work), and we ignore // compact blocks with less work than our tip, it is safe to treat // reconstructed compact blocks as having been requested. ProcessBlock(pfrom, pblock, /*force_processing=*/true, /*min_pow_checked=*/true); LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid() if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) { // Clear download state for this block, which is in // process from some other peer. We do this after calling // ProcessNewBlock so that a malleated cmpctblock announcement // can't be used to interfere with block relay. RemoveBlockRequest(pblock->GetHash(), std::nullopt); } } return; } if (msg_type == NetMsgType::BLOCKTXN) { // Ignore blocktxn received while importing if (m_chainman.m_blockman.LoadingBlocks()) { LogPrint(BCLog::NET, "Unexpected blocktxn message received from peer %d\n", pfrom.GetId()); return; } BlockTransactions resp; vRecv >> resp; return ProcessCompactBlockTxns(pfrom, *peer, resp); } if (msg_type == NetMsgType::HEADERS) { // Ignore headers received while importing if (m_chainman.m_blockman.LoadingBlocks()) { LogPrint(BCLog::NET, "Unexpected headers message received from peer %d\n", pfrom.GetId()); return; } // Assume that this is in response to any outstanding getheaders // request we may have sent, and clear out the time of our last request peer->m_last_getheaders_timestamp = {}; std::vector<CBlockHeader> headers; // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks. unsigned int nCount = ReadCompactSize(vRecv); if (nCount > MAX_HEADERS_RESULTS) { Misbehaving(*peer, 20, strprintf("headers message size = %u", nCount)); return; } headers.resize(nCount); for (unsigned int n = 0; n < nCount; n++) { vRecv >> headers[n]; ReadCompactSize(vRecv); // ignore tx count; assume it is 0. } ProcessHeadersMessage(pfrom, *peer, std::move(headers), /*via_compact_block=*/false); // Check if the headers presync progress needs to be reported to validation. // This needs to be done without holding the m_headers_presync_mutex lock. if (m_headers_presync_should_signal.exchange(false)) { HeadersPresyncStats stats; { LOCK(m_headers_presync_mutex); auto it = m_headers_presync_stats.find(m_headers_presync_bestpeer); if (it != m_headers_presync_stats.end()) stats = it->second; } if (stats.second) { m_chainman.ReportHeadersPresync(stats.first, stats.second->first, stats.second->second); } } return; } if (msg_type == NetMsgType::BLOCK) { // Ignore block received while importing if (m_chainman.m_blockman.LoadingBlocks()) { LogPrint(BCLog::NET, "Unexpected block message received from peer %d\n", pfrom.GetId()); return; } std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); vRecv >> TX_WITH_WITNESS(*pblock); LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom.GetId()); bool forceProcessing = false; const uint256 hash(pblock->GetHash()); bool min_pow_checked = false; { LOCK(cs_main); // Always process the block if we requested it, since we may // need it even when it's not a candidate for a new best tip. forceProcessing = IsBlockRequested(hash); RemoveBlockRequest(hash, pfrom.GetId()); // mapBlockSource is only used for punishing peers and setting // which peers send us compact blocks, so the race between here and // cs_main in ProcessNewBlock is fine. mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true)); // Check work on this block against our anti-dos thresholds. const CBlockIndex* prev_block = m_chainman.m_blockman.LookupBlockIndex(pblock->hashPrevBlock); if (prev_block && prev_block->nChainWork + CalculateHeadersWork({pblock->GetBlockHeader()}) >= GetAntiDoSWorkThreshold()) { min_pow_checked = true; } } ProcessBlock(pfrom, pblock, forceProcessing, min_pow_checked); return; } if (msg_type == NetMsgType::GETADDR) { // This asymmetric behavior for inbound and outbound connections was introduced // to prevent a fingerprinting attack: an attacker can send specific fake addresses // to users' AddrMan and later request them by sending getaddr messages. // Making nodes which are behind NAT and can only make outgoing connections ignore // the getaddr message mitigates the attack. if (!pfrom.IsInboundConn()) { LogPrint(BCLog::NET, "Ignoring \"getaddr\" from %s connection. peer=%d\n", pfrom.ConnectionTypeAsString(), pfrom.GetId()); return; } // Since this must be an inbound connection, SetupAddressRelay will // never fail. Assume(SetupAddressRelay(pfrom, *peer)); // Only send one GetAddr response per connection to reduce resource waste // and discourage addr stamping of INV announcements. if (peer->m_getaddr_recvd) { LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom.GetId()); return; } peer->m_getaddr_recvd = true; peer->m_addrs_to_send.clear(); std::vector<CAddress> vAddr; if (pfrom.HasPermission(NetPermissionFlags::Addr)) { vAddr = m_connman.GetAddresses(MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND, /*network=*/std::nullopt); } else { vAddr = m_connman.GetAddresses(pfrom, MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND); } for (const CAddress &addr : vAddr) { PushAddress(*peer, addr); } return; } if (msg_type == NetMsgType::MEMPOOL) { // Only process received mempool messages if we advertise NODE_BLOOM // or if the peer has mempool permissions. if (!(peer->m_our_services & NODE_BLOOM) && !pfrom.HasPermission(NetPermissionFlags::Mempool)) { if (!pfrom.HasPermission(NetPermissionFlags::NoBan)) { LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom.GetId()); pfrom.fDisconnect = true; } return; } if (m_connman.OutboundTargetReached(false) && !pfrom.HasPermission(NetPermissionFlags::Mempool)) { if (!pfrom.HasPermission(NetPermissionFlags::NoBan)) { LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom.GetId()); pfrom.fDisconnect = true; } return; } if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { LOCK(tx_relay->m_tx_inventory_mutex); tx_relay->m_send_mempool = true; } return; } if (msg_type == NetMsgType::PING) { if (pfrom.GetCommonVersion() > BIP0031_VERSION) { uint64_t nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. MakeAndPushMessage(pfrom, NetMsgType::PONG, nonce); } return; } if (msg_type == NetMsgType::PONG) { const auto ping_end = time_received; uint64_t nonce = 0; size_t nAvail = vRecv.in_avail(); bool bPingFinished = false; std::string sProblem; if (nAvail >= sizeof(nonce)) { vRecv >> nonce; // Only process pong message if there is an outstanding ping (old ping without nonce should never pong) if (peer->m_ping_nonce_sent != 0) { if (nonce == peer->m_ping_nonce_sent) { // Matching pong received, this ping is no longer outstanding bPingFinished = true; const auto ping_time = ping_end - peer->m_ping_start.load(); if (ping_time.count() >= 0) { // Let connman know about this successful ping-pong pfrom.PongReceived(ping_time); } else { // This should never happen sProblem = "Timing mishap"; } } else { // Nonce mismatches are normal when pings are overlapping sProblem = "Nonce mismatch"; if (nonce == 0) { // This is most likely a bug in another implementation somewhere; cancel this ping bPingFinished = true; sProblem = "Nonce zero"; } } } else { sProblem = "Unsolicited pong without ping"; } } else { // This is most likely a bug in another implementation somewhere; cancel this ping bPingFinished = true; sProblem = "Short payload"; } if (!(sProblem.empty())) { LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n", pfrom.GetId(), sProblem, peer->m_ping_nonce_sent, nonce, nAvail); } if (bPingFinished) { peer->m_ping_nonce_sent = 0; } return; } if (msg_type == NetMsgType::FILTERLOAD) { if (!(peer->m_our_services & NODE_BLOOM)) { LogPrint(BCLog::NET, "filterload received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId()); pfrom.fDisconnect = true; return; } CBloomFilter filter; vRecv >> filter; if (!filter.IsWithinSizeConstraints()) { // There is no excuse for sending a too-large filter Misbehaving(*peer, 100, "too-large bloom filter"); } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { { LOCK(tx_relay->m_bloom_filter_mutex); tx_relay->m_bloom_filter.reset(new CBloomFilter(filter)); tx_relay->m_relay_txs = true; } pfrom.m_bloom_filter_loaded = true; pfrom.m_relays_txs = true; } return; } if (msg_type == NetMsgType::FILTERADD) { if (!(peer->m_our_services & NODE_BLOOM)) { LogPrint(BCLog::NET, "filteradd received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId()); pfrom.fDisconnect = true; return; } std::vector<unsigned char> vData; vRecv >> vData; // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object, // and thus, the maximum size any matched object can have) in a filteradd message bool bad = false; if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) { bad = true; } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { LOCK(tx_relay->m_bloom_filter_mutex); if (tx_relay->m_bloom_filter) { tx_relay->m_bloom_filter->insert(vData); } else { bad = true; } } if (bad) { Misbehaving(*peer, 100, "bad filteradd message"); } return; } if (msg_type == NetMsgType::FILTERCLEAR) { if (!(peer->m_our_services & NODE_BLOOM)) { LogPrint(BCLog::NET, "filterclear received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId()); pfrom.fDisconnect = true; return; } auto tx_relay = peer->GetTxRelay(); if (!tx_relay) return; { LOCK(tx_relay->m_bloom_filter_mutex); tx_relay->m_bloom_filter = nullptr; tx_relay->m_relay_txs = true; } pfrom.m_bloom_filter_loaded = false; pfrom.m_relays_txs = true; return; } if (msg_type == NetMsgType::FEEFILTER) { CAmount newFeeFilter = 0; vRecv >> newFeeFilter; if (MoneyRange(newFeeFilter)) { if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { tx_relay->m_fee_filter_received = newFeeFilter; } LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom.GetId()); } return; } if (msg_type == NetMsgType::GETCFILTERS) { ProcessGetCFilters(pfrom, *peer, vRecv); return; } if (msg_type == NetMsgType::GETCFHEADERS) { ProcessGetCFHeaders(pfrom, *peer, vRecv); return; } if (msg_type == NetMsgType::GETCFCHECKPT) { ProcessGetCFCheckPt(pfrom, *peer, vRecv); return; } if (msg_type == NetMsgType::NOTFOUND) { std::vector<CInv> vInv; vRecv >> vInv; if (vInv.size() <= MAX_PEER_TX_ANNOUNCEMENTS + MAX_BLOCKS_IN_TRANSIT_PER_PEER) { LOCK(::cs_main); for (CInv &inv : vInv) { if (inv.IsGenTxMsg()) { // If we receive a NOTFOUND message for a tx we requested, mark the announcement for it as // completed in TxRequestTracker. m_txrequest.ReceivedResponse(pfrom.GetId(), inv.hash); } } } return; } // Ignore unknown commands for extensibility LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId()); return; } bool PeerManagerImpl::MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer) { { LOCK(peer.m_misbehavior_mutex); // There's nothing to do if the m_should_discourage flag isn't set if (!peer.m_should_discourage) return false; peer.m_should_discourage = false; } // peer.m_misbehavior_mutex if (pnode.HasPermission(NetPermissionFlags::NoBan)) { // We never disconnect or discourage peers for bad behavior if they have NetPermissionFlags::NoBan permission LogPrintf("Warning: not punishing noban peer %d!\n", peer.m_id); return false; } if (pnode.IsManualConn()) { // We never disconnect or discourage manual peers for bad behavior LogPrintf("Warning: not punishing manually connected peer %d!\n", peer.m_id); return false; } if (pnode.addr.IsLocal()) { // We disconnect local peers for bad behavior but don't discourage (since that would discourage // all peers on the same local address) LogPrint(BCLog::NET, "Warning: disconnecting but not discouraging %s peer %d!\n", pnode.m_inbound_onion ? "inbound onion" : "local", peer.m_id); pnode.fDisconnect = true; return true; } // Normal case: Disconnect the peer and discourage all nodes sharing the address LogPrint(BCLog::NET, "Disconnecting and discouraging peer %d!\n", peer.m_id); if (m_banman) m_banman->Discourage(pnode.addr); m_connman.DisconnectNode(pnode.addr); return true; } bool PeerManagerImpl::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc) { AssertLockHeld(g_msgproc_mutex); PeerRef peer = GetPeerRef(pfrom->GetId()); if (peer == nullptr) return false; { LOCK(peer->m_getdata_requests_mutex); if (!peer->m_getdata_requests.empty()) { ProcessGetData(*pfrom, *peer, interruptMsgProc); } } const bool processed_orphan = ProcessOrphanTx(*peer); if (pfrom->fDisconnect) return false; if (processed_orphan) return true; // this maintains the order of responses // and prevents m_getdata_requests to grow unbounded { LOCK(peer->m_getdata_requests_mutex); if (!peer->m_getdata_requests.empty()) return true; } // Don't bother if send buffer is too full to respond anyway if (pfrom->fPauseSend) return false; auto poll_result{pfrom->PollMessage()}; if (!poll_result) { // No message to process return false; } CNetMessage& msg{poll_result->first}; bool fMoreWork = poll_result->second; TRACE6(net, inbound_message, pfrom->GetId(), pfrom->m_addr_name.c_str(), pfrom->ConnectionTypeAsString().c_str(), msg.m_type.c_str(), msg.m_recv.size(), msg.m_recv.data() ); if (m_opts.capture_messages) { CaptureMessage(pfrom->addr, msg.m_type, MakeUCharSpan(msg.m_recv), /*is_incoming=*/true); } try { ProcessMessage(*pfrom, msg.m_type, msg.m_recv, msg.m_time, interruptMsgProc); if (interruptMsgProc) return false; { LOCK(peer->m_getdata_requests_mutex); if (!peer->m_getdata_requests.empty()) fMoreWork = true; } // Does this peer has an orphan ready to reconsider? // (Note: we may have provided a parent for an orphan provided // by another peer that was already processed; in that case, // the extra work may not be noticed, possibly resulting in an // unnecessary 100ms delay) if (m_orphanage.HaveTxToReconsider(peer->m_id)) fMoreWork = true; } catch (const std::exception& e) { LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' (%s) caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size, e.what(), typeid(e).name()); } catch (...) { LogPrint(BCLog::NET, "%s(%s, %u bytes): Unknown exception caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size); } return fMoreWork; } void PeerManagerImpl::ConsiderEviction(CNode& pto, Peer& peer, std::chrono::seconds time_in_seconds) { AssertLockHeld(cs_main); CNodeState &state = *State(pto.GetId()); if (!state.m_chain_sync.m_protect && pto.IsOutboundOrBlockRelayConn() && state.fSyncStarted) { // This is an outbound peer subject to disconnection if they don't // announce a block with as much work as the current tip within // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if // their chain has more work than ours, we should sync to it, // unless it's invalid, in which case we should find that out and // disconnect from them elsewhere). if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork) { if (state.m_chain_sync.m_timeout != 0s) { state.m_chain_sync.m_timeout = 0s; state.m_chain_sync.m_work_header = nullptr; state.m_chain_sync.m_sent_getheaders = false; } } else if (state.m_chain_sync.m_timeout == 0s || (state.m_chain_sync.m_work_header != nullptr && state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= state.m_chain_sync.m_work_header->nChainWork)) { // Our best block known by this peer is behind our tip, and we're either noticing // that for the first time, OR this peer was able to catch up to some earlier point // where we checked against our tip. // Either way, set a new timeout based on current tip. state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT; state.m_chain_sync.m_work_header = m_chainman.ActiveChain().Tip(); state.m_chain_sync.m_sent_getheaders = false; } else if (state.m_chain_sync.m_timeout > 0s && time_in_seconds > state.m_chain_sync.m_timeout) { // No evidence yet that our peer has synced to a chain with work equal to that // of our tip, when we first detected it was behind. Send a single getheaders // message to give the peer a chance to update us. if (state.m_chain_sync.m_sent_getheaders) { // They've run out of time to catch up! LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto.GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>"); pto.fDisconnect = true; } else { assert(state.m_chain_sync.m_work_header); // Here, we assume that the getheaders message goes out, // because it'll either go out or be skipped because of a // getheaders in-flight already, in which case the peer should // still respond to us with a sufficiently high work chain tip. MaybeSendGetHeaders(pto, GetLocator(state.m_chain_sync.m_work_header->pprev), peer); LogPrint(BCLog::NET, "sending getheaders to outbound peer=%d to verify chain work (current best known block:%s, benchmark blockhash: %s)\n", pto.GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", state.m_chain_sync.m_work_header->GetBlockHash().ToString()); state.m_chain_sync.m_sent_getheaders = true; // Bump the timeout to allow a response, which could clear the timeout // (if the response shows the peer has synced), reset the timeout (if // the peer syncs to the required work but not to our tip), or result // in disconnect (if we advance to the timeout and pindexBestKnownBlock // has not sufficiently progressed) state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME; } } } } void PeerManagerImpl::EvictExtraOutboundPeers(std::chrono::seconds now) { // If we have any extra block-relay-only peers, disconnect the youngest unless // it's given us a block -- in which case, compare with the second-youngest, and // out of those two, disconnect the peer who least recently gave us a block. // The youngest block-relay-only peer would be the extra peer we connected // to temporarily in order to sync our tip; see net.cpp. // Note that we use higher nodeid as a measure for most recent connection. if (m_connman.GetExtraBlockRelayCount() > 0) { std::pair<NodeId, std::chrono::seconds> youngest_peer{-1, 0}, next_youngest_peer{-1, 0}; m_connman.ForEachNode([&](CNode* pnode) { if (!pnode->IsBlockOnlyConn() || pnode->fDisconnect) return; if (pnode->GetId() > youngest_peer.first) { next_youngest_peer = youngest_peer; youngest_peer.first = pnode->GetId(); youngest_peer.second = pnode->m_last_block_time; } }); NodeId to_disconnect = youngest_peer.first; if (youngest_peer.second > next_youngest_peer.second) { // Our newest block-relay-only peer gave us a block more recently; // disconnect our second youngest. to_disconnect = next_youngest_peer.first; } m_connman.ForNode(to_disconnect, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { AssertLockHeld(::cs_main); // Make sure we're not getting a block right now, and that // we've been connected long enough for this eviction to happen // at all. // Note that we only request blocks from a peer if we learn of a // valid headers chain with at least as much work as our tip. CNodeState *node_state = State(pnode->GetId()); if (node_state == nullptr || (now - pnode->m_connected >= MINIMUM_CONNECT_TIME && node_state->vBlocksInFlight.empty())) { pnode->fDisconnect = true; LogPrint(BCLog::NET, "disconnecting extra block-relay-only peer=%d (last block received at time %d)\n", pnode->GetId(), count_seconds(pnode->m_last_block_time)); return true; } else { LogPrint(BCLog::NET, "keeping block-relay-only peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", pnode->GetId(), count_seconds(pnode->m_connected), node_state->vBlocksInFlight.size()); } return false; }); } // Check whether we have too many outbound-full-relay peers if (m_connman.GetExtraFullOutboundCount() > 0) { // If we have more outbound-full-relay peers than we target, disconnect one. // Pick the outbound-full-relay peer that least recently announced // us a new block, with ties broken by choosing the more recent // connection (higher node id) // Protect peers from eviction if we don't have another connection // to their network, counting both outbound-full-relay and manual peers. NodeId worst_peer = -1; int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max(); m_connman.ForEachNode([&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_connman.GetNodesMutex()) { AssertLockHeld(::cs_main); // Only consider outbound-full-relay peers that are not already // marked for disconnection if (!pnode->IsFullOutboundConn() || pnode->fDisconnect) return; CNodeState *state = State(pnode->GetId()); if (state == nullptr) return; // shouldn't be possible, but just in case // Don't evict our protected peers if (state->m_chain_sync.m_protect) return; // If this is the only connection on a particular network that is // OUTBOUND_FULL_RELAY or MANUAL, protect it. if (!m_connman.MultipleManualOrFullOutboundConns(pnode->addr.GetNetwork())) return; if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) { worst_peer = pnode->GetId(); oldest_block_announcement = state->m_last_block_announcement; } }); if (worst_peer != -1) { bool disconnected = m_connman.ForNode(worst_peer, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { AssertLockHeld(::cs_main); // Only disconnect a peer that has been connected to us for // some reasonable fraction of our check-frequency, to give // it time for new information to have arrived. // Also don't disconnect any peer we're trying to download a // block from. CNodeState &state = *State(pnode->GetId()); if (now - pnode->m_connected > MINIMUM_CONNECT_TIME && state.vBlocksInFlight.empty()) { LogPrint(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement); pnode->fDisconnect = true; return true; } else { LogPrint(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", pnode->GetId(), count_seconds(pnode->m_connected), state.vBlocksInFlight.size()); return false; } }); if (disconnected) { // If we disconnected an extra peer, that means we successfully // connected to at least one peer after the last time we // detected a stale tip. Don't try any more extra peers until // we next detect a stale tip, to limit the load we put on the // network from these extra connections. m_connman.SetTryNewOutboundPeer(false); } } } } void PeerManagerImpl::CheckForStaleTipAndEvictPeers() { LOCK(cs_main); auto now{GetTime<std::chrono::seconds>()}; EvictExtraOutboundPeers(now); if (now > m_stale_tip_check_time) { // Check whether our tip is stale, and if so, allow using an extra // outbound peer if (!m_chainman.m_blockman.LoadingBlocks() && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) { LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n", count_seconds(now - m_last_tip_update.load())); m_connman.SetTryNewOutboundPeer(true); } else if (m_connman.GetTryNewOutboundPeer()) { m_connman.SetTryNewOutboundPeer(false); } m_stale_tip_check_time = now + STALE_CHECK_INTERVAL; } if (!m_initial_sync_finished && CanDirectFetch()) { m_connman.StartExtraBlockRelayPeers(); m_initial_sync_finished = true; } } void PeerManagerImpl::MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now) { if (m_connman.ShouldRunInactivityChecks(node_to, std::chrono::duration_cast<std::chrono::seconds>(now)) && peer.m_ping_nonce_sent && now > peer.m_ping_start.load() + TIMEOUT_INTERVAL) { // The ping timeout is using mocktime. To disable the check during // testing, increase -peertimeout. LogPrint(BCLog::NET, "ping timeout: %fs peer=%d\n", 0.000001 * count_microseconds(now - peer.m_ping_start.load()), peer.m_id); node_to.fDisconnect = true; return; } bool pingSend = false; if (peer.m_ping_queued) { // RPC ping request by user pingSend = true; } if (peer.m_ping_nonce_sent == 0 && now > peer.m_ping_start.load() + PING_INTERVAL) { // Ping automatically sent as a latency probe & keepalive. pingSend = true; } if (pingSend) { uint64_t nonce; do { nonce = GetRand<uint64_t>(); } while (nonce == 0); peer.m_ping_queued = false; peer.m_ping_start = now; if (node_to.GetCommonVersion() > BIP0031_VERSION) { peer.m_ping_nonce_sent = nonce; MakeAndPushMessage(node_to, NetMsgType::PING, nonce); } else { // Peer is too old to support ping command with nonce, pong will never arrive. peer.m_ping_nonce_sent = 0; MakeAndPushMessage(node_to, NetMsgType::PING); } } } void PeerManagerImpl::MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time) { // Nothing to do for non-address-relay peers if (!peer.m_addr_relay_enabled) return; LOCK(peer.m_addr_send_times_mutex); // Periodically advertise our local address to the peer. if (fListen && !m_chainman.IsInitialBlockDownload() && peer.m_next_local_addr_send < current_time) { // If we've sent before, clear the bloom filter for the peer, so that our // self-announcement will actually go out. // This might be unnecessary if the bloom filter has already rolled // over since our last self-announcement, but there is only a small // bandwidth cost that we can incur by doing this (which happens // once a day on average). if (peer.m_next_local_addr_send != 0us) { peer.m_addr_known->reset(); } if (std::optional<CService> local_service = GetLocalAddrForPeer(node)) { CAddress local_addr{*local_service, peer.m_our_services, Now<NodeSeconds>()}; PushAddress(peer, local_addr); } peer.m_next_local_addr_send = GetExponentialRand(current_time, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL); } // We sent an `addr` message to this peer recently. Nothing more to do. if (current_time <= peer.m_next_addr_send) return; peer.m_next_addr_send = GetExponentialRand(current_time, AVG_ADDRESS_BROADCAST_INTERVAL); if (!Assume(peer.m_addrs_to_send.size() <= MAX_ADDR_TO_SEND)) { // Should be impossible since we always check size before adding to // m_addrs_to_send. Recover by trimming the vector. peer.m_addrs_to_send.resize(MAX_ADDR_TO_SEND); } // Remove addr records that the peer already knows about, and add new // addrs to the m_addr_known filter on the same pass. auto addr_already_known = [&peer](const CAddress& addr) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) { bool ret = peer.m_addr_known->contains(addr.GetKey()); if (!ret) peer.m_addr_known->insert(addr.GetKey()); return ret; }; peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(), peer.m_addrs_to_send.end(), addr_already_known), peer.m_addrs_to_send.end()); // No addr messages to send if (peer.m_addrs_to_send.empty()) return; if (peer.m_wants_addrv2) { MakeAndPushMessage(node, NetMsgType::ADDRV2, CAddress::V2_NETWORK(peer.m_addrs_to_send)); } else { MakeAndPushMessage(node, NetMsgType::ADDR, CAddress::V1_NETWORK(peer.m_addrs_to_send)); } peer.m_addrs_to_send.clear(); // we only send the big addr message once if (peer.m_addrs_to_send.capacity() > 40) { peer.m_addrs_to_send.shrink_to_fit(); } } void PeerManagerImpl::MaybeSendSendHeaders(CNode& node, Peer& peer) { // Delay sending SENDHEADERS (BIP 130) until we're done with an // initial-headers-sync with this peer. Receiving headers announcements for // new blocks while trying to sync their headers chain is problematic, // because of the state tracking done. if (!peer.m_sent_sendheaders && node.GetCommonVersion() >= SENDHEADERS_VERSION) { LOCK(cs_main); CNodeState &state = *State(node.GetId()); if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork > m_chainman.MinimumChainWork()) { // Tell our peer we prefer to receive headers rather than inv's // We send this to non-NODE NETWORK peers as well, because even // non-NODE NETWORK peers can announce blocks (such as pruning // nodes) MakeAndPushMessage(node, NetMsgType::SENDHEADERS); peer.m_sent_sendheaders = true; } } } void PeerManagerImpl::MaybeSendFeefilter(CNode& pto, Peer& peer, std::chrono::microseconds current_time) { if (m_opts.ignore_incoming_txs) return; if (pto.GetCommonVersion() < FEEFILTER_VERSION) return; // peers with the forcerelay permission should not filter txs to us if (pto.HasPermission(NetPermissionFlags::ForceRelay)) return; // Don't send feefilter messages to outbound block-relay-only peers since they should never announce // transactions to us, regardless of feefilter state. if (pto.IsBlockOnlyConn()) return; CAmount currentFilter = m_mempool.GetMinFee().GetFeePerK(); if (m_chainman.IsInitialBlockDownload()) { // Received tx-inv messages are discarded when the active // chainstate is in IBD, so tell the peer to not send them. currentFilter = MAX_MONEY; } else { static const CAmount MAX_FILTER{m_fee_filter_rounder.round(MAX_MONEY)}; if (peer.m_fee_filter_sent == MAX_FILTER) { // Send the current filter if we sent MAX_FILTER previously // and made it out of IBD. peer.m_next_send_feefilter = 0us; } } if (current_time > peer.m_next_send_feefilter) { CAmount filterToSend = m_fee_filter_rounder.round(currentFilter); // We always have a fee filter of at least the min relay fee filterToSend = std::max(filterToSend, m_mempool.m_min_relay_feerate.GetFeePerK()); if (filterToSend != peer.m_fee_filter_sent) { MakeAndPushMessage(pto, NetMsgType::FEEFILTER, filterToSend); peer.m_fee_filter_sent = filterToSend; } peer.m_next_send_feefilter = GetExponentialRand(current_time, AVG_FEEFILTER_BROADCAST_INTERVAL); } // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY. else if (current_time + MAX_FEEFILTER_CHANGE_DELAY < peer.m_next_send_feefilter && (currentFilter < 3 * peer.m_fee_filter_sent / 4 || currentFilter > 4 * peer.m_fee_filter_sent / 3)) { peer.m_next_send_feefilter = current_time + GetRandomDuration<std::chrono::microseconds>(MAX_FEEFILTER_CHANGE_DELAY); } } namespace { class CompareInvMempoolOrder { CTxMemPool* mp; bool m_wtxid_relay; public: explicit CompareInvMempoolOrder(CTxMemPool *_mempool, bool use_wtxid) { mp = _mempool; m_wtxid_relay = use_wtxid; } bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b) { /* As std::make_heap produces a max-heap, we want the entries with the * fewest ancestors/highest fee to sort later. */ return mp->CompareDepthAndScore(*b, *a, m_wtxid_relay); } }; } // namespace bool PeerManagerImpl::RejectIncomingTxs(const CNode& peer) const { // block-relay-only peers may never send txs to us if (peer.IsBlockOnlyConn()) return true; if (peer.IsFeelerConn()) return true; // In -blocksonly mode, peers need the 'relay' permission to send txs to us if (m_opts.ignore_incoming_txs && !peer.HasPermission(NetPermissionFlags::Relay)) return true; return false; } bool PeerManagerImpl::SetupAddressRelay(const CNode& node, Peer& peer) { // We don't participate in addr relay with outbound block-relay-only // connections to prevent providing adversaries with the additional // information of addr traffic to infer the link. if (node.IsBlockOnlyConn()) return false; if (!peer.m_addr_relay_enabled.exchange(true)) { // During version message processing (non-block-relay-only outbound peers) // or on first addr-related message we have received (inbound peers), initialize // m_addr_known. peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001); } return true; } bool PeerManagerImpl::SendMessages(CNode* pto) { AssertLockHeld(g_msgproc_mutex); PeerRef peer = GetPeerRef(pto->GetId()); if (!peer) return false; const Consensus::Params& consensusParams = m_chainparams.GetConsensus(); // We must call MaybeDiscourageAndDisconnect first, to ensure that we'll // disconnect misbehaving peers even before the version handshake is complete. if (MaybeDiscourageAndDisconnect(*pto, *peer)) return true; // Don't send anything until the version handshake is complete if (!pto->fSuccessfullyConnected || pto->fDisconnect) return true; const auto current_time{GetTime<std::chrono::microseconds>()}; if (pto->IsAddrFetchConn() && current_time - pto->m_connected > 10 * AVG_ADDRESS_BROADCAST_INTERVAL) { LogPrint(BCLog::NET, "addrfetch connection timeout; disconnecting peer=%d\n", pto->GetId()); pto->fDisconnect = true; return true; } MaybeSendPing(*pto, *peer, current_time); // MaybeSendPing may have marked peer for disconnection if (pto->fDisconnect) return true; MaybeSendAddr(*pto, *peer, current_time); MaybeSendSendHeaders(*pto, *peer); { LOCK(cs_main); CNodeState &state = *State(pto->GetId()); // Start block sync if (m_chainman.m_best_header == nullptr) { m_chainman.m_best_header = m_chainman.ActiveChain().Tip(); } // Determine whether we might try initial headers sync or parallel // block download from this peer -- this mostly affects behavior while // in IBD (once out of IBD, we sync from all peers). bool sync_blocks_and_headers_from_peer = false; if (state.fPreferredDownload) { sync_blocks_and_headers_from_peer = true; } else if (CanServeBlocks(*peer) && !pto->IsAddrFetchConn()) { // Typically this is an inbound peer. If we don't have any outbound // peers, or if we aren't downloading any blocks from such peers, // then allow block downloads from this peer, too. // We prefer downloading blocks from outbound peers to avoid // putting undue load on (say) some home user who is just making // outbound connections to the network, but if our only source of // the latest blocks is from an inbound peer, we have to be sure to // eventually download it (and not just wait indefinitely for an // outbound peer to have it). if (m_num_preferred_download_peers == 0 || mapBlocksInFlight.empty()) { sync_blocks_and_headers_from_peer = true; } } if (!state.fSyncStarted && CanServeBlocks(*peer) && !m_chainman.m_blockman.LoadingBlocks()) { // Only actively request headers from a single peer, unless we're close to today. if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) || m_chainman.m_best_header->Time() > GetAdjustedTime() - 24h) { const CBlockIndex* pindexStart = m_chainman.m_best_header; /* If possible, start at the block preceding the currently best known header. This ensures that we always get a non-empty list of headers back as long as the peer is up-to-date. With a non-empty response, we can initialise the peer's known best block. This wouldn't be possible if we requested starting at m_chainman.m_best_header and got back an empty response. */ if (pindexStart->pprev) pindexStart = pindexStart->pprev; if (MaybeSendGetHeaders(*pto, GetLocator(pindexStart), *peer)) { LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), peer->m_starting_height); state.fSyncStarted = true; peer->m_headers_sync_timeout = current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE + ( // Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to microseconds before scaling // to maintain precision std::chrono::microseconds{HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER} * Ticks<std::chrono::seconds>(GetAdjustedTime() - m_chainman.m_best_header->Time()) / consensusParams.nPowTargetSpacing ); nSyncStarted++; } } } // // Try sending block announcements via headers // { // If we have no more than MAX_BLOCKS_TO_ANNOUNCE in our // list of block hashes we're relaying, and our peer wants // headers announcements, then find the first header // not yet known to our peer but would connect, and send. // If no header would connect, or if we have too many // blocks, or if the peer doesn't want headers, just // add all to the inv queue. LOCK(peer->m_block_inv_mutex); std::vector<CBlock> vHeaders; bool fRevertToInv = ((!peer->m_prefers_headers && (!state.m_requested_hb_cmpctblocks || peer->m_blocks_for_headers_relay.size() > 1)) || peer->m_blocks_for_headers_relay.size() > MAX_BLOCKS_TO_ANNOUNCE); const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date if (!fRevertToInv) { bool fFoundStartingHeader = false; // Try to find first header that our peer doesn't have, and // then send all headers past that one. If we come across any // headers that aren't on m_chainman.ActiveChain(), give up. for (const uint256& hash : peer->m_blocks_for_headers_relay) { const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash); assert(pindex); if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) { // Bail out if we reorged away from this block fRevertToInv = true; break; } if (pBestIndex != nullptr && pindex->pprev != pBestIndex) { // This means that the list of blocks to announce don't // connect to each other. // This shouldn't really be possible to hit during // regular operation (because reorgs should take us to // a chain that has some block not on the prior chain, // which should be caught by the prior check), but one // way this could happen is by using invalidateblock / // reconsiderblock repeatedly on the tip, causing it to // be added multiple times to m_blocks_for_headers_relay. // Robustly deal with this rare situation by reverting // to an inv. fRevertToInv = true; break; } pBestIndex = pindex; if (fFoundStartingHeader) { // add this to the headers message vHeaders.emplace_back(pindex->GetBlockHeader()); } else if (PeerHasHeader(&state, pindex)) { continue; // keep looking for the first new block } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) { // Peer doesn't have this header but they do have the prior one. // Start sending headers. fFoundStartingHeader = true; vHeaders.emplace_back(pindex->GetBlockHeader()); } else { // Peer doesn't have this header or the prior one -- nothing will // connect, so bail out. fRevertToInv = true; break; } } } if (!fRevertToInv && !vHeaders.empty()) { if (vHeaders.size() == 1 && state.m_requested_hb_cmpctblocks) { // We only send up to 1 block as header-and-ids, as otherwise // probably means we're doing an initial-ish-sync or they're slow LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__, vHeaders.front().GetHash().ToString(), pto->GetId()); std::optional<CSerializedNetMsg> cached_cmpctblock_msg; { LOCK(m_most_recent_block_mutex); if (m_most_recent_block_hash == pBestIndex->GetBlockHash()) { cached_cmpctblock_msg = NetMsg::Make(NetMsgType::CMPCTBLOCK, *m_most_recent_compact_block); } } if (cached_cmpctblock_msg.has_value()) { PushMessage(*pto, std::move(cached_cmpctblock_msg.value())); } else { CBlock block; const bool ret{m_chainman.m_blockman.ReadBlockFromDisk(block, *pBestIndex)}; assert(ret); CBlockHeaderAndShortTxIDs cmpctblock{block}; MakeAndPushMessage(*pto, NetMsgType::CMPCTBLOCK, cmpctblock); } state.pindexBestHeaderSent = pBestIndex; } else if (peer->m_prefers_headers) { if (vHeaders.size() > 1) { LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__, vHeaders.size(), vHeaders.front().GetHash().ToString(), vHeaders.back().GetHash().ToString(), pto->GetId()); } else { LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__, vHeaders.front().GetHash().ToString(), pto->GetId()); } MakeAndPushMessage(*pto, NetMsgType::HEADERS, TX_WITH_WITNESS(vHeaders)); state.pindexBestHeaderSent = pBestIndex; } else fRevertToInv = true; } if (fRevertToInv) { // If falling back to using an inv, just try to inv the tip. // The last entry in m_blocks_for_headers_relay was our tip at some point // in the past. if (!peer->m_blocks_for_headers_relay.empty()) { const uint256& hashToAnnounce = peer->m_blocks_for_headers_relay.back(); const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hashToAnnounce); assert(pindex); // Warn if we're announcing a block that is not on the main chain. // This should be very rare and could be optimized out. // Just log for now. if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) { LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n", hashToAnnounce.ToString(), m_chainman.ActiveChain().Tip()->GetBlockHash().ToString()); } // If the peer's chain has this block, don't inv it back. if (!PeerHasHeader(&state, pindex)) { peer->m_blocks_for_inv_relay.push_back(hashToAnnounce); LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__, pto->GetId(), hashToAnnounce.ToString()); } } } peer->m_blocks_for_headers_relay.clear(); } // // Message: inventory // std::vector<CInv> vInv; { LOCK(peer->m_block_inv_mutex); vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(), INVENTORY_BROADCAST_TARGET)); // Add blocks for (const uint256& hash : peer->m_blocks_for_inv_relay) { vInv.emplace_back(MSG_BLOCK, hash); if (vInv.size() == MAX_INV_SZ) { MakeAndPushMessage(*pto, NetMsgType::INV, vInv); vInv.clear(); } } peer->m_blocks_for_inv_relay.clear(); } if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) { LOCK(tx_relay->m_tx_inventory_mutex); // Check whether periodic sends should happen bool fSendTrickle = pto->HasPermission(NetPermissionFlags::NoBan); if (tx_relay->m_next_inv_send_time < current_time) { fSendTrickle = true; if (pto->IsInboundConn()) { tx_relay->m_next_inv_send_time = NextInvToInbounds(current_time, INBOUND_INVENTORY_BROADCAST_INTERVAL); } else { tx_relay->m_next_inv_send_time = GetExponentialRand(current_time, OUTBOUND_INVENTORY_BROADCAST_INTERVAL); } } // Time to send but the peer has requested we not relay transactions. if (fSendTrickle) { LOCK(tx_relay->m_bloom_filter_mutex); if (!tx_relay->m_relay_txs) tx_relay->m_tx_inventory_to_send.clear(); } // Respond to BIP35 mempool requests if (fSendTrickle && tx_relay->m_send_mempool) { auto vtxinfo = m_mempool.infoAll(); tx_relay->m_send_mempool = false; const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()}; LOCK(tx_relay->m_bloom_filter_mutex); for (const auto& txinfo : vtxinfo) { CInv inv{ peer->m_wtxid_relay ? MSG_WTX : MSG_TX, peer->m_wtxid_relay ? txinfo.tx->GetWitnessHash().ToUint256() : txinfo.tx->GetHash().ToUint256(), }; tx_relay->m_tx_inventory_to_send.erase(inv.hash); // Don't send transactions that peers will not put into their mempool if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) { continue; } if (tx_relay->m_bloom_filter) { if (!tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue; } tx_relay->m_tx_inventory_known_filter.insert(inv.hash); vInv.push_back(inv); if (vInv.size() == MAX_INV_SZ) { MakeAndPushMessage(*pto, NetMsgType::INV, vInv); vInv.clear(); } } } // Determine transactions to relay if (fSendTrickle) { // Produce a vector with all candidates for sending std::vector<std::set<uint256>::iterator> vInvTx; vInvTx.reserve(tx_relay->m_tx_inventory_to_send.size()); for (std::set<uint256>::iterator it = tx_relay->m_tx_inventory_to_send.begin(); it != tx_relay->m_tx_inventory_to_send.end(); it++) { vInvTx.push_back(it); } const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()}; // Topologically and fee-rate sort the inventory we send for privacy and priority reasons. // A heap is used so that not all items need sorting if only a few are being sent. CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool, peer->m_wtxid_relay); std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder); // No reason to drain out at many times the network's capacity, // especially since we have many peers and some will draw much shorter delays. unsigned int nRelayedTransactions = 0; LOCK(tx_relay->m_bloom_filter_mutex); size_t broadcast_max{INVENTORY_BROADCAST_TARGET + (tx_relay->m_tx_inventory_to_send.size()/1000)*5}; broadcast_max = std::min<size_t>(INVENTORY_BROADCAST_MAX, broadcast_max); while (!vInvTx.empty() && nRelayedTransactions < broadcast_max) { // Fetch the top element from the heap std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder); std::set<uint256>::iterator it = vInvTx.back(); vInvTx.pop_back(); uint256 hash = *it; CInv inv(peer->m_wtxid_relay ? MSG_WTX : MSG_TX, hash); // Remove it from the to-be-sent set tx_relay->m_tx_inventory_to_send.erase(it); // Check if not in the filter already if (tx_relay->m_tx_inventory_known_filter.contains(hash)) { continue; } // Not in the mempool anymore? don't bother sending it. auto txinfo = m_mempool.info(ToGenTxid(inv)); if (!txinfo.tx) { continue; } // Peer told you to not send transactions at that feerate? Don't bother sending it. if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) { continue; } if (tx_relay->m_bloom_filter && !tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue; // Send vInv.push_back(inv); nRelayedTransactions++; if (vInv.size() == MAX_INV_SZ) { MakeAndPushMessage(*pto, NetMsgType::INV, vInv); vInv.clear(); } tx_relay->m_tx_inventory_known_filter.insert(hash); } // Ensure we'll respond to GETDATA requests for anything we've just announced LOCK(m_mempool.cs); tx_relay->m_last_inv_sequence = m_mempool.GetSequence(); } } if (!vInv.empty()) MakeAndPushMessage(*pto, NetMsgType::INV, vInv); // Detect whether we're stalling auto stalling_timeout = m_block_stalling_timeout.load(); if (state.m_stalling_since.count() && state.m_stalling_since < current_time - stalling_timeout) { // Stalling only triggers when the block download window cannot move. During normal steady state, // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection // should only happen during initial block download. LogPrintf("Peer=%d%s is stalling block download, disconnecting\n", pto->GetId(), fLogIPs ? strprintf(" peeraddr=%s", pto->addr.ToStringAddrPort()) : ""); pto->fDisconnect = true; // Increase timeout for the next peer so that we don't disconnect multiple peers if our own // bandwidth is insufficient. const auto new_timeout = std::min(2 * stalling_timeout, BLOCK_STALLING_TIMEOUT_MAX); if (stalling_timeout != new_timeout && m_block_stalling_timeout.compare_exchange_strong(stalling_timeout, new_timeout)) { LogPrint(BCLog::NET, "Increased stalling timeout temporarily to %d seconds\n", count_seconds(new_timeout)); } return true; } // In case there is a block that has been in flight from this peer for block_interval * (1 + 0.5 * N) // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout. // We compensate for other peers to prevent killing off peers due to our own downstream link // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes // to unreasonably increase our timeout. if (state.vBlocksInFlight.size() > 0) { QueuedBlock &queuedBlock = state.vBlocksInFlight.front(); int nOtherPeersWithValidatedDownloads = m_peers_downloading_from - 1; if (current_time > state.m_downloading_since + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) { LogPrintf("Timeout downloading block %s from peer=%d%s, disconnecting\n", queuedBlock.pindex->GetBlockHash().ToString(), pto->GetId(), fLogIPs ? strprintf(" peeraddr=%s", pto->addr.ToStringAddrPort()) : ""); pto->fDisconnect = true; return true; } } // Check for headers sync timeouts if (state.fSyncStarted && peer->m_headers_sync_timeout < std::chrono::microseconds::max()) { // Detect whether this is a stalling initial-headers-sync peer if (m_chainman.m_best_header->Time() <= GetAdjustedTime() - 24h) { if (current_time > peer->m_headers_sync_timeout && nSyncStarted == 1 && (m_num_preferred_download_peers - state.fPreferredDownload >= 1)) { // Disconnect a peer (without NetPermissionFlags::NoBan permission) if it is our only sync peer, // and we have others we could be using instead. // Note: If all our peers are inbound, then we won't // disconnect our sync peer for stalling; we have bigger // problems if we can't get any outbound peers. if (!pto->HasPermission(NetPermissionFlags::NoBan)) { LogPrintf("Timeout downloading headers from peer=%d%s, disconnecting\n", pto->GetId(), fLogIPs ? strprintf(" peeraddr=%s", pto->addr.ToStringAddrPort()) : ""); pto->fDisconnect = true; return true; } else { LogPrintf("Timeout downloading headers from noban peer=%d%s, not disconnecting\n", pto->GetId(), fLogIPs ? strprintf(" peeraddr=%s", pto->addr.ToStringAddrPort()) : ""); // Reset the headers sync state so that we have a // chance to try downloading from a different peer. // Note: this will also result in at least one more // getheaders message to be sent to // this peer (eventually). state.fSyncStarted = false; nSyncStarted--; peer->m_headers_sync_timeout = 0us; } } } else { // After we've caught up once, reset the timeout so we can't trigger // disconnect later. peer->m_headers_sync_timeout = std::chrono::microseconds::max(); } } // Check that outbound peers have reasonable chains // GetTime() is used by this anti-DoS logic so we can test this using mocktime ConsiderEviction(*pto, *peer, GetTime<std::chrono::seconds>()); // // Message: getdata (blocks) // std::vector<CInv> vGetData; if (CanServeBlocks(*peer) && ((sync_blocks_and_headers_from_peer && !IsLimitedPeer(*peer)) || !m_chainman.IsInitialBlockDownload()) && state.vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) { std::vector<const CBlockIndex*> vToDownload; NodeId staller = -1; auto get_inflight_budget = [&state]() { return std::max(0, MAX_BLOCKS_IN_TRANSIT_PER_PEER - static_cast<int>(state.vBlocksInFlight.size())); }; // If a snapshot chainstate is in use, we want to find its next blocks // before the background chainstate to prioritize getting to network tip. FindNextBlocksToDownload(*peer, get_inflight_budget(), vToDownload, staller); if (m_chainman.BackgroundSyncInProgress() && !IsLimitedPeer(*peer)) { TryDownloadingHistoricalBlocks( *peer, get_inflight_budget(), vToDownload, m_chainman.GetBackgroundSyncTip(), Assert(m_chainman.GetSnapshotBaseBlock())); } for (const CBlockIndex *pindex : vToDownload) { uint32_t nFetchFlags = GetFetchFlags(*peer); vGetData.emplace_back(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()); BlockRequested(pto->GetId(), *pindex); LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(), pindex->nHeight, pto->GetId()); } if (state.vBlocksInFlight.empty() && staller != -1) { if (State(staller)->m_stalling_since == 0us) { State(staller)->m_stalling_since = current_time; LogPrint(BCLog::NET, "Stall started peer=%d\n", staller); } } } // // Message: getdata (transactions) // std::vector<std::pair<NodeId, GenTxid>> expired; auto requestable = m_txrequest.GetRequestable(pto->GetId(), current_time, &expired); for (const auto& entry : expired) { LogPrint(BCLog::NET, "timeout of inflight %s %s from peer=%d\n", entry.second.IsWtxid() ? "wtx" : "tx", entry.second.GetHash().ToString(), entry.first); } for (const GenTxid& gtxid : requestable) { if (!AlreadyHaveTx(gtxid)) { LogPrint(BCLog::NET, "Requesting %s %s peer=%d\n", gtxid.IsWtxid() ? "wtx" : "tx", gtxid.GetHash().ToString(), pto->GetId()); vGetData.emplace_back(gtxid.IsWtxid() ? MSG_WTX : (MSG_TX | GetFetchFlags(*peer)), gtxid.GetHash()); if (vGetData.size() >= MAX_GETDATA_SZ) { MakeAndPushMessage(*pto, NetMsgType::GETDATA, vGetData); vGetData.clear(); } m_txrequest.RequestedTx(pto->GetId(), gtxid.GetHash(), current_time + GETDATA_TX_INTERVAL); } else { // We have already seen this transaction, no need to download. This is just a belt-and-suspenders, as // this should already be called whenever a transaction becomes AlreadyHaveTx(). m_txrequest.ForgetTxHash(gtxid.GetHash()); } } if (!vGetData.empty()) MakeAndPushMessage(*pto, NetMsgType::GETDATA, vGetData); } // release cs_main MaybeSendFeefilter(*pto, *peer, current_time); return true; }
0
bitcoin
bitcoin/src/Makefile.univalue.include
include univalue/sources.mk LIBUNIVALUE = libunivalue.la noinst_LTLIBRARIES += $(LIBUNIVALUE) libunivalue_la_SOURCES = $(UNIVALUE_LIB_SOURCES_INT) $(UNIVALUE_DIST_HEADERS_INT) $(UNIVALUE_LIB_HEADERS_INT) $(UNIVALUE_TEST_FILES_INT) libunivalue_la_CPPFLAGS = $(AM_CPPFLAGS) -I$(srcdir)/$(UNIVALUE_INCLUDE_DIR_INT)
0
bitcoin
bitcoin/src/randomenv.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_RANDOMENV_H #define BITCOIN_RANDOMENV_H #include <crypto/sha512.h> /** Gather non-cryptographic environment data that changes over time. */ void RandAddDynamicEnv(CSHA512& hasher); /** Gather non-cryptographic environment data that does not change over time. */ void RandAddStaticEnv(CSHA512& hasher); #endif // BITCOIN_RANDOMENV_H
0
bitcoin
bitcoin/src/deploymentinfo.cpp
// Copyright (c) 2016-2021 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 <deploymentinfo.h> #include <consensus/params.h> #include <string_view> const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS] = { { /*.name =*/ "testdummy", /*.gbt_force =*/ true, }, { /*.name =*/ "taproot", /*.gbt_force =*/ true, }, }; std::string DeploymentName(Consensus::BuriedDeployment dep) { assert(ValidDeployment(dep)); switch (dep) { case Consensus::DEPLOYMENT_HEIGHTINCB: return "bip34"; case Consensus::DEPLOYMENT_CLTV: return "bip65"; case Consensus::DEPLOYMENT_DERSIG: return "bip66"; case Consensus::DEPLOYMENT_CSV: return "csv"; case Consensus::DEPLOYMENT_SEGWIT: return "segwit"; } // no default case, so the compiler can warn about missing cases return ""; } std::optional<Consensus::BuriedDeployment> GetBuriedDeployment(const std::string_view name) { if (name == "segwit") { return Consensus::BuriedDeployment::DEPLOYMENT_SEGWIT; } else if (name == "bip34") { return Consensus::BuriedDeployment::DEPLOYMENT_HEIGHTINCB; } else if (name == "dersig") { return Consensus::BuriedDeployment::DEPLOYMENT_DERSIG; } else if (name == "cltv") { return Consensus::BuriedDeployment::DEPLOYMENT_CLTV; } else if (name == "csv") { return Consensus::BuriedDeployment::DEPLOYMENT_CSV; } return std::nullopt; }
0
bitcoin
bitcoin/src/addrdb.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 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 <addrdb.h> #include <addrman.h> #include <chainparams.h> #include <clientversion.h> #include <common/args.h> #include <common/settings.h> #include <cstdint> #include <hash.h> #include <logging.h> #include <logging/timer.h> #include <netbase.h> #include <netgroup.h> #include <random.h> #include <streams.h> #include <tinyformat.h> #include <univalue.h> #include <util/fs.h> #include <util/fs_helpers.h> #include <util/translation.h> namespace { class DbNotFoundError : public std::exception { using std::exception::exception; }; template <typename Stream, typename Data> bool SerializeDB(Stream& stream, const Data& data) { // Write and commit header, data try { HashedSourceWriter hashwriter{stream}; hashwriter << Params().MessageStart() << data; stream << hashwriter.GetHash(); } catch (const std::exception& e) { return error("%s: Serialize or I/O error - %s", __func__, e.what()); } return true; } template <typename Data> bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data) { // Generate random temporary filename const uint16_t randv{GetRand<uint16_t>()}; std::string tmpfn = strprintf("%s.%04x", prefix, randv); // open temp output file fs::path pathTmp = gArgs.GetDataDirNet() / fs::u8path(tmpfn); FILE *file = fsbridge::fopen(pathTmp, "wb"); AutoFile fileout{file}; if (fileout.IsNull()) { fileout.fclose(); remove(pathTmp); return error("%s: Failed to open file %s", __func__, fs::PathToString(pathTmp)); } // Serialize if (!SerializeDB(fileout, data)) { fileout.fclose(); remove(pathTmp); return false; } if (!FileCommit(fileout.Get())) { fileout.fclose(); remove(pathTmp); return error("%s: Failed to flush file %s", __func__, fs::PathToString(pathTmp)); } fileout.fclose(); // replace existing file, if any, with new file if (!RenameOver(pathTmp, path)) { remove(pathTmp); return error("%s: Rename-into-place failed", __func__); } return true; } template <typename Stream, typename Data> void DeserializeDB(Stream& stream, Data&& data, bool fCheckSum = true) { HashVerifier verifier{stream}; // de-serialize file header (network specific magic number) and .. MessageStartChars pchMsgTmp; verifier >> pchMsgTmp; // ... verify the network matches ours if (pchMsgTmp != Params().MessageStart()) { throw std::runtime_error{"Invalid network magic number"}; } // de-serialize data verifier >> data; // verify checksum if (fCheckSum) { uint256 hashTmp; stream >> hashTmp; if (hashTmp != verifier.GetHash()) { throw std::runtime_error{"Checksum mismatch, data corrupted"}; } } } template <typename Data> void DeserializeFileDB(const fs::path& path, Data&& data) { FILE* file = fsbridge::fopen(path, "rb"); AutoFile filein{file}; if (filein.IsNull()) { throw DbNotFoundError{}; } DeserializeDB(filein, data); } } // namespace CBanDB::CBanDB(fs::path ban_list_path) : m_banlist_dat(ban_list_path + ".dat"), m_banlist_json(ban_list_path + ".json") { } bool CBanDB::Write(const banmap_t& banSet) { std::vector<std::string> errors; if (common::WriteSettings(m_banlist_json, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) { return true; } for (const auto& err : errors) { error("%s", err); } return false; } bool CBanDB::Read(banmap_t& banSet) { if (fs::exists(m_banlist_dat)) { LogPrintf("banlist.dat ignored because it can only be read by " PACKAGE_NAME " version 22.x. Remove %s to silence this warning.\n", fs::quoted(fs::PathToString(m_banlist_dat))); } // If the JSON banlist does not exist, then recreate it if (!fs::exists(m_banlist_json)) { return false; } std::map<std::string, common::SettingsValue> settings; std::vector<std::string> errors; if (!common::ReadSettings(m_banlist_json, settings, errors)) { for (const auto& err : errors) { LogPrintf("Cannot load banlist %s: %s\n", fs::PathToString(m_banlist_json), err); } return false; } try { BanMapFromJson(settings[JSON_KEY], banSet); } catch (const std::runtime_error& e) { LogPrintf("Cannot parse banlist %s: %s\n", fs::PathToString(m_banlist_json), e.what()); return false; } return true; } bool DumpPeerAddresses(const ArgsManager& args, const AddrMan& addr) { const auto pathAddr = args.GetDataDirNet() / "peers.dat"; return SerializeFileDB("peers", pathAddr, addr); } void ReadFromStream(AddrMan& addr, DataStream& ssPeers) { DeserializeDB(ssPeers, addr, false); } util::Result<std::unique_ptr<AddrMan>> LoadAddrman(const NetGroupManager& netgroupman, const ArgsManager& args) { auto check_addrman = std::clamp<int32_t>(args.GetIntArg("-checkaddrman", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), 0, 1000000); auto addrman{std::make_unique<AddrMan>(netgroupman, /*deterministic=*/false, /*consistency_check_ratio=*/check_addrman)}; const auto start{SteadyClock::now()}; const auto path_addr{args.GetDataDirNet() / "peers.dat"}; try { DeserializeFileDB(path_addr, *addrman); LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman->Size(), Ticks<std::chrono::milliseconds>(SteadyClock::now() - start)); } catch (const DbNotFoundError&) { // Addrman can be in an inconsistent state after failure, reset it addrman = std::make_unique<AddrMan>(netgroupman, /*deterministic=*/false, /*consistency_check_ratio=*/check_addrman); LogPrintf("Creating peers.dat because the file was not found (%s)\n", fs::quoted(fs::PathToString(path_addr))); DumpPeerAddresses(args, *addrman); } catch (const InvalidAddrManVersionError&) { if (!RenameOver(path_addr, (fs::path)path_addr + ".bak")) { return util::Error{strprintf(_("Failed to rename invalid peers.dat file. Please move or delete it and try again."))}; } // Addrman can be in an inconsistent state after failure, reset it addrman = std::make_unique<AddrMan>(netgroupman, /*deterministic=*/false, /*consistency_check_ratio=*/check_addrman); LogPrintf("Creating new peers.dat because the file version was not compatible (%s). Original backed up to peers.dat.bak\n", fs::quoted(fs::PathToString(path_addr))); DumpPeerAddresses(args, *addrman); } catch (const std::exception& e) { return util::Error{strprintf(_("Invalid or corrupt peers.dat (%s). If you believe this is a bug, please report it to %s. As a workaround, you can move the file (%s) out of the way (rename, move, or delete) to have a new one created on the next start."), e.what(), PACKAGE_BUGREPORT, fs::quoted(fs::PathToString(path_addr)))}; } return addrman; } void DumpAnchors(const fs::path& anchors_db_path, const std::vector<CAddress>& anchors) { LOG_TIME_SECONDS(strprintf("Flush %d outbound block-relay-only peer addresses to anchors.dat", anchors.size())); SerializeFileDB("anchors", anchors_db_path, CAddress::V2_DISK(anchors)); } std::vector<CAddress> ReadAnchors(const fs::path& anchors_db_path) { std::vector<CAddress> anchors; try { DeserializeFileDB(anchors_db_path, CAddress::V2_DISK(anchors)); LogPrintf("Loaded %i addresses from %s\n", anchors.size(), fs::quoted(fs::PathToString(anchors_db_path.filename()))); } catch (const std::exception&) { anchors.clear(); } fs::remove(anchors_db_path); return anchors; }
0
bitcoin
bitcoin/src/outputtype.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 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 <outputtype.h> #include <pubkey.h> #include <script/script.h> #include <script/sign.h> #include <script/signingprovider.h> #include <util/vector.h> #include <assert.h> #include <optional> #include <string> static const std::string OUTPUT_TYPE_STRING_LEGACY = "legacy"; static const std::string OUTPUT_TYPE_STRING_P2SH_SEGWIT = "p2sh-segwit"; static const std::string OUTPUT_TYPE_STRING_BECH32 = "bech32"; static const std::string OUTPUT_TYPE_STRING_BECH32M = "bech32m"; static const std::string OUTPUT_TYPE_STRING_UNKNOWN = "unknown"; std::optional<OutputType> ParseOutputType(const std::string& type) { if (type == OUTPUT_TYPE_STRING_LEGACY) { return OutputType::LEGACY; } else if (type == OUTPUT_TYPE_STRING_P2SH_SEGWIT) { return OutputType::P2SH_SEGWIT; } else if (type == OUTPUT_TYPE_STRING_BECH32) { return OutputType::BECH32; } else if (type == OUTPUT_TYPE_STRING_BECH32M) { return OutputType::BECH32M; } return std::nullopt; } const std::string& FormatOutputType(OutputType type) { switch (type) { case OutputType::LEGACY: return OUTPUT_TYPE_STRING_LEGACY; case OutputType::P2SH_SEGWIT: return OUTPUT_TYPE_STRING_P2SH_SEGWIT; case OutputType::BECH32: return OUTPUT_TYPE_STRING_BECH32; case OutputType::BECH32M: return OUTPUT_TYPE_STRING_BECH32M; case OutputType::UNKNOWN: return OUTPUT_TYPE_STRING_UNKNOWN; } // no default case, so the compiler can warn about missing cases assert(false); } CTxDestination GetDestinationForKey(const CPubKey& key, OutputType type) { switch (type) { case OutputType::LEGACY: return PKHash(key); case OutputType::P2SH_SEGWIT: case OutputType::BECH32: { if (!key.IsCompressed()) return PKHash(key); CTxDestination witdest = WitnessV0KeyHash(key); CScript witprog = GetScriptForDestination(witdest); if (type == OutputType::P2SH_SEGWIT) { return ScriptHash(witprog); } else { return witdest; } } case OutputType::BECH32M: case OutputType::UNKNOWN: {} // This function should never be used with BECH32M or UNKNOWN, so let it assert } // no default case, so the compiler can warn about missing cases assert(false); } std::vector<CTxDestination> GetAllDestinationsForKey(const CPubKey& key) { PKHash keyid(key); CTxDestination p2pkh{keyid}; if (key.IsCompressed()) { CTxDestination segwit = WitnessV0KeyHash(keyid); CTxDestination p2sh = ScriptHash(GetScriptForDestination(segwit)); return Vector(std::move(p2pkh), std::move(p2sh), std::move(segwit)); } else { return Vector(std::move(p2pkh)); } } CTxDestination AddAndGetDestinationForScript(FillableSigningProvider& keystore, const CScript& script, OutputType type) { // Add script to keystore keystore.AddCScript(script); // Note that scripts over 520 bytes are not yet supported. switch (type) { case OutputType::LEGACY: return ScriptHash(script); case OutputType::P2SH_SEGWIT: case OutputType::BECH32: { CTxDestination witdest = WitnessV0ScriptHash(script); CScript witprog = GetScriptForDestination(witdest); // Add the redeemscript, so that P2WSH and P2SH-P2WSH outputs are recognized as ours. keystore.AddCScript(witprog); if (type == OutputType::BECH32) { return witdest; } else { return ScriptHash(witprog); } } case OutputType::BECH32M: case OutputType::UNKNOWN: {} // This function should not be used for BECH32M or UNKNOWN, so let it assert } // no default case, so the compiler can warn about missing cases assert(false); } std::optional<OutputType> OutputTypeFromDestination(const CTxDestination& dest) { if (std::holds_alternative<PKHash>(dest) || std::holds_alternative<ScriptHash>(dest)) { return OutputType::LEGACY; } if (std::holds_alternative<WitnessV0KeyHash>(dest) || std::holds_alternative<WitnessV0ScriptHash>(dest)) { return OutputType::BECH32; } if (std::holds_alternative<WitnessV1Taproot>(dest) || std::holds_alternative<WitnessUnknown>(dest)) { return OutputType::BECH32M; } return std::nullopt; }
0
bitcoin
bitcoin/src/netaddress.h
// Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_NETADDRESS_H #define BITCOIN_NETADDRESS_H #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <compat/compat.h> #include <crypto/siphash.h> #include <prevector.h> #include <random.h> #include <serialize.h> #include <tinyformat.h> #include <util/strencodings.h> #include <util/string.h> #include <array> #include <cstdint> #include <ios> #include <string> #include <vector> /** * A network type. * @note An address may belong to more than one network, for example `10.0.0.1` * belongs to both `NET_UNROUTABLE` and `NET_IPV4`. * Keep these sequential starting from 0 and `NET_MAX` as the last entry. * We have loops like `for (int i = 0; i < NET_MAX; ++i)` that expect to iterate * over all enum values and also `GetExtNetwork()` "extends" this enum by * introducing standalone constants starting from `NET_MAX`. */ enum Network { /// Addresses from these networks are not publicly routable on the global Internet. NET_UNROUTABLE = 0, /// IPv4 NET_IPV4, /// IPv6 NET_IPV6, /// TOR (v2 or v3) NET_ONION, /// I2P NET_I2P, /// CJDNS NET_CJDNS, /// A set of addresses that represent the hash of a string or FQDN. We use /// them in AddrMan to keep track of which DNS seeds were used. NET_INTERNAL, /// Dummy value to indicate the number of NET_* constants. NET_MAX, }; /// Prefix of an IPv6 address when it contains an embedded IPv4 address. /// Used when (un)serializing addresses in ADDRv1 format (pre-BIP155). static const std::array<uint8_t, 12> IPV4_IN_IPV6_PREFIX{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF}; /// Prefix of an IPv6 address when it contains an embedded TORv2 address. /// Used when (un)serializing addresses in ADDRv1 format (pre-BIP155). /// Such dummy IPv6 addresses are guaranteed to not be publicly routable as they /// fall under RFC4193's fc00::/7 subnet allocated to unique-local addresses. static const std::array<uint8_t, 6> TORV2_IN_IPV6_PREFIX{ 0xFD, 0x87, 0xD8, 0x7E, 0xEB, 0x43}; /// Prefix of an IPv6 address when it contains an embedded "internal" address. /// Used when (un)serializing addresses in ADDRv1 format (pre-BIP155). /// The prefix comes from 0xFD + SHA256("bitcoin")[0:5]. /// Such dummy IPv6 addresses are guaranteed to not be publicly routable as they /// fall under RFC4193's fc00::/7 subnet allocated to unique-local addresses. static const std::array<uint8_t, 6> INTERNAL_IN_IPV6_PREFIX{ 0xFD, 0x6B, 0x88, 0xC0, 0x87, 0x24 // 0xFD + sha256("bitcoin")[0:5]. }; /// All CJDNS addresses start with 0xFC. See /// https://github.com/cjdelisle/cjdns/blob/master/doc/Whitepaper.md#pulling-it-all-together static constexpr uint8_t CJDNS_PREFIX{0xFC}; /// Size of IPv4 address (in bytes). static constexpr size_t ADDR_IPV4_SIZE = 4; /// Size of IPv6 address (in bytes). static constexpr size_t ADDR_IPV6_SIZE = 16; /// Size of TORv3 address (in bytes). This is the length of just the address /// as used in BIP155, without the checksum and the version byte. static constexpr size_t ADDR_TORV3_SIZE = 32; /// Size of I2P address (in bytes). static constexpr size_t ADDR_I2P_SIZE = 32; /// Size of CJDNS address (in bytes). static constexpr size_t ADDR_CJDNS_SIZE = 16; /// Size of "internal" (NET_INTERNAL) address (in bytes). static constexpr size_t ADDR_INTERNAL_SIZE = 10; /// SAM 3.1 and earlier do not support specifying ports and force the port to 0. static constexpr uint16_t I2P_SAM31_PORT{0}; std::string OnionToString(Span<const uint8_t> addr); /** * Network address. */ class CNetAddr { protected: /** * Raw representation of the network address. * In network byte order (big endian) for IPv4 and IPv6. */ prevector<ADDR_IPV6_SIZE, uint8_t> m_addr{ADDR_IPV6_SIZE, 0x0}; /** * Network to which this address belongs. */ Network m_net{NET_IPV6}; /** * Scope id if scoped/link-local IPV6 address. * See https://tools.ietf.org/html/rfc4007 */ uint32_t m_scope_id{0}; public: CNetAddr(); explicit CNetAddr(const struct in_addr& ipv4Addr); void SetIP(const CNetAddr& ip); /** * Set from a legacy IPv6 address. * Legacy IPv6 address may be a normal IPv6 address, or another address * (e.g. IPv4) disguised as IPv6. This encoding is used in the legacy * `addr` encoding. */ void SetLegacyIPv6(Span<const uint8_t> ipv6); bool SetInternal(const std::string& name); /** * Parse a Tor or I2P address and set this object to it. * @param[in] addr Address to parse, for example * pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion or * ukeu3k5oycgaauneqgtnvselmt4yemvoilkln7jpvamvfx7dnkdq.b32.i2p. * @returns Whether the operation was successful. * @see CNetAddr::IsTor(), CNetAddr::IsI2P() */ bool SetSpecial(const std::string& addr); bool IsBindAny() const; // INADDR_ANY equivalent [[nodiscard]] bool IsIPv4() const { return m_net == NET_IPV4; } // IPv4 mapped address (::FFFF:0:0/96, 0.0.0.0/0) [[nodiscard]] bool IsIPv6() const { return m_net == NET_IPV6; } // IPv6 address (not mapped IPv4, not Tor) bool IsRFC1918() const; // IPv4 private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12) bool IsRFC2544() const; // IPv4 inter-network communications (198.18.0.0/15) bool IsRFC6598() const; // IPv4 ISP-level NAT (100.64.0.0/10) bool IsRFC5737() const; // IPv4 documentation addresses (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24) bool IsRFC3849() const; // IPv6 documentation address (2001:0DB8::/32) bool IsRFC3927() const; // IPv4 autoconfig (169.254.0.0/16) bool IsRFC3964() const; // IPv6 6to4 tunnelling (2002::/16) bool IsRFC4193() const; // IPv6 unique local (FC00::/7) bool IsRFC4380() const; // IPv6 Teredo tunnelling (2001::/32) bool IsRFC4843() const; // IPv6 ORCHID (deprecated) (2001:10::/28) bool IsRFC7343() const; // IPv6 ORCHIDv2 (2001:20::/28) bool IsRFC4862() const; // IPv6 autoconfig (FE80::/64) bool IsRFC6052() const; // IPv6 well-known prefix for IPv4-embedded address (64:FF9B::/96) bool IsRFC6145() const; // IPv6 IPv4-translated address (::FFFF:0:0:0/96) (actually defined in RFC2765) bool IsHeNet() const; // IPv6 Hurricane Electric - https://he.net (2001:0470::/36) [[nodiscard]] bool IsTor() const { return m_net == NET_ONION; } [[nodiscard]] bool IsI2P() const { return m_net == NET_I2P; } [[nodiscard]] bool IsCJDNS() const { return m_net == NET_CJDNS; } [[nodiscard]] bool HasCJDNSPrefix() const { return m_addr[0] == CJDNS_PREFIX; } bool IsLocal() const; bool IsRoutable() const; bool IsInternal() const; bool IsValid() const; /** * Whether this object is a privacy network. * TODO: consider adding IsCJDNS() here when more peers adopt CJDNS, see: * https://github.com/bitcoin/bitcoin/pull/27411#issuecomment-1497176155 */ [[nodiscard]] bool IsPrivacyNet() const { return IsTor() || IsI2P(); } /** * Check if the current object can be serialized in pre-ADDRv2/BIP155 format. */ bool IsAddrV1Compatible() const; enum Network GetNetwork() const; std::string ToStringAddr() const; bool GetInAddr(struct in_addr* pipv4Addr) const; Network GetNetClass() const; //! For IPv4, mapped IPv4, SIIT translated IPv4, Teredo, 6to4 tunneled addresses, return the relevant IPv4 address as a uint32. uint32_t GetLinkedIPv4() const; //! Whether this address has a linked IPv4 address (see GetLinkedIPv4()). bool HasLinkedIPv4() const; std::vector<unsigned char> GetAddrBytes() const; int GetReachabilityFrom(const CNetAddr& paddrPartner) const; explicit CNetAddr(const struct in6_addr& pipv6Addr, const uint32_t scope = 0); 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) { return !(a == b); } friend bool operator<(const CNetAddr& a, const CNetAddr& b); /** * Whether this address should be relayed to other peers even if we can't reach it ourselves. */ bool IsRelayable() const { return IsIPv4() || IsIPv6() || IsTor() || IsI2P() || IsCJDNS(); } enum class Encoding { V1, V2, //!< BIP155 encoding }; struct SerParams { const Encoding enc; SER_PARAMS_OPFUNC }; static constexpr SerParams V1{Encoding::V1}; static constexpr SerParams V2{Encoding::V2}; /** * Serialize to a stream. */ template <typename Stream> void Serialize(Stream& s) const { if (s.GetParams().enc == Encoding::V2) { SerializeV2Stream(s); } else { SerializeV1Stream(s); } } /** * Unserialize from a stream. */ template <typename Stream> void Unserialize(Stream& s) { if (s.GetParams().enc == Encoding::V2) { UnserializeV2Stream(s); } else { UnserializeV1Stream(s); } } friend class CSubNet; private: /** * Parse a Tor address and set this object to it. * @param[in] addr Address to parse, must be a valid C string, for example * pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion. * @returns Whether the operation was successful. * @see CNetAddr::IsTor() */ bool SetTor(const std::string& addr); /** * Parse an I2P address and set this object to it. * @param[in] addr Address to parse, must be a valid C string, for example * ukeu3k5oycgaauneqgtnvselmt4yemvoilkln7jpvamvfx7dnkdq.b32.i2p. * @returns Whether the operation was successful. * @see CNetAddr::IsI2P() */ bool SetI2P(const std::string& addr); /** * BIP155 network ids recognized by this software. */ enum BIP155Network : uint8_t { IPV4 = 1, IPV6 = 2, TORV2 = 3, TORV3 = 4, I2P = 5, CJDNS = 6, }; /** * Size of CNetAddr when serialized as ADDRv1 (pre-BIP155) (in bytes). */ static constexpr size_t V1_SERIALIZATION_SIZE = ADDR_IPV6_SIZE; /** * Maximum size of an address as defined in BIP155 (in bytes). * This is only the size of the address, not the entire CNetAddr object * when serialized. */ static constexpr size_t MAX_ADDRV2_SIZE = 512; /** * Get the BIP155 network id of this address. * Must not be called for IsInternal() objects. * @returns BIP155 network id, except TORV2 which is no longer supported. */ BIP155Network GetBIP155Network() const; /** * Set `m_net` from the provided BIP155 network id and size after validation. * @retval true the network was recognized, is valid and `m_net` was set * @retval false not recognised (from future?) and should be silently ignored * @throws std::ios_base::failure if the network is one of the BIP155 founding * networks (id 1..6) with wrong address size. */ bool SetNetFromBIP155Network(uint8_t possible_bip155_net, size_t address_size); /** * Serialize in pre-ADDRv2/BIP155 format to an array. */ void SerializeV1Array(uint8_t (&arr)[V1_SERIALIZATION_SIZE]) const { size_t prefix_size; switch (m_net) { case NET_IPV6: assert(m_addr.size() == sizeof(arr)); memcpy(arr, m_addr.data(), m_addr.size()); return; case NET_IPV4: prefix_size = sizeof(IPV4_IN_IPV6_PREFIX); assert(prefix_size + m_addr.size() == sizeof(arr)); memcpy(arr, IPV4_IN_IPV6_PREFIX.data(), prefix_size); memcpy(arr + prefix_size, m_addr.data(), m_addr.size()); return; case NET_INTERNAL: prefix_size = sizeof(INTERNAL_IN_IPV6_PREFIX); assert(prefix_size + m_addr.size() == sizeof(arr)); memcpy(arr, INTERNAL_IN_IPV6_PREFIX.data(), prefix_size); memcpy(arr + prefix_size, m_addr.data(), m_addr.size()); return; case NET_ONION: case NET_I2P: case NET_CJDNS: break; case NET_UNROUTABLE: case NET_MAX: assert(false); } // no default case, so the compiler can warn about missing cases // Serialize ONION, I2P and CJDNS as all-zeros. memset(arr, 0x0, V1_SERIALIZATION_SIZE); } /** * Serialize in pre-ADDRv2/BIP155 format to a stream. */ template <typename Stream> void SerializeV1Stream(Stream& s) const { uint8_t serialized[V1_SERIALIZATION_SIZE]; SerializeV1Array(serialized); s << serialized; } /** * Serialize as ADDRv2 / BIP155. */ template <typename Stream> void SerializeV2Stream(Stream& s) const { if (IsInternal()) { // Serialize NET_INTERNAL as embedded in IPv6. We need to // serialize such addresses from addrman. s << static_cast<uint8_t>(BIP155Network::IPV6); s << COMPACTSIZE(ADDR_IPV6_SIZE); SerializeV1Stream(s); return; } s << static_cast<uint8_t>(GetBIP155Network()); s << m_addr; } /** * Unserialize from a pre-ADDRv2/BIP155 format from an array. * * This function is only called from UnserializeV1Stream() and is a wrapper * for SetLegacyIPv6(); however, we keep it for symmetry with * SerializeV1Array() to have pairs of ser/unser functions and to make clear * that if one is altered, a corresponding reverse modification should be * applied to the other. */ void UnserializeV1Array(uint8_t (&arr)[V1_SERIALIZATION_SIZE]) { // Use SetLegacyIPv6() so that m_net is set correctly. For example // ::FFFF:0102:0304 should be set as m_net=NET_IPV4 (1.2.3.4). SetLegacyIPv6(arr); } /** * Unserialize from a pre-ADDRv2/BIP155 format from a stream. */ template <typename Stream> void UnserializeV1Stream(Stream& s) { uint8_t serialized[V1_SERIALIZATION_SIZE]; s >> serialized; UnserializeV1Array(serialized); } /** * Unserialize from a ADDRv2 / BIP155 format. */ template <typename Stream> void UnserializeV2Stream(Stream& s) { uint8_t bip155_net; s >> bip155_net; size_t address_size; s >> COMPACTSIZE(address_size); if (address_size > MAX_ADDRV2_SIZE) { throw std::ios_base::failure(strprintf( "Address too long: %u > %u", address_size, MAX_ADDRV2_SIZE)); } m_scope_id = 0; if (SetNetFromBIP155Network(bip155_net, address_size)) { m_addr.resize(address_size); s >> Span{m_addr}; if (m_net != NET_IPV6) { return; } // Do some special checks on IPv6 addresses. // Recognize NET_INTERNAL embedded in IPv6, such addresses are not // gossiped but could be coming from addrman, when unserializing from // disk. if (HasPrefix(m_addr, INTERNAL_IN_IPV6_PREFIX)) { m_net = NET_INTERNAL; memmove(m_addr.data(), m_addr.data() + INTERNAL_IN_IPV6_PREFIX.size(), ADDR_INTERNAL_SIZE); m_addr.resize(ADDR_INTERNAL_SIZE); return; } if (!HasPrefix(m_addr, IPV4_IN_IPV6_PREFIX) && !HasPrefix(m_addr, TORV2_IN_IPV6_PREFIX)) { return; } // IPv4 and TORv2 are not supposed to be embedded in IPv6 (like in V1 // encoding). Unserialize as !IsValid(), thus ignoring them. } else { // If we receive an unknown BIP155 network id (from the future?) then // ignore the address - unserialize as !IsValid(). s.ignore(address_size); } // Mimic a default-constructed CNetAddr object which is !IsValid() and thus // will not be gossiped, but continue reading next addresses from the stream. m_net = NET_IPV6; m_addr.assign(ADDR_IPV6_SIZE, 0x0); } }; class CSubNet { protected: /// Network (base) address CNetAddr network; /// Netmask, in network byte order uint8_t netmask[16]; /// Is this value valid? (only used to signal parse errors) bool valid; public: /** * Construct an invalid subnet (empty, `Match()` always returns false). */ CSubNet(); /** * Construct from a given network start and number of bits (CIDR mask). * @param[in] addr Network start. Must be IPv4 or IPv6, otherwise an invalid subnet is * created. * @param[in] mask CIDR mask, must be in [0, 32] for IPv4 addresses and in [0, 128] for * IPv6 addresses. Otherwise an invalid subnet is created. */ CSubNet(const CNetAddr& addr, uint8_t mask); /** * Construct from a given network start and mask. * @param[in] addr Network start. Must be IPv4 or IPv6, otherwise an invalid subnet is * created. * @param[in] mask Network mask, must be of the same type as `addr` and not contain 0-bits * followed by 1-bits. Otherwise an invalid subnet is created. */ CSubNet(const CNetAddr& addr, const CNetAddr& mask); /** * Construct a single-host subnet. * @param[in] addr The sole address to be contained in the subnet, can also be non-IPv[46]. */ explicit CSubNet(const CNetAddr& addr); bool Match(const CNetAddr& addr) const; std::string ToString() const; bool IsValid() const; friend bool operator==(const CSubNet& a, const CSubNet& b); friend bool operator!=(const CSubNet& a, const CSubNet& b) { return !(a == b); } friend bool operator<(const CSubNet& a, const CSubNet& b); }; /** A combination of a network address (CNetAddr) and a (TCP) port */ class CService : public CNetAddr { protected: uint16_t port; // host order public: CService(); CService(const CNetAddr& ip, uint16_t port); CService(const struct in_addr& ipv4Addr, uint16_t port); explicit CService(const struct sockaddr_in& addr); uint16_t GetPort() const; bool GetSockAddr(struct sockaddr* paddr, socklen_t* addrlen) const; bool SetSockAddr(const struct sockaddr* paddr); friend bool operator==(const CService& a, const CService& b); friend bool operator!=(const CService& a, const CService& b) { return !(a == b); } friend bool operator<(const CService& a, const CService& b); std::vector<unsigned char> GetKey() const; std::string ToStringAddrPort() const; CService(const struct in6_addr& ipv6Addr, uint16_t port); explicit CService(const struct sockaddr_in6& addr); SERIALIZE_METHODS(CService, obj) { READWRITE(AsBase<CNetAddr>(obj), Using<BigEndianFormatter<2>>(obj.port)); } friend class CServiceHash; friend CService MaybeFlipIPv6toCJDNS(const CService& service); }; class CServiceHash { public: CServiceHash() : m_salt_k0{GetRand<uint64_t>()}, m_salt_k1{GetRand<uint64_t>()} { } CServiceHash(uint64_t salt_k0, uint64_t salt_k1) : m_salt_k0{salt_k0}, m_salt_k1{salt_k1} {} size_t operator()(const CService& a) const noexcept { CSipHasher hasher(m_salt_k0, m_salt_k1); hasher.Write(a.m_net); hasher.Write(a.port); hasher.Write(a.m_addr); return static_cast<size_t>(hasher.Finalize()); } private: const uint64_t m_salt_k0; const uint64_t m_salt_k1; }; #endif // BITCOIN_NETADDRESS_H
0
bitcoin
bitcoin/src/txrequest.h
// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TXREQUEST_H #define BITCOIN_TXREQUEST_H #include <primitives/transaction.h> #include <net.h> // For NodeId #include <uint256.h> #include <chrono> #include <vector> #include <stdint.h> /** Data structure to keep track of, and schedule, transaction downloads from peers. * * === Specification === * * We keep track of which peers have announced which transactions, and use that to determine which requests * should go to which peer, when, and in what order. * * The following information is tracked per peer/tx combination ("announcement"): * - Which peer announced it (through their NodeId) * - The txid or wtxid of the transaction (collectively called "txhash" in what follows) * - Whether it was a tx or wtx announcement (see BIP339). * - What the earliest permitted time is that that transaction can be requested from that peer (called "reqtime"). * - Whether it's from a "preferred" peer or not. Which announcements get this flag is determined by the caller, but * this is designed for outbound peers, or other peers that we have a higher level of trust in. Even when the * peers' preferredness changes, the preferred flag of existing announcements from that peer won't change. * - Whether or not the transaction was requested already, and if so, when it times out (called "expiry"). * - Whether or not the transaction request failed already (timed out, or invalid transaction or NOTFOUND was * received). * * Transaction requests are then assigned to peers, following these rules: * * - No transaction is requested as long as another request for the same txhash is outstanding (it needs to fail * first by passing expiry, or a NOTFOUND or invalid transaction has to be received for it). * * Rationale: to avoid wasting bandwidth on multiple copies of the same transaction. Note that this only works * per txhash, so if the same transaction is announced both through txid and wtxid, we have no means * to prevent fetching both (the caller can however mitigate this by delaying one, see further). * * - The same transaction is never requested twice from the same peer, unless the announcement was forgotten in * between, and re-announced. Announcements are forgotten only: * - If a peer goes offline, all its announcements are forgotten. * - If a transaction has been successfully received, or is otherwise no longer needed, the caller can call * ForgetTxHash, which removes all announcements across all peers with the specified txhash. * - If for a given txhash only already-failed announcements remain, they are all forgotten. * * Rationale: giving a peer multiple chances to announce a transaction would allow them to bias requests in their * favor, worsening transaction censoring attacks. The flip side is that as long as an attacker manages * to prevent us from receiving a transaction, failed announcements (including those from honest peers) * will linger longer, increasing memory usage somewhat. The impact of this is limited by imposing a * cap on the number of tracked announcements per peer. As failed requests in response to announcements * from honest peers should be rare, this almost solely hinders attackers. * Transaction censoring attacks can be done by announcing transactions quickly while not answering * requests for them. See https://allquantor.at/blockchainbib/pdf/miller2015topology.pdf for more * information. * * - Transactions are not requested from a peer until its reqtime has passed. * * Rationale: enable the calling code to define a delay for less-than-ideal peers, so that (presumed) better * peers have a chance to give their announcement first. * * - If multiple viable candidate peers exist according to the above rules, pick a peer as follows: * * - If any preferred peers are available, non-preferred peers are not considered for what follows. * * Rationale: preferred peers are more trusted by us, so are less likely to be under attacker control. * * - Pick a uniformly random peer among the candidates. * * Rationale: random assignments are hard to influence for attackers. * * Together these rules strike a balance between being fast in non-adverserial conditions and minimizing * susceptibility to censorship attacks. An attacker that races the network: * - Will be unsuccessful if all preferred connections are honest (and there is at least one preferred connection). * - If there are P preferred connections of which Ph>=1 are honest, the attacker can delay us from learning * about a transaction by k expiration periods, where k ~ 1 + NHG(N=P-1,K=P-Ph-1,r=1), which has mean * P/(Ph+1) (where NHG stands for Negative Hypergeometric distribution). The "1 +" is due to the fact that the * attacker can be the first to announce through a preferred connection in this scenario, which very likely means * they get the first request. * - If all P preferred connections are to the attacker, and there are NP non-preferred connections of which NPh>=1 * are honest, where we assume that the attacker can disconnect and reconnect those connections, the distribution * becomes k ~ P + NB(p=1-NPh/NP,r=1) (where NB stands for Negative Binomial distribution), which has mean * P-1+NP/NPh. * * Complexity: * - Memory usage is proportional to the total number of tracked announcements (Size()) plus the number of * peers with a nonzero number of tracked announcements. * - CPU usage is generally logarithmic in the total number of tracked announcements, plus the number of * announcements affected by an operation (amortized O(1) per announcement). */ class TxRequestTracker { // Avoid littering this header file with implementation details. class Impl; const std::unique_ptr<Impl> m_impl; public: //! Construct a TxRequestTracker. explicit TxRequestTracker(bool deterministic = false); ~TxRequestTracker(); // Conceptually, the data structure consists of a collection of "announcements", one for each peer/txhash // combination: // // - CANDIDATE announcements represent transactions that were announced by a peer, and that become available for // download after their reqtime has passed. // // - REQUESTED announcements represent transactions that have been requested, and which we're awaiting a // response for from that peer. Their expiry value determines when the request times out. // // - COMPLETED announcements represent transactions that have been requested from a peer, and a NOTFOUND or a // transaction was received in response (valid or not), or they timed out. They're only kept around to // prevent requesting them again. If only COMPLETED announcements for a given txhash remain (so no CANDIDATE // or REQUESTED ones), all of them are deleted (this is an invariant, and maintained by all operations below). // // The operations below manipulate the data structure. /** Adds a new CANDIDATE announcement. * * Does nothing if one already exists for that (txhash, peer) combination (whether it's CANDIDATE, REQUESTED, or * COMPLETED). Note that the txid/wtxid property is ignored for determining uniqueness, so if an announcement * is added for a wtxid H, while one for txid H from the same peer already exists, it will be ignored. This is * harmless as the txhashes being equal implies it is a non-segwit transaction, so it doesn't matter how it is * fetched. The new announcement is given the specified preferred and reqtime values, and takes its is_wtxid * from the specified gtxid. */ void ReceivedInv(NodeId peer, const GenTxid& gtxid, bool preferred, std::chrono::microseconds reqtime); /** Deletes all announcements for a given peer. * * It should be called when a peer goes offline. */ void DisconnectedPeer(NodeId peer); /** Deletes all announcements for a given txhash (both txid and wtxid ones). * * This should be called when a transaction is no longer needed. The caller should ensure that new announcements * for the same txhash will not trigger new ReceivedInv calls, at least in the short term after this call. */ void ForgetTxHash(const uint256& txhash); /** Find the txids to request now from peer. * * It does the following: * - Convert all REQUESTED announcements (for all txhashes/peers) with (expiry <= now) to COMPLETED ones. * These are returned in expired, if non-nullptr. * - Requestable announcements are selected: CANDIDATE announcements from the specified peer with * (reqtime <= now) for which no existing REQUESTED announcement with the same txhash from a different peer * exists, and for which the specified peer is the best choice among all (reqtime <= now) CANDIDATE * announcements with the same txhash (subject to preferredness rules, and tiebreaking using a deterministic * salted hash of peer and txhash). * - The selected announcements are converted to GenTxids using their is_wtxid flag, and returned in * announcement order (even if multiple were added at the same time, or when the clock went backwards while * they were being added). This is done to minimize disruption from dependent transactions being requested * out of order: if multiple dependent transactions are announced simultaneously by one peer, and end up * being requested from them, the requests will happen in announcement order. */ std::vector<GenTxid> GetRequestable(NodeId peer, std::chrono::microseconds now, std::vector<std::pair<NodeId, GenTxid>>* expired = nullptr); /** Marks a transaction as requested, with a specified expiry. * * If no CANDIDATE announcement for the provided peer and txhash exists, this call has no effect. Otherwise: * - That announcement is converted to REQUESTED. * - If any other REQUESTED announcement for the same txhash already existed, it means an unexpected request * was made (GetRequestable will never advise doing so). In this case it is converted to COMPLETED, as we're * no longer waiting for a response to it. */ void RequestedTx(NodeId peer, const uint256& txhash, std::chrono::microseconds expiry); /** Converts a CANDIDATE or REQUESTED announcement to a COMPLETED one. If no such announcement exists for the * provided peer and txhash, nothing happens. * * It should be called whenever a transaction or NOTFOUND was received from a peer. When the transaction is * not needed entirely anymore, ForgetTxhash should be called instead of, or in addition to, this call. */ void ReceivedResponse(NodeId peer, const uint256& txhash); // The operations below inspect the data structure. /** Count how many REQUESTED announcements a peer has. */ size_t CountInFlight(NodeId peer) const; /** Count how many CANDIDATE announcements a peer has. */ size_t CountCandidates(NodeId peer) const; /** Count how many announcements a peer has (REQUESTED, CANDIDATE, and COMPLETED combined). */ size_t Count(NodeId peer) const; /** Count how many announcements are being tracked in total across all peers and transaction hashes. */ size_t Size() const; /** Access to the internal priority computation (testing only) */ uint64_t ComputePriority(const uint256& txhash, NodeId peer, bool preferred) const; /** Run internal consistency check (testing only). */ void SanityCheck() const; /** Run a time-dependent internal consistency check (testing only). * * This can only be called immediately after GetRequestable, with the same 'now' parameter. */ void PostGetRequestableSanityCheck(std::chrono::microseconds now) const; }; #endif // BITCOIN_TXREQUEST_H
0
bitcoin
bitcoin/src/uint256.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UINT256_H #define BITCOIN_UINT256_H #include <crypto/common.h> #include <span.h> #include <algorithm> #include <array> #include <cassert> #include <cstring> #include <stdint.h> #include <string> /** Template base class for fixed-sized opaque blobs. */ template<unsigned int BITS> class base_blob { protected: static constexpr int WIDTH = BITS / 8; static_assert(BITS % 8 == 0, "base_blob currently only supports whole bytes."); std::array<uint8_t, WIDTH> m_data; static_assert(WIDTH == sizeof(m_data), "Sanity check"); public: /* construct 0 value by default */ constexpr base_blob() : m_data() {} /* constructor for constants between 1 and 255 */ constexpr explicit base_blob(uint8_t v) : m_data{v} {} constexpr explicit base_blob(Span<const unsigned char> vch) { assert(vch.size() == WIDTH); std::copy(vch.begin(), vch.end(), m_data.begin()); } constexpr bool IsNull() const { return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) { return val == 0; }); } constexpr void SetNull() { std::fill(m_data.begin(), m_data.end(), 0); } constexpr int Compare(const base_blob& other) const { return std::memcmp(m_data.data(), other.m_data.data(), WIDTH); } friend constexpr bool operator==(const base_blob& a, const base_blob& b) { return a.Compare(b) == 0; } friend constexpr bool operator!=(const base_blob& a, const base_blob& b) { return a.Compare(b) != 0; } friend constexpr bool operator<(const base_blob& a, const base_blob& b) { return a.Compare(b) < 0; } std::string GetHex() const; void SetHex(const char* psz); void SetHex(const std::string& str); std::string ToString() const; constexpr const unsigned char* data() const { return m_data.data(); } constexpr unsigned char* data() { return m_data.data(); } constexpr unsigned char* begin() { return m_data.data(); } constexpr unsigned char* end() { return m_data.data() + WIDTH; } constexpr const unsigned char* begin() const { return m_data.data(); } constexpr const unsigned char* end() const { return m_data.data() + WIDTH; } static constexpr unsigned int size() { return WIDTH; } constexpr uint64_t GetUint64(int pos) const { return ReadLE64(m_data.data() + pos * 8); } template<typename Stream> void Serialize(Stream& s) const { s << Span(m_data); } template<typename Stream> void Unserialize(Stream& s) { s.read(MakeWritableByteSpan(m_data)); } }; /** 160-bit opaque blob. * @note This type is called uint160 for historical reasons only. It is an opaque * blob of 160 bits and has no integer operations. */ class uint160 : public base_blob<160> { public: constexpr uint160() = default; constexpr explicit uint160(Span<const unsigned char> vch) : base_blob<160>(vch) {} }; /** 256-bit opaque blob. * @note This type is called uint256 for historical reasons only. It is an * opaque blob of 256 bits and has no integer operations. Use arith_uint256 if * those are required. */ class uint256 : public base_blob<256> { public: constexpr uint256() = default; constexpr explicit uint256(uint8_t v) : base_blob<256>(v) {} constexpr explicit uint256(Span<const unsigned char> vch) : base_blob<256>(vch) {} static const uint256 ZERO; static const uint256 ONE; }; /* uint256 from const char *. * This is a separate function because the constructor uint256(const char*) can result * in dangerously catching uint256(0). */ inline uint256 uint256S(const char *str) { uint256 rv; rv.SetHex(str); return rv; } /* uint256 from std::string. * This is a separate function because the constructor uint256(const std::string &str) can result * in dangerously catching uint256(0) via std::string(const char*). */ inline uint256 uint256S(const std::string& str) { uint256 rv; rv.SetHex(str); return rv; } #endif // BITCOIN_UINT256_H
0
bitcoin
bitcoin/src/chain.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 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 <chain.h> #include <tinyformat.h> #include <util/time.h> std::string CBlockFileInfo::ToString() const { return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, FormatISO8601Date(nTimeFirst), FormatISO8601Date(nTimeLast)); } std::string CBlockIndex::ToString() const { return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)", pprev, nHeight, hashMerkleRoot.ToString(), GetBlockHash().ToString()); } void CChain::SetTip(CBlockIndex& block) { CBlockIndex* pindex = &block; vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } std::vector<uint256> LocatorEntries(const CBlockIndex* index) { int step = 1; std::vector<uint256> have; if (index == nullptr) return have; have.reserve(32); while (index) { have.emplace_back(index->GetBlockHash()); if (index->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int height = std::max(index->nHeight - step, 0); // Use skiplist. index = index->GetAncestor(height); if (have.size() > 10) step *= 2; } return have; } CBlockLocator GetLocator(const CBlockIndex* index) { return CBlockLocator{LocatorEntries(index)}; } CBlockLocator CChain::GetLocator() const { return ::GetLocator(Tip()); } const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if (pindex == nullptr) { return nullptr; } if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime, int height) const { std::pair<int64_t, int> blockparams = std::make_pair(nTime, height); std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), blockparams, [](CBlockIndex* pBlock, const std::pair<int64_t, int>& blockparams) -> bool { return pBlock->GetBlockTimeMax() < blockparams.first || pBlock->nHeight < blockparams.second; }); return (lower == vChain.end() ? nullptr : *lower); } /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ int static inline GetSkipHeight(int height) { if (height < 2) return 0; // Determine which height to jump back to. Any number strictly lower than height is acceptable, // but the following expression seems to perform well in simulations (max 110 steps to go back // up to 2**18 blocks). return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); } const CBlockIndex* CBlockIndex::GetAncestor(int height) const { if (height > nHeight || height < 0) { return nullptr; } const CBlockIndex* pindexWalk = this; int heightWalk = nHeight; while (heightWalk > height) { int heightSkip = GetSkipHeight(heightWalk); int heightSkipPrev = GetSkipHeight(heightWalk - 1); if (pindexWalk->pskip != nullptr && (heightSkip == height || (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height)))) { // Only follow pskip if pprev->pskip isn't better than pskip->pprev. pindexWalk = pindexWalk->pskip; heightWalk = heightSkip; } else { assert(pindexWalk->pprev); pindexWalk = pindexWalk->pprev; heightWalk--; } } return pindexWalk; } CBlockIndex* CBlockIndex::GetAncestor(int height) { return const_cast<CBlockIndex*>(static_cast<const CBlockIndex*>(this)->GetAncestor(height)); } void CBlockIndex::BuildSkip() { if (pprev) pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); } arith_uint256 GetBlockProof(const CBlockIndex& block) { arith_uint256 bnTarget; bool fNegative; bool fOverflow; bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); if (fNegative || fOverflow || bnTarget == 0) return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for an arith_uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (bnTarget+1) + 1. return (~bnTarget / (bnTarget + 1)) + 1; } int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) { arith_uint256 r; int sign = 1; if (to.nChainWork > from.nChainWork) { r = to.nChainWork - from.nChainWork; } else { r = from.nChainWork - to.nChainWork; sign = -1; } r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); if (r.bits() > 63) { return sign * std::numeric_limits<int64_t>::max(); } return sign * int64_t(r.GetLow64()); } /** Find the last common ancestor two blocks have. * Both pa and pb must be non-nullptr. */ const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) { if (pa->nHeight > pb->nHeight) { pa = pa->GetAncestor(pb->nHeight); } else if (pb->nHeight > pa->nHeight) { pb = pb->GetAncestor(pa->nHeight); } while (pa != pb && pa && pb) { pa = pa->pprev; pb = pb->pprev; } // Eventually all chain branches meet at the genesis block. assert(pa == pb); return pa; }
0
bitcoin
bitcoin/src/netaddress.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 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 <netaddress.h> #include <crypto/common.h> #include <crypto/sha3.h> #include <hash.h> #include <prevector.h> #include <tinyformat.h> #include <util/strencodings.h> #include <util/string.h> #include <algorithm> #include <array> #include <cstdint> #include <ios> #include <iterator> #include <tuple> CNetAddr::BIP155Network CNetAddr::GetBIP155Network() const { switch (m_net) { case NET_IPV4: return BIP155Network::IPV4; case NET_IPV6: return BIP155Network::IPV6; case NET_ONION: return BIP155Network::TORV3; case NET_I2P: return BIP155Network::I2P; case NET_CJDNS: return BIP155Network::CJDNS; case NET_INTERNAL: // should have been handled before calling this function case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE case NET_MAX: // m_net is never and should not be set to NET_MAX assert(false); } // no default case, so the compiler can warn about missing cases assert(false); } bool CNetAddr::SetNetFromBIP155Network(uint8_t possible_bip155_net, size_t address_size) { switch (possible_bip155_net) { case BIP155Network::IPV4: if (address_size == ADDR_IPV4_SIZE) { m_net = NET_IPV4; return true; } throw std::ios_base::failure( strprintf("BIP155 IPv4 address with length %u (should be %u)", address_size, ADDR_IPV4_SIZE)); case BIP155Network::IPV6: if (address_size == ADDR_IPV6_SIZE) { m_net = NET_IPV6; return true; } throw std::ios_base::failure( strprintf("BIP155 IPv6 address with length %u (should be %u)", address_size, ADDR_IPV6_SIZE)); case BIP155Network::TORV3: if (address_size == ADDR_TORV3_SIZE) { m_net = NET_ONION; return true; } throw std::ios_base::failure( strprintf("BIP155 TORv3 address with length %u (should be %u)", address_size, ADDR_TORV3_SIZE)); case BIP155Network::I2P: if (address_size == ADDR_I2P_SIZE) { m_net = NET_I2P; return true; } throw std::ios_base::failure( strprintf("BIP155 I2P address with length %u (should be %u)", address_size, ADDR_I2P_SIZE)); case BIP155Network::CJDNS: if (address_size == ADDR_CJDNS_SIZE) { m_net = NET_CJDNS; return true; } throw std::ios_base::failure( strprintf("BIP155 CJDNS address with length %u (should be %u)", address_size, ADDR_CJDNS_SIZE)); } // Don't throw on addresses with unknown network ids (maybe from the future). // Instead silently drop them and have the unserialization code consume // subsequent ones which may be known to us. return false; } /** * Construct an unspecified IPv6 network address (::/128). * * @note This address is considered invalid by CNetAddr::IsValid() */ CNetAddr::CNetAddr() = default; void CNetAddr::SetIP(const CNetAddr& ipIn) { // Size check. switch (ipIn.m_net) { case NET_IPV4: assert(ipIn.m_addr.size() == ADDR_IPV4_SIZE); break; case NET_IPV6: assert(ipIn.m_addr.size() == ADDR_IPV6_SIZE); break; case NET_ONION: assert(ipIn.m_addr.size() == ADDR_TORV3_SIZE); break; case NET_I2P: assert(ipIn.m_addr.size() == ADDR_I2P_SIZE); break; case NET_CJDNS: assert(ipIn.m_addr.size() == ADDR_CJDNS_SIZE); break; case NET_INTERNAL: assert(ipIn.m_addr.size() == ADDR_INTERNAL_SIZE); break; case NET_UNROUTABLE: case NET_MAX: assert(false); } // no default case, so the compiler can warn about missing cases m_net = ipIn.m_net; m_addr = ipIn.m_addr; } void CNetAddr::SetLegacyIPv6(Span<const uint8_t> ipv6) { assert(ipv6.size() == ADDR_IPV6_SIZE); size_t skip{0}; if (HasPrefix(ipv6, IPV4_IN_IPV6_PREFIX)) { // IPv4-in-IPv6 m_net = NET_IPV4; skip = sizeof(IPV4_IN_IPV6_PREFIX); } else if (HasPrefix(ipv6, TORV2_IN_IPV6_PREFIX)) { // TORv2-in-IPv6 (unsupported). Unserialize as !IsValid(), thus ignoring them. // Mimic a default-constructed CNetAddr object which is !IsValid() and thus // will not be gossiped, but continue reading next addresses from the stream. m_net = NET_IPV6; m_addr.assign(ADDR_IPV6_SIZE, 0x0); return; } else if (HasPrefix(ipv6, INTERNAL_IN_IPV6_PREFIX)) { // Internal-in-IPv6 m_net = NET_INTERNAL; skip = sizeof(INTERNAL_IN_IPV6_PREFIX); } else { // IPv6 m_net = NET_IPV6; } m_addr.assign(ipv6.begin() + skip, ipv6.end()); } /** * Create an "internal" address that represents a name or FQDN. AddrMan uses * these fake addresses to keep track of which DNS seeds were used. * @returns Whether or not the operation was successful. * @see NET_INTERNAL, INTERNAL_IN_IPV6_PREFIX, CNetAddr::IsInternal(), CNetAddr::IsRFC4193() */ bool CNetAddr::SetInternal(const std::string &name) { if (name.empty()) { return false; } m_net = NET_INTERNAL; unsigned char hash[32] = {}; CSHA256().Write((const unsigned char*)name.data(), name.size()).Finalize(hash); m_addr.assign(hash, hash + ADDR_INTERNAL_SIZE); return true; } namespace torv3 { // https://gitweb.torproject.org/torspec.git/tree/rend-spec-v3.txt?id=7116c9cdaba248aae07a3f1d0e15d9dd102f62c5#n2175 static constexpr size_t CHECKSUM_LEN = 2; static const unsigned char VERSION[] = {3}; static constexpr size_t TOTAL_LEN = ADDR_TORV3_SIZE + CHECKSUM_LEN + sizeof(VERSION); static void Checksum(Span<const uint8_t> addr_pubkey, uint8_t (&checksum)[CHECKSUM_LEN]) { // TORv3 CHECKSUM = H(".onion checksum" | PUBKEY | VERSION)[:2] static const unsigned char prefix[] = ".onion checksum"; static constexpr size_t prefix_len = 15; SHA3_256 hasher; hasher.Write(Span{prefix}.first(prefix_len)); hasher.Write(addr_pubkey); hasher.Write(VERSION); uint8_t checksum_full[SHA3_256::OUTPUT_SIZE]; hasher.Finalize(checksum_full); memcpy(checksum, checksum_full, sizeof(checksum)); } }; // namespace torv3 bool CNetAddr::SetSpecial(const std::string& addr) { if (!ContainsNoNUL(addr)) { return false; } if (SetTor(addr)) { return true; } if (SetI2P(addr)) { return true; } return false; } bool CNetAddr::SetTor(const std::string& addr) { static const char* suffix{".onion"}; static constexpr size_t suffix_len{6}; if (addr.size() <= suffix_len || addr.substr(addr.size() - suffix_len) != suffix) { return false; } auto input = DecodeBase32(std::string_view{addr}.substr(0, addr.size() - suffix_len)); if (!input) { return false; } if (input->size() == torv3::TOTAL_LEN) { Span<const uint8_t> input_pubkey{input->data(), ADDR_TORV3_SIZE}; Span<const uint8_t> input_checksum{input->data() + ADDR_TORV3_SIZE, torv3::CHECKSUM_LEN}; Span<const uint8_t> input_version{input->data() + ADDR_TORV3_SIZE + torv3::CHECKSUM_LEN, sizeof(torv3::VERSION)}; if (input_version != torv3::VERSION) { return false; } uint8_t calculated_checksum[torv3::CHECKSUM_LEN]; torv3::Checksum(input_pubkey, calculated_checksum); if (input_checksum != calculated_checksum) { return false; } m_net = NET_ONION; m_addr.assign(input_pubkey.begin(), input_pubkey.end()); return true; } return false; } bool CNetAddr::SetI2P(const std::string& addr) { // I2P addresses that we support consist of 52 base32 characters + ".b32.i2p". static constexpr size_t b32_len{52}; static const char* suffix{".b32.i2p"}; static constexpr size_t suffix_len{8}; if (addr.size() != b32_len + suffix_len || ToLower(addr.substr(b32_len)) != suffix) { return false; } // Remove the ".b32.i2p" suffix and pad to a multiple of 8 chars, so DecodeBase32() // can decode it. const std::string b32_padded = addr.substr(0, b32_len) + "===="; auto address_bytes = DecodeBase32(b32_padded); if (!address_bytes || address_bytes->size() != ADDR_I2P_SIZE) { return false; } m_net = NET_I2P; m_addr.assign(address_bytes->begin(), address_bytes->end()); return true; } CNetAddr::CNetAddr(const struct in_addr& ipv4Addr) { m_net = NET_IPV4; const uint8_t* ptr = reinterpret_cast<const uint8_t*>(&ipv4Addr); m_addr.assign(ptr, ptr + ADDR_IPV4_SIZE); } CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr, const uint32_t scope) { SetLegacyIPv6({reinterpret_cast<const uint8_t*>(&ipv6Addr), sizeof(ipv6Addr)}); m_scope_id = scope; } bool CNetAddr::IsBindAny() const { if (!IsIPv4() && !IsIPv6()) { return false; } return std::all_of(m_addr.begin(), m_addr.end(), [](uint8_t b) { return b == 0; }); } bool CNetAddr::IsRFC1918() const { return IsIPv4() && ( m_addr[0] == 10 || (m_addr[0] == 192 && m_addr[1] == 168) || (m_addr[0] == 172 && m_addr[1] >= 16 && m_addr[1] <= 31)); } bool CNetAddr::IsRFC2544() const { return IsIPv4() && m_addr[0] == 198 && (m_addr[1] == 18 || m_addr[1] == 19); } bool CNetAddr::IsRFC3927() const { return IsIPv4() && HasPrefix(m_addr, std::array<uint8_t, 2>{169, 254}); } bool CNetAddr::IsRFC6598() const { return IsIPv4() && m_addr[0] == 100 && m_addr[1] >= 64 && m_addr[1] <= 127; } bool CNetAddr::IsRFC5737() const { return IsIPv4() && (HasPrefix(m_addr, std::array<uint8_t, 3>{192, 0, 2}) || HasPrefix(m_addr, std::array<uint8_t, 3>{198, 51, 100}) || HasPrefix(m_addr, std::array<uint8_t, 3>{203, 0, 113})); } bool CNetAddr::IsRFC3849() const { return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x0D, 0xB8}); } bool CNetAddr::IsRFC3964() const { return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 2>{0x20, 0x02}); } bool CNetAddr::IsRFC6052() const { return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 12>{0x00, 0x64, 0xFF, 0x9B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); } bool CNetAddr::IsRFC4380() const { return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x00, 0x00}); } bool CNetAddr::IsRFC4862() const { return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 8>{0xFE, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); } bool CNetAddr::IsRFC4193() const { return IsIPv6() && (m_addr[0] & 0xFE) == 0xFC; } bool CNetAddr::IsRFC6145() const { return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 12>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00}); } bool CNetAddr::IsRFC4843() const { return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 3>{0x20, 0x01, 0x00}) && (m_addr[3] & 0xF0) == 0x10; } bool CNetAddr::IsRFC7343() const { return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 3>{0x20, 0x01, 0x00}) && (m_addr[3] & 0xF0) == 0x20; } bool CNetAddr::IsHeNet() const { return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x04, 0x70}); } bool CNetAddr::IsLocal() const { // IPv4 loopback (127.0.0.0/8 or 0.0.0.0/8) if (IsIPv4() && (m_addr[0] == 127 || m_addr[0] == 0)) { return true; } // IPv6 loopback (::1/128) static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}; if (IsIPv6() && memcmp(m_addr.data(), pchLocal, sizeof(pchLocal)) == 0) { return true; } return false; } /** * @returns Whether or not this network address is a valid address that @a could * be used to refer to an actual host. * * @note A valid address may or may not be publicly routable on the global * internet. As in, the set of valid addresses is a superset of the set of * publicly routable addresses. * * @see CNetAddr::IsRoutable() */ bool CNetAddr::IsValid() const { // unspecified IPv6 address (::/128) unsigned char ipNone6[16] = {}; if (IsIPv6() && memcmp(m_addr.data(), ipNone6, sizeof(ipNone6)) == 0) { return false; } if (IsCJDNS() && !HasCJDNSPrefix()) { return false; } // documentation IPv6 address if (IsRFC3849()) return false; if (IsInternal()) return false; if (IsIPv4()) { const uint32_t addr = ReadBE32(m_addr.data()); if (addr == INADDR_ANY || addr == INADDR_NONE) { return false; } } return true; } /** * @returns Whether or not this network address is publicly routable on the * global internet. * * @note A routable address is always valid. As in, the set of routable addresses * is a subset of the set of valid addresses. * * @see CNetAddr::IsValid() */ bool CNetAddr::IsRoutable() const { return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || IsRFC4193() || IsRFC4843() || IsRFC7343() || IsLocal() || IsInternal()); } /** * @returns Whether or not this is a dummy address that represents a name. * * @see CNetAddr::SetInternal(const std::string &) */ bool CNetAddr::IsInternal() const { return m_net == NET_INTERNAL; } bool CNetAddr::IsAddrV1Compatible() const { switch (m_net) { case NET_IPV4: case NET_IPV6: case NET_INTERNAL: return true; case NET_ONION: case NET_I2P: case NET_CJDNS: return false; case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE case NET_MAX: // m_net is never and should not be set to NET_MAX assert(false); } // no default case, so the compiler can warn about missing cases assert(false); } enum Network CNetAddr::GetNetwork() const { if (IsInternal()) return NET_INTERNAL; if (!IsRoutable()) return NET_UNROUTABLE; return m_net; } static std::string IPv4ToString(Span<const uint8_t> a) { return strprintf("%u.%u.%u.%u", a[0], a[1], a[2], a[3]); } // Return an IPv6 address text representation with zero compression as described in RFC 5952 // ("A Recommendation for IPv6 Address Text Representation"). static std::string IPv6ToString(Span<const uint8_t> a, uint32_t scope_id) { assert(a.size() == ADDR_IPV6_SIZE); const std::array groups{ ReadBE16(&a[0]), ReadBE16(&a[2]), ReadBE16(&a[4]), ReadBE16(&a[6]), ReadBE16(&a[8]), ReadBE16(&a[10]), ReadBE16(&a[12]), ReadBE16(&a[14]), }; // The zero compression implementation is inspired by Rust's std::net::Ipv6Addr, see // https://github.com/rust-lang/rust/blob/cc4103089f40a163f6d143f06359cba7043da29b/library/std/src/net/ip.rs#L1635-L1683 struct ZeroSpan { size_t start_index{0}; size_t len{0}; }; // Find longest sequence of consecutive all-zero fields. Use first zero sequence if two or more // zero sequences of equal length are found. ZeroSpan longest, current; for (size_t i{0}; i < groups.size(); ++i) { if (groups[i] != 0) { current = {i + 1, 0}; continue; } current.len += 1; if (current.len > longest.len) { longest = current; } } std::string r; r.reserve(39); for (size_t i{0}; i < groups.size(); ++i) { // Replace the longest sequence of consecutive all-zero fields with two colons ("::"). if (longest.len >= 2 && i >= longest.start_index && i < longest.start_index + longest.len) { if (i == longest.start_index) { r += "::"; } continue; } r += strprintf("%s%x", ((!r.empty() && r.back() != ':') ? ":" : ""), groups[i]); } if (scope_id != 0) { r += strprintf("%%%u", scope_id); } return r; } std::string OnionToString(Span<const uint8_t> addr) { uint8_t checksum[torv3::CHECKSUM_LEN]; torv3::Checksum(addr, checksum); // TORv3 onion_address = base32(PUBKEY | CHECKSUM | VERSION) + ".onion" prevector<torv3::TOTAL_LEN, uint8_t> address{addr.begin(), addr.end()}; address.insert(address.end(), checksum, checksum + torv3::CHECKSUM_LEN); address.insert(address.end(), torv3::VERSION, torv3::VERSION + sizeof(torv3::VERSION)); return EncodeBase32(address) + ".onion"; } std::string CNetAddr::ToStringAddr() const { switch (m_net) { case NET_IPV4: return IPv4ToString(m_addr); case NET_IPV6: return IPv6ToString(m_addr, m_scope_id); case NET_ONION: return OnionToString(m_addr); case NET_I2P: return EncodeBase32(m_addr, false /* don't pad with = */) + ".b32.i2p"; case NET_CJDNS: return IPv6ToString(m_addr, 0); case NET_INTERNAL: return EncodeBase32(m_addr) + ".internal"; case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE case NET_MAX: // m_net is never and should not be set to NET_MAX assert(false); } // no default case, so the compiler can warn about missing cases assert(false); } bool operator==(const CNetAddr& a, const CNetAddr& b) { return a.m_net == b.m_net && a.m_addr == b.m_addr; } bool operator<(const CNetAddr& a, const CNetAddr& b) { return std::tie(a.m_net, a.m_addr) < std::tie(b.m_net, b.m_addr); } /** * Try to get our IPv4 address. * * @param[out] pipv4Addr The in_addr struct to which to copy. * * @returns Whether or not the operation was successful, in particular, whether * or not our address was an IPv4 address. * * @see CNetAddr::IsIPv4() */ bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const { if (!IsIPv4()) return false; assert(sizeof(*pipv4Addr) == m_addr.size()); memcpy(pipv4Addr, m_addr.data(), m_addr.size()); return true; } /** * Try to get our IPv6 (or CJDNS) address. * * @param[out] pipv6Addr The in6_addr struct to which to copy. * * @returns Whether or not the operation was successful, in particular, whether * or not our address was an IPv6 address. * * @see CNetAddr::IsIPv6() */ bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const { if (!IsIPv6() && !IsCJDNS()) { return false; } assert(sizeof(*pipv6Addr) == m_addr.size()); memcpy(pipv6Addr, m_addr.data(), m_addr.size()); return true; } bool CNetAddr::HasLinkedIPv4() const { return IsRoutable() && (IsIPv4() || IsRFC6145() || IsRFC6052() || IsRFC3964() || IsRFC4380()); } uint32_t CNetAddr::GetLinkedIPv4() const { if (IsIPv4()) { return ReadBE32(m_addr.data()); } else if (IsRFC6052() || IsRFC6145()) { // mapped IPv4, SIIT translated IPv4: the IPv4 address is the last 4 bytes of the address return ReadBE32(Span{m_addr}.last(ADDR_IPV4_SIZE).data()); } else if (IsRFC3964()) { // 6to4 tunneled IPv4: the IPv4 address is in bytes 2-6 return ReadBE32(Span{m_addr}.subspan(2, ADDR_IPV4_SIZE).data()); } else if (IsRFC4380()) { // Teredo tunneled IPv4: the IPv4 address is in the last 4 bytes of the address, but bitflipped return ~ReadBE32(Span{m_addr}.last(ADDR_IPV4_SIZE).data()); } assert(false); } Network CNetAddr::GetNetClass() const { // Make sure that if we return NET_IPV6, then IsIPv6() is true. The callers expect that. // Check for "internal" first because such addresses are also !IsRoutable() // and we don't want to return NET_UNROUTABLE in that case. if (IsInternal()) { return NET_INTERNAL; } if (!IsRoutable()) { return NET_UNROUTABLE; } if (HasLinkedIPv4()) { return NET_IPV4; } return m_net; } std::vector<unsigned char> CNetAddr::GetAddrBytes() const { if (IsAddrV1Compatible()) { uint8_t serialized[V1_SERIALIZATION_SIZE]; SerializeV1Array(serialized); return {std::begin(serialized), std::end(serialized)}; } return std::vector<unsigned char>(m_addr.begin(), m_addr.end()); } // private extensions to enum Network, only returned by GetExtNetwork, // and only used in GetReachabilityFrom static const int NET_TEREDO = NET_MAX; int static GetExtNetwork(const CNetAddr& addr) { if (addr.IsRFC4380()) return NET_TEREDO; return addr.GetNetwork(); } /** Calculates a metric for how reachable (*this) is from a given partner */ int CNetAddr::GetReachabilityFrom(const CNetAddr& paddrPartner) const { enum Reachability { REACH_UNREACHABLE, REACH_DEFAULT, REACH_TEREDO, REACH_IPV6_WEAK, REACH_IPV4, REACH_IPV6_STRONG, REACH_PRIVATE }; if (!IsRoutable() || IsInternal()) return REACH_UNREACHABLE; int ourNet = GetExtNetwork(*this); int theirNet = GetExtNetwork(paddrPartner); bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145(); switch(theirNet) { case NET_IPV4: switch(ourNet) { default: return REACH_DEFAULT; case NET_IPV4: return REACH_IPV4; } case NET_IPV6: switch(ourNet) { default: return REACH_DEFAULT; case NET_TEREDO: return REACH_TEREDO; case NET_IPV4: return REACH_IPV4; case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled } case NET_ONION: switch(ourNet) { default: return REACH_DEFAULT; case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well case NET_ONION: return REACH_PRIVATE; } case NET_I2P: switch (ourNet) { case NET_I2P: return REACH_PRIVATE; default: return REACH_DEFAULT; } case NET_CJDNS: switch (ourNet) { case NET_CJDNS: return REACH_PRIVATE; default: return REACH_DEFAULT; } case NET_TEREDO: switch(ourNet) { default: return REACH_DEFAULT; case NET_TEREDO: return REACH_TEREDO; case NET_IPV6: return REACH_IPV6_WEAK; case NET_IPV4: return REACH_IPV4; } case NET_UNROUTABLE: default: switch(ourNet) { default: return REACH_DEFAULT; case NET_TEREDO: return REACH_TEREDO; case NET_IPV6: return REACH_IPV6_WEAK; case NET_IPV4: return REACH_IPV4; case NET_ONION: return REACH_PRIVATE; // either from Tor, or don't care about our address } } } CService::CService() : port(0) { } CService::CService(const CNetAddr& cip, uint16_t portIn) : CNetAddr(cip), port(portIn) { } CService::CService(const struct in_addr& ipv4Addr, uint16_t portIn) : CNetAddr(ipv4Addr), port(portIn) { } CService::CService(const struct in6_addr& ipv6Addr, uint16_t portIn) : CNetAddr(ipv6Addr), port(portIn) { } CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port)) { assert(addr.sin_family == AF_INET); } CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr, addr.sin6_scope_id), port(ntohs(addr.sin6_port)) { assert(addr.sin6_family == AF_INET6); } bool CService::SetSockAddr(const struct sockaddr *paddr) { switch (paddr->sa_family) { case AF_INET: *this = CService(*(const struct sockaddr_in*)paddr); return true; case AF_INET6: *this = CService(*(const struct sockaddr_in6*)paddr); return true; default: return false; } } uint16_t CService::GetPort() const { return port; } bool operator==(const CService& a, const CService& b) { return static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port == b.port; } bool operator<(const CService& a, const CService& b) { return static_cast<CNetAddr>(a) < static_cast<CNetAddr>(b) || (static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port < b.port); } /** * Obtain the IPv4/6 socket address this represents. * * @param[out] paddr The obtained socket address. * @param[in,out] addrlen The size, in bytes, of the address structure pointed * to by paddr. The value that's pointed to by this * parameter might change after calling this function if * the size of the corresponding address structure * changed. * * @returns Whether or not the operation was successful. */ bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const { if (IsIPv4()) { if (*addrlen < (socklen_t)sizeof(struct sockaddr_in)) return false; *addrlen = sizeof(struct sockaddr_in); struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr; memset(paddrin, 0, *addrlen); if (!GetInAddr(&paddrin->sin_addr)) return false; paddrin->sin_family = AF_INET; paddrin->sin_port = htons(port); return true; } if (IsIPv6() || IsCJDNS()) { if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6)) return false; *addrlen = sizeof(struct sockaddr_in6); struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr; memset(paddrin6, 0, *addrlen); if (!GetIn6Addr(&paddrin6->sin6_addr)) return false; paddrin6->sin6_scope_id = m_scope_id; paddrin6->sin6_family = AF_INET6; paddrin6->sin6_port = htons(port); return true; } return false; } /** * @returns An identifier unique to this service's address and port number. */ std::vector<unsigned char> CService::GetKey() const { auto key = GetAddrBytes(); key.push_back(port / 0x100); // most significant byte of our port key.push_back(port & 0x0FF); // least significant byte of our port return key; } std::string CService::ToStringAddrPort() const { const auto port_str = strprintf("%u", port); if (IsIPv4() || IsTor() || IsI2P() || IsInternal()) { return ToStringAddr() + ":" + port_str; } else { return "[" + ToStringAddr() + "]:" + port_str; } } CSubNet::CSubNet(): valid(false) { memset(netmask, 0, sizeof(netmask)); } CSubNet::CSubNet(const CNetAddr& addr, uint8_t mask) : CSubNet() { valid = (addr.IsIPv4() && mask <= ADDR_IPV4_SIZE * 8) || (addr.IsIPv6() && mask <= ADDR_IPV6_SIZE * 8); if (!valid) { return; } assert(mask <= sizeof(netmask) * 8); network = addr; uint8_t n = mask; for (size_t i = 0; i < network.m_addr.size(); ++i) { const uint8_t bits = n < 8 ? n : 8; netmask[i] = (uint8_t)((uint8_t)0xFF << (8 - bits)); // Set first bits. network.m_addr[i] &= netmask[i]; // Normalize network according to netmask. n -= bits; } } /** * @returns The number of 1-bits in the prefix of the specified subnet mask. If * the specified subnet mask is not a valid one, -1. */ static inline int NetmaskBits(uint8_t x) { switch(x) { case 0x00: return 0; case 0x80: return 1; case 0xc0: return 2; case 0xe0: return 3; case 0xf0: return 4; case 0xf8: return 5; case 0xfc: return 6; case 0xfe: return 7; case 0xff: return 8; default: return -1; } } CSubNet::CSubNet(const CNetAddr& addr, const CNetAddr& mask) : CSubNet() { valid = (addr.IsIPv4() || addr.IsIPv6()) && addr.m_net == mask.m_net; if (!valid) { return; } // Check if `mask` contains 1-bits after 0-bits (which is an invalid netmask). bool zeros_found = false; for (auto b : mask.m_addr) { const int num_bits = NetmaskBits(b); if (num_bits == -1 || (zeros_found && num_bits != 0)) { valid = false; return; } if (num_bits < 8) { zeros_found = true; } } assert(mask.m_addr.size() <= sizeof(netmask)); memcpy(netmask, mask.m_addr.data(), mask.m_addr.size()); network = addr; // Normalize network according to netmask for (size_t x = 0; x < network.m_addr.size(); ++x) { network.m_addr[x] &= netmask[x]; } } CSubNet::CSubNet(const CNetAddr& addr) : CSubNet() { switch (addr.m_net) { case NET_IPV4: case NET_IPV6: valid = true; assert(addr.m_addr.size() <= sizeof(netmask)); memset(netmask, 0xFF, addr.m_addr.size()); break; case NET_ONION: case NET_I2P: case NET_CJDNS: valid = true; break; case NET_INTERNAL: case NET_UNROUTABLE: case NET_MAX: return; } network = addr; } /** * @returns True if this subnet is valid, the specified address is valid, and * the specified address belongs in this subnet. */ bool CSubNet::Match(const CNetAddr &addr) const { if (!valid || !addr.IsValid() || network.m_net != addr.m_net) return false; switch (network.m_net) { case NET_IPV4: case NET_IPV6: break; case NET_ONION: case NET_I2P: case NET_CJDNS: case NET_INTERNAL: return addr == network; case NET_UNROUTABLE: case NET_MAX: return false; } assert(network.m_addr.size() == addr.m_addr.size()); for (size_t x = 0; x < addr.m_addr.size(); ++x) { if ((addr.m_addr[x] & netmask[x]) != network.m_addr[x]) { return false; } } return true; } std::string CSubNet::ToString() const { std::string suffix; switch (network.m_net) { case NET_IPV4: case NET_IPV6: { assert(network.m_addr.size() <= sizeof(netmask)); uint8_t cidr = 0; for (size_t i = 0; i < network.m_addr.size(); ++i) { if (netmask[i] == 0x00) { break; } cidr += NetmaskBits(netmask[i]); } suffix = strprintf("/%u", cidr); break; } case NET_ONION: case NET_I2P: case NET_CJDNS: case NET_INTERNAL: case NET_UNROUTABLE: case NET_MAX: break; } return network.ToStringAddr() + suffix; } bool CSubNet::IsValid() const { return valid; } bool operator==(const CSubNet& a, const CSubNet& b) { return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16); } bool operator<(const CSubNet& a, const CSubNet& b) { return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0)); }
0
bitcoin
bitcoin/src/coins.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_COINS_H #define BITCOIN_COINS_H #include <compressor.h> #include <core_memusage.h> #include <memusage.h> #include <primitives/transaction.h> #include <serialize.h> #include <support/allocators/pool.h> #include <uint256.h> #include <util/hasher.h> #include <assert.h> #include <stdint.h> #include <functional> #include <unordered_map> /** * A UTXO entry. * * Serialized format: * - VARINT((coinbase ? 1 : 0) | (height << 1)) * - the non-spent CTxOut (via TxOutCompression) */ class Coin { public: //! unspent transaction output CTxOut out; //! whether containing transaction was a coinbase unsigned int fCoinBase : 1; //! at which height this containing transaction was included in the active block chain uint32_t nHeight : 31; //! construct a Coin from a CTxOut and height/coinbase information. Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {} Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {} void Clear() { out.SetNull(); fCoinBase = false; nHeight = 0; } //! empty constructor Coin() : fCoinBase(false), nHeight(0) { } bool IsCoinBase() const { return fCoinBase; } template<typename Stream> void Serialize(Stream &s) const { assert(!IsSpent()); uint32_t code = nHeight * uint32_t{2} + fCoinBase; ::Serialize(s, VARINT(code)); ::Serialize(s, Using<TxOutCompression>(out)); } template<typename Stream> void Unserialize(Stream &s) { uint32_t code = 0; ::Unserialize(s, VARINT(code)); nHeight = code >> 1; fCoinBase = code & 1; ::Unserialize(s, Using<TxOutCompression>(out)); } /** Either this coin never existed (see e.g. coinEmpty in coins.cpp), or it * did exist and has been spent. */ bool IsSpent() const { return out.IsNull(); } size_t DynamicMemoryUsage() const { return memusage::DynamicUsage(out.scriptPubKey); } }; /** * A Coin in one level of the coins database caching hierarchy. * * A coin can either be: * - unspent or spent (in which case the Coin object will be nulled out - see Coin.Clear()) * - DIRTY or not DIRTY * - FRESH or not FRESH * * Out of these 2^3 = 8 states, only some combinations are valid: * - unspent, FRESH, DIRTY (e.g. a new coin created in the cache) * - unspent, not FRESH, DIRTY (e.g. a coin changed in the cache during a reorg) * - unspent, not FRESH, not DIRTY (e.g. an unspent coin fetched from the parent cache) * - spent, FRESH, not DIRTY (e.g. a spent coin fetched from the parent cache) * - spent, not FRESH, DIRTY (e.g. a coin is spent and spentness needs to be flushed to the parent) */ struct CCoinsCacheEntry { Coin coin; // The actual cached data. unsigned char flags; enum Flags { /** * DIRTY means the CCoinsCacheEntry is potentially different from the * version in the parent cache. Failure to mark a coin as DIRTY when * it is potentially different from the parent cache will cause a * consensus failure, since the coin's state won't get written to the * parent when the cache is flushed. */ DIRTY = (1 << 0), /** * FRESH means the parent cache does not have this coin or that it is a * spent coin in the parent cache. If a FRESH coin in the cache is * later spent, it can be deleted entirely and doesn't ever need to be * flushed to the parent. This is a performance optimization. Marking a * coin as FRESH when it exists unspent in the parent cache will cause a * consensus failure, since it might not be deleted from the parent * when this cache is flushed. */ FRESH = (1 << 1), }; CCoinsCacheEntry() : flags(0) {} explicit CCoinsCacheEntry(Coin&& coin_) : coin(std::move(coin_)), flags(0) {} CCoinsCacheEntry(Coin&& coin_, unsigned char flag) : coin(std::move(coin_)), flags(flag) {} }; /** * PoolAllocator's MAX_BLOCK_SIZE_BYTES parameter here uses sizeof the data, and adds the size * of 4 pointers. We do not know the exact node size used in the std::unordered_node implementation * because it is implementation defined. Most implementations have an overhead of 1 or 2 pointers, * so nodes can be connected in a linked list, and in some cases the hash value is stored as well. * Using an additional sizeof(void*)*4 for MAX_BLOCK_SIZE_BYTES should thus be sufficient so that * all implementations can allocate the nodes from the PoolAllocator. */ using CCoinsMap = std::unordered_map<COutPoint, CCoinsCacheEntry, SaltedOutpointHasher, std::equal_to<COutPoint>, PoolAllocator<std::pair<const COutPoint, CCoinsCacheEntry>, sizeof(std::pair<const COutPoint, CCoinsCacheEntry>) + sizeof(void*) * 4>>; using CCoinsMapMemoryResource = CCoinsMap::allocator_type::ResourceType; /** Cursor for iterating over CoinsView state */ class CCoinsViewCursor { public: CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {} virtual ~CCoinsViewCursor() {} virtual bool GetKey(COutPoint &key) const = 0; virtual bool GetValue(Coin &coin) const = 0; virtual bool Valid() const = 0; virtual void Next() = 0; //! Get best block at the time this cursor was created const uint256 &GetBestBlock() const { return hashBlock; } private: uint256 hashBlock; }; /** Abstract view on the open txout dataset. */ class CCoinsView { public: /** Retrieve the Coin (unspent transaction output) for a given outpoint. * Returns true only when an unspent coin was found, which is returned in coin. * When false is returned, coin's value is unspecified. */ virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const; //! Just check whether a given outpoint is unspent. virtual bool HaveCoin(const COutPoint &outpoint) const; //! Retrieve the block hash whose state this CCoinsView currently represents virtual uint256 GetBestBlock() const; //! Retrieve the range of blocks that may have been only partially written. //! If the database is in a consistent state, the result is the empty vector. //! Otherwise, a two-element vector is returned consisting of the new and //! the old block hash, in that order. virtual std::vector<uint256> GetHeadBlocks() const; //! Do a bulk modification (multiple Coin changes + BestBlock change). //! The passed mapCoins can be modified. virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase = true); //! Get a cursor to iterate over the whole state virtual std::unique_ptr<CCoinsViewCursor> Cursor() const; //! As we use CCoinsViews polymorphically, have a virtual destructor virtual ~CCoinsView() {} //! Estimate database size (0 if not implemented) virtual size_t EstimateSize() const { return 0; } }; /** CCoinsView backed by another CCoinsView */ class CCoinsViewBacked : public CCoinsView { protected: CCoinsView *base; public: CCoinsViewBacked(CCoinsView *viewIn); bool GetCoin(const COutPoint &outpoint, Coin &coin) const override; bool HaveCoin(const COutPoint &outpoint) const override; uint256 GetBestBlock() const override; std::vector<uint256> GetHeadBlocks() const override; void SetBackend(CCoinsView &viewIn); bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase = true) override; std::unique_ptr<CCoinsViewCursor> Cursor() const override; size_t EstimateSize() const override; }; /** CCoinsView that adds a memory cache for transactions to another CCoinsView */ class CCoinsViewCache : public CCoinsViewBacked { private: const bool m_deterministic; protected: /** * Make mutable so that we can "fill the cache" even from Get-methods * declared as "const". */ mutable uint256 hashBlock; mutable CCoinsMapMemoryResource m_cache_coins_memory_resource{}; mutable CCoinsMap cacheCoins; /* Cached dynamic memory usage for the inner Coin objects. */ mutable size_t cachedCoinsUsage{0}; public: CCoinsViewCache(CCoinsView *baseIn, bool deterministic = false); /** * By deleting the copy constructor, we prevent accidentally using it when one intends to create a cache on top of a base cache. */ CCoinsViewCache(const CCoinsViewCache &) = delete; // Standard CCoinsView methods bool GetCoin(const COutPoint &outpoint, Coin &coin) const override; bool HaveCoin(const COutPoint &outpoint) const override; uint256 GetBestBlock() const override; void SetBestBlock(const uint256 &hashBlock); bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase = true) override; std::unique_ptr<CCoinsViewCursor> Cursor() const override { throw std::logic_error("CCoinsViewCache cursor iteration not supported."); } /** * Check if we have the given utxo already loaded in this cache. * The semantics are the same as HaveCoin(), but no calls to * the backing CCoinsView are made. */ bool HaveCoinInCache(const COutPoint &outpoint) const; /** * Return a reference to Coin in the cache, or coinEmpty if not found. This is * more efficient than GetCoin. * * Generally, do not hold the reference returned for more than a short scope. * While the current implementation allows for modifications to the contents * of the cache while holding the reference, this behavior should not be relied * on! To be safe, best to not hold the returned reference through any other * calls to this cache. */ const Coin& AccessCoin(const COutPoint &output) const; /** * Add a coin. Set possible_overwrite to true if an unspent version may * already exist in the cache. */ void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite); /** * Emplace a coin into cacheCoins without performing any checks, marking * the emplaced coin as dirty. * * NOT FOR GENERAL USE. Used only when loading coins from a UTXO snapshot. * @sa ChainstateManager::PopulateAndValidateSnapshot() */ void EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin); /** * Spend a coin. Pass moveto in order to get the deleted data. * If no unspent output exists for the passed outpoint, this call * has no effect. */ bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr); /** * Push the modifications applied to this cache to its base and wipe local state. * Failure to call this method or Sync() before destruction will cause the changes * to be forgotten. * If false is returned, the state of this cache (and its backing view) will be undefined. */ bool Flush(); /** * Push the modifications applied to this cache to its base while retaining * the contents of this cache (except for spent coins, which we erase). * Failure to call this method or Flush() before destruction will cause the changes * to be forgotten. * If false is returned, the state of this cache (and its backing view) will be undefined. */ bool Sync(); /** * Removes the UTXO with the given outpoint from the cache, if it is * not modified. */ void Uncache(const COutPoint &outpoint); //! Calculate the size of the cache (in number of transaction outputs) unsigned int GetCacheSize() const; //! Calculate the size of the cache (in bytes) size_t DynamicMemoryUsage() const; //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view bool HaveInputs(const CTransaction& tx) const; //! Force a reallocation of the cache map. This is required when downsizing //! the cache because the map's allocator may be hanging onto a lot of //! memory despite having called .clear(). //! //! See: https://stackoverflow.com/questions/42114044/how-to-release-unordered-map-memory void ReallocateCache(); //! Run an internal sanity check on the cache data structure. */ void SanityCheck() const; private: /** * @note this is marked const, but may actually append to `cacheCoins`, increasing * memory usage. */ CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const; }; //! Utility function to add all of a transaction's outputs to a cache. //! When check is false, this assumes that overwrites are only possible for coinbase transactions. //! When check is true, the underlying view may be queried to determine whether an addition is //! an overwrite. // TODO: pass in a boolean to limit these possible overwrites to known // (pre-BIP34) cases. void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false); //! Utility function to find any unspent output with a given txid. //! This function can be quite expensive because in the event of a transaction //! which is not found in the cache, it can cause up to MAX_OUTPUTS_PER_BLOCK //! lookups to database, so it should be used with care. const Coin& AccessByTxid(const CCoinsViewCache& cache, const Txid& txid); /** * This is a minimally invasive approach to shutdown on LevelDB read errors from the * chainstate, while keeping user interface out of the common library, which is shared * between bitcoind, and bitcoin-qt and non-server tools. * * Writes do not need similar protection, as failure to write is handled by the caller. */ class CCoinsViewErrorCatcher final : public CCoinsViewBacked { public: explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {} void AddReadErrCallback(std::function<void()> f) { m_err_callbacks.emplace_back(std::move(f)); } bool GetCoin(const COutPoint &outpoint, Coin &coin) const override; bool HaveCoin(const COutPoint &outpoint) const override; private: /** A list of callbacks to execute upon leveldb read error. */ std::vector<std::function<void()>> m_err_callbacks; }; #endif // BITCOIN_COINS_H
0
bitcoin
bitcoin/src/dummywallet.cpp
// Copyright (c) 2018-2021 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 <common/args.h> #include <logging.h> #include <walletinitinterface.h> class ArgsManager; namespace interfaces { class Chain; class Handler; class Wallet; class WalletLoader; } class DummyWalletInit : public WalletInitInterface { public: bool HasWalletSupport() const override {return false;} void AddWalletOptions(ArgsManager& argsman) const override; bool ParameterInteraction() const override {return true;} void Construct(node::NodeContext& node) const override {LogPrintf("No wallet support compiled in!\n");} }; void DummyWalletInit::AddWalletOptions(ArgsManager& argsman) const { argsman.AddHiddenArgs({ "-addresstype", "-avoidpartialspends", "-changetype", "-consolidatefeerate=<amt>", "-disablewallet", "-discardfee=<amt>", "-fallbackfee=<amt>", "-keypool=<n>", "-maxapsfee=<n>", "-maxtxfee=<amt>", "-mintxfee=<amt>", "-paytxfee=<amt>", "-signer=<cmd>", "-spendzeroconfchange", "-txconfirmtarget=<n>", "-wallet=<path>", "-walletbroadcast", "-walletdir=<dir>", "-walletnotify=<cmd>", "-walletrbf", "-dblogsize=<n>", "-flushwallet", "-privdb", "-walletrejectlongchains", "-walletcrosschain", "-unsafesqlitesync", }); } const WalletInitInterface& g_wallet_init_interface = DummyWalletInit(); namespace interfaces { std::unique_ptr<WalletLoader> MakeWalletLoader(Chain& chain, ArgsManager& args) { throw std::logic_error("Wallet function called in non-wallet build."); } } // namespace interfaces
0
bitcoin
bitcoin/src/netgroup.h
// Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_NETGROUP_H #define BITCOIN_NETGROUP_H #include <netaddress.h> #include <uint256.h> #include <vector> /** * Netgroup manager */ class NetGroupManager { public: explicit NetGroupManager(std::vector<bool> asmap) : m_asmap{std::move(asmap)} {} /** Get a checksum identifying the asmap being used. */ uint256 GetAsmapChecksum() const; /** * Get the canonical identifier of the network group for address. * * The groups are assigned in a way where it should be costly for an attacker to * obtain addresses with many different group identifiers, even if it is cheap * to obtain addresses with the same identifier. * * @note No two connections will be attempted to addresses with the same network * group. */ std::vector<unsigned char> GetGroup(const CNetAddr& address) const; /** * Get the autonomous system on the BGP path to address. * * The ip->AS mapping depends on how asmap is constructed. */ uint32_t GetMappedAS(const CNetAddr& address) const; /** * Analyze and log current health of ASMap based buckets. */ void ASMapHealthCheck(const std::vector<CNetAddr>& clearnet_addrs) const; /** * Indicates whether ASMap is being used for clearnet bucketing. */ bool UsingASMap() const; private: /** Compressed IP->ASN mapping, loaded from a file when a node starts. * * This mapping is then used for bucketing nodes in Addrman and for * ensuring we connect to a diverse set of peers in Connman. The map is * empty if no file was provided. * * If asmap is provided, nodes will be bucketed by AS they belong to, in * order to make impossible for a node to connect to several nodes hosted * in a single AS. This is done in response to Erebus attack, but also to * generally diversify the connections every node creates, especially * useful when a large fraction of nodes operate under a couple of cloud * providers. * * If a new asmap is provided, the existing addrman records are * re-bucketed. * * This is initialized in the constructor, const, and therefore is * thread-safe. */ const std::vector<bool> m_asmap; }; #endif // BITCOIN_NETGROUP_H
0
bitcoin
bitcoin/src/blockencodings.h
// Copyright (c) 2016-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_BLOCKENCODINGS_H #define BITCOIN_BLOCKENCODINGS_H #include <primitives/block.h> #include <functional> class CTxMemPool; class BlockValidationState; namespace Consensus { struct Params; }; // Transaction compression schemes for compact block relay can be introduced by writing // an actual formatter here. using TransactionCompression = DefaultFormatter; class DifferenceFormatter { uint64_t m_shift = 0; public: template<typename Stream, typename I> void Ser(Stream& s, I v) { if (v < m_shift || v >= std::numeric_limits<uint64_t>::max()) throw std::ios_base::failure("differential value overflow"); WriteCompactSize(s, v - m_shift); m_shift = uint64_t(v) + 1; } template<typename Stream, typename I> void Unser(Stream& s, I& v) { uint64_t n = ReadCompactSize(s); m_shift += n; if (m_shift < n || m_shift >= std::numeric_limits<uint64_t>::max() || m_shift < std::numeric_limits<I>::min() || m_shift > std::numeric_limits<I>::max()) throw std::ios_base::failure("differential value overflow"); v = I(m_shift++); } }; class BlockTransactionsRequest { public: // A BlockTransactionsRequest message uint256 blockhash; std::vector<uint16_t> indexes; SERIALIZE_METHODS(BlockTransactionsRequest, obj) { READWRITE(obj.blockhash, Using<VectorFormatter<DifferenceFormatter>>(obj.indexes)); } }; class BlockTransactions { public: // A BlockTransactions message uint256 blockhash; std::vector<CTransactionRef> txn; BlockTransactions() {} explicit BlockTransactions(const BlockTransactionsRequest& req) : blockhash(req.blockhash), txn(req.indexes.size()) {} SERIALIZE_METHODS(BlockTransactions, obj) { READWRITE(obj.blockhash, TX_WITH_WITNESS(Using<VectorFormatter<TransactionCompression>>(obj.txn))); } }; // Dumb serialization/storage-helper for CBlockHeaderAndShortTxIDs and PartiallyDownloadedBlock struct PrefilledTransaction { // Used as an offset since last prefilled tx in CBlockHeaderAndShortTxIDs, // as a proper transaction-in-block-index in PartiallyDownloadedBlock uint16_t index; CTransactionRef tx; SERIALIZE_METHODS(PrefilledTransaction, obj) { READWRITE(COMPACTSIZE(obj.index), TX_WITH_WITNESS(Using<TransactionCompression>(obj.tx))); } }; typedef enum ReadStatus_t { READ_STATUS_OK, READ_STATUS_INVALID, // Invalid object, peer is sending bogus crap READ_STATUS_FAILED, // Failed to process object READ_STATUS_CHECKBLOCK_FAILED, // Used only by FillBlock to indicate a // failure in CheckBlock. } ReadStatus; class CBlockHeaderAndShortTxIDs { private: mutable uint64_t shorttxidk0, shorttxidk1; uint64_t nonce; void FillShortTxIDSelector() const; friend class PartiallyDownloadedBlock; protected: std::vector<uint64_t> shorttxids; std::vector<PrefilledTransaction> prefilledtxn; public: static constexpr int SHORTTXIDS_LENGTH = 6; CBlockHeader header; // Dummy for deserialization CBlockHeaderAndShortTxIDs() {} CBlockHeaderAndShortTxIDs(const CBlock& block); uint64_t GetShortID(const uint256& txhash) const; size_t BlockTxCount() const { return shorttxids.size() + prefilledtxn.size(); } SERIALIZE_METHODS(CBlockHeaderAndShortTxIDs, obj) { READWRITE(obj.header, obj.nonce, Using<VectorFormatter<CustomUintFormatter<SHORTTXIDS_LENGTH>>>(obj.shorttxids), obj.prefilledtxn); if (ser_action.ForRead()) { if (obj.BlockTxCount() > std::numeric_limits<uint16_t>::max()) { throw std::ios_base::failure("indexes overflowed 16 bits"); } obj.FillShortTxIDSelector(); } } }; class PartiallyDownloadedBlock { protected: std::vector<CTransactionRef> txn_available; size_t prefilled_count = 0, mempool_count = 0, extra_count = 0; const CTxMemPool* pool; public: CBlockHeader header; // Can be overridden for testing using CheckBlockFn = std::function<bool(const CBlock&, BlockValidationState&, const Consensus::Params&, bool, bool)>; CheckBlockFn m_check_block_mock{nullptr}; explicit PartiallyDownloadedBlock(CTxMemPool* poolIn) : pool(poolIn) {} // extra_txn is a list of extra transactions to look at, in <witness hash, reference> form ReadStatus InitData(const CBlockHeaderAndShortTxIDs& cmpctblock, const std::vector<std::pair<uint256, CTransactionRef>>& extra_txn); bool IsTxAvailable(size_t index) const; ReadStatus FillBlock(CBlock& block, const std::vector<CTransactionRef>& vtx_missing); }; #endif // BITCOIN_BLOCKENCODINGS_H
0
bitcoin
bitcoin/src/blockfilter.cpp
// Copyright (c) 2018-2022 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 <mutex> #include <set> #include <blockfilter.h> #include <crypto/siphash.h> #include <hash.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <script/script.h> #include <streams.h> #include <undo.h> #include <util/golombrice.h> #include <util/string.h> static const std::map<BlockFilterType, std::string> g_filter_types = { {BlockFilterType::BASIC, "basic"}, }; uint64_t GCSFilter::HashToRange(const Element& element) const { uint64_t hash = CSipHasher(m_params.m_siphash_k0, m_params.m_siphash_k1) .Write(element) .Finalize(); return FastRange64(hash, m_F); } std::vector<uint64_t> GCSFilter::BuildHashedSet(const ElementSet& elements) const { std::vector<uint64_t> hashed_elements; hashed_elements.reserve(elements.size()); for (const Element& element : elements) { hashed_elements.push_back(HashToRange(element)); } std::sort(hashed_elements.begin(), hashed_elements.end()); return hashed_elements; } GCSFilter::GCSFilter(const Params& params) : m_params(params), m_N(0), m_F(0), m_encoded{0} {} GCSFilter::GCSFilter(const Params& params, std::vector<unsigned char> encoded_filter, bool skip_decode_check) : m_params(params), m_encoded(std::move(encoded_filter)) { SpanReader stream{m_encoded}; uint64_t N = ReadCompactSize(stream); m_N = static_cast<uint32_t>(N); if (m_N != N) { throw std::ios_base::failure("N must be <2^32"); } m_F = static_cast<uint64_t>(m_N) * static_cast<uint64_t>(m_params.m_M); if (skip_decode_check) return; // Verify that the encoded filter contains exactly N elements. If it has too much or too little // data, a std::ios_base::failure exception will be raised. BitStreamReader bitreader{stream}; for (uint64_t i = 0; i < m_N; ++i) { GolombRiceDecode(bitreader, m_params.m_P); } if (!stream.empty()) { throw std::ios_base::failure("encoded_filter contains excess data"); } } GCSFilter::GCSFilter(const Params& params, const ElementSet& elements) : m_params(params) { size_t N = elements.size(); m_N = static_cast<uint32_t>(N); if (m_N != N) { throw std::invalid_argument("N must be <2^32"); } m_F = static_cast<uint64_t>(m_N) * static_cast<uint64_t>(m_params.m_M); VectorWriter stream{m_encoded, 0}; WriteCompactSize(stream, m_N); if (elements.empty()) { return; } BitStreamWriter bitwriter{stream}; uint64_t last_value = 0; for (uint64_t value : BuildHashedSet(elements)) { uint64_t delta = value - last_value; GolombRiceEncode(bitwriter, m_params.m_P, delta); last_value = value; } bitwriter.Flush(); } bool GCSFilter::MatchInternal(const uint64_t* element_hashes, size_t size) const { SpanReader stream{m_encoded}; // Seek forward by size of N uint64_t N = ReadCompactSize(stream); assert(N == m_N); BitStreamReader bitreader{stream}; uint64_t value = 0; size_t hashes_index = 0; for (uint32_t i = 0; i < m_N; ++i) { uint64_t delta = GolombRiceDecode(bitreader, m_params.m_P); value += delta; while (true) { if (hashes_index == size) { return false; } else if (element_hashes[hashes_index] == value) { return true; } else if (element_hashes[hashes_index] > value) { break; } hashes_index++; } } return false; } bool GCSFilter::Match(const Element& element) const { uint64_t query = HashToRange(element); return MatchInternal(&query, 1); } bool GCSFilter::MatchAny(const ElementSet& elements) const { const std::vector<uint64_t> queries = BuildHashedSet(elements); return MatchInternal(queries.data(), queries.size()); } const std::string& BlockFilterTypeName(BlockFilterType filter_type) { static std::string unknown_retval; auto it = g_filter_types.find(filter_type); return it != g_filter_types.end() ? it->second : unknown_retval; } bool BlockFilterTypeByName(const std::string& name, BlockFilterType& filter_type) { for (const auto& entry : g_filter_types) { if (entry.second == name) { filter_type = entry.first; return true; } } return false; } const std::set<BlockFilterType>& AllBlockFilterTypes() { static std::set<BlockFilterType> types; static std::once_flag flag; std::call_once(flag, []() { for (const auto& entry : g_filter_types) { types.insert(entry.first); } }); return types; } const std::string& ListBlockFilterTypes() { static std::string type_list{Join(g_filter_types, ", ", [](const auto& entry) { return entry.second; })}; return type_list; } static GCSFilter::ElementSet BasicFilterElements(const CBlock& block, const CBlockUndo& block_undo) { GCSFilter::ElementSet elements; for (const CTransactionRef& tx : block.vtx) { for (const CTxOut& txout : tx->vout) { const CScript& script = txout.scriptPubKey; if (script.empty() || script[0] == OP_RETURN) continue; elements.emplace(script.begin(), script.end()); } } for (const CTxUndo& tx_undo : block_undo.vtxundo) { for (const Coin& prevout : tx_undo.vprevout) { const CScript& script = prevout.out.scriptPubKey; if (script.empty()) continue; elements.emplace(script.begin(), script.end()); } } return elements; } BlockFilter::BlockFilter(BlockFilterType filter_type, const uint256& block_hash, std::vector<unsigned char> filter, bool skip_decode_check) : m_filter_type(filter_type), m_block_hash(block_hash) { GCSFilter::Params params; if (!BuildParams(params)) { throw std::invalid_argument("unknown filter_type"); } m_filter = GCSFilter(params, std::move(filter), skip_decode_check); } BlockFilter::BlockFilter(BlockFilterType filter_type, const CBlock& block, const CBlockUndo& block_undo) : m_filter_type(filter_type), m_block_hash(block.GetHash()) { GCSFilter::Params params; if (!BuildParams(params)) { throw std::invalid_argument("unknown filter_type"); } m_filter = GCSFilter(params, BasicFilterElements(block, block_undo)); } bool BlockFilter::BuildParams(GCSFilter::Params& params) const { switch (m_filter_type) { case BlockFilterType::BASIC: params.m_siphash_k0 = m_block_hash.GetUint64(0); params.m_siphash_k1 = m_block_hash.GetUint64(1); params.m_P = BASIC_FILTER_P; params.m_M = BASIC_FILTER_M; return true; case BlockFilterType::INVALID: return false; } return false; } uint256 BlockFilter::GetHash() const { return Hash(GetEncodedFilter()); } uint256 BlockFilter::ComputeHeader(const uint256& prev_header) const { return Hash(GetHash(), prev_header); }
0
bitcoin
bitcoin/src/netbase.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 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 <netbase.h> #include <compat/compat.h> #include <logging.h> #include <sync.h> #include <tinyformat.h> #include <util/sock.h> #include <util/strencodings.h> #include <util/string.h> #include <util/time.h> #include <atomic> #include <chrono> #include <cstdint> #include <functional> #include <limits> #include <memory> // Settings static GlobalMutex g_proxyinfo_mutex; static Proxy proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex); static Proxy nameProxy GUARDED_BY(g_proxyinfo_mutex); int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT; bool fNameLookup = DEFAULT_NAME_LOOKUP; // Need ample time for negotiation for very slow proxies such as Tor std::chrono::milliseconds g_socks5_recv_timeout = 20s; CThreadInterrupt g_socks5_interrupt; ReachableNets g_reachable_nets; std::vector<CNetAddr> WrappedGetAddrInfo(const std::string& name, bool allow_lookup) { addrinfo ai_hint{}; // We want a TCP port, which is a streaming socket type ai_hint.ai_socktype = SOCK_STREAM; ai_hint.ai_protocol = IPPROTO_TCP; // We don't care which address family (IPv4 or IPv6) is returned ai_hint.ai_family = AF_UNSPEC; // If we allow lookups of hostnames, use the AI_ADDRCONFIG flag to only // return addresses whose family we have an address configured for. // // If we don't allow lookups, then use the AI_NUMERICHOST flag for // getaddrinfo to only decode numerical network addresses and suppress // hostname lookups. ai_hint.ai_flags = allow_lookup ? AI_ADDRCONFIG : AI_NUMERICHOST; addrinfo* ai_res{nullptr}; const int n_err{getaddrinfo(name.c_str(), nullptr, &ai_hint, &ai_res)}; if (n_err != 0) { return {}; } // Traverse the linked list starting with ai_trav. addrinfo* ai_trav{ai_res}; std::vector<CNetAddr> resolved_addresses; while (ai_trav != nullptr) { if (ai_trav->ai_family == AF_INET) { assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in)); resolved_addresses.emplace_back(reinterpret_cast<sockaddr_in*>(ai_trav->ai_addr)->sin_addr); } if (ai_trav->ai_family == AF_INET6) { assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in6)); const sockaddr_in6* s6{reinterpret_cast<sockaddr_in6*>(ai_trav->ai_addr)}; resolved_addresses.emplace_back(s6->sin6_addr, s6->sin6_scope_id); } ai_trav = ai_trav->ai_next; } freeaddrinfo(ai_res); return resolved_addresses; } DNSLookupFn g_dns_lookup{WrappedGetAddrInfo}; enum Network ParseNetwork(const std::string& net_in) { std::string net = ToLower(net_in); if (net == "ipv4") return NET_IPV4; if (net == "ipv6") return NET_IPV6; if (net == "onion") return NET_ONION; if (net == "tor") { LogPrintf("Warning: net name 'tor' is deprecated and will be removed in the future. You should use 'onion' instead.\n"); return NET_ONION; } if (net == "i2p") { return NET_I2P; } if (net == "cjdns") { return NET_CJDNS; } return NET_UNROUTABLE; } std::string GetNetworkName(enum Network net) { switch (net) { case NET_UNROUTABLE: return "not_publicly_routable"; case NET_IPV4: return "ipv4"; case NET_IPV6: return "ipv6"; case NET_ONION: return "onion"; case NET_I2P: return "i2p"; case NET_CJDNS: return "cjdns"; case NET_INTERNAL: return "internal"; case NET_MAX: assert(false); } // no default case, so the compiler can warn about missing cases assert(false); } std::vector<std::string> GetNetworkNames(bool append_unroutable) { std::vector<std::string> names; for (int n = 0; n < NET_MAX; ++n) { const enum Network network{static_cast<Network>(n)}; if (network == NET_UNROUTABLE || network == NET_INTERNAL) continue; names.emplace_back(GetNetworkName(network)); } if (append_unroutable) { names.emplace_back(GetNetworkName(NET_UNROUTABLE)); } return names; } static std::vector<CNetAddr> LookupIntern(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function) { if (!ContainsNoNUL(name)) return {}; { CNetAddr addr; // From our perspective, onion addresses are not hostnames but rather // direct encodings of CNetAddr much like IPv4 dotted-decimal notation // or IPv6 colon-separated hextet notation. Since we can't use // getaddrinfo to decode them and it wouldn't make sense to resolve // them, we return a network address representing it instead. See // CNetAddr::SetSpecial(const std::string&) for more details. if (addr.SetSpecial(name)) return {addr}; } std::vector<CNetAddr> addresses; for (const CNetAddr& resolved : dns_lookup_function(name, fAllowLookup)) { if (nMaxSolutions > 0 && addresses.size() >= nMaxSolutions) { break; } /* Never allow resolving to an internal address. Consider any such result invalid */ if (!resolved.IsInternal()) { addresses.push_back(resolved); } } return addresses; } std::vector<CNetAddr> LookupHost(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function) { if (!ContainsNoNUL(name)) return {}; std::string strHost = name; if (strHost.empty()) return {}; if (strHost.front() == '[' && strHost.back() == ']') { strHost = strHost.substr(1, strHost.size() - 2); } return LookupIntern(strHost, nMaxSolutions, fAllowLookup, dns_lookup_function); } std::optional<CNetAddr> LookupHost(const std::string& name, bool fAllowLookup, DNSLookupFn dns_lookup_function) { const std::vector<CNetAddr> addresses{LookupHost(name, 1, fAllowLookup, dns_lookup_function)}; return addresses.empty() ? std::nullopt : std::make_optional(addresses.front()); } std::vector<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function) { if (name.empty() || !ContainsNoNUL(name)) { return {}; } uint16_t port{portDefault}; std::string hostname; SplitHostPort(name, port, hostname); const std::vector<CNetAddr> addresses{LookupIntern(hostname, nMaxSolutions, fAllowLookup, dns_lookup_function)}; if (addresses.empty()) return {}; std::vector<CService> services; services.reserve(addresses.size()); for (const auto& addr : addresses) services.emplace_back(addr, port); return services; } std::optional<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, DNSLookupFn dns_lookup_function) { const std::vector<CService> services{Lookup(name, portDefault, fAllowLookup, 1, dns_lookup_function)}; return services.empty() ? std::nullopt : std::make_optional(services.front()); } CService LookupNumeric(const std::string& name, uint16_t portDefault, DNSLookupFn dns_lookup_function) { if (!ContainsNoNUL(name)) { return {}; } // "1.2:345" will fail to resolve the ip, but will still set the port. // If the ip fails to resolve, re-init the result. return Lookup(name, portDefault, /*fAllowLookup=*/false, dns_lookup_function).value_or(CService{}); } /** SOCKS version */ enum SOCKSVersion: uint8_t { SOCKS4 = 0x04, SOCKS5 = 0x05 }; /** Values defined for METHOD in RFC1928 */ enum SOCKS5Method: uint8_t { NOAUTH = 0x00, //!< No authentication required GSSAPI = 0x01, //!< GSSAPI USER_PASS = 0x02, //!< Username/password NO_ACCEPTABLE = 0xff, //!< No acceptable methods }; /** Values defined for CMD in RFC1928 */ enum SOCKS5Command: uint8_t { CONNECT = 0x01, BIND = 0x02, UDP_ASSOCIATE = 0x03 }; /** Values defined for REP in RFC1928 */ enum SOCKS5Reply: uint8_t { SUCCEEDED = 0x00, //!< Succeeded GENFAILURE = 0x01, //!< General failure NOTALLOWED = 0x02, //!< Connection not allowed by ruleset NETUNREACHABLE = 0x03, //!< Network unreachable HOSTUNREACHABLE = 0x04, //!< Network unreachable CONNREFUSED = 0x05, //!< Connection refused TTLEXPIRED = 0x06, //!< TTL expired CMDUNSUPPORTED = 0x07, //!< Command not supported ATYPEUNSUPPORTED = 0x08, //!< Address type not supported }; /** Values defined for ATYPE in RFC1928 */ enum SOCKS5Atyp: uint8_t { IPV4 = 0x01, DOMAINNAME = 0x03, IPV6 = 0x04, }; /** Status codes that can be returned by InterruptibleRecv */ enum class IntrRecvError { OK, Timeout, Disconnected, NetworkError, Interrupted }; /** * Try to read a specified number of bytes from a socket. Please read the "see * also" section for more detail. * * @param data The buffer where the read bytes should be stored. * @param len The number of bytes to read into the specified buffer. * @param timeout The total timeout for this read. * @param sock The socket (has to be in non-blocking mode) from which to read bytes. * * @returns An IntrRecvError indicating the resulting status of this read. * IntrRecvError::OK only if all of the specified number of bytes were * read. * * @see This function can be interrupted by calling g_socks5_interrupt(). * Sockets can be made non-blocking with Sock::SetNonBlocking(). */ static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, std::chrono::milliseconds timeout, const Sock& sock) { auto curTime{Now<SteadyMilliseconds>()}; const auto endTime{curTime + timeout}; while (len > 0 && curTime < endTime) { ssize_t ret = sock.Recv(data, len, 0); // Optimistically try the recv first if (ret > 0) { len -= ret; data += ret; } else if (ret == 0) { // Unexpected disconnection return IntrRecvError::Disconnected; } else { // Other error or blocking int nErr = WSAGetLastError(); if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) { // Only wait at most MAX_WAIT_FOR_IO at a time, unless // we're approaching the end of the specified total timeout const auto remaining = std::chrono::milliseconds{endTime - curTime}; const auto timeout = std::min(remaining, std::chrono::milliseconds{MAX_WAIT_FOR_IO}); if (!sock.Wait(timeout, Sock::RECV)) { return IntrRecvError::NetworkError; } } else { return IntrRecvError::NetworkError; } } if (g_socks5_interrupt) { return IntrRecvError::Interrupted; } curTime = Now<SteadyMilliseconds>(); } return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout; } /** Convert SOCKS5 reply to an error message */ static std::string Socks5ErrorString(uint8_t err) { switch(err) { case SOCKS5Reply::GENFAILURE: return "general failure"; case SOCKS5Reply::NOTALLOWED: return "connection not allowed"; case SOCKS5Reply::NETUNREACHABLE: return "network unreachable"; case SOCKS5Reply::HOSTUNREACHABLE: return "host unreachable"; case SOCKS5Reply::CONNREFUSED: return "connection refused"; case SOCKS5Reply::TTLEXPIRED: return "TTL expired"; case SOCKS5Reply::CMDUNSUPPORTED: return "protocol error"; case SOCKS5Reply::ATYPEUNSUPPORTED: return "address type not supported"; default: return "unknown"; } } bool Socks5(const std::string& strDest, uint16_t port, const ProxyCredentials* auth, const Sock& sock) { try { IntrRecvError recvr; LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest); if (strDest.size() > 255) { return error("Hostname too long"); } // Construct the version identifier/method selection message std::vector<uint8_t> vSocks5Init; vSocks5Init.push_back(SOCKSVersion::SOCKS5); // We want the SOCK5 protocol if (auth) { vSocks5Init.push_back(0x02); // 2 method identifiers follow... vSocks5Init.push_back(SOCKS5Method::NOAUTH); vSocks5Init.push_back(SOCKS5Method::USER_PASS); } else { vSocks5Init.push_back(0x01); // 1 method identifier follows... vSocks5Init.push_back(SOCKS5Method::NOAUTH); } sock.SendComplete(vSocks5Init, g_socks5_recv_timeout, g_socks5_interrupt); uint8_t pchRet1[2]; if (InterruptibleRecv(pchRet1, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) { LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port); return false; } if (pchRet1[0] != SOCKSVersion::SOCKS5) { return error("Proxy failed to initialize"); } if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) { // Perform username/password authentication (as described in RFC1929) std::vector<uint8_t> vAuth; vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation if (auth->username.size() > 255 || auth->password.size() > 255) return error("Proxy username or password too long"); vAuth.push_back(auth->username.size()); vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end()); vAuth.push_back(auth->password.size()); vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end()); sock.SendComplete(vAuth, g_socks5_recv_timeout, g_socks5_interrupt); LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password); uint8_t pchRetA[2]; if (InterruptibleRecv(pchRetA, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) { return error("Error reading proxy authentication response"); } if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) { return error("Proxy authentication unsuccessful"); } } else if (pchRet1[1] == SOCKS5Method::NOAUTH) { // Perform no authentication } else { return error("Proxy requested wrong authentication method %02x", pchRet1[1]); } std::vector<uint8_t> vSocks5; vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT vSocks5.push_back(0x00); // RSV Reserved must be 0 vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end()); vSocks5.push_back((port >> 8) & 0xFF); vSocks5.push_back((port >> 0) & 0xFF); sock.SendComplete(vSocks5, g_socks5_recv_timeout, g_socks5_interrupt); uint8_t pchRet2[4]; if ((recvr = InterruptibleRecv(pchRet2, 4, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) { if (recvr == IntrRecvError::Timeout) { /* If a timeout happens here, this effectively means we timed out while connecting * to the remote node. This is very common for Tor, so do not print an * error message. */ return false; } else { return error("Error while reading proxy response"); } } if (pchRet2[0] != SOCKSVersion::SOCKS5) { return error("Proxy failed to accept request"); } if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) { // Failures to connect to a peer that are not proxy errors LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1])); return false; } if (pchRet2[2] != 0x00) { // Reserved field must be 0 return error("Error: malformed proxy response"); } uint8_t pchRet3[256]; switch (pchRet2[3]) { case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, g_socks5_recv_timeout, sock); break; case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, g_socks5_recv_timeout, sock); break; case SOCKS5Atyp::DOMAINNAME: { recvr = InterruptibleRecv(pchRet3, 1, g_socks5_recv_timeout, sock); if (recvr != IntrRecvError::OK) { return error("Error reading from proxy"); } int nRecv = pchRet3[0]; recvr = InterruptibleRecv(pchRet3, nRecv, g_socks5_recv_timeout, sock); break; } default: return error("Error: malformed proxy response"); } if (recvr != IntrRecvError::OK) { return error("Error reading from proxy"); } if (InterruptibleRecv(pchRet3, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) { return error("Error reading from proxy"); } LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest); return true; } catch (const std::runtime_error& e) { return error("Error during SOCKS5 proxy handshake: %s", e.what()); } } std::unique_ptr<Sock> CreateSockTCP(const CService& address_family) { // Create a sockaddr from the specified service. struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!address_family.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { LogPrintf("Cannot create socket for %s: unsupported network\n", address_family.ToStringAddrPort()); return nullptr; } // Create a TCP socket in the address family of the specified service. SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hSocket == INVALID_SOCKET) { return nullptr; } auto sock = std::make_unique<Sock>(hSocket); // Ensure that waiting for I/O on this socket won't result in undefined // behavior. if (!sock->IsSelectable()) { LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n"); return nullptr; } #ifdef SO_NOSIGPIPE int set = 1; // Set the no-sigpipe option on the socket for BSD systems, other UNIXes // should use the MSG_NOSIGNAL flag for every send. if (sock->SetSockOpt(SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int)) == SOCKET_ERROR) { LogPrintf("Error setting SO_NOSIGPIPE on socket: %s, continuing anyway\n", NetworkErrorString(WSAGetLastError())); } #endif // Set the no-delay option (disable Nagle's algorithm) on the TCP socket. const int on{1}; if (sock->SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) == SOCKET_ERROR) { LogPrint(BCLog::NET, "Unable to set TCP_NODELAY on a newly created socket, continuing anyway\n"); } // Set the non-blocking option on the socket. if (!sock->SetNonBlocking()) { LogPrintf("Error setting socket to non-blocking: %s\n", NetworkErrorString(WSAGetLastError())); return nullptr; } return sock; } std::function<std::unique_ptr<Sock>(const CService&)> CreateSock = CreateSockTCP; template<typename... Args> static void LogConnectFailure(bool manual_connection, const char* fmt, const Args&... args) { std::string error_message = tfm::format(fmt, args...); if (manual_connection) { LogPrintf("%s\n", error_message); } else { LogPrint(BCLog::NET, "%s\n", error_message); } } bool ConnectSocketDirectly(const CService &addrConnect, const Sock& sock, int nTimeout, bool manual_connection) { // Create a sockaddr from the specified service. struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToStringAddrPort()); return false; } // Connect to the addrConnect service on the hSocket socket. if (sock.Connect(reinterpret_cast<struct sockaddr*>(&sockaddr), len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); // WSAEINVAL is here because some legacy version of winsock uses it if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) { // Connection didn't actually fail, but is being established // asynchronously. Thus, use async I/O api (select/poll) // synchronously to check for successful connection with a timeout. const Sock::Event requested = Sock::RECV | Sock::SEND; Sock::Event occurred; if (!sock.Wait(std::chrono::milliseconds{nTimeout}, requested, &occurred)) { LogPrintf("wait for connect to %s failed: %s\n", addrConnect.ToStringAddrPort(), NetworkErrorString(WSAGetLastError())); return false; } else if (occurred == 0) { LogPrint(BCLog::NET, "connection attempt to %s timed out\n", addrConnect.ToStringAddrPort()); return false; } // Even if the wait was successful, the connect might not // have been successful. The reason for this failure is hidden away // in the SO_ERROR for the socket in modern systems. We read it into // sockerr here. int sockerr; socklen_t sockerr_len = sizeof(sockerr); if (sock.GetSockOpt(SOL_SOCKET, SO_ERROR, (sockopt_arg_type)&sockerr, &sockerr_len) == SOCKET_ERROR) { LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToStringAddrPort(), NetworkErrorString(WSAGetLastError())); return false; } if (sockerr != 0) { LogConnectFailure(manual_connection, "connect() to %s failed after wait: %s", addrConnect.ToStringAddrPort(), NetworkErrorString(sockerr)); return false; } } #ifdef WIN32 else if (WSAGetLastError() != WSAEISCONN) #else else #endif { LogConnectFailure(manual_connection, "connect() to %s failed: %s", addrConnect.ToStringAddrPort(), NetworkErrorString(WSAGetLastError())); return false; } } return true; } bool SetProxy(enum Network net, const Proxy &addrProxy) { assert(net >= 0 && net < NET_MAX); if (!addrProxy.IsValid()) return false; LOCK(g_proxyinfo_mutex); proxyInfo[net] = addrProxy; return true; } bool GetProxy(enum Network net, Proxy &proxyInfoOut) { assert(net >= 0 && net < NET_MAX); LOCK(g_proxyinfo_mutex); if (!proxyInfo[net].IsValid()) return false; proxyInfoOut = proxyInfo[net]; return true; } bool SetNameProxy(const Proxy &addrProxy) { if (!addrProxy.IsValid()) return false; LOCK(g_proxyinfo_mutex); nameProxy = addrProxy; return true; } bool GetNameProxy(Proxy &nameProxyOut) { LOCK(g_proxyinfo_mutex); if(!nameProxy.IsValid()) return false; nameProxyOut = nameProxy; return true; } bool HaveNameProxy() { LOCK(g_proxyinfo_mutex); return nameProxy.IsValid(); } bool IsProxy(const CNetAddr &addr) { LOCK(g_proxyinfo_mutex); for (int i = 0; i < NET_MAX; i++) { if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy)) return true; } return false; } bool ConnectThroughProxy(const Proxy& proxy, const std::string& strDest, uint16_t port, const Sock& sock, int nTimeout, bool& outProxyConnectionFailed) { // first connect to proxy server if (!ConnectSocketDirectly(proxy.proxy, sock, nTimeout, true)) { outProxyConnectionFailed = true; return false; } // do socks negotiation if (proxy.randomize_credentials) { ProxyCredentials random_auth; static std::atomic_int counter(0); random_auth.username = random_auth.password = strprintf("%i", counter++); if (!Socks5(strDest, port, &random_auth, sock)) { return false; } } else { if (!Socks5(strDest, port, nullptr, sock)) { return false; } } return true; } CSubNet LookupSubNet(const std::string& subnet_str) { CSubNet subnet; assert(!subnet.IsValid()); if (!ContainsNoNUL(subnet_str)) { return subnet; } const size_t slash_pos{subnet_str.find_last_of('/')}; const std::string str_addr{subnet_str.substr(0, slash_pos)}; std::optional<CNetAddr> addr{LookupHost(str_addr, /*fAllowLookup=*/false)}; if (addr.has_value()) { addr = static_cast<CNetAddr>(MaybeFlipIPv6toCJDNS(CService{addr.value(), /*port=*/0})); if (slash_pos != subnet_str.npos) { const std::string netmask_str{subnet_str.substr(slash_pos + 1)}; uint8_t netmask; if (ParseUInt8(netmask_str, &netmask)) { // Valid number; assume CIDR variable-length subnet masking. subnet = CSubNet{addr.value(), netmask}; } else { // Invalid number; try full netmask syntax. Never allow lookup for netmask. const std::optional<CNetAddr> full_netmask{LookupHost(netmask_str, /*fAllowLookup=*/false)}; if (full_netmask.has_value()) { subnet = CSubNet{addr.value(), full_netmask.value()}; } } } else { // Single IP subnet (<ipv4>/32 or <ipv6>/128). subnet = CSubNet{addr.value()}; } } return subnet; } bool IsBadPort(uint16_t port) { /* Don't forget to update doc/p2p-bad-ports.md if you change this list. */ switch (port) { case 1: // tcpmux case 7: // echo case 9: // discard case 11: // systat case 13: // daytime case 15: // netstat case 17: // qotd case 19: // chargen case 20: // ftp data case 21: // ftp access case 22: // ssh case 23: // telnet case 25: // smtp case 37: // time case 42: // name case 43: // nicname case 53: // domain case 69: // tftp case 77: // priv-rjs case 79: // finger case 87: // ttylink case 95: // supdup case 101: // hostname case 102: // iso-tsap case 103: // gppitnp case 104: // acr-nema case 109: // pop2 case 110: // pop3 case 111: // sunrpc case 113: // auth case 115: // sftp case 117: // uucp-path case 119: // nntp case 123: // NTP case 135: // loc-srv /epmap case 137: // netbios case 139: // netbios case 143: // imap2 case 161: // snmp case 179: // BGP case 389: // ldap case 427: // SLP (Also used by Apple Filing Protocol) case 465: // smtp+ssl case 512: // print / exec case 513: // login case 514: // shell case 515: // printer case 526: // tempo case 530: // courier case 531: // chat case 532: // netnews case 540: // uucp case 548: // AFP (Apple Filing Protocol) case 554: // rtsp case 556: // remotefs case 563: // nntp+ssl case 587: // smtp (rfc6409) case 601: // syslog-conn (rfc3195) case 636: // ldap+ssl case 989: // ftps-data case 990: // ftps case 993: // ldap+ssl case 995: // pop3+ssl case 1719: // h323gatestat case 1720: // h323hostcall case 1723: // pptp case 2049: // nfs case 3659: // apple-sasl / PasswordServer case 4045: // lockd case 5060: // sip case 5061: // sips case 6000: // X11 case 6566: // sane-port case 6665: // Alternate IRC case 6666: // Alternate IRC case 6667: // Standard IRC case 6668: // Alternate IRC case 6669: // Alternate IRC case 6697: // IRC + TLS case 10080: // Amanda return true; } return false; } CService MaybeFlipIPv6toCJDNS(const CService& service) { CService ret{service}; if (ret.IsIPv6() && ret.HasCJDNSPrefix() && g_reachable_nets.Contains(NET_CJDNS)) { ret.m_net = NET_CJDNS; } return ret; }
0
bitcoin
bitcoin/src/deploymentinfo.h
// Copyright (c) 2016-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_DEPLOYMENTINFO_H #define BITCOIN_DEPLOYMENTINFO_H #include <consensus/params.h> #include <optional> #include <string> struct VBDeploymentInfo { /** Deployment name */ const char *name; /** Whether GBT clients can safely ignore this rule in simplified usage */ bool gbt_force; }; extern const VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]; std::string DeploymentName(Consensus::BuriedDeployment dep); inline std::string DeploymentName(Consensus::DeploymentPos pos) { assert(Consensus::ValidDeployment(pos)); return VersionBitsDeploymentInfo[pos].name; } std::optional<Consensus::BuriedDeployment> GetBuriedDeployment(const std::string_view deployment_name); #endif // BITCOIN_DEPLOYMENTINFO_H
0
bitcoin
bitcoin/src/cuckoocache.h
// Copyright (c) 2016 Jeremy Rubin // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CUCKOOCACHE_H #define BITCOIN_CUCKOOCACHE_H #include <util/fastrange.h> #include <algorithm> // std::find #include <array> #include <atomic> #include <cmath> #include <cstring> #include <limits> #include <memory> #include <optional> #include <utility> #include <vector> /** High-performance cache primitives. * * Summary: * * 1. @ref bit_packed_atomic_flags is bit-packed atomic flags for garbage collection * * 2. @ref cache is a cache which is performant in memory usage and lookup speed. It * is lockfree for erase operations. Elements are lazily erased on the next insert. */ namespace CuckooCache { /** @ref bit_packed_atomic_flags implements a container for garbage collection flags * that is only thread unsafe on calls to setup. This class bit-packs collection * flags for memory efficiency. * * All operations are `std::memory_order_relaxed` so external mechanisms must * ensure that writes and reads are properly synchronized. * * On setup(n), all bits up to `n` are marked as collected. * * Under the hood, because it is an 8-bit type, it makes sense to use a multiple * of 8 for setup, but it will be safe if that is not the case as well. */ class bit_packed_atomic_flags { std::unique_ptr<std::atomic<uint8_t>[]> mem; public: /** No default constructor, as there must be some size. */ bit_packed_atomic_flags() = delete; /** * bit_packed_atomic_flags constructor creates memory to sufficiently * keep track of garbage collection information for `size` entries. * * @param size the number of elements to allocate space for * * @post bit_set, bit_unset, and bit_is_set function properly forall x. x < * size * @post All calls to bit_is_set (without subsequent bit_unset) will return * true. */ explicit bit_packed_atomic_flags(uint32_t size) { // pad out the size if needed size = (size + 7) / 8; mem.reset(new std::atomic<uint8_t>[size]); for (uint32_t i = 0; i < size; ++i) mem[i].store(0xFF); }; /** setup marks all entries and ensures that bit_packed_atomic_flags can store * at least `b` entries. * * @param b the number of elements to allocate space for * @post bit_set, bit_unset, and bit_is_set function properly forall x. x < * b * @post All calls to bit_is_set (without subsequent bit_unset) will return * true. */ inline void setup(uint32_t b) { bit_packed_atomic_flags d(b); std::swap(mem, d.mem); } /** bit_set sets an entry as discardable. * * @param s the index of the entry to bit_set * @post immediately subsequent call (assuming proper external memory * ordering) to bit_is_set(s) == true. */ inline void bit_set(uint32_t s) { mem[s >> 3].fetch_or(uint8_t(1 << (s & 7)), std::memory_order_relaxed); } /** bit_unset marks an entry as something that should not be overwritten. * * @param s the index of the entry to bit_unset * @post immediately subsequent call (assuming proper external memory * ordering) to bit_is_set(s) == false. */ inline void bit_unset(uint32_t s) { mem[s >> 3].fetch_and(uint8_t(~(1 << (s & 7))), std::memory_order_relaxed); } /** bit_is_set queries the table for discardability at `s`. * * @param s the index of the entry to read * @returns true if the bit at index `s` was set, false otherwise * */ inline bool bit_is_set(uint32_t s) const { return (1 << (s & 7)) & mem[s >> 3].load(std::memory_order_relaxed); } }; /** @ref cache implements a cache with properties similar to a cuckoo-set. * * The cache is able to hold up to `(~(uint32_t)0) - 1` elements. * * Read Operations: * - contains() for `erase=false` * * Read+Erase Operations: * - contains() for `erase=true` * * Erase Operations: * - allow_erase() * * Write Operations: * - setup() * - setup_bytes() * - insert() * - please_keep() * * Synchronization Free Operations: * - invalid() * - compute_hashes() * * User Must Guarantee: * * 1. Write requires synchronized access (e.g. a lock) * 2. Read requires no concurrent Write, synchronized with last insert. * 3. Erase requires no concurrent Write, synchronized with last insert. * 4. An Erase caller must release all memory before allowing a new Writer. * * * Note on function names: * - The name "allow_erase" is used because the real discard happens later. * - The name "please_keep" is used because elements may be erased anyways on insert. * * @tparam Element should be a movable and copyable type * @tparam Hash should be a function/callable which takes a template parameter * hash_select and an Element and extracts a hash from it. Should return * high-entropy uint32_t hashes for `Hash h; h<0>(e) ... h<7>(e)`. */ template <typename Element, typename Hash> class cache { private: /** table stores all the elements */ std::vector<Element> table; /** size stores the total available slots in the hash table */ uint32_t size{0}; /** The bit_packed_atomic_flags array is marked mutable because we want * garbage collection to be allowed to occur from const methods */ mutable bit_packed_atomic_flags collection_flags; /** epoch_flags tracks how recently an element was inserted into * the cache. true denotes recent, false denotes not-recent. See insert() * method for full semantics. */ mutable std::vector<bool> epoch_flags; /** epoch_heuristic_counter is used to determine when an epoch might be aged * & an expensive scan should be done. epoch_heuristic_counter is * decremented on insert and reset to the new number of inserts which would * cause the epoch to reach epoch_size when it reaches zero. */ uint32_t epoch_heuristic_counter{0}; /** epoch_size is set to be the number of elements supposed to be in a * epoch. When the number of non-erased elements in an epoch * exceeds epoch_size, a new epoch should be started and all * current entries demoted. epoch_size is set to be 45% of size because * we want to keep load around 90%, and we support 3 epochs at once -- * one "dead" which has been erased, one "dying" which has been marked to be * erased next, and one "living" which new inserts add to. */ uint32_t epoch_size{0}; /** depth_limit determines how many elements insert should try to replace. * Should be set to log2(n). */ uint8_t depth_limit{0}; /** hash_function is a const instance of the hash function. It cannot be * static or initialized at call time as it may have internal state (such as * a nonce). */ const Hash hash_function; /** compute_hashes is convenience for not having to write out this * expression everywhere we use the hash values of an Element. * * We need to map the 32-bit input hash onto a hash bucket in a range [0, size) in a * manner which preserves as much of the hash's uniformity as possible. Ideally * this would be done by bitmasking but the size is usually not a power of two. * * The naive approach would be to use a mod -- which isn't perfectly uniform but so * long as the hash is much larger than size it is not that bad. Unfortunately, * mod/division is fairly slow on ordinary microprocessors (e.g. 90-ish cycles on * haswell, ARM doesn't even have an instruction for it.); when the divisor is a * constant the compiler will do clever tricks to turn it into a multiply+add+shift, * but size is a run-time value so the compiler can't do that here. * * One option would be to implement the same trick the compiler uses and compute the * constants for exact division based on the size, as described in "{N}-bit Unsigned * Division via {N}-bit Multiply-Add" by Arch D. Robison in 2005. But that code is * somewhat complicated and the result is still slower than an even simpler option: * see the FastRange32 function in util/fastrange.h. * * The resulting non-uniformity is also more equally distributed which would be * advantageous for something like linear probing, though it shouldn't matter * one way or the other for a cuckoo table. * * The primary disadvantage of this approach is increased intermediate precision is * required but for a 32-bit random number we only need the high 32 bits of a * 32*32->64 multiply, which means the operation is reasonably fast even on a * typical 32-bit processor. * * @param e The element whose hashes will be returned * @returns Deterministic hashes derived from `e` uniformly mapped onto the range [0, size) */ inline std::array<uint32_t, 8> compute_hashes(const Element& e) const { return {{FastRange32(hash_function.template operator()<0>(e), size), FastRange32(hash_function.template operator()<1>(e), size), FastRange32(hash_function.template operator()<2>(e), size), FastRange32(hash_function.template operator()<3>(e), size), FastRange32(hash_function.template operator()<4>(e), size), FastRange32(hash_function.template operator()<5>(e), size), FastRange32(hash_function.template operator()<6>(e), size), FastRange32(hash_function.template operator()<7>(e), size)}}; } /** invalid returns a special index that can never be inserted to * @returns the special constexpr index that can never be inserted to */ constexpr uint32_t invalid() const { return ~(uint32_t)0; } /** allow_erase marks the element at index `n` as discardable. Threadsafe * without any concurrent insert. * @param n the index to allow erasure of */ inline void allow_erase(uint32_t n) const { collection_flags.bit_set(n); } /** please_keep marks the element at index `n` as an entry that should be kept. * Threadsafe without any concurrent insert. * @param n the index to prioritize keeping */ inline void please_keep(uint32_t n) const { collection_flags.bit_unset(n); } /** epoch_check handles the changing of epochs for elements stored in the * cache. epoch_check should be run before every insert. * * First, epoch_check decrements and checks the cheap heuristic, and then does * a more expensive scan if the cheap heuristic runs out. If the expensive * scan succeeds, the epochs are aged and old elements are allow_erased. The * cheap heuristic is reset to retrigger after the worst case growth of the * current epoch's elements would exceed the epoch_size. */ void epoch_check() { if (epoch_heuristic_counter != 0) { --epoch_heuristic_counter; return; } // count the number of elements from the latest epoch which // have not been erased. uint32_t epoch_unused_count = 0; for (uint32_t i = 0; i < size; ++i) epoch_unused_count += epoch_flags[i] && !collection_flags.bit_is_set(i); // If there are more non-deleted entries in the current epoch than the // epoch size, then allow_erase on all elements in the old epoch (marked // false) and move all elements in the current epoch to the old epoch // but do not call allow_erase on their indices. if (epoch_unused_count >= epoch_size) { for (uint32_t i = 0; i < size; ++i) if (epoch_flags[i]) epoch_flags[i] = false; else allow_erase(i); epoch_heuristic_counter = epoch_size; } else // reset the epoch_heuristic_counter to next do a scan when worst // case behavior (no intermittent erases) would exceed epoch size, // with a reasonable minimum scan size. // Ordinarily, we would have to sanity check std::min(epoch_size, // epoch_unused_count), but we already know that `epoch_unused_count // < epoch_size` in this branch epoch_heuristic_counter = std::max(1u, std::max(epoch_size / 16, epoch_size - epoch_unused_count)); } public: /** You must always construct a cache with some elements via a subsequent * call to setup or setup_bytes, otherwise operations may segfault. */ cache() : table(), collection_flags(0), epoch_flags(), hash_function() { } /** setup initializes the container to store no more than new_size * elements and no less than 2 elements. * * setup should only be called once. * * @param new_size the desired number of elements to store * @returns the maximum number of elements storable */ uint32_t setup(uint32_t new_size) { // depth_limit must be at least one otherwise errors can occur. size = std::max<uint32_t>(2, new_size); depth_limit = static_cast<uint8_t>(std::log2(static_cast<float>(size))); table.resize(size); collection_flags.setup(size); epoch_flags.resize(size); // Set to 45% as described above epoch_size = std::max(uint32_t{1}, (45 * size) / 100); // Initially set to wait for a whole epoch epoch_heuristic_counter = epoch_size; return size; } /** setup_bytes is a convenience function which accounts for internal memory * usage when deciding how many elements to store. It isn't perfect because * it doesn't account for any overhead (struct size, MallocUsage, collection * and epoch flags). This was done to simplify selecting a power of two * size. In the expected use case, an extra two bits per entry should be * negligible compared to the size of the elements. * * @param bytes the approximate number of bytes to use for this data * structure * @returns A pair of the maximum number of elements storable (see setup() * documentation for more detail) and the approxmiate total size of these * elements in bytes or std::nullopt if the size requested is too large. */ std::optional<std::pair<uint32_t, size_t>> setup_bytes(size_t bytes) { size_t requested_num_elems = bytes / sizeof(Element); if (std::numeric_limits<uint32_t>::max() < requested_num_elems) { return std::nullopt; } auto num_elems = setup(bytes/sizeof(Element)); size_t approx_size_bytes = num_elems * sizeof(Element); return std::make_pair(num_elems, approx_size_bytes); } /** insert loops at most depth_limit times trying to insert a hash * at various locations in the table via a variant of the Cuckoo Algorithm * with eight hash locations. * * It drops the last tried element if it runs out of depth before * encountering an open slot. * * Thus: * * ``` * insert(x); * return contains(x, false); * ``` * * is not guaranteed to return true. * * @param e the element to insert * @post one of the following: All previously inserted elements and e are * now in the table, one previously inserted element is evicted from the * table, the entry attempted to be inserted is evicted. */ inline void insert(Element e) { epoch_check(); uint32_t last_loc = invalid(); bool last_epoch = true; std::array<uint32_t, 8> locs = compute_hashes(e); // Make sure we have not already inserted this element // If we have, make sure that it does not get deleted for (const uint32_t loc : locs) if (table[loc] == e) { please_keep(loc); epoch_flags[loc] = last_epoch; return; } for (uint8_t depth = 0; depth < depth_limit; ++depth) { // First try to insert to an empty slot, if one exists for (const uint32_t loc : locs) { if (!collection_flags.bit_is_set(loc)) continue; table[loc] = std::move(e); please_keep(loc); epoch_flags[loc] = last_epoch; return; } /** Swap with the element at the location that was * not the last one looked at. Example: * * 1. On first iteration, last_loc == invalid(), find returns last, so * last_loc defaults to locs[0]. * 2. On further iterations, where last_loc == locs[k], last_loc will * go to locs[k+1 % 8], i.e., next of the 8 indices wrapping around * to 0 if needed. * * This prevents moving the element we just put in. * * The swap is not a move -- we must switch onto the evicted element * for the next iteration. */ last_loc = locs[(1 + (std::find(locs.begin(), locs.end(), last_loc) - locs.begin())) & 7]; std::swap(table[last_loc], e); // Can't std::swap a std::vector<bool>::reference and a bool&. bool epoch = last_epoch; last_epoch = epoch_flags[last_loc]; epoch_flags[last_loc] = epoch; // Recompute the locs -- unfortunately happens one too many times! locs = compute_hashes(e); } } /** contains iterates through the hash locations for a given element * and checks to see if it is present. * * contains does not check garbage collected state (in other words, * garbage is only collected when the space is needed), so: * * ``` * insert(x); * if (contains(x, true)) * return contains(x, false); * else * return true; * ``` * * executed on a single thread will always return true! * * This is a great property for re-org performance for example. * * contains returns a bool set true if the element was found. * * @param e the element to check * @param erase whether to attempt setting the garbage collect flag * * @post if erase is true and the element is found, then the garbage collect * flag is set * @returns true if the element is found, false otherwise */ inline bool contains(const Element& e, const bool erase) const { std::array<uint32_t, 8> locs = compute_hashes(e); for (const uint32_t loc : locs) if (table[loc] == e) { if (erase) allow_erase(loc); return true; } return false; } }; } // namespace CuckooCache #endif // BITCOIN_CUCKOOCACHE_H
0
bitcoin
bitcoin/src/.clang-format
Language: Cpp AccessModifierOffset: -4 AlignAfterOpenBracket: true AlignEscapedNewlinesLeft: true AlignTrailingComments: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: true AllowShortFunctionsOnASingleLine: All AllowShortIfStatementsOnASingleLine: true AllowShortLoopsOnASingleLine: false AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: true BinPackArguments: true BinPackParameters: true BreakBeforeBinaryOperators: false BreakBeforeBraces: Custom BraceWrapping: AfterClass: true AfterFunction: true BreakBeforeTernaryOperators: false BreakConstructorInitializersBeforeComma: false ColumnLimit: 0 CommentPragmas: '^ IWYU pragma:' ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: true DerivePointerAlignment: false DisableFormat: false IndentCaseLabels: false IndentFunctionDeclarationAfterType: false IndentWidth: 4 KeepEmptyLinesAtTheStartOfBlocks: false MaxEmptyLinesToKeep: 2 NamespaceIndentation: None PointerAlignment: Left SpaceBeforeAssignmentOperators: true SpaceBeforeParens: ControlStatements SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpacesInContainerLiterals: true SpacesInCStyleCastParentheses: false SpacesInParentheses: false BreakBeforeConceptDeclarations: Always RequiresExpressionIndentation: OuterScope Standard: c++20 UseTab: Never
0
bitcoin
bitcoin/src/undo.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UNDO_H #define BITCOIN_UNDO_H #include <coins.h> #include <compressor.h> #include <consensus/consensus.h> #include <primitives/transaction.h> #include <serialize.h> /** Formatter for undo information for a CTxIn * * Contains the prevout's CTxOut being spent, and its metadata as well * (coinbase or not, height). The serialization contains a dummy value of * zero. This is compatible with older versions which expect to see * the transaction version there. */ struct TxInUndoFormatter { template<typename Stream> void Ser(Stream &s, const Coin& txout) { ::Serialize(s, VARINT(txout.nHeight * uint32_t{2} + txout.fCoinBase )); if (txout.nHeight > 0) { // Required to maintain compatibility with older undo format. ::Serialize(s, (unsigned char)0); } ::Serialize(s, Using<TxOutCompression>(txout.out)); } template<typename Stream> void Unser(Stream &s, Coin& txout) { uint32_t nCode = 0; ::Unserialize(s, VARINT(nCode)); txout.nHeight = nCode >> 1; txout.fCoinBase = nCode & 1; if (txout.nHeight > 0) { // Old versions stored the version number for the last spend of // a transaction's outputs. Non-final spends were indicated with // height = 0. unsigned int nVersionDummy; ::Unserialize(s, VARINT(nVersionDummy)); } ::Unserialize(s, Using<TxOutCompression>(txout.out)); } }; /** Undo information for a CTransaction */ class CTxUndo { public: // undo information for all txins std::vector<Coin> vprevout; SERIALIZE_METHODS(CTxUndo, obj) { READWRITE(Using<VectorFormatter<TxInUndoFormatter>>(obj.vprevout)); } }; /** Undo information for a CBlock */ class CBlockUndo { public: std::vector<CTxUndo> vtxundo; // for all but the coinbase SERIALIZE_METHODS(CBlockUndo, obj) { READWRITE(obj.vtxundo); } }; #endif // BITCOIN_UNDO_H
0
bitcoin
bitcoin/src/bech32.cpp
// Copyright (c) 2017, 2021 Pieter Wuille // Copyright (c) 2021-2022 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 <bech32.h> #include <util/vector.h> #include <array> #include <assert.h> #include <numeric> #include <optional> namespace bech32 { namespace { typedef std::vector<uint8_t> data; /** The Bech32 and Bech32m character set for encoding. */ const char* CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; /** The Bech32 and Bech32m character set for decoding. */ const int8_t CHARSET_REV[128] = { -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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, 10, 17, 21, 20, 26, 30, 7, 5, -1, -1, -1, -1, -1, -1, -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1, -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1 }; /** We work with the finite field GF(1024) defined as a degree 2 extension of the base field GF(32) * The defining polynomial of the extension is x^2 + 9x + 23. * Let (e) be a root of this defining polynomial. Then (e) is a primitive element of GF(1024), * that is, a generator of the field. Every non-zero element of the field can then be represented * as (e)^k for some power k. * The array GF1024_EXP contains all these powers of (e) - GF1024_EXP[k] = (e)^k in GF(1024). * Conversely, GF1024_LOG contains the discrete logarithms of these powers, so * GF1024_LOG[GF1024_EXP[k]] == k. * The following function generates the two tables GF1024_EXP and GF1024_LOG as constexprs. */ constexpr std::pair<std::array<int16_t, 1023>, std::array<int16_t, 1024>> GenerateGFTables() { // Build table for GF(32). // We use these tables to perform arithmetic in GF(32) below, when constructing the // tables for GF(1024). std::array<int8_t, 31> GF32_EXP{}; std::array<int8_t, 32> GF32_LOG{}; // fmod encodes the defining polynomial of GF(32) over GF(2), x^5 + x^3 + 1. // Because coefficients in GF(2) are binary digits, the coefficients are packed as 101001. const int fmod = 41; // Elements of GF(32) are encoded as vectors of length 5 over GF(2), that is, // 5 binary digits. Each element (b_4, b_3, b_2, b_1, b_0) encodes a polynomial // b_4*x^4 + b_3*x^3 + b_2*x^2 + b_1*x^1 + b_0 (modulo fmod). // For example, 00001 = 1 is the multiplicative identity. GF32_EXP[0] = 1; GF32_LOG[0] = -1; GF32_LOG[1] = 0; int v = 1; for (int i = 1; i < 31; ++i) { // Multiplication by x is the same as shifting left by 1, as // every coefficient of the polynomial is moved up one place. v = v << 1; // If the polynomial now has an x^5 term, we subtract fmod from it // to remain working modulo fmod. Subtraction is the same as XOR in characteristic // 2 fields. if (v & 32) v ^= fmod; GF32_EXP[i] = v; GF32_LOG[v] = i; } // Build table for GF(1024) std::array<int16_t, 1023> GF1024_EXP{}; std::array<int16_t, 1024> GF1024_LOG{}; GF1024_EXP[0] = 1; GF1024_LOG[0] = -1; GF1024_LOG[1] = 0; // Each element v of GF(1024) is encoded as a 10 bit integer in the following way: // v = v1 || v0 where v0, v1 are 5-bit integers (elements of GF(32)). // The element (e) is encoded as 1 || 0, to represent 1*(e) + 0. Every other element // a*(e) + b is represented as a || b (a and b are both GF(32) elements). Given (v), // we compute (e)*(v) by multiplying in the following way: // // v0' = 23*v1 // v1' = 9*v1 + v0 // e*v = v1' || v0' // // Where 23, 9 are GF(32) elements encoded as described above. Multiplication in GF(32) // is done using the log/exp tables: // e^x * e^y = e^(x + y) so a * b = EXP[ LOG[a] + LOG [b] ] // for non-zero a and b. v = 1; for (int i = 1; i < 1023; ++i) { int v0 = v & 31; int v1 = v >> 5; int v0n = v1 ? GF32_EXP.at((GF32_LOG.at(v1) + GF32_LOG.at(23)) % 31) : 0; int v1n = (v1 ? GF32_EXP.at((GF32_LOG.at(v1) + GF32_LOG.at(9)) % 31) : 0) ^ v0; v = v1n << 5 | v0n; GF1024_EXP[i] = v; GF1024_LOG[v] = i; } return std::make_pair(GF1024_EXP, GF1024_LOG); } constexpr auto tables = GenerateGFTables(); constexpr const std::array<int16_t, 1023>& GF1024_EXP = tables.first; constexpr const std::array<int16_t, 1024>& GF1024_LOG = tables.second; /* Determine the final constant to use for the specified encoding. */ uint32_t EncodingConstant(Encoding encoding) { assert(encoding == Encoding::BECH32 || encoding == Encoding::BECH32M); return encoding == Encoding::BECH32 ? 1 : 0x2bc830a3; } /** This function will compute what 6 5-bit values to XOR into the last 6 input values, in order to * make the checksum 0. These 6 values are packed together in a single 30-bit integer. The higher * bits correspond to earlier values. */ uint32_t PolyMod(const data& v) { // The input is interpreted as a list of coefficients of a polynomial over F = GF(32), with an // implicit 1 in front. If the input is [v0,v1,v2,v3,v4], that polynomial is v(x) = // 1*x^5 + v0*x^4 + v1*x^3 + v2*x^2 + v3*x + v4. The implicit 1 guarantees that // [v0,v1,v2,...] has a distinct checksum from [0,v0,v1,v2,...]. // The output is a 30-bit integer whose 5-bit groups are the coefficients of the remainder of // v(x) mod g(x), where g(x) is the Bech32 generator, // x^6 + {29}x^5 + {22}x^4 + {20}x^3 + {21}x^2 + {29}x + {18}. g(x) is chosen in such a way // that the resulting code is a BCH code, guaranteeing detection of up to 3 errors within a // window of 1023 characters. Among the various possible BCH codes, one was selected to in // fact guarantee detection of up to 4 errors within a window of 89 characters. // Note that the coefficients are elements of GF(32), here represented as decimal numbers // between {}. In this finite field, addition is just XOR of the corresponding numbers. For // example, {27} + {13} = {27 ^ 13} = {22}. Multiplication is more complicated, and requires // treating the bits of values themselves as coefficients of a polynomial over a smaller field, // GF(2), and multiplying those polynomials mod a^5 + a^3 + 1. For example, {5} * {26} = // (a^2 + 1) * (a^4 + a^3 + a) = (a^4 + a^3 + a) * a^2 + (a^4 + a^3 + a) = a^6 + a^5 + a^4 + a // = a^3 + 1 (mod a^5 + a^3 + 1) = {9}. // During the course of the loop below, `c` contains the bitpacked coefficients of the // polynomial constructed from just the values of v that were processed so far, mod g(x). In // the above example, `c` initially corresponds to 1 mod g(x), and after processing 2 inputs of // v, it corresponds to x^2 + v0*x + v1 mod g(x). As 1 mod g(x) = 1, that is the starting value // for `c`. // The following Sage code constructs the generator used: // // B = GF(2) # Binary field // BP.<b> = B[] # Polynomials over the binary field // F_mod = b**5 + b**3 + 1 // F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition // FP.<x> = F[] # Polynomials over GF(32) // E_mod = x**2 + F.fetch_int(9)*x + F.fetch_int(23) // E.<e> = F.extension(E_mod) # GF(1024) extension field definition // for p in divisors(E.order() - 1): # Verify e has order 1023. // assert((e**p == 1) == (p % 1023 == 0)) // G = lcm([(e**i).minpoly() for i in range(997,1000)]) // print(G) # Print out the generator // // It demonstrates that g(x) is the least common multiple of the minimal polynomials // of 3 consecutive powers (997,998,999) of a primitive element (e) of GF(1024). // That guarantees it is, in fact, the generator of a primitive BCH code with cycle // length 1023 and distance 4. See https://en.wikipedia.org/wiki/BCH_code for more details. uint32_t c = 1; for (const auto v_i : v) { // We want to update `c` to correspond to a polynomial with one extra term. If the initial // value of `c` consists of the coefficients of c(x) = f(x) mod g(x), we modify it to // correspond to c'(x) = (f(x) * x + v_i) mod g(x), where v_i is the next input to // process. Simplifying: // c'(x) = (f(x) * x + v_i) mod g(x) // ((f(x) mod g(x)) * x + v_i) mod g(x) // (c(x) * x + v_i) mod g(x) // If c(x) = c0*x^5 + c1*x^4 + c2*x^3 + c3*x^2 + c4*x + c5, we want to compute // c'(x) = (c0*x^5 + c1*x^4 + c2*x^3 + c3*x^2 + c4*x + c5) * x + v_i mod g(x) // = c0*x^6 + c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i mod g(x) // = c0*(x^6 mod g(x)) + c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i // If we call (x^6 mod g(x)) = k(x), this can be written as // c'(x) = (c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i) + c0*k(x) // First, determine the value of c0: uint8_t c0 = c >> 25; // Then compute c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i: c = ((c & 0x1ffffff) << 5) ^ v_i; // Finally, for each set bit n in c0, conditionally add {2^n}k(x). These constants can be // computed using the following Sage code (continuing the code above): // // for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(g(x) mod x^6), packed in hex integers. // v = 0 // for coef in reversed((F.fetch_int(i)*(G % x**6)).coefficients(sparse=True)): // v = v*32 + coef.integer_representation() // print("0x%x" % v) // if (c0 & 1) c ^= 0x3b6a57b2; // k(x) = {29}x^5 + {22}x^4 + {20}x^3 + {21}x^2 + {29}x + {18} if (c0 & 2) c ^= 0x26508e6d; // {2}k(x) = {19}x^5 + {5}x^4 + x^3 + {3}x^2 + {19}x + {13} if (c0 & 4) c ^= 0x1ea119fa; // {4}k(x) = {15}x^5 + {10}x^4 + {2}x^3 + {6}x^2 + {15}x + {26} if (c0 & 8) c ^= 0x3d4233dd; // {8}k(x) = {30}x^5 + {20}x^4 + {4}x^3 + {12}x^2 + {30}x + {29} if (c0 & 16) c ^= 0x2a1462b3; // {16}k(x) = {21}x^5 + x^4 + {8}x^3 + {24}x^2 + {21}x + {19} } return c; } /** Syndrome computes the values s_j = R(e^j) for j in [997, 998, 999]. As described above, the * generator polynomial G is the LCM of the minimal polynomials of (e)^997, (e)^998, and (e)^999. * * Consider a codeword with errors, of the form R(x) = C(x) + E(x). The residue is the bit-packed * result of computing R(x) mod G(X), where G is the generator of the code. Because C(x) is a valid * codeword, it is a multiple of G(X), so the residue is in fact just E(x) mod G(x). Note that all * of the (e)^j are roots of G(x) by definition, so R((e)^j) = E((e)^j). * * Let R(x) = r1*x^5 + r2*x^4 + r3*x^3 + r4*x^2 + r5*x + r6 * * To compute R((e)^j), we are really computing: * r1*(e)^(j*5) + r2*(e)^(j*4) + r3*(e)^(j*3) + r4*(e)^(j*2) + r5*(e)^j + r6 * * Now note that all of the (e)^(j*i) for i in [5..0] are constants and can be precomputed. * But even more than that, we can consider each coefficient as a bit-string. * For example, take r5 = (b_5, b_4, b_3, b_2, b_1) written out as 5 bits. Then: * r5*(e)^j = b_1*(e)^j + b_2*(2*(e)^j) + b_3*(4*(e)^j) + b_4*(8*(e)^j) + b_5*(16*(e)^j) * where all the (2^i*(e)^j) are constants and can be precomputed. * * Then we just add each of these corresponding constants to our final value based on the * bit values b_i. This is exactly what is done in the Syndrome function below. */ constexpr std::array<uint32_t, 25> GenerateSyndromeConstants() { std::array<uint32_t, 25> SYNDROME_CONSTS{}; for (int k = 1; k < 6; ++k) { for (int shift = 0; shift < 5; ++shift) { int16_t b = GF1024_LOG.at(size_t{1} << shift); int16_t c0 = GF1024_EXP.at((997*k + b) % 1023); int16_t c1 = GF1024_EXP.at((998*k + b) % 1023); int16_t c2 = GF1024_EXP.at((999*k + b) % 1023); uint32_t c = c2 << 20 | c1 << 10 | c0; int ind = 5*(k-1) + shift; SYNDROME_CONSTS[ind] = c; } } return SYNDROME_CONSTS; } constexpr std::array<uint32_t, 25> SYNDROME_CONSTS = GenerateSyndromeConstants(); /** * Syndrome returns the three values s_997, s_998, and s_999 described above, * packed into a 30-bit integer, where each group of 10 bits encodes one value. */ uint32_t Syndrome(const uint32_t residue) { // low is the first 5 bits, corresponding to the r6 in the residue // (the constant term of the polynomial). uint32_t low = residue & 0x1f; // We begin by setting s_j = low = r6 for all three values of j, because these are unconditional. uint32_t result = low ^ (low << 10) ^ (low << 20); // Then for each following bit, we add the corresponding precomputed constant if the bit is 1. // For example, 0x31edd3c4 is 1100011110 1101110100 1111000100 when unpacked in groups of 10 // bits, corresponding exactly to a^999 || a^998 || a^997 (matching the corresponding values in // GF1024_EXP above). In this way, we compute all three values of s_j for j in (997, 998, 999) // simultaneously. Recall that XOR corresponds to addition in a characteristic 2 field. for (int i = 0; i < 25; ++i) { result ^= ((residue >> (5+i)) & 1 ? SYNDROME_CONSTS.at(i) : 0); } return result; } /** Convert to lower case. */ inline unsigned char LowerCase(unsigned char c) { return (c >= 'A' && c <= 'Z') ? (c - 'A') + 'a' : c; } /** Return indices of invalid characters in a Bech32 string. */ bool CheckCharacters(const std::string& str, std::vector<int>& errors) { bool lower = false, upper = false; for (size_t i = 0; i < str.size(); ++i) { unsigned char c{(unsigned char)(str[i])}; if (c >= 'a' && c <= 'z') { if (upper) { errors.push_back(i); } else { lower = true; } } else if (c >= 'A' && c <= 'Z') { if (lower) { errors.push_back(i); } else { upper = true; } } else if (c < 33 || c > 126) { errors.push_back(i); } } return errors.empty(); } /** Expand a HRP for use in checksum computation. */ data ExpandHRP(const std::string& hrp) { data ret; ret.reserve(hrp.size() + 90); ret.resize(hrp.size() * 2 + 1); for (size_t i = 0; i < hrp.size(); ++i) { unsigned char c = hrp[i]; ret[i] = c >> 5; ret[i + hrp.size() + 1] = c & 0x1f; } ret[hrp.size()] = 0; return ret; } /** Verify a checksum. */ Encoding VerifyChecksum(const std::string& hrp, const data& values) { // PolyMod computes what value to xor into the final values to make the checksum 0. However, // if we required that the checksum was 0, it would be the case that appending a 0 to a valid // list of values would result in a new valid list. For that reason, Bech32 requires the // resulting checksum to be 1 instead. In Bech32m, this constant was amended. See // https://gist.github.com/sipa/14c248c288c3880a3b191f978a34508e for details. const uint32_t check = PolyMod(Cat(ExpandHRP(hrp), values)); if (check == EncodingConstant(Encoding::BECH32)) return Encoding::BECH32; if (check == EncodingConstant(Encoding::BECH32M)) return Encoding::BECH32M; return Encoding::INVALID; } /** Create a checksum. */ data CreateChecksum(Encoding encoding, const std::string& hrp, const data& values) { data enc = Cat(ExpandHRP(hrp), values); enc.resize(enc.size() + 6); // Append 6 zeroes uint32_t mod = PolyMod(enc) ^ EncodingConstant(encoding); // Determine what to XOR into those 6 zeroes. data ret(6); for (size_t i = 0; i < 6; ++i) { // Convert the 5-bit groups in mod to checksum values. ret[i] = (mod >> (5 * (5 - i))) & 31; } return ret; } } // namespace /** Encode a Bech32 or Bech32m string. */ std::string Encode(Encoding encoding, const std::string& hrp, const data& values) { // First ensure that the HRP is all lowercase. BIP-173 and BIP350 require an encoder // to return a lowercase Bech32/Bech32m string, but if given an uppercase HRP, the // result will always be invalid. for (const char& c : hrp) assert(c < 'A' || c > 'Z'); data checksum = CreateChecksum(encoding, hrp, values); data combined = Cat(values, checksum); std::string ret = hrp + '1'; ret.reserve(ret.size() + combined.size()); for (const auto c : combined) { ret += CHARSET[c]; } return ret; } /** Decode a Bech32 or Bech32m string. */ DecodeResult Decode(const std::string& str) { std::vector<int> errors; if (!CheckCharacters(str, errors)) return {}; size_t pos = str.rfind('1'); if (str.size() > 90 || pos == str.npos || pos == 0 || pos + 7 > str.size()) { return {}; } data values(str.size() - 1 - pos); for (size_t i = 0; i < str.size() - 1 - pos; ++i) { unsigned char c = str[i + pos + 1]; int8_t rev = CHARSET_REV[c]; if (rev == -1) { return {}; } values[i] = rev; } std::string hrp; for (size_t i = 0; i < pos; ++i) { hrp += LowerCase(str[i]); } Encoding result = VerifyChecksum(hrp, values); if (result == Encoding::INVALID) return {}; return {result, std::move(hrp), data(values.begin(), values.end() - 6)}; } /** Find index of an incorrect character in a Bech32 string. */ std::pair<std::string, std::vector<int>> LocateErrors(const std::string& str) { std::vector<int> error_locations{}; if (str.size() > 90) { error_locations.resize(str.size() - 90); std::iota(error_locations.begin(), error_locations.end(), 90); return std::make_pair("Bech32 string too long", std::move(error_locations)); } if (!CheckCharacters(str, error_locations)){ return std::make_pair("Invalid character or mixed case", std::move(error_locations)); } size_t pos = str.rfind('1'); if (pos == str.npos) { return std::make_pair("Missing separator", std::vector<int>{}); } if (pos == 0 || pos + 7 > str.size()) { error_locations.push_back(pos); return std::make_pair("Invalid separator position", std::move(error_locations)); } std::string hrp; for (size_t i = 0; i < pos; ++i) { hrp += LowerCase(str[i]); } size_t length = str.size() - 1 - pos; // length of data part data values(length); for (size_t i = pos + 1; i < str.size(); ++i) { unsigned char c = str[i]; int8_t rev = CHARSET_REV[c]; if (rev == -1) { error_locations.push_back(i); return std::make_pair("Invalid Base 32 character", std::move(error_locations)); } values[i - pos - 1] = rev; } // We attempt error detection with both bech32 and bech32m, and choose the one with the fewest errors // We can't simply use the segwit version, because that may be one of the errors std::optional<Encoding> error_encoding; for (Encoding encoding : {Encoding::BECH32, Encoding::BECH32M}) { std::vector<int> possible_errors; // Recall that (ExpandHRP(hrp) ++ values) is interpreted as a list of coefficients of a polynomial // over GF(32). PolyMod computes the "remainder" of this polynomial modulo the generator G(x). uint32_t residue = PolyMod(Cat(ExpandHRP(hrp), values)) ^ EncodingConstant(encoding); // All valid codewords should be multiples of G(x), so this remainder (after XORing with the encoding // constant) should be 0 - hence 0 indicates there are no errors present. if (residue != 0) { // If errors are present, our polynomial must be of the form C(x) + E(x) where C is the valid // codeword (a multiple of G(x)), and E encodes the errors. uint32_t syn = Syndrome(residue); // Unpack the three 10-bit syndrome values int s0 = syn & 0x3FF; int s1 = (syn >> 10) & 0x3FF; int s2 = syn >> 20; // Get the discrete logs of these values in GF1024 for more efficient computation int l_s0 = GF1024_LOG.at(s0); int l_s1 = GF1024_LOG.at(s1); int l_s2 = GF1024_LOG.at(s2); // First, suppose there is only a single error. Then E(x) = e1*x^p1 for some position p1 // Then s0 = E((e)^997) = e1*(e)^(997*p1) and s1 = E((e)^998) = e1*(e)^(998*p1) // Therefore s1/s0 = (e)^p1, and by the same logic, s2/s1 = (e)^p1 too. // Hence, s1^2 == s0*s2, which is exactly the condition we check first: if (l_s0 != -1 && l_s1 != -1 && l_s2 != -1 && (2 * l_s1 - l_s2 - l_s0 + 2046) % 1023 == 0) { // Compute the error position p1 as l_s1 - l_s0 = p1 (mod 1023) size_t p1 = (l_s1 - l_s0 + 1023) % 1023; // the +1023 ensures it is positive // Now because s0 = e1*(e)^(997*p1), we get e1 = s0/((e)^(997*p1)). Remember that (e)^1023 = 1, // so 1/((e)^997) = (e)^(1023-997). int l_e1 = l_s0 + (1023 - 997) * p1; // Finally, some sanity checks on the result: // - The error position should be within the length of the data // - e1 should be in GF(32), which implies that e1 = (e)^(33k) for some k (the 31 non-zero elements // of GF(32) form an index 33 subgroup of the 1023 non-zero elements of GF(1024)). if (p1 < length && !(l_e1 % 33)) { // Polynomials run from highest power to lowest, so the index p1 is from the right. // We don't return e1 because it is dangerous to suggest corrections to the user, // the user should check the address themselves. possible_errors.push_back(str.size() - p1 - 1); } // Otherwise, suppose there are two errors. Then E(x) = e1*x^p1 + e2*x^p2. } else { // For all possible first error positions p1 for (size_t p1 = 0; p1 < length; ++p1) { // We have guessed p1, and want to solve for p2. Recall that E(x) = e1*x^p1 + e2*x^p2, so // s0 = E((e)^997) = e1*(e)^(997^p1) + e2*(e)^(997*p2), and similar for s1 and s2. // // Consider s2 + s1*(e)^p1 // = 2e1*(e)^(999^p1) + e2*(e)^(999*p2) + e2*(e)^(998*p2)*(e)^p1 // = e2*(e)^(999*p2) + e2*(e)^(998*p2)*(e)^p1 // (Because we are working in characteristic 2.) // = e2*(e)^(998*p2) ((e)^p2 + (e)^p1) // int s2_s1p1 = s2 ^ (s1 == 0 ? 0 : GF1024_EXP.at((l_s1 + p1) % 1023)); if (s2_s1p1 == 0) continue; int l_s2_s1p1 = GF1024_LOG.at(s2_s1p1); // Similarly, s1 + s0*(e)^p1 // = e2*(e)^(997*p2) ((e)^p2 + (e)^p1) int s1_s0p1 = s1 ^ (s0 == 0 ? 0 : GF1024_EXP.at((l_s0 + p1) % 1023)); if (s1_s0p1 == 0) continue; int l_s1_s0p1 = GF1024_LOG.at(s1_s0p1); // So, putting these together, we can compute the second error position as // (e)^p2 = (s2 + s1^p1)/(s1 + s0^p1) // p2 = log((e)^p2) size_t p2 = (l_s2_s1p1 - l_s1_s0p1 + 1023) % 1023; // Sanity checks that p2 is a valid position and not the same as p1 if (p2 >= length || p1 == p2) continue; // Now we want to compute the error values e1 and e2. // Similar to above, we compute s1 + s0*(e)^p2 // = e1*(e)^(997*p1) ((e)^p1 + (e)^p2) int s1_s0p2 = s1 ^ (s0 == 0 ? 0 : GF1024_EXP.at((l_s0 + p2) % 1023)); if (s1_s0p2 == 0) continue; int l_s1_s0p2 = GF1024_LOG.at(s1_s0p2); // And compute (the log of) 1/((e)^p1 + (e)^p2)) int inv_p1_p2 = 1023 - GF1024_LOG.at(GF1024_EXP.at(p1) ^ GF1024_EXP.at(p2)); // Then (s1 + s0*(e)^p1) * (1/((e)^p1 + (e)^p2))) // = e2*(e)^(997*p2) // Then recover e2 by dividing by (e)^(997*p2) int l_e2 = l_s1_s0p1 + inv_p1_p2 + (1023 - 997) * p2; // Check that e2 is in GF(32) if (l_e2 % 33) continue; // In the same way, (s1 + s0*(e)^p2) * (1/((e)^p1 + (e)^p2))) // = e1*(e)^(997*p1) // So recover e1 by dividing by (e)^(997*p1) int l_e1 = l_s1_s0p2 + inv_p1_p2 + (1023 - 997) * p1; // Check that e1 is in GF(32) if (l_e1 % 33) continue; // Again, we do not return e1 or e2 for safety. // Order the error positions from the left of the string and return them if (p1 > p2) { possible_errors.push_back(str.size() - p1 - 1); possible_errors.push_back(str.size() - p2 - 1); } else { possible_errors.push_back(str.size() - p2 - 1); possible_errors.push_back(str.size() - p1 - 1); } break; } } } else { // No errors return std::make_pair("", std::vector<int>{}); } if (error_locations.empty() || (!possible_errors.empty() && possible_errors.size() < error_locations.size())) { error_locations = std::move(possible_errors); if (!error_locations.empty()) error_encoding = encoding; } } std::string error_message = error_encoding == Encoding::BECH32M ? "Invalid Bech32m checksum" : error_encoding == Encoding::BECH32 ? "Invalid Bech32 checksum" : "Invalid checksum"; return std::make_pair(error_message, std::move(error_locations)); } } // namespace bech32
0
bitcoin
bitcoin/src/addrdb.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_ADDRDB_H #define BITCOIN_ADDRDB_H #include <net_types.h> #include <util/fs.h> #include <util/result.h> #include <memory> #include <vector> class ArgsManager; class AddrMan; class CAddress; class DataStream; class NetGroupManager; /** Only used by tests. */ void ReadFromStream(AddrMan& addr, DataStream& ssPeers); bool DumpPeerAddresses(const ArgsManager& args, const AddrMan& addr); /** Access to the banlist database (banlist.json) */ class CBanDB { private: /** * JSON key under which the data is stored in the json database. */ static constexpr const char* JSON_KEY = "banned_nets"; const fs::path m_banlist_dat; const fs::path m_banlist_json; public: explicit CBanDB(fs::path ban_list_path); bool Write(const banmap_t& banSet); /** * Read the banlist from disk. * @param[out] banSet The loaded list. Set if `true` is returned, otherwise it is left * in an undefined state. * @return true on success */ bool Read(banmap_t& banSet); }; /** Returns an error string on failure */ util::Result<std::unique_ptr<AddrMan>> LoadAddrman(const NetGroupManager& netgroupman, const ArgsManager& args); /** * Dump the anchor IP address database (anchors.dat) * * Anchors are last known outgoing block-relay-only peers that are * tried to re-connect to on startup. */ void DumpAnchors(const fs::path& anchors_db_path, const std::vector<CAddress>& anchors); /** * Read the anchor IP address database (anchors.dat) * * Deleting anchors.dat is intentional as it avoids renewed peering to anchors after * an unclean shutdown and thus potential exploitation of the anchor peer policy. */ std::vector<CAddress> ReadAnchors(const fs::path& anchors_db_path); #endif // BITCOIN_ADDRDB_H
0
bitcoin
bitcoin/src/validation.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_VALIDATION_H #define BITCOIN_VALIDATION_H #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <arith_uint256.h> #include <attributes.h> #include <chain.h> #include <checkqueue.h> #include <kernel/chain.h> #include <consensus/amount.h> #include <deploymentstatus.h> #include <kernel/chainparams.h> #include <kernel/chainstatemanager_opts.h> #include <kernel/cs_main.h> // IWYU pragma: export #include <node/blockstorage.h> #include <policy/feerate.h> #include <policy/packages.h> #include <policy/policy.h> #include <script/script_error.h> #include <sync.h> #include <txdb.h> #include <txmempool.h> // For CTxMemPool::cs #include <uint256.h> #include <util/check.h> #include <util/fs.h> #include <util/hasher.h> #include <util/result.h> #include <util/translation.h> #include <versionbits.h> #include <atomic> #include <map> #include <memory> #include <optional> #include <set> #include <stdint.h> #include <string> #include <thread> #include <type_traits> #include <utility> #include <vector> class Chainstate; class CTxMemPool; class ChainstateManager; struct ChainTxData; class DisconnectedBlockTransactions; struct PrecomputedTransactionData; struct LockPoints; struct AssumeutxoData; namespace node { class SnapshotMetadata; } // namespace node namespace Consensus { struct Params; } // namespace Consensus namespace util { class SignalInterrupt; } // namespace util /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pruned. */ static const unsigned int MIN_BLOCKS_TO_KEEP = 288; static const signed int DEFAULT_CHECKBLOCKS = 6; static constexpr int DEFAULT_CHECKLEVEL{3}; // Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat) // At 1MB per block, 288 blocks = 288MB. // Add 15% for Undo data = 331MB // Add 20% for Orphan block rate = 397MB // We want the low water mark after pruning to be at least 397 MB and since we prune in // full block file chunks, we need the high water mark which triggers the prune to be // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB // Setting the target to >= 550 MiB will make it likely we can respect the target. static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024; /** Current sync state passed to tip changed callbacks. */ enum class SynchronizationState { INIT_REINDEX, INIT_DOWNLOAD, POST_INIT }; extern GlobalMutex g_best_block_mutex; extern std::condition_variable g_best_block_cv; /** Used to notify getblocktemplate RPC of new tips. */ extern uint256 g_best_block; /** Documentation for argument 'checklevel'. */ extern const std::vector<std::string> CHECKLEVEL_DOC; CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams); bool FatalError(kernel::Notifications& notifications, BlockValidationState& state, const std::string& strMessage, const bilingual_str& userMessage = {}); /** Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip). */ double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex); /** Prune block files up to a given height */ void PruneBlockFilesManual(Chainstate& active_chainstate, int nManualPruneHeight); /** * Validation result for a transaction evaluated by MemPoolAccept (single or package). * Here are the expected fields and properties of a result depending on its ResultType, applicable to * results returned from package evaluation: *+---------------------------+----------------+-------------------+------------------+----------------+-------------------+ *| Field or property | VALID | INVALID | MEMPOOL_ENTRY | DIFFERENT_WITNESS | *| | |--------------------------------------| | | *| | | TX_RECONSIDERABLE | Other | | | *+---------------------------+----------------+-------------------+------------------+----------------+-------------------+ *| txid in mempool? | yes | no | no* | yes | yes | *| wtxid in mempool? | yes | no | no* | yes | no | *| m_state | yes, IsValid() | yes, IsInvalid() | yes, IsInvalid() | yes, IsValid() | yes, IsValid() | *| m_replaced_transactions | yes | no | no | no | no | *| m_vsize | yes | no | no | yes | no | *| m_base_fees | yes | no | no | yes | no | *| m_effective_feerate | yes | yes | no | no | no | *| m_wtxids_fee_calculations | yes | yes | no | no | no | *| m_other_wtxid | no | no | no | no | yes | *+---------------------------+----------------+-------------------+------------------+----------------+-------------------+ * (*) Individual transaction acceptance doesn't return MEMPOOL_ENTRY and DIFFERENT_WITNESS. It returns * INVALID, with the errors txn-already-in-mempool and txn-same-nonwitness-data-in-mempool * respectively. In those cases, the txid or wtxid may be in the mempool for a TX_CONFLICT. */ struct MempoolAcceptResult { /** Used to indicate the results of mempool validation. */ enum class ResultType { VALID, //!> Fully validated, valid. INVALID, //!> Invalid. MEMPOOL_ENTRY, //!> Valid, transaction was already in the mempool. DIFFERENT_WITNESS, //!> Not validated. A same-txid-different-witness tx (see m_other_wtxid) already exists in the mempool and was not replaced. }; /** Result type. Present in all MempoolAcceptResults. */ const ResultType m_result_type; /** Contains information about why the transaction failed. */ const TxValidationState m_state; /** Mempool transactions replaced by the tx. */ const std::optional<std::list<CTransactionRef>> m_replaced_transactions; /** Virtual size as used by the mempool, calculated using serialized size and sigops. */ const std::optional<int64_t> m_vsize; /** Raw base fees in satoshis. */ const std::optional<CAmount> m_base_fees; /** The feerate at which this transaction was considered. This includes any fee delta added * using prioritisetransaction (i.e. modified fees). If this transaction was submitted as a * package, this is the package feerate, which may also include its descendants and/or * ancestors (see m_wtxids_fee_calculations below). */ const std::optional<CFeeRate> m_effective_feerate; /** Contains the wtxids of the transactions used for fee-related checks. Includes this * transaction's wtxid and may include others if this transaction was validated as part of a * package. This is not necessarily equivalent to the list of transactions passed to * ProcessNewPackage(). * Only present when m_result_type = ResultType::VALID. */ const std::optional<std::vector<Wtxid>> m_wtxids_fee_calculations; /** The wtxid of the transaction in the mempool which has the same txid but different witness. */ const std::optional<uint256> m_other_wtxid; static MempoolAcceptResult Failure(TxValidationState state) { return MempoolAcceptResult(state); } static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector<Wtxid>& wtxids_fee_calculations) { return MempoolAcceptResult(state, effective_feerate, wtxids_fee_calculations); } static MempoolAcceptResult Success(std::list<CTransactionRef>&& replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector<Wtxid>& wtxids_fee_calculations) { return MempoolAcceptResult(std::move(replaced_txns), vsize, fees, effective_feerate, wtxids_fee_calculations); } static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees) { return MempoolAcceptResult(vsize, fees); } static MempoolAcceptResult MempoolTxDifferentWitness(const uint256& other_wtxid) { return MempoolAcceptResult(other_wtxid); } // Private constructors. Use static methods MempoolAcceptResult::Success, etc. to construct. private: /** Constructor for failure case */ explicit MempoolAcceptResult(TxValidationState state) : m_result_type(ResultType::INVALID), m_state(state) { Assume(!state.IsValid()); // Can be invalid or error } /** Constructor for success case */ explicit MempoolAcceptResult(std::list<CTransactionRef>&& replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector<Wtxid>& wtxids_fee_calculations) : m_result_type(ResultType::VALID), m_replaced_transactions(std::move(replaced_txns)), m_vsize{vsize}, m_base_fees(fees), m_effective_feerate(effective_feerate), m_wtxids_fee_calculations(wtxids_fee_calculations) {} /** Constructor for fee-related failure case */ explicit MempoolAcceptResult(TxValidationState state, CFeeRate effective_feerate, const std::vector<Wtxid>& wtxids_fee_calculations) : m_result_type(ResultType::INVALID), m_state(state), m_effective_feerate(effective_feerate), m_wtxids_fee_calculations(wtxids_fee_calculations) {} /** Constructor for already-in-mempool case. It wouldn't replace any transactions. */ explicit MempoolAcceptResult(int64_t vsize, CAmount fees) : m_result_type(ResultType::MEMPOOL_ENTRY), m_vsize{vsize}, m_base_fees(fees) {} /** Constructor for witness-swapped case. */ explicit MempoolAcceptResult(const uint256& other_wtxid) : m_result_type(ResultType::DIFFERENT_WITNESS), m_other_wtxid(other_wtxid) {} }; /** * Validation result for package mempool acceptance. */ struct PackageMempoolAcceptResult { PackageValidationState m_state; /** * Map from wtxid to finished MempoolAcceptResults. The client is responsible * for keeping track of the transaction objects themselves. If a result is not * present, it means validation was unfinished for that transaction. If there * was a package-wide error (see result in m_state), m_tx_results will be empty. */ std::map<uint256, MempoolAcceptResult> m_tx_results; explicit PackageMempoolAcceptResult(PackageValidationState state, std::map<uint256, MempoolAcceptResult>&& results) : m_state{state}, m_tx_results(std::move(results)) {} explicit PackageMempoolAcceptResult(PackageValidationState state, CFeeRate feerate, std::map<uint256, MempoolAcceptResult>&& results) : m_state{state}, m_tx_results(std::move(results)) {} /** Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult */ explicit PackageMempoolAcceptResult(const uint256& wtxid, const MempoolAcceptResult& result) : m_tx_results{ {wtxid, result} } {} }; /** * Try to add a transaction to the mempool. This is an internal function and is exposed only for testing. * Client code should use ChainstateManager::ProcessTransaction() * * @param[in] active_chainstate Reference to the active chainstate. * @param[in] tx The transaction to submit for mempool acceptance. * @param[in] accept_time The timestamp for adding the transaction to the mempool. * It is also used to determine when the entry expires. * @param[in] bypass_limits When true, don't enforce mempool fee and capacity limits, * and set entry_sequence to zero. * @param[in] test_accept When true, run validation checks but don't submit to mempool. * * @returns a MempoolAcceptResult indicating whether the transaction was accepted/rejected with reason. */ MempoolAcceptResult AcceptToMemoryPool(Chainstate& active_chainstate, const CTransactionRef& tx, int64_t accept_time, bool bypass_limits, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** * Validate (and maybe submit) a package to the mempool. See doc/policy/packages.md for full details * on package validation rules. * @param[in] test_accept When true, run validation checks but don't submit to mempool. * @returns a PackageMempoolAcceptResult which includes a MempoolAcceptResult for each transaction. * If a transaction fails, validation will exit early and some results may be missing. It is also * possible for the package to be partially submitted. */ PackageMempoolAcceptResult ProcessNewPackage(Chainstate& active_chainstate, CTxMemPool& pool, const Package& txns, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /* Mempool validation helper functions */ /** * Check if transaction will be final in the next block to be created. */ bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); /** * Calculate LockPoints required to check if transaction will be BIP68 final in the next block * to be created on top of tip. * * @param[in] tip Chain tip for which tx sequence locks are calculated. For * example, the tip of the current active chain. * @param[in] coins_view Any CCoinsView that provides access to the relevant coins for * checking sequence locks. For example, it can be a CCoinsViewCache * that isn't connected to anything but contains all the relevant * coins, or a CCoinsViewMemPool that is connected to the * mempool and chainstate UTXO set. In the latter case, the caller * is responsible for holding the appropriate locks to ensure that * calls to GetCoin() return correct coins. * @param[in] tx The transaction being evaluated. * * @returns The resulting height and time calculated and the hash of the block needed for * calculation, or std::nullopt if there is an error. */ std::optional<LockPoints> CalculateLockPointsAtTip( CBlockIndex* tip, const CCoinsView& coins_view, const CTransaction& tx); /** * Check if transaction will be BIP68 final in the next block to be created on top of tip. * @param[in] tip Chain tip to check tx sequence locks against. For example, * the tip of the current active chain. * @param[in] lock_points LockPoints containing the height and time at which this * transaction is final. * Simulates calling SequenceLocks() with data from the tip passed in. * The LockPoints should not be considered valid if CheckSequenceLocksAtTip returns false. */ bool CheckSequenceLocksAtTip(CBlockIndex* tip, const LockPoints& lock_points); /** * Closure representing one script verification * Note that this stores references to the spending transaction */ class CScriptCheck { private: CTxOut m_tx_out; const CTransaction *ptxTo; unsigned int nIn; unsigned int nFlags; bool cacheStore; ScriptError error{SCRIPT_ERR_UNKNOWN_ERROR}; PrecomputedTransactionData *txdata; public: CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) : m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), txdata(txdataIn) { } CScriptCheck(const CScriptCheck&) = delete; CScriptCheck& operator=(const CScriptCheck&) = delete; CScriptCheck(CScriptCheck&&) = default; CScriptCheck& operator=(CScriptCheck&&) = default; bool operator()(); ScriptError GetScriptError() const { return error; } }; // CScriptCheck is used a lot in std::vector, make sure that's efficient static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>); static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>); static_assert(std::is_nothrow_destructible_v<CScriptCheck>); /** Initializes the script-execution cache */ [[nodiscard]] bool InitScriptExecutionCache(size_t max_size_bytes); /** Functions for validating blocks and updating the block tree */ /** Context-independent validity checks */ bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true); /** Check a block is completely valid from start to finish (only works on top of our current best block) */ bool TestBlockValidity(BlockValidationState& state, const CChainParams& chainparams, Chainstate& chainstate, const CBlock& block, CBlockIndex* pindexPrev, const std::function<NodeClock::time_point()>& adjusted_time_callback, bool fCheckPOW = true, bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Check with the proof of work on each blockheader matches the value in nBits */ bool HasValidProofOfWork(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams); /** Return the sum of the work on a given set of headers */ arith_uint256 CalculateHeadersWork(const std::vector<CBlockHeader>& headers); enum class VerifyDBResult { SUCCESS, CORRUPTED_BLOCK_DB, INTERRUPTED, SKIPPED_L3_CHECKS, SKIPPED_MISSING_BLOCKS, }; /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */ class CVerifyDB { private: kernel::Notifications& m_notifications; public: explicit CVerifyDB(kernel::Notifications& notifications); ~CVerifyDB(); [[nodiscard]] VerifyDBResult VerifyDB( Chainstate& chainstate, const Consensus::Params& consensus_params, CCoinsView& coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main); }; enum DisconnectResult { DISCONNECT_OK, // All good. DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block. DISCONNECT_FAILED // Something else went wrong. }; class ConnectTrace; /** @see Chainstate::FlushStateToDisk */ enum class FlushStateMode { NONE, IF_NEEDED, PERIODIC, ALWAYS }; /** * A convenience class for constructing the CCoinsView* hierarchy used * to facilitate access to the UTXO set. * * This class consists of an arrangement of layered CCoinsView objects, * preferring to store and retrieve coins in memory via `m_cacheview` but * ultimately falling back on cache misses to the canonical store of UTXOs on * disk, `m_dbview`. */ class CoinsViews { public: //! The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk. //! All unspent coins reside in this store. CCoinsViewDB m_dbview GUARDED_BY(cs_main); //! This view wraps access to the leveldb instance and handles read errors gracefully. CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main); //! This is the top layer of the cache hierarchy - it keeps as many coins in memory as //! can fit per the dbcache setting. std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main); //! This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it //! *does not* create a CCoinsViewCache instance by default. This is done separately because the //! presence of the cache has implications on whether or not we're allowed to flush the cache's //! state to disk, which should not be done until the health of the database is verified. //! //! All arguments forwarded onto CCoinsViewDB. CoinsViews(DBParams db_params, CoinsViewOptions options); //! Initialize the CCoinsViewCache member. void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); }; enum class CoinsCacheSizeState { //! The coins cache is in immediate need of a flush. CRITICAL = 2, //! The cache is at >= 90% capacity. LARGE = 1, OK = 0 }; /** * Chainstate stores and provides an API to update our local knowledge of the * current best chain. * * Eventually, the API here is targeted at being exposed externally as a * consumable libconsensus library, so any functions added must only call * other class member functions, pure functions in other parts of the consensus * library, callbacks via the validation interface, or read/write-to-disk * functions (eventually this will also be via callbacks). * * Anything that is contingent on the current tip of the chain is stored here, * whereas block information and metadata independent of the current tip is * kept in `BlockManager`. */ class Chainstate { protected: /** * The ChainState Mutex * A lock that must be held when modifying this ChainState - held in ActivateBestChain() and * InvalidateBlock() */ Mutex m_chainstate_mutex; //! Optional mempool that is kept in sync with the chain. //! Only the active chainstate has a mempool. CTxMemPool* m_mempool; //! Manages the UTXO set, which is a reflection of the contents of `m_chain`. std::unique_ptr<CoinsViews> m_coins_views; //! This toggle exists for use when doing background validation for UTXO //! snapshots. //! //! In the expected case, it is set once the background validation chain reaches the //! same height as the base of the snapshot and its UTXO set is found to hash to //! the expected assumeutxo value. It signals that we should no longer connect //! blocks to the background chainstate. When set on the background validation //! chainstate, it signifies that we have fully validated the snapshot chainstate. //! //! In the unlikely case that the snapshot chainstate is found to be invalid, this //! is set to true on the snapshot chainstate. bool m_disabled GUARDED_BY(::cs_main) {false}; //! Cached result of LookupBlockIndex(*m_from_snapshot_blockhash) const CBlockIndex* m_cached_snapshot_base GUARDED_BY(::cs_main) {nullptr}; public: //! Reference to a BlockManager instance which itself is shared across all //! Chainstate instances. node::BlockManager& m_blockman; //! The chainstate manager that owns this chainstate. The reference is //! necessary so that this instance can check whether it is the active //! chainstate within deeply nested method calls. ChainstateManager& m_chainman; explicit Chainstate( CTxMemPool* mempool, node::BlockManager& blockman, ChainstateManager& chainman, std::optional<uint256> from_snapshot_blockhash = std::nullopt); //! Return the current role of the chainstate. See `ChainstateManager` //! documentation for a description of the different types of chainstates. //! //! @sa ChainstateRole ChainstateRole GetRole() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main); /** * Initialize the CoinsViews UTXO set database management data structures. The in-memory * cache is initialized separately. * * All parameters forwarded to CoinsViews. */ void InitCoinsDB( size_t cache_size_bytes, bool in_memory, bool should_wipe, fs::path leveldb_name = "chainstate"); //! Initialize the in-memory coins cache (to be done after the health of the on-disk database //! is verified). void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); //! @returns whether or not the CoinsViews object has been fully initialized and we can //! safely flush this object to disk. bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { AssertLockHeld(::cs_main); return m_coins_views && m_coins_views->m_cacheview; } //! The current chain of blockheaders we consult and build on. //! @see CChain, CBlockIndex. CChain m_chain; /** * The blockhash which is the base of the snapshot this chainstate was created from. * * std::nullopt if this chainstate was not created from a snapshot. */ const std::optional<uint256> m_from_snapshot_blockhash; /** * The base of the snapshot this chainstate was created from. * * nullptr if this chainstate was not created from a snapshot. */ const CBlockIndex* SnapshotBase() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); /** * The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for * itself and all ancestors) *or* BLOCK_ASSUMED_VALID (if using background * chainstates) and as good as our current tip or better. Entries may be failed, * though, and pruning nodes may be missing the data for the block. */ std::set<CBlockIndex*, node::CBlockIndexWorkComparator> setBlockIndexCandidates; //! @returns A reference to the in-memory cache of the UTXO set. CCoinsViewCache& CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { AssertLockHeld(::cs_main); Assert(m_coins_views); return *Assert(m_coins_views->m_cacheview); } //! @returns A reference to the on-disk UTXO set database. CCoinsViewDB& CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { AssertLockHeld(::cs_main); return Assert(m_coins_views)->m_dbview; } //! @returns A pointer to the mempool. CTxMemPool* GetMempool() { return m_mempool; } //! @returns A reference to a wrapped view of the in-memory UTXO set that //! handles disk read errors gracefully. CCoinsViewErrorCatcher& CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { AssertLockHeld(::cs_main); return Assert(m_coins_views)->m_catcherview; } //! Destructs all objects related to accessing the UTXO set. void ResetCoinsViews() { m_coins_views.reset(); } //! Does this chainstate have a UTXO set attached? bool HasCoinsViews() const { return (bool)m_coins_views; } //! The cache size of the on-disk coins view. size_t m_coinsdb_cache_size_bytes{0}; //! The cache size of the in-memory coins view. size_t m_coinstip_cache_size_bytes{0}; //! Resize the CoinsViews caches dynamically and flush state to disk. //! @returns true unless an error occurred during the flush. bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); /** * Update the on-disk chain state. * The caches and indexes are flushed depending on the mode we're called with * if they're too large, if it's been a while since the last write, * or always and in all cases if we're in prune mode and are deleting files. * * If FlushStateMode::NONE is used, then FlushStateToDisk(...) won't do anything * besides checking if we need to prune. * * @returns true unless a system error occurred */ bool FlushStateToDisk( BlockValidationState& state, FlushStateMode mode, int nManualPruneHeight = 0); //! Unconditionally flush all changes to disk. void ForceFlushStateToDisk(); //! Prune blockfiles from the disk if necessary and then flush chainstate changes //! if we pruned. void PruneAndFlush(); /** * Find the best known block, and make it the tip of the block chain. The * result is either failure or an activated best chain. pblock is either * nullptr or a pointer to a block that is already loaded (to avoid loading * it again from disk). * * ActivateBestChain is split into steps (see ActivateBestChainStep) so that * we avoid holding cs_main for an extended period of time; the length of this * call may be quite long during reindexing or a substantial reorg. * * May not be called with cs_main held. May not be called in a * validationinterface callback. * * Note that if this is called while a snapshot chainstate is active, and if * it is called on a background chainstate whose tip has reached the base block * of the snapshot, its execution will take *MINUTES* while it hashes the * background UTXO set to verify the assumeutxo value the snapshot was activated * with. `cs_main` will be held during this time. * * @returns true unless a system error occurred */ bool ActivateBestChain( BlockValidationState& state, std::shared_ptr<const CBlock> pblock = nullptr) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex) LOCKS_EXCLUDED(::cs_main); // Block (dis)connection on a given view: DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main); // Apply the effects of a block disconnection on the UTXO set. bool DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs); // Manual block validity manipulation: /** Mark a block as precious and reorganize. * * May not be called in a validationinterface callback. */ bool PreciousBlock(BlockValidationState& state, CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex) LOCKS_EXCLUDED(::cs_main); /** Mark a block as invalid. */ bool InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex) LOCKS_EXCLUDED(::cs_main); /** Remove invalidity status from a block and its descendants. */ void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Replay blocks that aren't fully applied to the database. */ bool ReplayBlocks(); /** Whether the chain state needs to be redownloaded due to lack of witness data */ [[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Ensures we have a genesis block in the block tree, possibly writing one to disk. */ bool LoadGenesisBlock(); void TryAddBlockIndexCandidate(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main); void PruneBlockIndexCandidates(); void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); /** Find the last common block of this chain and a locator. */ const CBlockIndex* FindForkInGlobalIndex(const CBlockLocator& locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Update the chain tip based on database information, i.e. CoinsTip()'s best block. */ bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main); //! Dictates whether we need to flush the cache to disk or not. //! //! @return the state of the size of the coins cache. CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); CoinsCacheSizeState GetCoinsCacheSizeState( size_t max_coins_cache_size_bytes, size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); //! Indirection necessary to make lock annotations work with an optional mempool. RecursiveMutex* MempoolMutex() const LOCK_RETURNED(m_mempool->cs) { return m_mempool ? &m_mempool->cs : nullptr; } private: bool ActivateBestChainStep(BlockValidationState& state, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs); bool ConnectTip(BlockValidationState& state, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions& disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs); void InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main); CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main); bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main); void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main); void InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** * Make mempool consistent after a reorg, by re-adding or recursively erasing * disconnected block transactions from the mempool, and also removing any * other transactions from the mempool that are no longer valid given the new * tip/height. * * Note: we assume that disconnectpool only contains transactions that are NOT * confirmed in the current chain nor already in the mempool (otherwise, * in-mempool descendants of such transactions would be removed). * * Passing fAddToMempool=false will skip trying to add the transactions back, * and instead just erase from the mempool as needed. */ void MaybeUpdateMempoolForReorg( DisconnectedBlockTransactions& disconnectpool, bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs); /** Check warning conditions and do some notifications on new chain tip set. */ void UpdateTip(const CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); SteadyClock::time_point m_last_write{}; SteadyClock::time_point m_last_flush{}; /** * In case of an invalid snapshot, rename the coins leveldb directory so * that it can be examined for issue diagnosis. */ [[nodiscard]] util::Result<void> InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); friend ChainstateManager; }; enum class SnapshotCompletionResult { SUCCESS, SKIPPED, // Expected assumeutxo configuration data is not found for the height of the // base block. MISSING_CHAINPARAMS, // Failed to generate UTXO statistics (to check UTXO set hash) for the background // chainstate. STATS_FAILED, // The UTXO set hash of the background validation chainstate does not match // the one expected by assumeutxo chainparams. HASH_MISMATCH, // The blockhash of the current tip of the background validation chainstate does // not match the one expected by the snapshot chainstate. BASE_BLOCKHASH_MISMATCH, }; /** * Provides an interface for creating and interacting with one or two * chainstates: an IBD chainstate generated by downloading blocks, and * an optional snapshot chainstate loaded from a UTXO snapshot. Managed * chainstates can be maintained at different heights simultaneously. * * This class provides abstractions that allow the retrieval of the current * most-work chainstate ("Active") as well as chainstates which may be in * background use to validate UTXO snapshots. * * Definitions: * * *IBD chainstate*: a chainstate whose current state has been "fully" * validated by the initial block download process. * * *Snapshot chainstate*: a chainstate populated by loading in an * assumeutxo UTXO snapshot. * * *Active chainstate*: the chainstate containing the current most-work * chain. Consulted by most parts of the system (net_processing, * wallet) as a reflection of the current chain and UTXO set. * This may either be an IBD chainstate or a snapshot chainstate. * * *Background IBD chainstate*: an IBD chainstate for which the * IBD process is happening in the background while use of the * active (snapshot) chainstate allows the rest of the system to function. */ class ChainstateManager { private: //! The chainstate used under normal operation (i.e. "regular" IBD) or, if //! a snapshot is in use, for background validation. //! //! Its contents (including on-disk data) will be deleted *upon shutdown* //! after background validation of the snapshot has completed. We do not //! free the chainstate contents immediately after it finishes validation //! to cautiously avoid a case where some other part of the system is still //! using this pointer (e.g. net_processing). //! //! Once this pointer is set to a corresponding chainstate, it will not //! be reset until init.cpp:Shutdown(). //! //! It is important for the pointer to not be deleted until shutdown, //! because cs_main is not always held when the pointer is accessed, for //! example when calling ActivateBestChain, so there's no way you could //! prevent code from using the pointer while deleting it. std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main); //! A chainstate initialized on the basis of a UTXO snapshot. If this is //! non-null, it is always our active chainstate. //! //! Once this pointer is set to a corresponding chainstate, it will not //! be reset until init.cpp:Shutdown(). //! //! It is important for the pointer to not be deleted until shutdown, //! because cs_main is not always held when the pointer is accessed, for //! example when calling ActivateBestChain, so there's no way you could //! prevent code from using the pointer while deleting it. std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main); //! Points to either the ibd or snapshot chainstate; indicates our //! most-work chain. Chainstate* m_active_chainstate GUARDED_BY(::cs_main) {nullptr}; CBlockIndex* m_best_invalid GUARDED_BY(::cs_main){nullptr}; //! Internal helper for ActivateSnapshot(). [[nodiscard]] bool PopulateAndValidateSnapshot( Chainstate& snapshot_chainstate, AutoFile& coins_file, const node::SnapshotMetadata& metadata); /** * If a block header hasn't already been seen, call CheckBlockHeader on it, ensure * that it doesn't descend from an invalid block, and then add it to m_block_index. * Caller must set min_pow_checked=true in order to add a new header to the * block index (permanent memory storage), indicating that the header is * known to be part of a sufficiently high-work chain (anti-dos check). */ bool AcceptBlockHeader( const CBlockHeader& block, BlockValidationState& state, CBlockIndex** ppindex, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main); friend Chainstate; /** Most recent headers presync progress update, for rate-limiting. */ std::chrono::time_point<std::chrono::steady_clock> m_last_presync_update GUARDED_BY(::cs_main) {}; std::array<ThresholdConditionCache, VERSIONBITS_NUM_BITS> m_warningcache GUARDED_BY(::cs_main); //! Return true if a chainstate is considered usable. //! //! This is false when a background validation chainstate has completed its //! validation of an assumed-valid chainstate, or when a snapshot //! chainstate has been found to be invalid. bool IsUsable(const Chainstate* const cs) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { return cs && !cs->m_disabled; } //! A queue for script verifications that have to be performed by worker threads. CCheckQueue<CScriptCheck> m_script_check_queue; public: using Options = kernel::ChainstateManagerOpts; explicit ChainstateManager(const util::SignalInterrupt& interrupt, Options options, node::BlockManager::Options blockman_options); //! Function to restart active indexes; set dynamically to avoid a circular //! dependency on `base/index.cpp`. std::function<void()> restart_indexes = std::function<void()>(); const CChainParams& GetParams() const { return m_options.chainparams; } const Consensus::Params& GetConsensus() const { return m_options.chainparams.GetConsensus(); } bool ShouldCheckBlockIndex() const { return *Assert(m_options.check_block_index); } const arith_uint256& MinimumChainWork() const { return *Assert(m_options.minimum_chain_work); } const uint256& AssumedValidBlock() const { return *Assert(m_options.assumed_valid_block); } kernel::Notifications& GetNotifications() const { return m_options.notifications; }; /** * Make various assertions about the state of the block index. * * By default this only executes fully when using the Regtest chain; see: m_options.check_block_index. */ void CheckBlockIndex(); /** * Alias for ::cs_main. * Should be used in new code to make it easier to make ::cs_main a member * of this class. * Generally, methods of this class should be annotated to require this * mutex. This will make calling code more verbose, but also help to: * - Clarify that the method will acquire a mutex that heavily affects * overall performance. * - Force call sites to think how long they need to acquire the mutex to * get consistent results. */ RecursiveMutex& GetMutex() const LOCK_RETURNED(::cs_main) { return ::cs_main; } const util::SignalInterrupt& m_interrupt; const Options m_options; std::thread m_thread_load; //! A single BlockManager instance is shared across each constructed //! chainstate to avoid duplicating block metadata. node::BlockManager m_blockman; /** * Whether initial block download has ended and IsInitialBlockDownload * should return false from now on. * * Mutable because we need to be able to mark IsInitialBlockDownload() * const, which latches this for caching purposes. */ mutable std::atomic<bool> m_cached_finished_ibd{false}; /** * Every received block is assigned a unique and increasing identifier, so we * know which one to give priority in case of a fork. */ /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */ int32_t nBlockSequenceId GUARDED_BY(::cs_main) = 1; /** Decreasing counter (used by subsequent preciousblock calls). */ int32_t nBlockReverseSequenceId = -1; /** chainwork for the last block that preciousblock has been applied to. */ arith_uint256 nLastPreciousChainwork = 0; // Reset the memory-only sequence counters we use to track block arrival // (used by tests to reset state) void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { AssertLockHeld(::cs_main); nBlockSequenceId = 1; nBlockReverseSequenceId = -1; } /** * In order to efficiently track invalidity of headers, we keep the set of * blocks which we tried to connect and found to be invalid here (ie which * were set to BLOCK_FAILED_VALID since the last restart). We can then * walk this set and check if a new header is a descendant of something in * this set, preventing us from having to walk m_block_index when we try * to connect a bad block and fail. * * While this is more complicated than marking everything which descends * from an invalid block as invalid at the time we discover it to be * invalid, doing so would require walking all of m_block_index to find all * descendants. Since this case should be very rare, keeping track of all * BLOCK_FAILED_VALID blocks in a set should be just fine and work just as * well. * * Because we already walk m_block_index in height-order at startup, we go * ahead and mark descendants of invalid blocks as FAILED_CHILD at that time, * instead of putting things in this set. */ std::set<CBlockIndex*> m_failed_blocks; /** Best header we've seen so far (used for getheaders queries' starting points). */ CBlockIndex* m_best_header GUARDED_BY(::cs_main){nullptr}; //! The total number of bytes available for us to use across all in-memory //! coins caches. This will be split somehow across chainstates. int64_t m_total_coinstip_cache{0}; // //! The total number of bytes available for us to use across all leveldb //! coins databases. This will be split somehow across chainstates. int64_t m_total_coinsdb_cache{0}; //! Instantiate a new chainstate. //! //! @param[in] mempool The mempool to pass to the chainstate // constructor Chainstate& InitializeChainstate(CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); //! Get all chainstates currently being used. std::vector<Chainstate*> GetAll(); //! Construct and activate a Chainstate on the basis of UTXO snapshot data. //! //! Steps: //! //! - Initialize an unused Chainstate. //! - Load its `CoinsViews` contents from `coins_file`. //! - Verify that the hash of the resulting coinsdb matches the expected hash //! per assumeutxo chain parameters. //! - Wait for our headers chain to include the base block of the snapshot. //! - "Fast forward" the tip of the new chainstate to the base of the snapshot, //! faking nTx* block index data along the way. //! - Move the new chainstate to `m_snapshot_chainstate` and make it our //! ChainstateActive(). [[nodiscard]] bool ActivateSnapshot( AutoFile& coins_file, const node::SnapshotMetadata& metadata, bool in_memory); //! Once the background validation chainstate has reached the height which //! is the base of the UTXO snapshot in use, compare its coins to ensure //! they match those expected by the snapshot. //! //! If the coins match (expected), then mark the validation chainstate for //! deletion and continue using the snapshot chainstate as active. //! Otherwise, revert to using the ibd chainstate and shutdown. SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); //! Returns nullptr if no snapshot has been loaded. const CBlockIndex* GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main); //! The most-work chain. Chainstate& ActiveChainstate() const; CChain& ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChainstate().m_chain; } int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Height(); } CBlockIndex* ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Tip(); } //! The state of a background sync (for net processing) bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return IsUsable(m_snapshot_chainstate.get()) && IsUsable(m_ibd_chainstate.get()); } //! The tip of the background sync chain const CBlockIndex* GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return BackgroundSyncInProgress() ? m_ibd_chainstate->m_chain.Tip() : nullptr; } node::BlockMap& BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { AssertLockHeld(::cs_main); return m_blockman.m_block_index; } /** * Track versionbit status */ mutable VersionBitsCache m_versionbitscache; //! @returns true if a snapshot-based chainstate is in use. Also implies //! that a background validation chainstate is also in use. bool IsSnapshotActive() const; std::optional<uint256> SnapshotBlockhash() const; //! Is there a snapshot in use and has it been fully validated? bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { return m_snapshot_chainstate && m_ibd_chainstate && m_ibd_chainstate->m_disabled; } /** Check whether we are doing an initial block download (synchronizing from disk or network) */ bool IsInitialBlockDownload() const; /** * Import blocks from an external file * * During reindexing, this function is called for each block file (datadir/blocks/blk?????.dat). * It reads all blocks contained in the given file and attempts to process them (add them to the * block index). The blocks may be out of order within each file and across files. Often this * function reads a block but finds that its parent hasn't been read yet, so the block can't be * processed yet. The function will add an entry to the blocks_with_unknown_parent map (which is * passed as an argument), so that when the block's parent is later read and processed, this * function can re-read the child block from disk and process it. * * Because a block's parent may be in a later file, not just later in the same file, the * blocks_with_unknown_parent map must be passed in and out with each call. It's a multimap, * rather than just a map, because multiple blocks may have the same parent (when chain splits * or stale blocks exist). It maps from parent-hash to child-disk-position. * * This function can also be used to read blocks from user-specified block files using the * -loadblock= option. There's no unknown-parent tracking, so the last two arguments are omitted. * * * @param[in] file_in File containing blocks to read * @param[in] dbp (optional) Disk block position (only for reindex) * @param[in,out] blocks_with_unknown_parent (optional) Map of disk positions for blocks with * unknown parent, key is parent block hash * (only used for reindex) * */ void LoadExternalBlockFile( AutoFile& file_in, FlatFilePos* dbp = nullptr, std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent = nullptr); /** * 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! * * If you want to *possibly* get feedback on whether block is valid, you must * install a CValidationInterface (see validationinterface.h) - this will have * its BlockChecked method called whenever *any* block completes validation. * * Note that we guarantee that either the proof-of-work is valid on block, or * (and possibly also) BlockChecked will have been called. * * May not be called in a validationinterface callback. * * @param[in] block The block we want to process. * @param[in] force_processing Process this block even if unrequested; used for non-network block sources. * @param[in] min_pow_checked True if proof-of-work anti-DoS checks have * been done by caller for headers chain * (note: only affects headers acceptance; if * block header is already present in block * index then this parameter has no effect) * @param[out] new_block A boolean which is set to indicate if the block was first received via this call * @returns If the block was processed, independently of block validity */ bool ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block) LOCKS_EXCLUDED(cs_main); /** * Process incoming block headers. * * May not be called in a * validationinterface callback. * * @param[in] block The block headers themselves * @param[in] min_pow_checked True if proof-of-work anti-DoS checks have been done by caller for headers chain * @param[out] state This may be set to an Error state if any error occurred processing them * @param[out] ppindex If set, the pointer will be set to point to the last new block index object for the given headers */ bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main); /** * Sufficiently validate a block for disk storage (and store on disk). * * @param[in] pblock The block we want to process. * @param[in] fRequested Whether we requested this block from a * peer. * @param[in] dbp The location on disk, if we are importing * this block from prior storage. * @param[in] min_pow_checked True if proof-of-work anti-DoS checks have * been done by caller for headers chain * * @param[out] state The state of the block validation. * @param[out] ppindex Optional return parameter to get the * CBlockIndex pointer for this block. * @param[out] fNewBlock Optional return parameter to indicate if the * block is new to our storage. * * @returns False if the block or header is invalid, or if saving to disk fails (likely a fatal error); true otherwise. */ bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main); void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** * Try to add a transaction to the memory pool. * * @param[in] tx The transaction to submit for mempool acceptance. * @param[in] test_accept When true, run validation checks but don't submit to mempool. */ [[nodiscard]] MempoolAcceptResult ProcessTransaction(const CTransactionRef& tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main); //! Load the block tree and coins database from disk, initializing state if we're running with -reindex bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main); //! Check to see if caches are out of balance and if so, call //! ResizeCoinsCaches() as needed. void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); /** Update uncommitted block structures (currently: only the witness reserved value). This is safe for submitted blocks. */ void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const; /** Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks). */ std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const; /** This is used by net_processing to report pre-synchronization progress of headers, as * headers are not yet fed to validation during that time, but validation is (for now) * responsible for logging and signalling through NotifyHeaderTip, so it needs this * information. */ void ReportHeadersPresync(const arith_uint256& work, int64_t height, int64_t timestamp); //! When starting up, search the datadir for a chainstate based on a UTXO //! snapshot that is in the process of being validated. bool DetectSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); //! Remove the snapshot-based chainstate and all on-disk artifacts. //! Used when reindex{-chainstate} is called during snapshot use. [[nodiscard]] bool DeleteSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); //! Switch the active chainstate to one based on a UTXO snapshot that was loaded //! previously. Chainstate& ActivateExistingSnapshot(uint256 base_blockhash) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); //! If we have validated a snapshot chain during this runtime, copy its //! chainstate directory over to the main `chainstate` location, completing //! validation of the snapshot. //! //! If the cleanup succeeds, the caller will need to ensure chainstates are //! reinitialized, since ResetChainstates() will be called before leveldb //! directories are moved or deleted. //! //! @sa node/chainstate:LoadChainstate() bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); //! @returns the chainstate that indexes should consult when ensuring that an //! index is synced with a chain where we can expect block index entries to have //! BLOCK_HAVE_DATA beneath the tip. //! //! In other words, give us the chainstate for which we can reasonably expect //! that all blocks beneath the tip have been indexed. In practice this means //! when using an assumed-valid chainstate based upon a snapshot, return only the //! fully validated chain. Chainstate& GetChainstateForIndexing() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); //! Return the [start, end] (inclusive) of block heights we can prune. //! //! start > end is possible, meaning no blocks can be pruned. std::pair<int, int> GetPruneRange( const Chainstate& chainstate, int last_height_can_prune) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); //! Return the height of the base block of the snapshot in use, if one exists, else //! nullopt. std::optional<int> GetSnapshotBaseHeight() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main); CCheckQueue<CScriptCheck>& GetCheckQueue() { return m_script_check_queue; } ~ChainstateManager(); }; /** Deployment* info via ChainstateManager */ template<typename DEP> bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const ChainstateManager& chainman, DEP dep) { return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep, chainman.m_versionbitscache); } template<typename DEP> bool DeploymentActiveAt(const CBlockIndex& index, const ChainstateManager& chainman, DEP dep) { return DeploymentActiveAt(index, chainman.GetConsensus(), dep, chainman.m_versionbitscache); } template<typename DEP> bool DeploymentEnabled(const ChainstateManager& chainman, DEP dep) { return DeploymentEnabled(chainman.GetConsensus(), dep); } /** Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30) */ bool IsBIP30Repeat(const CBlockIndex& block_index); /** Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30) */ bool IsBIP30Unspendable(const CBlockIndex& block_index); #endif // BITCOIN_VALIDATION_H
0
bitcoin
bitcoin/src/bip324.cpp
// Copyright (c) 2023 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 <bip324.h> #include <chainparams.h> #include <crypto/chacha20.h> #include <crypto/chacha20poly1305.h> #include <crypto/hkdf_sha256_32.h> #include <key.h> #include <pubkey.h> #include <random.h> #include <span.h> #include <support/cleanse.h> #include <uint256.h> #include <algorithm> #include <assert.h> #include <cstdint> #include <cstddef> #include <iterator> #include <string> BIP324Cipher::BIP324Cipher(const CKey& key, Span<const std::byte> ent32) noexcept : m_key(key) { m_our_pubkey = m_key.EllSwiftCreate(ent32); } BIP324Cipher::BIP324Cipher(const CKey& key, const EllSwiftPubKey& pubkey) noexcept : m_key(key), m_our_pubkey(pubkey) {} void BIP324Cipher::Initialize(const EllSwiftPubKey& their_pubkey, bool initiator, bool self_decrypt) noexcept { // Determine salt (fixed string + network magic bytes) const auto& message_header = Params().MessageStart(); std::string salt = std::string{"bitcoin_v2_shared_secret"} + std::string(std::begin(message_header), std::end(message_header)); // Perform ECDH to derive shared secret. ECDHSecret ecdh_secret = m_key.ComputeBIP324ECDHSecret(their_pubkey, m_our_pubkey, initiator); // Derive encryption keys from shared secret, and initialize stream ciphers and AEADs. bool side = (initiator != self_decrypt); CHKDF_HMAC_SHA256_L32 hkdf(UCharCast(ecdh_secret.data()), ecdh_secret.size(), salt); std::array<std::byte, 32> hkdf_32_okm; hkdf.Expand32("initiator_L", UCharCast(hkdf_32_okm.data())); (side ? m_send_l_cipher : m_recv_l_cipher).emplace(hkdf_32_okm, REKEY_INTERVAL); hkdf.Expand32("initiator_P", UCharCast(hkdf_32_okm.data())); (side ? m_send_p_cipher : m_recv_p_cipher).emplace(hkdf_32_okm, REKEY_INTERVAL); hkdf.Expand32("responder_L", UCharCast(hkdf_32_okm.data())); (side ? m_recv_l_cipher : m_send_l_cipher).emplace(hkdf_32_okm, REKEY_INTERVAL); hkdf.Expand32("responder_P", UCharCast(hkdf_32_okm.data())); (side ? m_recv_p_cipher : m_send_p_cipher).emplace(hkdf_32_okm, REKEY_INTERVAL); // Derive garbage terminators from shared secret. hkdf.Expand32("garbage_terminators", UCharCast(hkdf_32_okm.data())); std::copy(std::begin(hkdf_32_okm), std::begin(hkdf_32_okm) + GARBAGE_TERMINATOR_LEN, (initiator ? m_send_garbage_terminator : m_recv_garbage_terminator).begin()); std::copy(std::end(hkdf_32_okm) - GARBAGE_TERMINATOR_LEN, std::end(hkdf_32_okm), (initiator ? m_recv_garbage_terminator : m_send_garbage_terminator).begin()); // Derive session id from shared secret. hkdf.Expand32("session_id", UCharCast(m_session_id.data())); // Wipe all variables that contain information which could be used to re-derive encryption keys. memory_cleanse(ecdh_secret.data(), ecdh_secret.size()); memory_cleanse(hkdf_32_okm.data(), sizeof(hkdf_32_okm)); memory_cleanse(&hkdf, sizeof(hkdf)); m_key = CKey(); } void BIP324Cipher::Encrypt(Span<const std::byte> contents, Span<const std::byte> aad, bool ignore, Span<std::byte> output) noexcept { assert(output.size() == contents.size() + EXPANSION); // Encrypt length. std::byte len[LENGTH_LEN]; len[0] = std::byte{(uint8_t)(contents.size() & 0xFF)}; len[1] = std::byte{(uint8_t)((contents.size() >> 8) & 0xFF)}; len[2] = std::byte{(uint8_t)((contents.size() >> 16) & 0xFF)}; m_send_l_cipher->Crypt(len, output.first(LENGTH_LEN)); // Encrypt plaintext. std::byte header[HEADER_LEN] = {ignore ? IGNORE_BIT : std::byte{0}}; m_send_p_cipher->Encrypt(header, contents, aad, output.subspan(LENGTH_LEN)); } uint32_t BIP324Cipher::DecryptLength(Span<const std::byte> input) noexcept { assert(input.size() == LENGTH_LEN); std::byte buf[LENGTH_LEN]; // Decrypt length m_recv_l_cipher->Crypt(input, buf); // Convert to number. return uint32_t(buf[0]) + (uint32_t(buf[1]) << 8) + (uint32_t(buf[2]) << 16); } bool BIP324Cipher::Decrypt(Span<const std::byte> input, Span<const std::byte> aad, bool& ignore, Span<std::byte> contents) noexcept { assert(input.size() + LENGTH_LEN == contents.size() + EXPANSION); std::byte header[HEADER_LEN]; if (!m_recv_p_cipher->Decrypt(input, aad, header, contents)) return false; ignore = (header[0] & IGNORE_BIT) == IGNORE_BIT; return true; }
0
bitcoin
bitcoin/src/txorphanage.cpp
// Copyright (c) 2021-2022 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 <txorphanage.h> #include <consensus/validation.h> #include <logging.h> #include <policy/policy.h> #include <primitives/transaction.h> #include <cassert> /** Expiration time for orphan transactions in seconds */ static constexpr int64_t ORPHAN_TX_EXPIRE_TIME = 20 * 60; /** Minimum time between orphan transactions expire time checks in seconds */ static constexpr int64_t ORPHAN_TX_EXPIRE_INTERVAL = 5 * 60; bool TxOrphanage::AddTx(const CTransactionRef& tx, NodeId peer) { LOCK(m_mutex); const Txid& hash = tx->GetHash(); const Wtxid& wtxid = tx->GetWitnessHash(); if (m_orphans.count(hash)) return false; // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 100 orphans, each of which is at most 100,000 bytes big is // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case): unsigned int sz = GetTransactionWeight(*tx); if (sz > MAX_STANDARD_TX_WEIGHT) { LogPrint(BCLog::TXPACKAGES, "ignoring large orphan tx (size: %u, txid: %s, wtxid: %s)\n", sz, hash.ToString(), wtxid.ToString()); return false; } auto ret = m_orphans.emplace(hash, OrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME, m_orphan_list.size()}); assert(ret.second); m_orphan_list.push_back(ret.first); // Allow for lookups in the orphan pool by wtxid, as well as txid m_wtxid_to_orphan_it.emplace(tx->GetWitnessHash(), ret.first); for (const CTxIn& txin : tx->vin) { m_outpoint_to_orphan_it[txin.prevout].insert(ret.first); } LogPrint(BCLog::TXPACKAGES, "stored orphan tx %s (wtxid=%s) (mapsz %u outsz %u)\n", hash.ToString(), wtxid.ToString(), m_orphans.size(), m_outpoint_to_orphan_it.size()); return true; } int TxOrphanage::EraseTx(const Txid& txid) { LOCK(m_mutex); return EraseTxNoLock(txid); } int TxOrphanage::EraseTxNoLock(const Txid& txid) { AssertLockHeld(m_mutex); std::map<Txid, OrphanTx>::iterator it = m_orphans.find(txid); if (it == m_orphans.end()) return 0; for (const CTxIn& txin : it->second.tx->vin) { auto itPrev = m_outpoint_to_orphan_it.find(txin.prevout); if (itPrev == m_outpoint_to_orphan_it.end()) continue; itPrev->second.erase(it); if (itPrev->second.empty()) m_outpoint_to_orphan_it.erase(itPrev); } size_t old_pos = it->second.list_pos; assert(m_orphan_list[old_pos] == it); if (old_pos + 1 != m_orphan_list.size()) { // Unless we're deleting the last entry in m_orphan_list, move the last // entry to the position we're deleting. auto it_last = m_orphan_list.back(); m_orphan_list[old_pos] = it_last; it_last->second.list_pos = old_pos; } const auto& wtxid = it->second.tx->GetWitnessHash(); LogPrint(BCLog::TXPACKAGES, " removed orphan tx %s (wtxid=%s)\n", txid.ToString(), wtxid.ToString()); m_orphan_list.pop_back(); m_wtxid_to_orphan_it.erase(it->second.tx->GetWitnessHash()); m_orphans.erase(it); return 1; } void TxOrphanage::EraseForPeer(NodeId peer) { LOCK(m_mutex); m_peer_work_set.erase(peer); int nErased = 0; std::map<Txid, OrphanTx>::iterator iter = m_orphans.begin(); while (iter != m_orphans.end()) { std::map<Txid, OrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid if (maybeErase->second.fromPeer == peer) { nErased += EraseTxNoLock(maybeErase->second.tx->GetHash()); } } if (nErased > 0) LogPrint(BCLog::TXPACKAGES, "Erased %d orphan tx from peer=%d\n", nErased, peer); } void TxOrphanage::LimitOrphans(unsigned int max_orphans, FastRandomContext& rng) { LOCK(m_mutex); unsigned int nEvicted = 0; static int64_t nNextSweep; int64_t nNow = GetTime(); if (nNextSweep <= nNow) { // Sweep out expired orphan pool entries: int nErased = 0; int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL; std::map<Txid, OrphanTx>::iterator iter = m_orphans.begin(); while (iter != m_orphans.end()) { std::map<Txid, OrphanTx>::iterator maybeErase = iter++; if (maybeErase->second.nTimeExpire <= nNow) { nErased += EraseTxNoLock(maybeErase->second.tx->GetHash()); } else { nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime); } } // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan. nNextSweep = nMinExpTime + ORPHAN_TX_EXPIRE_INTERVAL; if (nErased > 0) LogPrint(BCLog::TXPACKAGES, "Erased %d orphan tx due to expiration\n", nErased); } while (m_orphans.size() > max_orphans) { // Evict a random orphan: size_t randompos = rng.randrange(m_orphan_list.size()); EraseTxNoLock(m_orphan_list[randompos]->first); ++nEvicted; } if (nEvicted > 0) LogPrint(BCLog::TXPACKAGES, "orphanage overflow, removed %u tx\n", nEvicted); } void TxOrphanage::AddChildrenToWorkSet(const CTransaction& tx) { LOCK(m_mutex); for (unsigned int i = 0; i < tx.vout.size(); i++) { const auto it_by_prev = m_outpoint_to_orphan_it.find(COutPoint(tx.GetHash(), i)); if (it_by_prev != m_outpoint_to_orphan_it.end()) { for (const auto& elem : it_by_prev->second) { // Get this source peer's work set, emplacing an empty set if it didn't exist // (note: if this peer wasn't still connected, we would have removed the orphan tx already) std::set<Txid>& orphan_work_set = m_peer_work_set.try_emplace(elem->second.fromPeer).first->second; // Add this tx to the work set orphan_work_set.insert(elem->first); LogPrint(BCLog::TXPACKAGES, "added %s (wtxid=%s) to peer %d workset\n", tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), elem->second.fromPeer); } } } } bool TxOrphanage::HaveTx(const GenTxid& gtxid) const { LOCK(m_mutex); if (gtxid.IsWtxid()) { return m_wtxid_to_orphan_it.count(Wtxid::FromUint256(gtxid.GetHash())); } else { return m_orphans.count(Txid::FromUint256(gtxid.GetHash())); } } CTransactionRef TxOrphanage::GetTxToReconsider(NodeId peer) { LOCK(m_mutex); auto work_set_it = m_peer_work_set.find(peer); if (work_set_it != m_peer_work_set.end()) { auto& work_set = work_set_it->second; while (!work_set.empty()) { Txid txid = *work_set.begin(); work_set.erase(work_set.begin()); const auto orphan_it = m_orphans.find(txid); if (orphan_it != m_orphans.end()) { return orphan_it->second.tx; } } } return nullptr; } bool TxOrphanage::HaveTxToReconsider(NodeId peer) { LOCK(m_mutex); auto work_set_it = m_peer_work_set.find(peer); if (work_set_it != m_peer_work_set.end()) { auto& work_set = work_set_it->second; return !work_set.empty(); } return false; } void TxOrphanage::EraseForBlock(const CBlock& block) { LOCK(m_mutex); std::vector<Txid> vOrphanErase; for (const CTransactionRef& ptx : block.vtx) { const CTransaction& tx = *ptx; // Which orphan pool entries must we evict? for (const auto& txin : tx.vin) { auto itByPrev = m_outpoint_to_orphan_it.find(txin.prevout); if (itByPrev == m_outpoint_to_orphan_it.end()) continue; for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) { const CTransaction& orphanTx = *(*mi)->second.tx; const auto& orphanHash = orphanTx.GetHash(); vOrphanErase.push_back(orphanHash); } } } // Erase orphan transactions included or precluded by this block if (vOrphanErase.size()) { int nErased = 0; for (const auto& orphanHash : vOrphanErase) { nErased += EraseTxNoLock(orphanHash); } LogPrint(BCLog::TXPACKAGES, "Erased %d orphan tx included or conflicted by block\n", nErased); } }
0
bitcoin
bitcoin/src/arith_uint256.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_ARITH_UINT256_H #define BITCOIN_ARITH_UINT256_H #include <cstdint> #include <cstring> #include <limits> #include <stdexcept> #include <string> class uint256; class uint_error : public std::runtime_error { public: explicit uint_error(const std::string& str) : std::runtime_error(str) {} }; /** Template base class for unsigned big integers. */ template<unsigned int BITS> class base_uint { protected: static_assert(BITS / 32 > 0 && BITS % 32 == 0, "Template parameter BITS must be a positive multiple of 32."); static constexpr int WIDTH = BITS / 32; uint32_t pn[WIDTH]; public: base_uint() { for (int i = 0; i < WIDTH; i++) pn[i] = 0; } base_uint(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] = b.pn[i]; } base_uint& operator=(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] = b.pn[i]; return *this; } base_uint(uint64_t b) { pn[0] = (unsigned int)b; pn[1] = (unsigned int)(b >> 32); for (int i = 2; i < WIDTH; i++) pn[i] = 0; } base_uint operator~() const { base_uint ret; for (int i = 0; i < WIDTH; i++) ret.pn[i] = ~pn[i]; return ret; } base_uint operator-() const { base_uint ret; for (int i = 0; i < WIDTH; i++) ret.pn[i] = ~pn[i]; ++ret; return ret; } double getdouble() const; base_uint& operator=(uint64_t b) { pn[0] = (unsigned int)b; pn[1] = (unsigned int)(b >> 32); for (int i = 2; i < WIDTH; i++) pn[i] = 0; return *this; } base_uint& operator^=(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] ^= b.pn[i]; return *this; } base_uint& operator&=(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] &= b.pn[i]; return *this; } base_uint& operator|=(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] |= b.pn[i]; return *this; } base_uint& operator^=(uint64_t b) { pn[0] ^= (unsigned int)b; pn[1] ^= (unsigned int)(b >> 32); return *this; } base_uint& operator|=(uint64_t b) { pn[0] |= (unsigned int)b; pn[1] |= (unsigned int)(b >> 32); return *this; } base_uint& operator<<=(unsigned int shift); base_uint& operator>>=(unsigned int shift); base_uint& operator+=(const base_uint& b) { uint64_t carry = 0; for (int i = 0; i < WIDTH; i++) { uint64_t n = carry + pn[i] + b.pn[i]; pn[i] = n & 0xffffffff; carry = n >> 32; } return *this; } base_uint& operator-=(const base_uint& b) { *this += -b; return *this; } base_uint& operator+=(uint64_t b64) { base_uint b; b = b64; *this += b; return *this; } base_uint& operator-=(uint64_t b64) { base_uint b; b = b64; *this += -b; return *this; } base_uint& operator*=(uint32_t b32); base_uint& operator*=(const base_uint& b); base_uint& operator/=(const base_uint& b); base_uint& operator++() { // prefix operator int i = 0; while (i < WIDTH && ++pn[i] == 0) i++; return *this; } base_uint operator++(int) { // postfix operator const base_uint ret = *this; ++(*this); return ret; } base_uint& operator--() { // prefix operator int i = 0; while (i < WIDTH && --pn[i] == std::numeric_limits<uint32_t>::max()) i++; return *this; } base_uint operator--(int) { // postfix operator const base_uint ret = *this; --(*this); return ret; } int CompareTo(const base_uint& b) const; bool EqualTo(uint64_t b) const; friend inline base_uint operator+(const base_uint& a, const base_uint& b) { return base_uint(a) += b; } friend inline base_uint operator-(const base_uint& a, const base_uint& b) { return base_uint(a) -= b; } friend inline base_uint operator*(const base_uint& a, const base_uint& b) { return base_uint(a) *= b; } friend inline base_uint operator/(const base_uint& a, const base_uint& b) { return base_uint(a) /= b; } friend inline base_uint operator|(const base_uint& a, const base_uint& b) { return base_uint(a) |= b; } friend inline base_uint operator&(const base_uint& a, const base_uint& b) { return base_uint(a) &= b; } friend inline base_uint operator^(const base_uint& a, const base_uint& b) { return base_uint(a) ^= b; } friend inline base_uint operator>>(const base_uint& a, int shift) { return base_uint(a) >>= shift; } friend inline base_uint operator<<(const base_uint& a, int shift) { return base_uint(a) <<= shift; } friend inline base_uint operator*(const base_uint& a, uint32_t b) { return base_uint(a) *= b; } friend inline bool operator==(const base_uint& a, const base_uint& b) { return memcmp(a.pn, b.pn, sizeof(a.pn)) == 0; } friend inline bool operator!=(const base_uint& a, const base_uint& b) { return memcmp(a.pn, b.pn, sizeof(a.pn)) != 0; } friend inline bool operator>(const base_uint& a, const base_uint& b) { return a.CompareTo(b) > 0; } friend inline bool operator<(const base_uint& a, const base_uint& b) { return a.CompareTo(b) < 0; } friend inline bool operator>=(const base_uint& a, const base_uint& b) { return a.CompareTo(b) >= 0; } friend inline bool operator<=(const base_uint& a, const base_uint& b) { return a.CompareTo(b) <= 0; } friend inline bool operator==(const base_uint& a, uint64_t b) { return a.EqualTo(b); } friend inline bool operator!=(const base_uint& a, uint64_t b) { return !a.EqualTo(b); } std::string GetHex() const; std::string ToString() const; unsigned int size() const { return sizeof(pn); } /** * Returns the position of the highest bit set plus one, or zero if the * value is zero. */ unsigned int bits() const; uint64_t GetLow64() const { static_assert(WIDTH >= 2, "Assertion WIDTH >= 2 failed (WIDTH = BITS / 32). BITS is a template parameter."); return pn[0] | (uint64_t)pn[1] << 32; } }; /** 256-bit unsigned big integer. */ class arith_uint256 : public base_uint<256> { public: arith_uint256() {} arith_uint256(const base_uint<256>& b) : base_uint<256>(b) {} arith_uint256(uint64_t b) : base_uint<256>(b) {} /** * The "compact" format is a representation of a whole * number N using an unsigned 32bit number similar to a * floating point format. * The most significant 8 bits are the unsigned exponent of base 256. * This exponent can be thought of as "number of bytes of N". * The lower 23 bits are the mantissa. * Bit number 24 (0x800000) represents the sign of N. * N = (-1^sign) * mantissa * 256^(exponent-3) * * Satoshi's original implementation used BN_bn2mpi() and BN_mpi2bn(). * MPI uses the most significant bit of the first byte as sign. * Thus 0x1234560000 is compact (0x05123456) * and 0xc0de000000 is compact (0x0600c0de) * * Bitcoin only uses this "compact" format for encoding difficulty * targets, which are unsigned 256bit quantities. Thus, all the * complexities of the sign bit and using base 256 are probably an * implementation accident. */ arith_uint256& SetCompact(uint32_t nCompact, bool *pfNegative = nullptr, bool *pfOverflow = nullptr); uint32_t GetCompact(bool fNegative = false) const; friend uint256 ArithToUint256(const arith_uint256 &); friend arith_uint256 UintToArith256(const uint256 &); }; uint256 ArithToUint256(const arith_uint256 &); arith_uint256 UintToArith256(const uint256 &); extern template class base_uint<256>; #endif // BITCOIN_ARITH_UINT256_H
0
bitcoin
bitcoin/src/Makefile.qttest.include
# Copyright (c) 2013-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. bin_PROGRAMS += qt/test/test_bitcoin-qt TESTS += qt/test/test_bitcoin-qt TEST_QT_MOC_CPP = \ qt/test/moc_apptests.cpp \ qt/test/moc_optiontests.cpp \ qt/test/moc_rpcnestedtests.cpp \ qt/test/moc_uritests.cpp if ENABLE_WALLET TEST_QT_MOC_CPP += \ qt/test/moc_addressbooktests.cpp \ qt/test/moc_wallettests.cpp endif # ENABLE_WALLET TEST_QT_H = \ qt/test/addressbooktests.h \ qt/test/apptests.h \ qt/test/optiontests.h \ qt/test/rpcnestedtests.h \ qt/test/uritests.h \ qt/test/util.h \ qt/test/wallettests.h qt_test_test_bitcoin_qt_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BITCOIN_QT_INCLUDES) \ $(QT_INCLUDES) $(QT_TEST_INCLUDES) $(BOOST_CPPFLAGS) qt_test_test_bitcoin_qt_SOURCES = \ init/bitcoin-qt.cpp \ qt/test/apptests.cpp \ qt/test/optiontests.cpp \ qt/test/rpcnestedtests.cpp \ qt/test/test_main.cpp \ qt/test/uritests.cpp \ qt/test/util.cpp \ $(TEST_QT_H) if ENABLE_WALLET qt_test_test_bitcoin_qt_SOURCES += \ qt/test/addressbooktests.cpp \ qt/test/wallettests.cpp \ wallet/test/wallet_test_fixture.cpp endif # ENABLE_WALLET nodist_qt_test_test_bitcoin_qt_SOURCES = $(TEST_QT_MOC_CPP) qt_test_test_bitcoin_qt_LDADD = $(LIBBITCOINQT) $(LIBBITCOIN_NODE) $(LIBTEST_UTIL) if ENABLE_WALLET qt_test_test_bitcoin_qt_LDADD += $(LIBBITCOIN_UTIL) $(LIBBITCOIN_WALLET) endif if ENABLE_ZMQ qt_test_test_bitcoin_qt_LDADD += $(LIBBITCOIN_ZMQ) $(ZMQ_LIBS) endif qt_test_test_bitcoin_qt_LDADD += $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBITCOIN_UTIL) $(LIBBITCOIN_CONSENSUS) $(LIBBITCOIN_CRYPTO) $(LIBUNIVALUE) $(LIBLEVELDB) \ $(LIBMEMENV) $(QT_LIBS) $(QT_DBUS_LIBS) $(QT_TEST_LIBS) \ $(QR_LIBS) $(BDB_LIBS) $(MINIUPNPC_LIBS) $(NATPMP_LIBS) $(LIBSECP256K1) \ $(EVENT_PTHREADS_LIBS) $(EVENT_LIBS) $(SQLITE_LIBS) qt_test_test_bitcoin_qt_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(QT_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) $(PTHREAD_FLAGS) qt_test_test_bitcoin_qt_CXXFLAGS = $(AM_CXXFLAGS) $(QT_PIE_FLAGS) CLEAN_BITCOIN_QT_TEST = $(TEST_QT_MOC_CPP) qt/test/*.gcda qt/test/*.gcno CLEANFILES += $(CLEAN_BITCOIN_QT_TEST) test_bitcoin_qt : qt/test/test_bitcoin-qt$(EXEEXT) test_bitcoin_qt_check : qt/test/test_bitcoin-qt$(EXEEXT) FORCE $(MAKE) check-TESTS TESTS=$^ test_bitcoin_qt_clean: FORCE rm -f $(CLEAN_BITCOIN_QT_TEST) $(qt_test_test_bitcoin_qt_OBJECTS)
0
bitcoin
bitcoin/src/core_read.cpp
// Copyright (c) 2009-2022 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 <core_io.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <script/script.h> #include <script/sign.h> #include <serialize.h> #include <streams.h> #include <util/result.h> #include <util/strencodings.h> #include <algorithm> #include <string> namespace { class OpCodeParser { private: std::map<std::string, opcodetype> mapOpNames; public: OpCodeParser() { for (unsigned int op = 0; op <= MAX_OPCODE; ++op) { // Allow OP_RESERVED to get into mapOpNames if (op < OP_NOP && op != OP_RESERVED) { continue; } std::string strName = GetOpName(static_cast<opcodetype>(op)); if (strName == "OP_UNKNOWN") { continue; } mapOpNames[strName] = static_cast<opcodetype>(op); // Convenience: OP_ADD and just ADD are both recognized: if (strName.compare(0, 3, "OP_") == 0) { // strName starts with "OP_" mapOpNames[strName.substr(3)] = static_cast<opcodetype>(op); } } } opcodetype Parse(const std::string& s) const { auto it = mapOpNames.find(s); if (it == mapOpNames.end()) throw std::runtime_error("script parse error: unknown opcode"); return it->second; } }; opcodetype ParseOpCode(const std::string& s) { static const OpCodeParser ocp; return ocp.Parse(s); } } // namespace CScript ParseScript(const std::string& s) { CScript result; std::vector<std::string> words = SplitString(s, " \t\n"); for (const std::string& w : words) { if (w.empty()) { // Empty string, ignore. (SplitString doesn't combine multiple separators) } 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 const auto num{ToIntegral<int64_t>(w)}; // limit the range of numbers ParseScript accepts in decimal // since numbers outside -0xFFFFFFFF...0xFFFFFFFF are illegal in scripts if (!num.has_value() || num > int64_t{0xffffffff} || num < -1 * int64_t{0xffffffff}) { throw std::runtime_error("script parse error: decimal numeric value only allowed in the " "range -0xFFFFFFFF...0xFFFFFFFF"); } result << num.value(); } 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 && 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. std::vector<unsigned char> value(w.begin() + 1, w.end() - 1); result << value; } else { // opcode, e.g. OP_ADD or ADD: result << ParseOpCode(w); } } return result; } // Check that all of the input and output scripts of a transaction contains valid opcodes static bool CheckTxScriptsSanity(const CMutableTransaction& tx) { // Check input scripts for non-coinbase txs if (!CTransaction(tx).IsCoinBase()) { for (unsigned int i = 0; i < tx.vin.size(); i++) { if (!tx.vin[i].scriptSig.HasValidOps() || tx.vin[i].scriptSig.size() > MAX_SCRIPT_SIZE) { return false; } } } // Check output scripts for (unsigned int i = 0; i < tx.vout.size(); i++) { if (!tx.vout[i].scriptPubKey.HasValidOps() || tx.vout[i].scriptPubKey.size() > MAX_SCRIPT_SIZE) { return false; } } return true; } static bool DecodeTx(CMutableTransaction& tx, const std::vector<unsigned char>& tx_data, bool try_no_witness, bool try_witness) { // General strategy: // - Decode both with extended serialization (which interprets the 0x0001 tag as a marker for // the presence of witnesses) and with legacy serialization (which interprets the tag as a // 0-input 1-output incomplete transaction). // - Restricted by try_no_witness (which disables legacy if false) and try_witness (which // disables extended if false). // - Ignore serializations that do not fully consume the hex string. // - If neither succeeds, fail. // - If only one succeeds, return that one. // - If both decode attempts succeed: // - If only one passes the CheckTxScriptsSanity check, return that one. // - If neither or both pass CheckTxScriptsSanity, return the extended one. CMutableTransaction tx_extended, tx_legacy; bool ok_extended = false, ok_legacy = false; // Try decoding with extended serialization support, and remember if the result successfully // consumes the entire input. if (try_witness) { DataStream ssData(tx_data); try { ssData >> TX_WITH_WITNESS(tx_extended); if (ssData.empty()) ok_extended = true; } catch (const std::exception&) { // Fall through. } } // Optimization: if extended decoding succeeded and the result passes CheckTxScriptsSanity, // don't bother decoding the other way. if (ok_extended && CheckTxScriptsSanity(tx_extended)) { tx = std::move(tx_extended); return true; } // Try decoding with legacy serialization, and remember if the result successfully consumes the entire input. if (try_no_witness) { DataStream ssData(tx_data); try { ssData >> TX_NO_WITNESS(tx_legacy); if (ssData.empty()) ok_legacy = true; } catch (const std::exception&) { // Fall through. } } // If legacy decoding succeeded and passes CheckTxScriptsSanity, that's our answer, as we know // at this point that extended decoding either failed or doesn't pass the sanity check. if (ok_legacy && CheckTxScriptsSanity(tx_legacy)) { tx = std::move(tx_legacy); return true; } // If extended decoding succeeded, and neither decoding passes sanity, return the extended one. if (ok_extended) { tx = std::move(tx_extended); return true; } // If legacy decoding succeeded and extended didn't, return the legacy one. if (ok_legacy) { tx = std::move(tx_legacy); return true; } // If none succeeded, we failed. return false; } bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness) { if (!IsHex(hex_tx)) { return false; } std::vector<unsigned char> txData(ParseHex(hex_tx)); return DecodeTx(tx, txData, try_no_witness, try_witness); } bool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header) { if (!IsHex(hex_header)) return false; const std::vector<unsigned char> header_data{ParseHex(hex_header)}; DataStream ser_header{header_data}; try { ser_header >> header; } catch (const std::exception&) { return false; } return true; } bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk) { if (!IsHex(strHexBlk)) return false; std::vector<unsigned char> blockData(ParseHex(strHexBlk)); DataStream ssBlock(blockData); try { ssBlock >> TX_WITH_WITNESS(block); } catch (const std::exception&) { return false; } return true; } bool ParseHashStr(const std::string& strHex, uint256& result) { if ((strHex.size() != 64) || !IsHex(strHex)) return false; result.SetHex(strHex); return true; } util::Result<int> SighashFromStr(const std::string& sighash) { static std::map<std::string, int> map_sighash_values = { {std::string("DEFAULT"), int(SIGHASH_DEFAULT)}, {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)}, }; const auto& it = map_sighash_values.find(sighash); if (it != map_sighash_values.end()) { return it->second; } else { return util::Error{Untranslated(sighash + " is not a valid sighash parameter.")}; } }
0
bitcoin
bitcoin/src/streams.cpp
// Copyright (c) 2009-present The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or https://opensource.org/license/mit/. #include <span.h> #include <streams.h> #include <array> std::size_t AutoFile::detail_fread(Span<std::byte> dst) { if (!m_file) throw std::ios_base::failure("AutoFile::read: file handle is nullptr"); if (m_xor.empty()) { return std::fread(dst.data(), 1, dst.size(), m_file); } else { const auto init_pos{std::ftell(m_file)}; if (init_pos < 0) throw std::ios_base::failure("AutoFile::read: ftell failed"); std::size_t ret{std::fread(dst.data(), 1, dst.size(), m_file)}; util::Xor(dst.subspan(0, ret), m_xor, init_pos); return ret; } } void AutoFile::read(Span<std::byte> dst) { if (detail_fread(dst) != dst.size()) { throw std::ios_base::failure(feof() ? "AutoFile::read: end of file" : "AutoFile::read: fread failed"); } } void AutoFile::ignore(size_t nSize) { if (!m_file) throw std::ios_base::failure("AutoFile::ignore: file handle is nullptr"); unsigned char data[4096]; while (nSize > 0) { size_t nNow = std::min<size_t>(nSize, sizeof(data)); if (std::fread(data, 1, nNow, m_file) != nNow) { throw std::ios_base::failure(feof() ? "AutoFile::ignore: end of file" : "AutoFile::ignore: fread failed"); } nSize -= nNow; } } void AutoFile::write(Span<const std::byte> src) { if (!m_file) throw std::ios_base::failure("AutoFile::write: file handle is nullptr"); if (m_xor.empty()) { if (std::fwrite(src.data(), 1, src.size(), m_file) != src.size()) { throw std::ios_base::failure("AutoFile::write: write failed"); } } else { auto current_pos{std::ftell(m_file)}; if (current_pos < 0) throw std::ios_base::failure("AutoFile::write: ftell failed"); std::array<std::byte, 4096> buf; while (src.size() > 0) { auto buf_now{Span{buf}.first(std::min<size_t>(src.size(), buf.size()))}; std::copy(src.begin(), src.begin() + buf_now.size(), buf_now.begin()); util::Xor(buf_now, m_xor, current_pos); if (std::fwrite(buf_now.data(), 1, buf_now.size(), m_file) != buf_now.size()) { throw std::ios_base::failure{"XorFile::write: failed"}; } src = src.subspan(buf_now.size()); current_pos += buf_now.size(); } } }
0
bitcoin
bitcoin/src/txdb.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 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 <txdb.h> #include <coins.h> #include <dbwrapper.h> #include <logging.h> #include <primitives/transaction.h> #include <random.h> #include <serialize.h> #include <uint256.h> #include <util/vector.h> #include <cassert> #include <cstdlib> #include <iterator> #include <utility> static constexpr uint8_t DB_COIN{'C'}; static constexpr uint8_t DB_BEST_BLOCK{'B'}; static constexpr uint8_t DB_HEAD_BLOCKS{'H'}; // Keys used in previous version that might still be found in the DB: static constexpr uint8_t DB_COINS{'c'}; bool CCoinsViewDB::NeedsUpgrade() { std::unique_ptr<CDBIterator> cursor{m_db->NewIterator()}; // DB_COINS was deprecated in v0.15.0, commit // 1088b02f0ccd7358d2b7076bb9e122d59d502d02 cursor->Seek(std::make_pair(DB_COINS, uint256{})); return cursor->Valid(); } namespace { struct CoinEntry { COutPoint* outpoint; uint8_t key; explicit CoinEntry(const COutPoint* ptr) : outpoint(const_cast<COutPoint*>(ptr)), key(DB_COIN) {} SERIALIZE_METHODS(CoinEntry, obj) { READWRITE(obj.key, obj.outpoint->hash, VARINT(obj.outpoint->n)); } }; } // namespace CCoinsViewDB::CCoinsViewDB(DBParams db_params, CoinsViewOptions options) : m_db_params{std::move(db_params)}, m_options{std::move(options)}, m_db{std::make_unique<CDBWrapper>(m_db_params)} { } void CCoinsViewDB::ResizeCache(size_t new_cache_size) { // We can't do this operation with an in-memory DB since we'll lose all the coins upon // reset. if (!m_db_params.memory_only) { // Have to do a reset first to get the original `m_db` state to release its // filesystem lock. m_db.reset(); m_db_params.cache_bytes = new_cache_size; m_db_params.wipe_data = false; m_db = std::make_unique<CDBWrapper>(m_db_params); } } bool CCoinsViewDB::GetCoin(const COutPoint &outpoint, Coin &coin) const { return m_db->Read(CoinEntry(&outpoint), coin); } bool CCoinsViewDB::HaveCoin(const COutPoint &outpoint) const { return m_db->Exists(CoinEntry(&outpoint)); } uint256 CCoinsViewDB::GetBestBlock() const { uint256 hashBestChain; if (!m_db->Read(DB_BEST_BLOCK, hashBestChain)) return uint256(); return hashBestChain; } std::vector<uint256> CCoinsViewDB::GetHeadBlocks() const { std::vector<uint256> vhashHeadBlocks; if (!m_db->Read(DB_HEAD_BLOCKS, vhashHeadBlocks)) { return std::vector<uint256>(); } return vhashHeadBlocks; } bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase) { CDBBatch batch(*m_db); size_t count = 0; size_t changed = 0; assert(!hashBlock.IsNull()); uint256 old_tip = GetBestBlock(); if (old_tip.IsNull()) { // We may be in the middle of replaying. std::vector<uint256> old_heads = GetHeadBlocks(); if (old_heads.size() == 2) { if (old_heads[0] != hashBlock) { LogPrintLevel(BCLog::COINDB, BCLog::Level::Error, "The coins database detected an inconsistent state, likely due to a previous crash or shutdown. You will need to restart bitcoind with the -reindex-chainstate or -reindex configuration option.\n"); } assert(old_heads[0] == hashBlock); old_tip = old_heads[1]; } } // In the first batch, mark the database as being in the middle of a // transition from old_tip to hashBlock. // A vector is used for future extensibility, as we may want to support // interrupting after partial writes from multiple independent reorgs. batch.Erase(DB_BEST_BLOCK); batch.Write(DB_HEAD_BLOCKS, Vector(hashBlock, old_tip)); for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { CoinEntry entry(&it->first); if (it->second.coin.IsSpent()) batch.Erase(entry); else batch.Write(entry, it->second.coin); changed++; } count++; it = erase ? mapCoins.erase(it) : std::next(it); if (batch.SizeEstimate() > m_options.batch_write_bytes) { LogPrint(BCLog::COINDB, "Writing partial batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0)); m_db->WriteBatch(batch); batch.Clear(); if (m_options.simulate_crash_ratio) { static FastRandomContext rng; if (rng.randrange(m_options.simulate_crash_ratio) == 0) { LogPrintf("Simulating a crash. Goodbye.\n"); _Exit(0); } } } } // In the last batch, mark the database as consistent with hashBlock again. batch.Erase(DB_HEAD_BLOCKS); batch.Write(DB_BEST_BLOCK, hashBlock); LogPrint(BCLog::COINDB, "Writing final batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0)); bool ret = m_db->WriteBatch(batch); LogPrint(BCLog::COINDB, "Committed %u changed transaction outputs (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count); return ret; } size_t CCoinsViewDB::EstimateSize() const { return m_db->EstimateSize(DB_COIN, uint8_t(DB_COIN + 1)); } /** Specialization of CCoinsViewCursor to iterate over a CCoinsViewDB */ class CCoinsViewDBCursor: public CCoinsViewCursor { public: // Prefer using CCoinsViewDB::Cursor() since we want to perform some // cache warmup on instantiation. CCoinsViewDBCursor(CDBIterator* pcursorIn, const uint256&hashBlockIn): CCoinsViewCursor(hashBlockIn), pcursor(pcursorIn) {} ~CCoinsViewDBCursor() = default; bool GetKey(COutPoint &key) const override; bool GetValue(Coin &coin) const override; bool Valid() const override; void Next() override; private: std::unique_ptr<CDBIterator> pcursor; std::pair<char, COutPoint> keyTmp; friend class CCoinsViewDB; }; std::unique_ptr<CCoinsViewCursor> CCoinsViewDB::Cursor() const { auto i = std::make_unique<CCoinsViewDBCursor>( const_cast<CDBWrapper&>(*m_db).NewIterator(), GetBestBlock()); /* It seems that there are no "const iterators" for LevelDB. Since we only need read operations on it, use a const-cast to get around that restriction. */ i->pcursor->Seek(DB_COIN); // Cache key of first record if (i->pcursor->Valid()) { CoinEntry entry(&i->keyTmp.second); i->pcursor->GetKey(entry); i->keyTmp.first = entry.key; } else { i->keyTmp.first = 0; // Make sure Valid() and GetKey() return false } return i; } bool CCoinsViewDBCursor::GetKey(COutPoint &key) const { // Return cached key if (keyTmp.first == DB_COIN) { key = keyTmp.second; return true; } return false; } bool CCoinsViewDBCursor::GetValue(Coin &coin) const { return pcursor->GetValue(coin); } bool CCoinsViewDBCursor::Valid() const { return keyTmp.first == DB_COIN; } void CCoinsViewDBCursor::Next() { pcursor->Next(); CoinEntry entry(&keyTmp.second); if (!pcursor->Valid() || !pcursor->GetKey(entry)) { keyTmp.first = 0; // Invalidate cached key after last record so that Valid() and GetKey() return false } else { keyTmp.first = entry.key; } }
0
bitcoin
bitcoin/src/versionbits.h
// Copyright (c) 2016-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_VERSIONBITS_H #define BITCOIN_VERSIONBITS_H #include <chain.h> #include <sync.h> #include <map> /** What block version to use for new blocks (pre versionbits) */ static const int32_t VERSIONBITS_LAST_OLD_BLOCK_VERSION = 4; /** What bits to set in version for versionbits blocks */ static const int32_t VERSIONBITS_TOP_BITS = 0x20000000UL; /** What bitmask determines whether versionbits is in use */ static const int32_t VERSIONBITS_TOP_MASK = 0xE0000000UL; /** Total bits available for versionbits */ static const int32_t VERSIONBITS_NUM_BITS = 29; /** BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages. * State transitions happen during retarget period if conditions are met * In case of reorg, transitions can go backward. Without transition, state is * inherited between periods. All blocks of a period share the same state. */ enum class ThresholdState { DEFINED, // First state that each softfork starts out as. The genesis block is by definition in this state for each deployment. STARTED, // For blocks past the starttime. LOCKED_IN, // For at least one retarget period after the first retarget period with STARTED blocks of which at least threshold have the associated bit set in nVersion, until min_activation_height is reached. ACTIVE, // For all blocks after the LOCKED_IN retarget period (final state) FAILED, // For all blocks once the first retarget period after the timeout time is hit, if LOCKED_IN wasn't already reached (final state) }; // A map that gives the state for blocks whose height is a multiple of Period(). // The map is indexed by the block's parent, however, so all keys in the map // will either be nullptr or a block with (height + 1) % Period() == 0. typedef std::map<const CBlockIndex*, ThresholdState> ThresholdConditionCache; /** Display status of an in-progress BIP9 softfork */ struct BIP9Stats { /** Length of blocks of the BIP9 signalling period */ int period; /** Number of blocks with the version bit set required to activate the softfork */ int threshold; /** Number of blocks elapsed since the beginning of the current period */ int elapsed; /** Number of blocks with the version bit set since the beginning of the current period */ int count; /** False if there are not enough blocks left in this period to pass activation threshold */ bool possible; }; /** * Abstract class that implements BIP9-style threshold logic, and caches results. */ class AbstractThresholdConditionChecker { protected: virtual bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const =0; virtual int64_t BeginTime(const Consensus::Params& params) const =0; virtual int64_t EndTime(const Consensus::Params& params) const =0; virtual int MinActivationHeight(const Consensus::Params& params) const { return 0; } virtual int Period(const Consensus::Params& params) const =0; virtual int Threshold(const Consensus::Params& params) const =0; public: /** Returns the numerical statistics of an in-progress BIP9 softfork in the period including pindex * If provided, signalling_blocks is set to true/false based on whether each block in the period signalled */ BIP9Stats GetStateStatisticsFor(const CBlockIndex* pindex, const Consensus::Params& params, std::vector<bool>* signalling_blocks = nullptr) const; /** Returns the state for pindex A based on parent pindexPrev B. Applies any state transition if conditions are present. * Caches state from first block of period. */ ThresholdState GetStateFor(const CBlockIndex* pindexPrev, const Consensus::Params& params, ThresholdConditionCache& cache) const; /** Returns the height since when the ThresholdState has started for pindex A based on parent pindexPrev B, all blocks of a period share the same */ int GetStateSinceHeightFor(const CBlockIndex* pindexPrev, const Consensus::Params& params, ThresholdConditionCache& cache) const; }; /** BIP 9 allows multiple softforks to be deployed in parallel. We cache * per-period state for every one of them. */ class VersionBitsCache { private: Mutex m_mutex; ThresholdConditionCache m_caches[Consensus::MAX_VERSION_BITS_DEPLOYMENTS] GUARDED_BY(m_mutex); public: /** Get the numerical statistics for a given deployment for the signalling period that includes pindex. * If provided, signalling_blocks is set to true/false based on whether each block in the period signalled */ static BIP9Stats Statistics(const CBlockIndex* pindex, const Consensus::Params& params, Consensus::DeploymentPos pos, std::vector<bool>* signalling_blocks = nullptr); static uint32_t Mask(const Consensus::Params& params, Consensus::DeploymentPos pos); /** Get the BIP9 state for a given deployment for the block after pindexPrev. */ ThresholdState State(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); /** Get the block height at which the BIP9 deployment switched into the state for the block after pindexPrev. */ int StateSinceHeight(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); /** Determine what nVersion a new block should use */ int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); void Clear() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); }; #endif // BITCOIN_VERSIONBITS_H
0
bitcoin
bitcoin/src/clientversion.cpp
// Copyright (c) 2012-2022 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 <clientversion.h> #include <util/translation.h> #include <tinyformat.h> #include <sstream> #include <string> #include <vector> /** * Name of client reported in the 'version' message. Report the same name * for both bitcoind and bitcoin-qt, to make it harder for attackers to * target servers or GUI users specifically. */ const std::string CLIENT_NAME("Satoshi"); #ifdef HAVE_BUILD_INFO #include <obj/build.h> // The <obj/build.h>, which is generated by the build environment (share/genbuild.sh), // could contain only one line of the following: // - "#define BUILD_GIT_TAG ...", if the top commit is tagged // - "#define BUILD_GIT_COMMIT ...", if the top commit is not tagged // - "// No build information available", if proper git information is not available #endif //! git will put "#define GIT_COMMIT_ID ..." on the next line inside archives. $Format:%n#define GIT_COMMIT_ID "%H"$ #ifdef BUILD_GIT_TAG #define BUILD_DESC BUILD_GIT_TAG #define BUILD_SUFFIX "" #else #define BUILD_DESC "v" PACKAGE_VERSION #if CLIENT_VERSION_IS_RELEASE #define BUILD_SUFFIX "" #elif defined(BUILD_GIT_COMMIT) #define BUILD_SUFFIX "-" BUILD_GIT_COMMIT #elif defined(GIT_COMMIT_ID) #define BUILD_SUFFIX "-g" GIT_COMMIT_ID #else #define BUILD_SUFFIX "-unk" #endif #endif static std::string FormatVersion(int nVersion) { return strprintf("%d.%d.%d", nVersion / 10000, (nVersion / 100) % 100, nVersion % 100); } std::string FormatFullVersion() { static const std::string CLIENT_BUILD(BUILD_DESC BUILD_SUFFIX); return CLIENT_BUILD; } /** * 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) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) { std::vector<std::string>::const_iterator it(comments.begin()); ss << "(" << *it; for(++it; it != comments.end(); ++it) ss << "; " << *it; ss << ")"; } ss << "/"; return ss.str(); } std::string CopyrightHolders(const std::string& strPrefix) { const auto copyright_devs = strprintf(_(COPYRIGHT_HOLDERS).translated, COPYRIGHT_HOLDERS_SUBSTITUTION); std::string strCopyrightHolders = strPrefix + copyright_devs; // Make sure Bitcoin Core copyright is not removed by accident if (copyright_devs.find("Bitcoin Core") == std::string::npos) { strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers"; } return strCopyrightHolders; } std::string LicenseInfo() { const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>"; return CopyrightHolders(strprintf(_("Copyright (C) %i-%i").translated, 2009, COPYRIGHT_YEAR) + " ") + "\n" + "\n" + strprintf(_("Please contribute if you find %s useful. " "Visit %s for further information about the software.").translated, PACKAGE_NAME, "<" PACKAGE_URL ">") + "\n" + strprintf(_("The source code is available from %s.").translated, URL_SOURCE_CODE) + "\n" + "\n" + _("This is experimental software.").translated + "\n" + strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s").translated, "COPYING", "<https://opensource.org/licenses/MIT>") + "\n"; }
0
bitcoin
bitcoin/src/uint256.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2020 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 <uint256.h> #include <util/strencodings.h> template <unsigned int BITS> std::string base_blob<BITS>::GetHex() const { uint8_t m_data_rev[WIDTH]; for (int i = 0; i < WIDTH; ++i) { m_data_rev[i] = m_data[WIDTH - 1 - i]; } return HexStr(m_data_rev); } template <unsigned int BITS> void base_blob<BITS>::SetHex(const char* psz) { std::fill(m_data.begin(), m_data.end(), 0); // skip leading spaces while (IsSpace(*psz)) psz++; // skip 0x if (psz[0] == '0' && ToLower(psz[1]) == 'x') psz += 2; // hex string to uint size_t digits = 0; while (::HexDigit(psz[digits]) != -1) digits++; unsigned char* p1 = m_data.data(); unsigned char* pend = p1 + WIDTH; while (digits > 0 && p1 < pend) { *p1 = ::HexDigit(psz[--digits]); if (digits > 0) { *p1 |= ((unsigned char)::HexDigit(psz[--digits]) << 4); p1++; } } } template <unsigned int BITS> void base_blob<BITS>::SetHex(const std::string& str) { SetHex(str.c_str()); } template <unsigned int BITS> std::string base_blob<BITS>::ToString() const { return (GetHex()); } // Explicit instantiations for base_blob<160> template std::string base_blob<160>::GetHex() const; template std::string base_blob<160>::ToString() const; template void base_blob<160>::SetHex(const char*); template void base_blob<160>::SetHex(const std::string&); // Explicit instantiations for base_blob<256> template std::string base_blob<256>::GetHex() const; template std::string base_blob<256>::ToString() const; template void base_blob<256>::SetHex(const char*); template void base_blob<256>::SetHex(const std::string&); const uint256 uint256::ZERO(0); const uint256 uint256::ONE(1);
0
bitcoin
bitcoin/src/chainparams.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CHAINPARAMS_H #define BITCOIN_CHAINPARAMS_H #include <kernel/chainparams.h> // IWYU pragma: export #include <memory> class ArgsManager; /** * Creates and returns a std::unique_ptr<CChainParams> of the chosen chain. */ std::unique_ptr<const CChainParams> CreateChainParams(const ArgsManager& args, const ChainType chain); /** * Return the currently selected parameters. This won't change after app * startup, except for unit tests. */ const CChainParams &Params(); /** * Sets the params returned by Params() to those for the given chain type. */ void SelectParams(const ChainType chain); #endif // BITCOIN_CHAINPARAMS_H
0
bitcoin
bitcoin/src/span.h
// Copyright (c) 2018-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_SPAN_H #define BITCOIN_SPAN_H #include <algorithm> #include <cassert> #include <cstddef> #include <span> #include <type_traits> #ifdef DEBUG #define CONSTEXPR_IF_NOT_DEBUG #define ASSERT_IF_DEBUG(x) assert((x)) #else #define CONSTEXPR_IF_NOT_DEBUG constexpr #define ASSERT_IF_DEBUG(x) #endif #if defined(__clang__) #if __has_attribute(lifetimebound) #define SPAN_ATTR_LIFETIMEBOUND [[clang::lifetimebound]] #else #define SPAN_ATTR_LIFETIMEBOUND #endif #else #define SPAN_ATTR_LIFETIMEBOUND #endif /** A Span is an object that can refer to a contiguous sequence of objects. * * This file implements a subset of C++20's std::span. It can be considered * temporary compatibility code until C++20 and is designed to be a * self-contained abstraction without depending on other project files. For this * reason, Clang lifetimebound is defined here instead of including * <attributes.h>, which also defines it. * * Things to be aware of when writing code that deals with Spans: * * - Similar to references themselves, Spans are subject to reference lifetime * issues. The user is responsible for making sure the objects pointed to by * a Span live as long as the Span is used. For example: * * std::vector<int> vec{1,2,3,4}; * Span<int> sp(vec); * vec.push_back(5); * printf("%i\n", sp.front()); // UB! * * may exhibit undefined behavior, as increasing the size of a vector may * invalidate references. * * - One particular pitfall is that Spans can be constructed from temporaries, * but this is unsafe when the Span is stored in a variable, outliving the * temporary. For example, this will compile, but exhibits undefined behavior: * * Span<const int> sp(std::vector<int>{1, 2, 3}); * printf("%i\n", sp.front()); // UB! * * The lifetime of the vector ends when the statement it is created in ends. * Thus the Span is left with a dangling reference, and using it is undefined. * * - Due to Span's automatic creation from range-like objects (arrays, and data * types that expose a data() and size() member function), functions that * accept a Span as input parameter can be called with any compatible * range-like object. For example, this works: * * void Foo(Span<const int> arg); * * Foo(std::vector<int>{1, 2, 3}); // Works * * This is very useful in cases where a function truly does not care about the * container, and only about having exactly a range of elements. However it * may also be surprising to see automatic conversions in this case. * * When a function accepts a Span with a mutable element type, it will not * accept temporaries; only variables or other references. For example: * * void FooMut(Span<int> arg); * * FooMut(std::vector<int>{1, 2, 3}); // Does not compile * std::vector<int> baz{1, 2, 3}; * FooMut(baz); // Works * * This is similar to how functions that take (non-const) lvalue references * as input cannot accept temporaries. This does not work either: * * void FooVec(std::vector<int>& arg); * FooVec(std::vector<int>{1, 2, 3}); // Does not compile * * The idea is that if a function accepts a mutable reference, a meaningful * result will be present in that variable after the call. Passing a temporary * is useless in that context. */ template<typename C> class Span { C* m_data; std::size_t m_size{0}; template <class T> struct is_Span_int : public std::false_type {}; template <class T> struct is_Span_int<Span<T>> : public std::true_type {}; template <class T> struct is_Span : public is_Span_int<typename std::remove_cv<T>::type>{}; public: constexpr Span() noexcept : m_data(nullptr) {} /** Construct a span from a begin pointer and a size. * * This implements a subset of the iterator-based std::span constructor in C++20, * which is hard to implement without std::address_of. */ template <typename T, typename std::enable_if<std::is_convertible<T (*)[], C (*)[]>::value, int>::type = 0> constexpr Span(T* begin, std::size_t size) noexcept : m_data(begin), m_size(size) {} /** Construct a span from a begin and end pointer. * * This implements a subset of the iterator-based std::span constructor in C++20, * which is hard to implement without std::address_of. */ template <typename T, typename std::enable_if<std::is_convertible<T (*)[], C (*)[]>::value, int>::type = 0> CONSTEXPR_IF_NOT_DEBUG Span(T* begin, T* end) noexcept : m_data(begin), m_size(end - begin) { ASSERT_IF_DEBUG(end >= begin); } /** Implicit conversion of spans between compatible types. * * Specifically, if a pointer to an array of type O can be implicitly converted to a pointer to an array of type * C, then permit implicit conversion of Span<O> to Span<C>. This matches the behavior of the corresponding * C++20 std::span constructor. * * For example this means that a Span<T> can be converted into a Span<const T>. */ template <typename O, typename std::enable_if<std::is_convertible<O (*)[], C (*)[]>::value, int>::type = 0> constexpr Span(const Span<O>& other) noexcept : m_data(other.m_data), m_size(other.m_size) {} /** Default copy constructor. */ constexpr Span(const Span&) noexcept = default; /** Default assignment operator. */ Span& operator=(const Span& other) noexcept = default; /** Construct a Span from an array. This matches the corresponding C++20 std::span constructor. */ template <int N> constexpr Span(C (&a)[N]) noexcept : m_data(a), m_size(N) {} /** Construct a Span for objects with .data() and .size() (std::string, std::array, std::vector, ...). * * This implements a subset of the functionality provided by the C++20 std::span range-based constructor. * * To prevent surprises, only Spans for constant value types are supported when passing in temporaries. * Note that this restriction does not exist when converting arrays or other Spans (see above). */ template <typename V> constexpr Span(V& other SPAN_ATTR_LIFETIMEBOUND, typename std::enable_if<!is_Span<V>::value && std::is_convertible<typename std::remove_pointer<decltype(std::declval<V&>().data())>::type (*)[], C (*)[]>::value && std::is_convertible<decltype(std::declval<V&>().size()), std::size_t>::value, std::nullptr_t>::type = nullptr) : m_data(other.data()), m_size(other.size()){} template <typename V> constexpr Span(const V& other SPAN_ATTR_LIFETIMEBOUND, typename std::enable_if<!is_Span<V>::value && std::is_convertible<typename std::remove_pointer<decltype(std::declval<const V&>().data())>::type (*)[], C (*)[]>::value && std::is_convertible<decltype(std::declval<const V&>().size()), std::size_t>::value, std::nullptr_t>::type = nullptr) : m_data(other.data()), m_size(other.size()){} constexpr C* data() const noexcept { return m_data; } constexpr C* begin() const noexcept { return m_data; } constexpr C* end() const noexcept { return m_data + m_size; } CONSTEXPR_IF_NOT_DEBUG C& front() const noexcept { ASSERT_IF_DEBUG(size() > 0); return m_data[0]; } CONSTEXPR_IF_NOT_DEBUG C& back() const noexcept { ASSERT_IF_DEBUG(size() > 0); return m_data[m_size - 1]; } constexpr std::size_t size() const noexcept { return m_size; } constexpr std::size_t size_bytes() const noexcept { return sizeof(C) * m_size; } constexpr bool empty() const noexcept { return size() == 0; } CONSTEXPR_IF_NOT_DEBUG C& operator[](std::size_t pos) const noexcept { ASSERT_IF_DEBUG(size() > pos); return m_data[pos]; } CONSTEXPR_IF_NOT_DEBUG Span<C> subspan(std::size_t offset) const noexcept { ASSERT_IF_DEBUG(size() >= offset); return Span<C>(m_data + offset, m_size - offset); } CONSTEXPR_IF_NOT_DEBUG Span<C> subspan(std::size_t offset, std::size_t count) const noexcept { ASSERT_IF_DEBUG(size() >= offset + count); return Span<C>(m_data + offset, count); } CONSTEXPR_IF_NOT_DEBUG Span<C> first(std::size_t count) const noexcept { ASSERT_IF_DEBUG(size() >= count); return Span<C>(m_data, count); } CONSTEXPR_IF_NOT_DEBUG Span<C> last(std::size_t count) const noexcept { ASSERT_IF_DEBUG(size() >= count); return Span<C>(m_data + m_size - count, count); } friend constexpr bool operator==(const Span& a, const Span& b) noexcept { return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin()); } friend constexpr bool operator!=(const Span& a, const Span& b) noexcept { return !(a == b); } friend constexpr bool operator<(const Span& a, const Span& b) noexcept { return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end()); } friend constexpr bool operator<=(const Span& a, const Span& b) noexcept { return !(b < a); } friend constexpr bool operator>(const Span& a, const Span& b) noexcept { return (b < a); } friend constexpr bool operator>=(const Span& a, const Span& b) noexcept { return !(a < b); } template <typename O> friend class Span; }; // Return result of calling .data() method on type T. This is used to be able to // write template deduction guides for the single-parameter Span constructor // below that will work if the value that is passed has a .data() method, and if // the data method does not return a void pointer. // // It is important to check for the void type specifically below, so the // deduction guides can be used in SFINAE contexts to check whether objects can // be converted to spans. If the deduction guides did not explicitly check for // void, and an object was passed that returned void* from data (like // std::vector<bool>), the template deduction would succeed, but the Span<void> // object instantiation would fail, resulting in a hard error, rather than a // SFINAE error. // https://stackoverflow.com/questions/68759148/sfinae-to-detect-the-explicitness-of-a-ctad-deduction-guide // https://stackoverflow.com/questions/16568986/what-happens-when-you-call-data-on-a-stdvectorbool template<typename T> using DataResult = std::remove_pointer_t<decltype(std::declval<T&>().data())>; // Deduction guides for Span // For the pointer/size based and iterator based constructor: template <typename T, typename EndOrSize> Span(T*, EndOrSize) -> Span<T>; // For the array constructor: template <typename T, std::size_t N> Span(T (&)[N]) -> Span<T>; // For the temporaries/rvalue references constructor, only supporting const output. template <typename T> Span(T&&) -> Span<std::enable_if_t<!std::is_lvalue_reference_v<T> && !std::is_void_v<DataResult<T&&>>, const DataResult<T&&>>>; // For (lvalue) references, supporting mutable output. template <typename T> Span(T&) -> Span<std::enable_if_t<!std::is_void_v<DataResult<T&>>, DataResult<T&>>>; /** Pop the last element off a span, and return a reference to that element. */ template <typename T> T& SpanPopBack(Span<T>& span) { size_t size = span.size(); ASSERT_IF_DEBUG(size > 0); T& back = span[size - 1]; span = Span<T>(span.data(), size - 1); return back; } // From C++20 as_bytes and as_writeable_bytes template <typename T> Span<const std::byte> AsBytes(Span<T> s) noexcept { return {reinterpret_cast<const std::byte*>(s.data()), s.size_bytes()}; } template <typename T> Span<std::byte> AsWritableBytes(Span<T> s) noexcept { return {reinterpret_cast<std::byte*>(s.data()), s.size_bytes()}; } template <typename V> Span<const std::byte> MakeByteSpan(V&& v) noexcept { return AsBytes(Span{std::forward<V>(v)}); } template <typename V> Span<std::byte> MakeWritableByteSpan(V&& v) noexcept { return AsWritableBytes(Span{std::forward<V>(v)}); } // Helper functions to safely cast basic byte pointers to unsigned char pointers. inline unsigned char* UCharCast(char* c) { return reinterpret_cast<unsigned char*>(c); } inline unsigned char* UCharCast(unsigned char* c) { return c; } inline unsigned char* UCharCast(std::byte* c) { return reinterpret_cast<unsigned char*>(c); } inline const unsigned char* UCharCast(const char* c) { return reinterpret_cast<const unsigned char*>(c); } inline const unsigned char* UCharCast(const unsigned char* c) { return c; } inline const unsigned char* UCharCast(const std::byte* c) { return reinterpret_cast<const unsigned char*>(c); } // Helper concept for the basic byte types. template <typename B> concept BasicByte = requires { UCharCast(std::span<B>{}.data()); }; // Helper function to safely convert a Span to a Span<[const] unsigned char>. template <typename T> constexpr auto UCharSpanCast(Span<T> s) -> Span<typename std::remove_pointer<decltype(UCharCast(s.data()))>::type> { return {UCharCast(s.data()), s.size()}; } /** Like the Span constructor, but for (const) unsigned char member types only. Only works for (un)signed char containers. */ template <typename V> constexpr auto MakeUCharSpan(V&& v) -> decltype(UCharSpanCast(Span{std::forward<V>(v)})) { return UCharSpanCast(Span{std::forward<V>(v)}); } #endif // BITCOIN_SPAN_H
0
bitcoin
bitcoin/src/protocol.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 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 <protocol.h> #include <common/system.h> #include <atomic> static std::atomic<bool> g_initial_block_download_completed(false); namespace NetMsgType { const char* VERSION = "version"; const char* VERACK = "verack"; const char* ADDR = "addr"; const char* ADDRV2 = "addrv2"; const char* SENDADDRV2 = "sendaddrv2"; const char* INV = "inv"; const char* GETDATA = "getdata"; const char* MERKLEBLOCK = "merkleblock"; const char* GETBLOCKS = "getblocks"; const char* GETHEADERS = "getheaders"; const char* TX = "tx"; const char* HEADERS = "headers"; const char* BLOCK = "block"; const char* GETADDR = "getaddr"; const char* MEMPOOL = "mempool"; const char* PING = "ping"; const char* PONG = "pong"; const char* NOTFOUND = "notfound"; const char* FILTERLOAD = "filterload"; const char* FILTERADD = "filteradd"; const char* FILTERCLEAR = "filterclear"; const char* SENDHEADERS = "sendheaders"; const char* FEEFILTER = "feefilter"; const char* SENDCMPCT = "sendcmpct"; const char* CMPCTBLOCK = "cmpctblock"; const char* GETBLOCKTXN = "getblocktxn"; const char* BLOCKTXN = "blocktxn"; const char* GETCFILTERS = "getcfilters"; const char* CFILTER = "cfilter"; const char* GETCFHEADERS = "getcfheaders"; const char* CFHEADERS = "cfheaders"; const char* GETCFCHECKPT = "getcfcheckpt"; const char* CFCHECKPT = "cfcheckpt"; const char* WTXIDRELAY = "wtxidrelay"; const char* SENDTXRCNCL = "sendtxrcncl"; } // namespace NetMsgType /** All known message types. Keep this in the same order as the list of * messages above and in protocol.h. */ const static std::vector<std::string> g_all_net_message_types{ NetMsgType::VERSION, NetMsgType::VERACK, NetMsgType::ADDR, NetMsgType::ADDRV2, NetMsgType::SENDADDRV2, NetMsgType::INV, NetMsgType::GETDATA, NetMsgType::MERKLEBLOCK, NetMsgType::GETBLOCKS, NetMsgType::GETHEADERS, NetMsgType::TX, NetMsgType::HEADERS, NetMsgType::BLOCK, NetMsgType::GETADDR, NetMsgType::MEMPOOL, NetMsgType::PING, NetMsgType::PONG, NetMsgType::NOTFOUND, NetMsgType::FILTERLOAD, NetMsgType::FILTERADD, NetMsgType::FILTERCLEAR, NetMsgType::SENDHEADERS, NetMsgType::FEEFILTER, NetMsgType::SENDCMPCT, NetMsgType::CMPCTBLOCK, NetMsgType::GETBLOCKTXN, NetMsgType::BLOCKTXN, NetMsgType::GETCFILTERS, NetMsgType::CFILTER, NetMsgType::GETCFHEADERS, NetMsgType::CFHEADERS, NetMsgType::GETCFCHECKPT, NetMsgType::CFCHECKPT, NetMsgType::WTXIDRELAY, NetMsgType::SENDTXRCNCL, }; CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn) : pchMessageStart{pchMessageStartIn} { // Copy the command name size_t i = 0; for (; i < COMMAND_SIZE && pszCommand[i] != 0; ++i) pchCommand[i] = pszCommand[i]; assert(pszCommand[i] == 0); // Assert that the command name passed in is not longer than COMMAND_SIZE nMessageSize = nMessageSizeIn; } std::string CMessageHeader::GetCommand() const { return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE)); } bool CMessageHeader::IsCommandValid() const { // Check the command string for errors for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; ++p1) { if (*p1 == 0) { // Must be all zeros after the first zero for (; p1 < pchCommand + COMMAND_SIZE; ++p1) { if (*p1 != 0) { return false; } } } else if (*p1 < ' ' || *p1 > 0x7E) { return false; } } return true; } ServiceFlags GetDesirableServiceFlags(ServiceFlags services) { if ((services & NODE_NETWORK_LIMITED) && g_initial_block_download_completed) { return ServiceFlags(NODE_NETWORK_LIMITED | NODE_WITNESS); } return ServiceFlags(NODE_NETWORK | NODE_WITNESS); } void SetServiceFlagsIBDCache(bool state) { g_initial_block_download_completed = state; } CInv::CInv() { type = 0; hash.SetNull(); } CInv::CInv(uint32_t typeIn, const uint256& hashIn) : type(typeIn), hash(hashIn) {} bool operator<(const CInv& a, const CInv& b) { return (a.type < b.type || (a.type == b.type && a.hash < b.hash)); } std::string CInv::GetCommand() const { std::string cmd; if (type & MSG_WITNESS_FLAG) cmd.append("witness-"); int masked = type & MSG_TYPE_MASK; switch (masked) { case MSG_TX: return cmd.append(NetMsgType::TX); // WTX is not a message type, just an inv type case MSG_WTX: return cmd.append("wtx"); case MSG_BLOCK: return cmd.append(NetMsgType::BLOCK); case MSG_FILTERED_BLOCK: return cmd.append(NetMsgType::MERKLEBLOCK); case MSG_CMPCT_BLOCK: return cmd.append(NetMsgType::CMPCTBLOCK); default: throw std::out_of_range(strprintf("CInv::GetCommand(): type=%d unknown type", type)); } } std::string CInv::ToString() const { try { return strprintf("%s %s", GetCommand(), hash.ToString()); } catch(const std::out_of_range &) { return strprintf("0x%08x %s", type, hash.ToString()); } } const std::vector<std::string> &getAllNetMessageTypes() { return g_all_net_message_types; } /** * Convert a service flag (NODE_*) to a human readable string. * It supports unknown service flags which will be returned as "UNKNOWN[...]". * @param[in] bit the service flag is calculated as (1 << bit) */ static std::string serviceFlagToStr(size_t bit) { const uint64_t service_flag = 1ULL << bit; switch ((ServiceFlags)service_flag) { case NODE_NONE: abort(); // impossible case NODE_NETWORK: return "NETWORK"; case NODE_BLOOM: return "BLOOM"; case NODE_WITNESS: return "WITNESS"; case NODE_COMPACT_FILTERS: return "COMPACT_FILTERS"; case NODE_NETWORK_LIMITED: return "NETWORK_LIMITED"; case NODE_P2P_V2: return "P2P_V2"; // Not using default, so we get warned when a case is missing } return strprintf("UNKNOWN[2^%u]", bit); } std::vector<std::string> serviceFlagsToStr(uint64_t flags) { std::vector<std::string> str_flags; for (size_t i = 0; i < sizeof(flags) * 8; ++i) { if (flags & (1ULL << i)) { str_flags.emplace_back(serviceFlagToStr(i)); } } return str_flags; } GenTxid ToGenTxid(const CInv& inv) { assert(inv.IsGenTxMsg()); return inv.IsMsgWtx() ? GenTxid::Wtxid(inv.hash) : GenTxid::Txid(inv.hash); }
0
bitcoin
bitcoin/src/threadsafety.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_THREADSAFETY_H #define BITCOIN_THREADSAFETY_H #include <mutex> #ifdef __clang__ // TL;DR Add GUARDED_BY(mutex) to member variables. The others are // rarely necessary. Ex: int nFoo GUARDED_BY(cs_foo); // // See https://clang.llvm.org/docs/ThreadSafetyAnalysis.html // for documentation. The clang compiler can do advanced static analysis // of locking when given the -Wthread-safety option. #define LOCKABLE __attribute__((lockable)) #define SCOPED_LOCKABLE __attribute__((scoped_lockable)) #define GUARDED_BY(x) __attribute__((guarded_by(x))) #define PT_GUARDED_BY(x) __attribute__((pt_guarded_by(x))) #define ACQUIRED_AFTER(...) __attribute__((acquired_after(__VA_ARGS__))) #define ACQUIRED_BEFORE(...) __attribute__((acquired_before(__VA_ARGS__))) #define EXCLUSIVE_LOCK_FUNCTION(...) __attribute__((exclusive_lock_function(__VA_ARGS__))) #define SHARED_LOCK_FUNCTION(...) __attribute__((shared_lock_function(__VA_ARGS__))) #define EXCLUSIVE_TRYLOCK_FUNCTION(...) __attribute__((exclusive_trylock_function(__VA_ARGS__))) #define SHARED_TRYLOCK_FUNCTION(...) __attribute__((shared_trylock_function(__VA_ARGS__))) #define UNLOCK_FUNCTION(...) __attribute__((unlock_function(__VA_ARGS__))) #define LOCK_RETURNED(x) __attribute__((lock_returned(x))) #define LOCKS_EXCLUDED(...) __attribute__((locks_excluded(__VA_ARGS__))) #define EXCLUSIVE_LOCKS_REQUIRED(...) __attribute__((exclusive_locks_required(__VA_ARGS__))) #define SHARED_LOCKS_REQUIRED(...) __attribute__((shared_locks_required(__VA_ARGS__))) #define NO_THREAD_SAFETY_ANALYSIS __attribute__((no_thread_safety_analysis)) #define ASSERT_EXCLUSIVE_LOCK(...) __attribute__((assert_exclusive_lock(__VA_ARGS__))) #else #define LOCKABLE #define SCOPED_LOCKABLE #define GUARDED_BY(x) #define PT_GUARDED_BY(x) #define ACQUIRED_AFTER(...) #define ACQUIRED_BEFORE(...) #define EXCLUSIVE_LOCK_FUNCTION(...) #define SHARED_LOCK_FUNCTION(...) #define EXCLUSIVE_TRYLOCK_FUNCTION(...) #define SHARED_TRYLOCK_FUNCTION(...) #define UNLOCK_FUNCTION(...) #define LOCK_RETURNED(x) #define LOCKS_EXCLUDED(...) #define EXCLUSIVE_LOCKS_REQUIRED(...) #define SHARED_LOCKS_REQUIRED(...) #define NO_THREAD_SAFETY_ANALYSIS #define ASSERT_EXCLUSIVE_LOCK(...) #endif // __GNUC__ // StdMutex provides an annotated version of std::mutex for us, // and should only be used when sync.h Mutex/LOCK/etc are not usable. class LOCKABLE StdMutex : public std::mutex { public: #ifdef __clang__ //! For negative capabilities in the Clang Thread Safety Analysis. //! A negative requirement uses the EXCLUSIVE_LOCKS_REQUIRED attribute, in conjunction //! with the ! operator, to indicate that a mutex should not be held. const StdMutex& operator!() const { return *this; } #endif // __clang__ }; // StdLockGuard provides an annotated version of std::lock_guard for us, // and should only be used when sync.h Mutex/LOCK/etc are not usable. class SCOPED_LOCKABLE StdLockGuard : public std::lock_guard<StdMutex> { public: explicit StdLockGuard(StdMutex& cs) EXCLUSIVE_LOCK_FUNCTION(cs) : std::lock_guard<StdMutex>(cs) {} ~StdLockGuard() UNLOCK_FUNCTION() {} }; #endif // BITCOIN_THREADSAFETY_H
0
bitcoin
bitcoin/src/walletinitinterface.h
// Copyright (c) 2017-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_WALLETINITINTERFACE_H #define BITCOIN_WALLETINITINTERFACE_H class ArgsManager; namespace node { struct NodeContext; } // namespace node class WalletInitInterface { public: /** Is the wallet component enabled */ virtual bool HasWalletSupport() const = 0; /** Get wallet help string */ virtual void AddWalletOptions(ArgsManager& argsman) const = 0; /** Check wallet parameter interaction */ virtual bool ParameterInteraction() const = 0; /** Add wallets that should be opened to list of chain clients. */ virtual void Construct(node::NodeContext& node) const = 0; virtual ~WalletInitInterface() {} }; extern const WalletInitInterface& g_wallet_init_interface; #endif // BITCOIN_WALLETINITINTERFACE_H
0
bitcoin
bitcoin/src/bitcoin-util.cpp
// Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <arith_uint256.h> #include <chain.h> #include <chainparams.h> #include <chainparamsbase.h> #include <clientversion.h> #include <common/args.h> #include <common/system.h> #include <compat/compat.h> #include <core_io.h> #include <streams.h> #include <util/exception.h> #include <util/strencodings.h> #include <util/translation.h> #include <atomic> #include <cstdio> #include <functional> #include <memory> #include <thread> static const int CONTINUE_EXECUTION=-1; const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr; static void SetupBitcoinUtilArgs(ArgsManager &argsman) { SetupHelpOptions(argsman); argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddCommand("grind", "Perform proof of work on hex header string"); SetupChainParamsBaseOptions(argsman); } // This function returns either one of EXIT_ codes when it's expected to stop the process or // CONTINUE_EXECUTION when it's expected to continue further. static int AppInitUtil(ArgsManager& args, int argc, char* argv[]) { SetupBitcoinUtilArgs(args); std::string error; if (!args.ParseParameters(argc, argv, error)) { tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error); return EXIT_FAILURE; } if (HelpRequested(args) || args.IsArgSet("-version")) { // First part of help message is specific to this utility std::string strUsage = PACKAGE_NAME " bitcoin-util utility version " + FormatFullVersion() + "\n"; if (args.IsArgSet("-version")) { strUsage += FormatParagraph(LicenseInfo()); } else { strUsage += "\n" "Usage: bitcoin-util [options] [commands] Do stuff\n"; strUsage += "\n" + args.GetHelpMessage(); } tfm::format(std::cout, "%s", strUsage); if (argc < 2) { tfm::format(std::cerr, "Error: too few parameters\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } // Check for chain settings (Params() calls are only valid after this clause) try { SelectParams(args.GetChainType()); } catch (const std::exception& e) { tfm::format(std::cerr, "Error: %s\n", e.what()); return EXIT_FAILURE; } return CONTINUE_EXECUTION; } static void grind_task(uint32_t nBits, CBlockHeader header, uint32_t offset, uint32_t step, std::atomic<bool>& found, uint32_t& proposed_nonce) { arith_uint256 target; bool neg, over; target.SetCompact(nBits, &neg, &over); if (target == 0 || neg || over) return; header.nNonce = offset; uint32_t finish = std::numeric_limits<uint32_t>::max() - step; finish = finish - (finish % step) + offset; while (!found && header.nNonce < finish) { const uint32_t next = (finish - header.nNonce < 5000*step) ? finish : header.nNonce + 5000*step; do { if (UintToArith256(header.GetHash()) <= target) { if (!found.exchange(true)) { proposed_nonce = header.nNonce; } return; } header.nNonce += step; } while(header.nNonce != next); } } static int Grind(const std::vector<std::string>& args, std::string& strPrint) { if (args.size() != 1) { strPrint = "Must specify block header to grind"; return EXIT_FAILURE; } CBlockHeader header; if (!DecodeHexBlockHeader(header, args[0])) { strPrint = "Could not decode block header"; return EXIT_FAILURE; } uint32_t nBits = header.nBits; std::atomic<bool> found{false}; uint32_t proposed_nonce{}; std::vector<std::thread> threads; int n_tasks = std::max(1u, std::thread::hardware_concurrency()); threads.reserve(n_tasks); for (int i = 0; i < n_tasks; ++i) { threads.emplace_back(grind_task, nBits, header, i, n_tasks, std::ref(found), std::ref(proposed_nonce)); } for (auto& t : threads) { t.join(); } if (found) { header.nNonce = proposed_nonce; } else { strPrint = "Could not satisfy difficulty target"; return EXIT_FAILURE; } DataStream ss{}; ss << header; strPrint = HexStr(ss); return EXIT_SUCCESS; } MAIN_FUNCTION { ArgsManager& args = gArgs; SetupEnvironment(); try { int ret = AppInitUtil(args, argc, argv); if (ret != CONTINUE_EXECUTION) { return ret; } } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInitUtil()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "AppInitUtil()"); return EXIT_FAILURE; } const auto cmd = args.GetCommand(); if (!cmd) { tfm::format(std::cerr, "Error: must specify a command\n"); return EXIT_FAILURE; } int ret = EXIT_FAILURE; std::string strPrint; try { if (cmd->command == "grind") { ret = Grind(cmd->args, strPrint); } else { assert(false); // unknown command should be caught earlier } } catch (const std::exception& e) { strPrint = std::string("error: ") + e.what(); } catch (...) { strPrint = "unknown error"; } if (strPrint != "") { tfm::format(ret == 0 ? std::cout : std::cerr, "%s\n", strPrint); } return ret; }
0
bitcoin
bitcoin/src/clientversion.h
// Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CLIENTVERSION_H #define BITCOIN_CLIENTVERSION_H #include <util/macros.h> #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif //HAVE_CONFIG_H // Check that required client information is defined #if !defined(CLIENT_VERSION_MAJOR) || !defined(CLIENT_VERSION_MINOR) || !defined(CLIENT_VERSION_BUILD) || !defined(CLIENT_VERSION_IS_RELEASE) || !defined(COPYRIGHT_YEAR) #error Client version information missing: version is not defined by bitcoin-config.h or in any other way #endif //! Copyright string used in Windows .rc files #define COPYRIGHT_STR "2009-" STRINGIZE(COPYRIGHT_YEAR) " " COPYRIGHT_HOLDERS_FINAL /** * bitcoind-res.rc includes this file, but it cannot cope with real c++ code. * WINDRES_PREPROC is defined to indicate that its pre-processor is running. * Anything other than a define should be guarded below. */ #if !defined(WINDRES_PREPROC) #include <string> #include <vector> static const int CLIENT_VERSION = 10000 * CLIENT_VERSION_MAJOR + 100 * CLIENT_VERSION_MINOR + 1 * CLIENT_VERSION_BUILD; extern const std::string CLIENT_NAME; std::string FormatFullVersion(); std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments); std::string CopyrightHolders(const std::string& strPrefix); /** Returns licensing information (for -version) */ std::string LicenseInfo(); #endif // WINDRES_PREPROC #endif // BITCOIN_CLIENTVERSION_H
0
bitcoin
bitcoin/src/init.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <init.h> #include <kernel/checks.h> #include <kernel/mempool_persist.h> #include <kernel/validation_cache_sizes.h> #include <addrman.h> #include <banman.h> #include <blockfilter.h> #include <chain.h> #include <chainparams.h> #include <chainparamsbase.h> #include <clientversion.h> #include <common/args.h> #include <common/system.h> #include <consensus/amount.h> #include <deploymentstatus.h> #include <hash.h> #include <httprpc.h> #include <httpserver.h> #include <index/blockfilterindex.h> #include <index/coinstatsindex.h> #include <index/txindex.h> #include <init/common.h> #include <interfaces/chain.h> #include <interfaces/init.h> #include <interfaces/node.h> #include <logging.h> #include <mapport.h> #include <net.h> #include <net_permissions.h> #include <net_processing.h> #include <netbase.h> #include <netgroup.h> #include <node/blockmanager_args.h> #include <node/blockstorage.h> #include <node/caches.h> #include <node/chainstate.h> #include <node/chainstatemanager_args.h> #include <node/context.h> #include <node/interface_ui.h> #include <node/kernel_notifications.h> #include <node/mempool_args.h> #include <node/mempool_persist_args.h> #include <node/miner.h> #include <node/peerman_args.h> #include <node/validation_cache_args.h> #include <policy/feerate.h> #include <policy/fees.h> #include <policy/fees_args.h> #include <policy/policy.h> #include <policy/settings.h> #include <protocol.h> #include <rpc/blockchain.h> #include <rpc/register.h> #include <rpc/server.h> #include <rpc/util.h> #include <scheduler.h> #include <script/sigcache.h> #include <sync.h> #include <timedata.h> #include <torcontrol.h> #include <txdb.h> #include <txmempool.h> #include <util/asmap.h> #include <util/chaintype.h> #include <util/check.h> #include <util/fs.h> #include <util/fs_helpers.h> #include <util/moneystr.h> #include <util/result.h> #include <util/strencodings.h> #include <util/string.h> #include <util/syserror.h> #include <util/thread.h> #include <util/threadnames.h> #include <util/time.h> #include <util/translation.h> #include <validation.h> #include <validationinterface.h> #include <walletinitinterface.h> #include <algorithm> #include <condition_variable> #include <cstdint> #include <cstdio> #include <fstream> #include <functional> #include <set> #include <string> #include <thread> #include <vector> #ifndef WIN32 #include <cerrno> #include <signal.h> #include <sys/stat.h> #endif #include <boost/signals2/signal.hpp> #if ENABLE_ZMQ #include <zmq/zmqabstractnotifier.h> #include <zmq/zmqnotificationinterface.h> #include <zmq/zmqrpc.h> #endif using kernel::DumpMempool; using kernel::LoadMempool; using kernel::ValidationCacheSizes; using node::ApplyArgsManOptions; using node::BlockManager; using node::CacheSizes; using node::CalculateCacheSizes; using node::DEFAULT_PERSIST_MEMPOOL; using node::DEFAULT_PRINTPRIORITY; using node::DEFAULT_STOPATHEIGHT; using node::fReindex; using node::KernelNotifications; using node::LoadChainstate; using node::MempoolPath; using node::NodeContext; using node::ShouldPersistMempool; using node::ImportBlocks; using node::VerifyLoadedChainstate; static constexpr bool DEFAULT_PROXYRANDOMIZE{true}; static constexpr bool DEFAULT_REST_ENABLE{false}; static constexpr bool DEFAULT_I2P_ACCEPT_INCOMING{true}; static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT{false}; #ifdef WIN32 // Win32 LevelDB doesn't use filedescriptors, and the ones used for // accessing block files don't count towards the fd_set size limit // anyway. #define MIN_CORE_FILEDESCRIPTORS 0 #else #define MIN_CORE_FILEDESCRIPTORS 150 #endif static const char* DEFAULT_ASMAP_FILENAME="ip_asn.map"; /** * The PID file facilities. */ static const char* BITCOIN_PID_FILENAME = "bitcoind.pid"; /** * True if this process has created a PID file. * Used to determine whether we should remove the PID file on shutdown. */ static bool g_generated_pid{false}; static fs::path GetPidFile(const ArgsManager& args) { return AbsPathForConfigVal(args, args.GetPathArg("-pid", BITCOIN_PID_FILENAME)); } [[nodiscard]] static bool CreatePidFile(const ArgsManager& args) { std::ofstream file{GetPidFile(args)}; if (file) { #ifdef WIN32 tfm::format(file, "%d\n", GetCurrentProcessId()); #else tfm::format(file, "%d\n", getpid()); #endif g_generated_pid = true; return true; } else { return InitError(strprintf(_("Unable to create the PID file '%s': %s"), fs::PathToString(GetPidFile(args)), SysErrorString(errno))); } } static void RemovePidFile(const ArgsManager& args) { if (!g_generated_pid) return; const auto pid_path{GetPidFile(args)}; if (std::error_code error; !fs::remove(pid_path, error)) { std::string msg{error ? error.message() : "File does not exist"}; LogPrintf("Unable to remove PID file (%s): %s\n", fs::PathToString(pid_path), msg); } } static std::optional<util::SignalInterrupt> g_shutdown; void InitContext(NodeContext& node) { assert(!g_shutdown); g_shutdown.emplace(); node.args = &gArgs; node.shutdown = &*g_shutdown; } ////////////////////////////////////////////////////////////////////////////// // // Shutdown // // // Thread management and startup/shutdown: // // The network-processing threads are all part of a thread group // created by AppInit() or the Qt main() function. // // A clean exit happens when the SignalInterrupt object is triggered, which // makes the main thread's SignalInterrupt::wait() call return, and join all // other ongoing threads in the thread group to the main thread. // Shutdown() is then called to clean up database connections, and stop other // threads that should only be stopped after the main network-processing // threads have exited. // // Shutdown for Qt is very similar, only it uses a QTimer to detect // ShutdownRequested() getting set, and then does the normal Qt // shutdown thing. // bool ShutdownRequested(node::NodeContext& node) { return bool{*Assert(node.shutdown)}; } #if HAVE_SYSTEM static void ShutdownNotify(const ArgsManager& args) { std::vector<std::thread> threads; for (const auto& cmd : args.GetArgs("-shutdownnotify")) { threads.emplace_back(runCommand, cmd); } for (auto& t : threads) { t.join(); } } #endif void Interrupt(NodeContext& node) { #if HAVE_SYSTEM ShutdownNotify(*node.args); #endif InterruptHTTPServer(); InterruptHTTPRPC(); InterruptRPC(); InterruptREST(); InterruptTorControl(); InterruptMapPort(); if (node.connman) node.connman->Interrupt(); if (g_txindex) { g_txindex->Interrupt(); } ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Interrupt(); }); if (g_coin_stats_index) { g_coin_stats_index->Interrupt(); } } void Shutdown(NodeContext& node) { static Mutex g_shutdown_mutex; TRY_LOCK(g_shutdown_mutex, lock_shutdown); if (!lock_shutdown) return; LogPrintf("%s: In progress...\n", __func__); Assert(node.args); /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way, /// for example if the data directory was found to be locked. /// Be sure that anything that writes files or flushes caches only does this if the respective /// module was initialized. util::ThreadRename("shutoff"); if (node.mempool) node.mempool->AddTransactionsUpdated(1); StopHTTPRPC(); StopREST(); StopRPC(); StopHTTPServer(); for (const auto& client : node.chain_clients) { client->flush(); } StopMapPort(); // Because these depend on each-other, we make sure that neither can be // using the other before destroying them. if (node.peerman) UnregisterValidationInterface(node.peerman.get()); if (node.connman) node.connman->Stop(); StopTorControl(); // After everything has been shut down, but before things get flushed, stop the // scheduler and load block thread. if (node.scheduler) node.scheduler->stop(); if (node.chainman && node.chainman->m_thread_load.joinable()) node.chainman->m_thread_load.join(); // After the threads that potentially access these pointers have been stopped, // destruct and reset all to nullptr. node.peerman.reset(); node.connman.reset(); node.banman.reset(); node.addrman.reset(); node.netgroupman.reset(); if (node.mempool && node.mempool->GetLoadTried() && ShouldPersistMempool(*node.args)) { DumpMempool(*node.mempool, MempoolPath(*node.args)); } // Drop transactions we were still watching, record fee estimations and Unregister // fee estimator from validation interface. if (node.fee_estimator) { node.fee_estimator->Flush(); UnregisterValidationInterface(node.fee_estimator.get()); } // FlushStateToDisk generates a ChainStateFlushed callback, which we should avoid missing if (node.chainman) { LOCK(cs_main); for (Chainstate* chainstate : node.chainman->GetAll()) { if (chainstate->CanFlushToDisk()) { chainstate->ForceFlushStateToDisk(); } } } // After there are no more peers/RPC left to give us new data which may generate // CValidationInterface callbacks, flush them... GetMainSignals().FlushBackgroundCallbacks(); // Stop and delete all indexes only after flushing background callbacks. if (g_txindex) { g_txindex->Stop(); g_txindex.reset(); } if (g_coin_stats_index) { g_coin_stats_index->Stop(); g_coin_stats_index.reset(); } ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Stop(); }); DestroyAllBlockFilterIndexes(); // Any future callbacks will be dropped. This should absolutely be safe - if // missing a callback results in an unrecoverable situation, unclean shutdown // would too. The only reason to do the above flushes is to let the wallet catch // up with our current chain to avoid any strange pruning edge cases and make // next startup faster by avoiding rescan. if (node.chainman) { LOCK(cs_main); for (Chainstate* chainstate : node.chainman->GetAll()) { if (chainstate->CanFlushToDisk()) { chainstate->ForceFlushStateToDisk(); chainstate->ResetCoinsViews(); } } } for (const auto& client : node.chain_clients) { client->stop(); } #if ENABLE_ZMQ if (g_zmq_notification_interface) { UnregisterValidationInterface(g_zmq_notification_interface.get()); g_zmq_notification_interface.reset(); } #endif node.chain_clients.clear(); UnregisterAllValidationInterfaces(); GetMainSignals().UnregisterBackgroundSignalScheduler(); node.mempool.reset(); node.fee_estimator.reset(); node.chainman.reset(); node.scheduler.reset(); node.kernel.reset(); RemovePidFile(*node.args); LogPrintf("%s: done\n", __func__); } /** * Signal handlers are very limited in what they are allowed to do. * The execution context the handler is invoked in is not guaranteed, * so we restrict handler operations to just touching variables: */ #ifndef WIN32 static void HandleSIGTERM(int) { // Return value is intentionally ignored because there is not a better way // of handling this failure in a signal handler. (void)(*Assert(g_shutdown))(); } static void HandleSIGHUP(int) { LogInstance().m_reopen_file = true; } #else static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType) { if (!(*Assert(g_shutdown))()) { LogPrintf("Error: failed to send shutdown signal on Ctrl-C\n"); return false; } Sleep(INFINITE); return true; } #endif #ifndef WIN32 static void registerSignalHandler(int signal, void(*handler)(int)) { struct sigaction sa; sa.sa_handler = handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(signal, &sa, nullptr); } #endif static boost::signals2::connection rpc_notify_block_change_connection; static void OnRPCStarted() { rpc_notify_block_change_connection = uiInterface.NotifyBlockTip_connect(std::bind(RPCNotifyBlockChange, std::placeholders::_2)); } static void OnRPCStopped() { rpc_notify_block_change_connection.disconnect(); RPCNotifyBlockChange(nullptr); g_best_block_cv.notify_all(); LogPrint(BCLog::RPC, "RPC stopped.\n"); } void SetupServerArgs(ArgsManager& argsman) { SetupHelpOptions(argsman); argsman.AddArg("-help-debug", "Print help message with debugging options and exit", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); // server-only for now init::AddLoggingArgs(argsman); const auto defaultBaseParams = CreateBaseChainParams(ChainType::MAIN); const auto testnetBaseParams = CreateBaseChainParams(ChainType::TESTNET); const auto signetBaseParams = CreateBaseChainParams(ChainType::SIGNET); const auto regtestBaseParams = CreateBaseChainParams(ChainType::REGTEST); const auto defaultChainParams = CreateChainParams(argsman, ChainType::MAIN); const auto testnetChainParams = CreateChainParams(argsman, ChainType::TESTNET); const auto signetChainParams = CreateChainParams(argsman, ChainType::SIGNET); const auto regtestChainParams = CreateChainParams(argsman, ChainType::REGTEST); // Hidden Options std::vector<std::string> hidden_args = { "-dbcrashratio", "-forcecompactdb", // GUI args. These will be overwritten by SetupUIArgs for the GUI "-choosedatadir", "-lang=<lang>", "-min", "-resetguisettings", "-splash", "-uiplatform"}; argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #if HAVE_SYSTEM argsman.AddArg("-alertnotify=<cmd>", "Execute command when an alert is raised (%s in cmd is replaced by message)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #endif argsman.AddArg("-assumevalid=<hex>", strprintf("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, signet: %s)", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex(), signetChainParams->GetConsensus().defaultAssumeValid.GetHex()), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-blocksdir=<dir>", "Specify directory to hold blocks subdirectory for *.dat files (default: <datadir>)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-fastprune", "Use smaller block files and lower minimum prune height for testing purposes", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); #if HAVE_SYSTEM argsman.AddArg("-blocknotify=<cmd>", "Execute command when the best block changes (%s in cmd is replaced by block hash)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #endif argsman.AddArg("-blockreconstructionextratxn=<n>", strprintf("Extra transactions to keep in memory for compact block reconstructions (default: %u)", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-blocksonly", strprintf("Whether to reject transactions from network peers. Automatic broadcast and rebroadcast of any transactions from inbound peers is disabled, unless the peer has the 'forcerelay' permission. RPC transactions are not affected. (default: %u)", DEFAULT_BLOCKSONLY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-coinstatsindex", strprintf("Maintain coinstats index used by the gettxoutsetinfo RPC (default: %u)", DEFAULT_COINSTATSINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-conf=<file>", strprintf("Specify path to read-only configuration file. Relative paths will be prefixed by datadir location (only useable from command line, not configuration file) (default: %s)", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS); argsman.AddArg("-dbcache=<n>", strprintf("Maximum database cache size <n> MiB (%d to %d, default: %d). In addition, unused mempool memory is shared for this cache (see -maxmempool).", nMinDbCache, nMaxDbCache, nDefaultDbCache), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-includeconf=<file>", "Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-allowignoredconf", strprintf("For backwards compatibility, treat an unused %s file in the datadir as a warning, not an error.", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-loadblock=<file>", "Imports blocks from external file on startup", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE_MB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-maxorphantx=<n>", strprintf("Keep at most <n> unconnectable transactions in memory (default: %u)", DEFAULT_MAX_ORPHAN_TRANSACTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-mempoolexpiry=<n>", strprintf("Do not keep transactions in the mempool longer than <n> hours (default: %u)", DEFAULT_MEMPOOL_EXPIRY_HOURS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-minimumchainwork=<hex>", strprintf("Minimum work assumed to exist on a valid chain in hex (default: %s, testnet: %s, signet: %s)", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex(), signetChainParams->GetConsensus().nMinimumChainWork.GetHex()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS); argsman.AddArg("-par=<n>", strprintf("Set the number of script verification threads (0 = auto, up to %d, <0 = leave that many cores free, default: %d)", MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-persistmempool", strprintf("Whether to save the mempool on shutdown and load on restart (default: %u)", DEFAULT_PERSIST_MEMPOOL), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-persistmempoolv1", strprintf("Whether a mempool.dat file created by -persistmempool or the savemempool RPC will be written in the legacy format " "(version 1) or the current format (version 2). This temporary option will be removed in the future. (default: %u)", DEFAULT_PERSIST_V1_DAT), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-pid=<file>", strprintf("Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)", BITCOIN_PID_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-prune=<n>", strprintf("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. " "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)", MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-reindex", "If enabled, wipe chain state and block index, and rebuild them from blk*.dat files on disk. Also wipe and rebuild other optional indexes that are active. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-reindex-chainstate", "If enabled, wipe chain state, and rebuild it from blk*.dat files on disk. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-settings=<file>", strprintf("Specify path to dynamic settings data file. Can be disabled with -nosettings. File is written at runtime and not meant to be edited by users (use %s instead for custom settings). Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME, BITCOIN_SETTINGS_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #if HAVE_SYSTEM argsman.AddArg("-startupnotify=<cmd>", "Execute command on startup.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-shutdownnotify=<cmd>", "Execute command immediately before beginning shutdown. The need for shutdown may be urgent, so be careful not to delay it long (if the command doesn't require interaction with the server, consider having it fork into the background).", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #endif argsman.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-blockfilterindex=<type>", strprintf("Maintain an index of compact filters by block (default: %s, values: %s).", DEFAULT_BLOCKFILTERINDEX, ListBlockFilterTypes()) + " If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-addnode=<ip>", strprintf("Add a node to connect to and attempt to keep the connection open (see the addnode RPC help for more info). This option can be specified multiple times to add multiple nodes; connections are limited to %u at a time and are counted separately from the -maxconnections limit.", MAX_ADDNODE_CONNECTIONS), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION); argsman.AddArg("-asmap=<file>", strprintf("Specify asn mapping used for bucketing of the peers (default: %s). Relative paths will be prefixed by the net-specific datadir location.", DEFAULT_ASMAP_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-bantime=<n>", strprintf("Default duration (in seconds) of manually configured bans (default: %u)", DEFAULT_MISBEHAVING_BANTIME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-bind=<addr>[:<port>][=onion]", strprintf("Bind to given address and always listen on it (default: 0.0.0.0). Use [host]:port notation for IPv6. Append =onion to tag any incoming connections to that address and port as incoming Tor connections (default: 127.0.0.1:%u=onion, testnet: 127.0.0.1:%u=onion, signet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)", defaultBaseParams->OnionServiceTargetPort(), testnetBaseParams->OnionServiceTargetPort(), signetBaseParams->OnionServiceTargetPort(), regtestBaseParams->OnionServiceTargetPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION); argsman.AddArg("-cjdnsreachable", "If set, then this host is configured for CJDNS (connecting to fc00::/8 addresses would lead us to the CJDNS network, see doc/cjdns.md) (default: 0)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-connect=<ip>", "Connect only to the specified node; -noconnect disables automatic connections (the rules for this peer are the same as for -addnode). This option can be specified multiple times to connect to multiple nodes.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION); argsman.AddArg("-discover", "Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-dns", strprintf("Allow DNS lookups for -addnode, -seednode and -connect (default: %u)", DEFAULT_NAME_LOOKUP), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-dnsseed", strprintf("Query for peer addresses via DNS lookup, if low on addresses (default: %u unless -connect used or -maxconnections=0)", DEFAULT_DNSSEED), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-externalip=<ip>", "Specify your own public address", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-fixedseeds", strprintf("Allow fixed seeds if DNS seeds don't provide peers (default: %u)", DEFAULT_FIXEDSEEDS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-forcednsseed", strprintf("Always query for peer addresses via DNS lookup (default: %u)", DEFAULT_FORCEDNSSEED), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-listen", strprintf("Accept connections from outside (default: %u if no -proxy, -connect or -maxconnections=0)", DEFAULT_LISTEN), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-listenonion", strprintf("Automatically create Tor onion service (default: %d)", DEFAULT_LISTEN_ONION), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-maxconnections=<n>", strprintf("Maintain at most <n> automatic connections to peers (default: %u). This limit does not apply to connections manually added via -addnode or the addnode RPC, which have a separate limit of %u.", DEFAULT_MAX_PEER_CONNECTIONS, MAX_ADDNODE_CONNECTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-maxreceivebuffer=<n>", strprintf("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXRECEIVEBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-maxsendbuffer=<n>", strprintf("Maximum per-connection memory usage for the send buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXSENDBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-maxtimeadjustment", strprintf("Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by outbound peers forward or backward by this amount (default: %u seconds).", DEFAULT_MAX_TIME_ADJUSTMENT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-maxuploadtarget=<n>", strprintf("Tries to keep outbound traffic under the given target per 24h. Limit does not apply to peers with 'download' permission or blocks created within past week. 0 = no limit (default: %s). Optional suffix units [k|K|m|M|g|G|t|T] (default: M). Lowercase is 1000 base while uppercase is 1024 base", DEFAULT_MAX_UPLOAD_TARGET), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-onion=<ip:port>", "Use separate SOCKS5 proxy to reach peers via Tor onion services, set -noonion to disable (default: -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-i2psam=<ip:port>", "I2P SAM proxy to reach I2P peers and accept I2P connections (default: none)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-i2pacceptincoming", strprintf("Whether to accept inbound I2P connections (default: %i). Ignored if -i2psam is not set. Listening for inbound I2P connections is done through the SAM proxy, not by binding to a local address and port.", DEFAULT_I2P_ACCEPT_INCOMING), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-onlynet=<net>", "Make automatic outbound connections only to network <net> (" + Join(GetNetworkNames(), ", ") + "). Inbound and manual connections are not affected by this option. It can be specified multiple times to allow multiple networks.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-v2transport", strprintf("Support v2 transport (default: %u)", DEFAULT_V2_TRANSPORT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-peerbloomfilters", strprintf("Support filtering of blocks and transaction with bloom filters (default: %u)", DEFAULT_PEERBLOOMFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-peerblockfilters", strprintf("Serve compact block filters to peers per BIP 157 (default: %u)", DEFAULT_PEERBLOCKFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-txreconciliation", strprintf("Enable transaction reconciliations per BIP 330 (default: %d)", DEFAULT_TXRECONCILIATION_ENABLE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION); // TODO: remove the sentence "Nodes not using ... incoming connections." once the changes from // https://github.com/bitcoin/bitcoin/pull/23542 have become widespread. argsman.AddArg("-port=<port>", strprintf("Listen for connections on <port>. Nodes not using the default ports (default: %u, testnet: %u, signet: %u, regtest: %u) are unlikely to get incoming connections. Not relevant for I2P (see doc/i2p.md).", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), signetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION); argsman.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy, set -noproxy to disable (default: disabled)", ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_ELISION, OptionsCategory::CONNECTION); argsman.AddArg("-proxyrandomize", strprintf("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)", DEFAULT_PROXYRANDOMIZE), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-seednode=<ip>", "Connect to a node to retrieve peer addresses, and disconnect. This option can be specified multiple times to connect to multiple nodes.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-networkactive", "Enable all P2P network activity (default: 1). Can be changed by the setnetworkactive RPC command", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-timeout=<n>", strprintf("Specify socket connection timeout in milliseconds. If an initial attempt to connect is unsuccessful after this amount of time, drop it (minimum: 1, default: %d)", DEFAULT_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-peertimeout=<n>", strprintf("Specify a p2p connection timeout delay in seconds. After connecting to a peer, wait this amount of time before considering disconnection based on inactivity (minimum: 1, default: %d)", DEFAULT_PEER_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION); argsman.AddArg("-torcontrol=<ip>:<port>", strprintf("Tor control host and port to use if onion listening enabled (default: %s). If no port is specified, the default port of %i will be used.", DEFAULT_TOR_CONTROL, DEFAULT_TOR_CONTROL_PORT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-torpassword=<pass>", "Tor control port password (default: empty)", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::CONNECTION); #ifdef USE_UPNP #if USE_UPNP argsman.AddArg("-upnp", "Use UPnP to map the listening port (default: 1 when listening and no -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); #else argsman.AddArg("-upnp", strprintf("Use UPnP to map the listening port (default: %u)", 0), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); #endif #else hidden_args.emplace_back("-upnp"); #endif #ifdef USE_NATPMP argsman.AddArg("-natpmp", strprintf("Use NAT-PMP to map the listening port (default: %s)", DEFAULT_NATPMP ? "1 when listening and no -proxy" : "0"), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); #else hidden_args.emplace_back("-natpmp"); #endif // USE_NATPMP argsman.AddArg("-whitebind=<[permissions@]addr>", "Bind to the given address and add permission flags to the peers connecting to it. " "Use [host]:port notation for IPv6. Allowed permissions: " + Join(NET_PERMISSIONS_DOC, ", ") + ". " "Specify multiple permissions separated by commas (default: download,noban,mempool,relay). Can be specified multiple times.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); argsman.AddArg("-whitelist=<[permissions@]IP address or network>", "Add permission flags to the peers connecting from the given IP address (e.g. 1.2.3.4) or " "CIDR-notated network (e.g. 1.2.3.0/24). Uses the same permissions as " "-whitebind. Can be specified multiple times." , ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION); g_wallet_init_interface.AddWalletOptions(argsman); #if ENABLE_ZMQ argsman.AddArg("-zmqpubhashblock=<address>", "Enable publish hash block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubhashtx=<address>", "Enable publish hash transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubrawblock=<address>", "Enable publish raw block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubrawtx=<address>", "Enable publish raw transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubsequence=<address>", "Enable publish hash block and tx sequence in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubhashblockhwm=<n>", strprintf("Set publish hash block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubhashtxhwm=<n>", strprintf("Set publish hash transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubrawblockhwm=<n>", strprintf("Set publish raw block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubrawtxhwm=<n>", strprintf("Set publish raw transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); argsman.AddArg("-zmqpubsequencehwm=<n>", strprintf("Set publish hash sequence message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ); #else hidden_args.emplace_back("-zmqpubhashblock=<address>"); hidden_args.emplace_back("-zmqpubhashtx=<address>"); hidden_args.emplace_back("-zmqpubrawblock=<address>"); hidden_args.emplace_back("-zmqpubrawtx=<address>"); hidden_args.emplace_back("-zmqpubsequence=<n>"); hidden_args.emplace_back("-zmqpubhashblockhwm=<n>"); hidden_args.emplace_back("-zmqpubhashtxhwm=<n>"); hidden_args.emplace_back("-zmqpubrawblockhwm=<n>"); hidden_args.emplace_back("-zmqpubrawtxhwm=<n>"); hidden_args.emplace_back("-zmqpubsequencehwm=<n>"); #endif argsman.AddArg("-checkblocks=<n>", strprintf("How many blocks to check at startup (default: %u, 0 = all)", DEFAULT_CHECKBLOCKS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-checklevel=<n>", strprintf("How thorough the block verification of -checkblocks is: %s (0-4, default: %u)", Join(CHECKLEVEL_DOC, ", "), DEFAULT_CHECKLEVEL), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-checkblockindex", strprintf("Do a consistency check for the block tree, chainstate, and other validation data structures occasionally. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-checkaddrman=<n>", strprintf("Run addrman consistency checks every <n> operations. Use 0 to disable. (default: %u)", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-checkmempool=<n>", strprintf("Run mempool consistency checks every <n> transactions. Use 0 to disable. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-checkpoints", strprintf("Enable rejection of any forks from the known historical chain until block %s (default: %u)", defaultChainParams->Checkpoints().GetHeight(), DEFAULT_CHECKPOINTS_ENABLED), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT_KVB), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT_KVB), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-addrmantest", "Allows to test address relay on localhost", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-capturemessages", "Capture all P2P messages to disk", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-mocktime=<n>", "Replace actual time with " + UNIX_EPOCH_TIME + " (default: 0)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-maxsigcachesize=<n>", strprintf("Limit sum of signature cache and script execution cache sizes to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_BYTES >> 20), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", Ticks<std::chrono::seconds>(DEFAULT_MAX_TIP_AGE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-printpriority", strprintf("Log transaction fee rate in " + CURRENCY_UNIT + "/kvB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-uacomment=<cmt>", "Append comment to the user agent string", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); SetupChainParamsBaseOptions(argsman); argsman.AddArg("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (test networks only; default: %u)", DEFAULT_ACCEPT_NON_STD_TXN), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY); argsman.AddArg("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kvB) used to define cost of relay, used for mempool limiting and replacement policy. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY); argsman.AddArg("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kvB) used to define dust, the value of an output such that it will cost more than its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY); argsman.AddArg("-acceptstalefeeestimates", strprintf("Read fee estimates even if they are stale (%sdefault: %u) fee estimates are considered stale if they are %s hours old", "regtest only; ", DEFAULT_ACCEPT_STALE_FEE_ESTIMATES, Ticks<std::chrono::hours>(MAX_FILE_AGE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST); argsman.AddArg("-bytespersigop", strprintf("Equivalent bytes per sigop in transactions for relay and mining (default: %u)", DEFAULT_BYTES_PER_SIGOP), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-datacarrier", strprintf("Relay and mine data carrier transactions (default: %u)", DEFAULT_ACCEPT_DATACARRIER), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-datacarriersize", strprintf("Relay and mine transactions whose data-carrying raw scriptPubKey " "is of this size or less (default: %u)", MAX_OP_RETURN_RELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-mempoolfullrbf", strprintf("Accept transaction replace-by-fee without requiring replaceability signaling (default: %u)", DEFAULT_MEMPOOL_FULL_RBF), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-permitbaremultisig", strprintf("Relay non-P2SH multisig (default: %u)", DEFAULT_PERMIT_BAREMULTISIG), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-minrelaytxfee=<amt>", strprintf("Fees (in %s/kvB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-whitelistforcerelay", strprintf("Add 'forcerelay' permission to whitelisted inbound peers with default permissions. This will relay transactions even if the transactions were already in the mempool. (default: %d)", DEFAULT_WHITELISTFORCERELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-whitelistrelay", strprintf("Add 'relay' permission to whitelisted inbound peers with default permissions. This will accept relayed transactions even when not relaying transactions (default: %d)", DEFAULT_WHITELISTRELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY); argsman.AddArg("-blockmaxweight=<n>", strprintf("Set maximum BIP141 block weight (default: %d)", DEFAULT_BLOCK_MAX_WEIGHT), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION); argsman.AddArg("-blockmintxfee=<amt>", strprintf("Set lowest fee rate (in %s/kvB) for transactions to be included in block creation. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION); argsman.AddArg("-blockversion=<n>", "Override block version to test forking scenarios", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::BLOCK_CREATION); argsman.AddArg("-rest", strprintf("Accept public REST requests (default: %u)", DEFAULT_REST_ENABLE), ArgsManager::ALLOW_ANY, OptionsCategory::RPC); argsman.AddArg("-rpcallowip=<ip>", "Allow JSON-RPC connections from specified source. Valid values 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), a network/CIDR (e.g. 1.2.3.4/24), all ipv4 (0.0.0.0/0), or all ipv6 (::/0). This option can be specified multiple times", ArgsManager::ALLOW_ANY, OptionsCategory::RPC); argsman.AddArg("-rpcauth=<userpw>", "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcauth. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC); argsman.AddArg("-rpcbind=<addr>[:port]", "Bind to given address to listen for JSON-RPC connections. Do not expose the RPC server to untrusted networks such as the public internet! 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)", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::RPC); argsman.AddArg("-rpcdoccheck", strprintf("Throw a non-fatal error at runtime if the documentation for an RPC is incorrect (default: %u)", DEFAULT_RPC_DOC_CHECK), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC); argsman.AddArg("-rpccookiefile=<loc>", "Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)", ArgsManager::ALLOW_ANY, OptionsCategory::RPC); argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC); argsman.AddArg("-rpcport=<port>", strprintf("Listen for JSON-RPC connections on <port> (default: %u, testnet: %u, signet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), signetBaseParams->RPCPort(), regtestBaseParams->RPCPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::RPC); argsman.AddArg("-rpcserialversion", strprintf("Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) (DEPRECATED) or segwit(1) (default: %d)", DEFAULT_RPC_SERIALIZE_VERSION), ArgsManager::ALLOW_ANY, OptionsCategory::RPC); argsman.AddArg("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC); argsman.AddArg("-rpcthreads=<n>", strprintf("Set the number of threads to service RPC calls (default: %d)", DEFAULT_HTTP_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::RPC); argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC); argsman.AddArg("-rpcwhitelist=<whitelist>", "Set a whitelist to filter incoming RPC calls for a specific user. The field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc 2>,...,<rpc n>. If multiple whitelists are set for a given user, they are set-intersected. See -rpcwhitelistdefault documentation for information on default whitelist behavior.", ArgsManager::ALLOW_ANY, OptionsCategory::RPC); argsman.AddArg("-rpcwhitelistdefault", "Sets default behavior for rpc whitelisting. Unless rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc server acts as if all rpc users are subject to empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault is set to 1 and no -rpcwhitelist is set, rpc server acts as if all rpc users are subject to empty whitelists.", ArgsManager::ALLOW_ANY, OptionsCategory::RPC); argsman.AddArg("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC); argsman.AddArg("-server", "Accept command line and JSON-RPC commands", ArgsManager::ALLOW_ANY, OptionsCategory::RPC); #if HAVE_DECL_FORK argsman.AddArg("-daemon", strprintf("Run in the background as a daemon and accept commands (default: %d)", DEFAULT_DAEMON), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-daemonwait", strprintf("Wait for initialization to be finished before exiting. This implies -daemon (default: %d)", DEFAULT_DAEMONWAIT), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); #else hidden_args.emplace_back("-daemon"); hidden_args.emplace_back("-daemonwait"); #endif // Add the hidden options argsman.AddHiddenArgs(hidden_args); } static bool fHaveGenesis = false; static GlobalMutex g_genesis_wait_mutex; static std::condition_variable g_genesis_wait_cv; static void BlockNotifyGenesisWait(const CBlockIndex* pBlockIndex) { if (pBlockIndex != nullptr) { { LOCK(g_genesis_wait_mutex); fHaveGenesis = true; } g_genesis_wait_cv.notify_all(); } } #if HAVE_SYSTEM static void StartupNotify(const ArgsManager& args) { std::string cmd = args.GetArg("-startupnotify", ""); if (!cmd.empty()) { std::thread t(runCommand, cmd); t.detach(); // thread runs free } } #endif static bool AppInitServers(NodeContext& node) { const ArgsManager& args = *Assert(node.args); RPCServer::OnStarted(&OnRPCStarted); RPCServer::OnStopped(&OnRPCStopped); if (!InitHTTPServer(*Assert(node.shutdown))) { return false; } StartRPC(); node.rpc_interruption_point = RpcInterruptionPoint; if (!StartHTTPRPC(&node)) return false; if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) StartREST(&node); StartHTTPServer(); return true; } // Parameter interaction based on rules void InitParameterInteraction(ArgsManager& args) { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified if (args.IsArgSet("-bind")) { if (args.SoftSetBoolArg("-listen", true)) LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__); } if (args.IsArgSet("-whitebind")) { if (args.SoftSetBoolArg("-listen", true)) LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__); } if (args.IsArgSet("-connect") || args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS) <= 0) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default if (args.SoftSetBoolArg("-dnsseed", false)) LogPrintf("%s: parameter interaction: -connect or -maxconnections=0 set -> setting -dnsseed=0\n", __func__); if (args.SoftSetBoolArg("-listen", false)) LogPrintf("%s: parameter interaction: -connect or -maxconnections=0 set -> setting -listen=0\n", __func__); } std::string proxy_arg = args.GetArg("-proxy", ""); if (proxy_arg != "" && proxy_arg != "0") { // to protect privacy, do not listen by default if a default proxy server is specified if (args.SoftSetBoolArg("-listen", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__); // to protect privacy, do not map ports when a proxy is set. The user may still specify -listen=1 // to listen locally, so don't rely on this happening through -listen below. if (args.SoftSetBoolArg("-upnp", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__); if (args.SoftSetBoolArg("-natpmp", false)) { LogPrintf("%s: parameter interaction: -proxy set -> setting -natpmp=0\n", __func__); } // to protect privacy, do not discover addresses by default if (args.SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__); } if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) { // do not map ports or try to retrieve public IP when not listening (pointless) if (args.SoftSetBoolArg("-upnp", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__); if (args.SoftSetBoolArg("-natpmp", false)) { LogPrintf("%s: parameter interaction: -listen=0 -> setting -natpmp=0\n", __func__); } if (args.SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__); if (args.SoftSetBoolArg("-listenonion", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__); if (args.SoftSetBoolArg("-i2pacceptincoming", false)) { LogPrintf("%s: parameter interaction: -listen=0 -> setting -i2pacceptincoming=0\n", __func__); } } if (args.IsArgSet("-externalip")) { // if an explicit public IP is specified, do not try to find others if (args.SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__); } if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) { // disable whitelistrelay in blocksonly mode if (args.SoftSetBoolArg("-whitelistrelay", false)) LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__); // Reduce default mempool size in blocksonly mode to avoid unexpected resource usage if (args.SoftSetArg("-maxmempool", ToString(DEFAULT_BLOCKSONLY_MAX_MEMPOOL_SIZE_MB))) LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -maxmempool=%d\n", __func__, DEFAULT_BLOCKSONLY_MAX_MEMPOOL_SIZE_MB); } // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place. if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) { if (args.SoftSetBoolArg("-whitelistrelay", true)) LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__); } if (args.IsArgSet("-onlynet")) { const auto onlynets = args.GetArgs("-onlynet"); bool clearnet_reachable = std::any_of(onlynets.begin(), onlynets.end(), [](const auto& net) { const auto n = ParseNetwork(net); return n == NET_IPV4 || n == NET_IPV6; }); if (!clearnet_reachable && args.SoftSetBoolArg("-dnsseed", false)) { LogPrintf("%s: parameter interaction: -onlynet excludes IPv4 and IPv6 -> setting -dnsseed=0\n", __func__); } } } /** * Initialize global loggers. * * Note that this is called very early in the process lifetime, so you should be * careful about what global state you rely on here. */ void InitLogging(const ArgsManager& args) { init::SetLoggingOptions(args); init::LogPackageVersion(); } namespace { // Variables internal to initialization process only int nMaxConnections; int nUserMaxConnections; int nFD; ServiceFlags nLocalServices = ServiceFlags(NODE_NETWORK_LIMITED | NODE_WITNESS); int64_t peer_connect_timeout; std::set<BlockFilterType> g_enabled_filter_types; } // namespace [[noreturn]] static void new_handler_terminate() { // Rather than throwing std::bad-alloc if allocation fails, terminate // immediately to (try to) avoid chain corruption. // Since LogPrintf may itself allocate memory, set the handler directly // to terminate first. std::set_new_handler(std::terminate); LogPrintf("Error: Out of memory. Terminating.\n"); // The log was successful, terminate now. std::terminate(); }; bool AppInitBasicSetup(const ArgsManager& args, std::atomic<int>& exit_status) { // ********************************************************* Step 1: setup #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0)); // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifdef WIN32 // Enable heap terminate-on-corruption HeapSetInformation(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0); #endif if (!SetupNetworking()) { return InitError(Untranslated("Initializing networking failed.")); } #ifndef WIN32 // Clean shutdown on SIGTERM registerSignalHandler(SIGTERM, HandleSIGTERM); registerSignalHandler(SIGINT, HandleSIGTERM); // Reopen debug.log on SIGHUP registerSignalHandler(SIGHUP, HandleSIGHUP); // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly signal(SIGPIPE, SIG_IGN); #else SetConsoleCtrlHandler(consoleCtrlHandler, true); #endif std::set_new_handler(new_handler_terminate); return true; } bool AppInitParameterInteraction(const ArgsManager& args) { const CChainParams& chainparams = Params(); // ********************************************************* Step 2: parameter interactions // also see: InitParameterInteraction() // Error if network-specific options (-addnode, -connect, etc) are // specified in default section of config file, but not overridden // on the command line or in this chain's section of the config file. ChainType chain = args.GetChainType(); if (chain == ChainType::SIGNET) { LogPrintf("Signet derived magic (message start): %s\n", HexStr(chainparams.MessageStart())); } bilingual_str errors; for (const auto& arg : args.GetUnsuitableSectionOnlyArgs()) { errors += strprintf(_("Config setting for %s only applied on %s network when in [%s] section.") + Untranslated("\n"), arg, ChainTypeToString(chain), ChainTypeToString(chain)); } if (!errors.empty()) { return InitError(errors); } // Warn if unrecognized section name are present in the config file. bilingual_str warnings; for (const auto& section : args.GetUnrecognizedSections()) { warnings += strprintf(Untranslated("%s:%i ") + _("Section [%s] is not recognized.") + Untranslated("\n"), section.m_file, section.m_line, section.m_name); } if (!warnings.empty()) { InitWarning(warnings); } if (!fs::is_directory(args.GetBlocksDirPath())) { return InitError(strprintf(_("Specified blocks directory \"%s\" does not exist."), args.GetArg("-blocksdir", ""))); } // parse and validate enabled filter types std::string blockfilterindex_value = args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX); if (blockfilterindex_value == "" || blockfilterindex_value == "1") { g_enabled_filter_types = AllBlockFilterTypes(); } else if (blockfilterindex_value != "0") { const std::vector<std::string> names = args.GetArgs("-blockfilterindex"); for (const auto& name : names) { BlockFilterType filter_type; if (!BlockFilterTypeByName(name, filter_type)) { return InitError(strprintf(_("Unknown -blockfilterindex value %s."), name)); } g_enabled_filter_types.insert(filter_type); } } // Signal NODE_P2P_V2 if BIP324 v2 transport is enabled. if (args.GetBoolArg("-v2transport", DEFAULT_V2_TRANSPORT)) { nLocalServices = ServiceFlags(nLocalServices | NODE_P2P_V2); } // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index are both enabled. if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) { if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) { return InitError(_("Cannot set -peerblockfilters without -blockfilterindex.")); } nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS); } if (args.GetIntArg("-prune", 0)) { if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) return InitError(_("Prune mode is incompatible with -txindex.")); if (args.GetBoolArg("-reindex-chainstate", false)) { return InitError(_("Prune mode is incompatible with -reindex-chainstate. Use full -reindex instead.")); } } // If -forcednsseed is set to true, ensure -dnsseed has not been set to false if (args.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED) && !args.GetBoolArg("-dnsseed", DEFAULT_DNSSEED)){ return InitError(_("Cannot set -forcednsseed to true when setting -dnsseed to false.")); } // -bind and -whitebind can't be set when not listening size_t nUserBind = args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size(); if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) { return InitError(Untranslated("Cannot set -bind or -whitebind together with -listen=0")); } // if listen=0, then disallow listenonion=1 if (!args.GetBoolArg("-listen", DEFAULT_LISTEN) && args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) { return InitError(Untranslated("Cannot set -listen=0 together with -listenonion=1")); } // Make sure enough file descriptors are available int nBind = std::max(nUserBind, size_t(1)); nUserMaxConnections = args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS); nMaxConnections = std::max(nUserMaxConnections, 0); nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS + nBind + NUM_FDS_MESSAGE_CAPTURE); #ifdef USE_POLL int fd_max = nFD; #else int fd_max = FD_SETSIZE; #endif // Trim requested connection counts, to fit into system limitations // <int> in std::min<int>(...) to work around FreeBSD compilation issue described in #2695 nMaxConnections = std::max(std::min<int>(nMaxConnections, fd_max - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS - NUM_FDS_MESSAGE_CAPTURE), 0); if (nFD < MIN_CORE_FILEDESCRIPTORS) return InitError(_("Not enough file descriptors available.")); nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS - NUM_FDS_MESSAGE_CAPTURE, nMaxConnections); if (nMaxConnections < nUserMaxConnections) InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections)); // ********************************************************* Step 3: parameter-to-internal-flags auto result = init::SetLoggingCategories(args); if (!result) return InitError(util::ErrorString(result)); result = init::SetLoggingLevel(args); if (!result) return InitError(util::ErrorString(result)); nConnectTimeout = args.GetIntArg("-timeout", DEFAULT_CONNECT_TIMEOUT); if (nConnectTimeout <= 0) { nConnectTimeout = DEFAULT_CONNECT_TIMEOUT; } peer_connect_timeout = args.GetIntArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT); if (peer_connect_timeout <= 0) { return InitError(Untranslated("peertimeout must be a positive integer.")); } // Sanity check argument for min fee for including tx in block // TODO: Harmonize which arguments need sanity checking and where that happens if (args.IsArgSet("-blockmintxfee")) { if (!ParseMoney(args.GetArg("-blockmintxfee", ""))) { return InitError(AmountErrMsg("blockmintxfee", args.GetArg("-blockmintxfee", ""))); } } nBytesPerSigOp = args.GetIntArg("-bytespersigop", nBytesPerSigOp); if (!g_wallet_init_interface.ParameterInteraction()) return false; // Option to startup with mocktime set (used for regression testing): SetMockTime(args.GetIntArg("-mocktime", 0)); // SetMockTime(0) is a no-op if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM); if (args.GetIntArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0) return InitError(Untranslated("rpcserialversion must be non-negative.")); if (args.GetIntArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1) return InitError(Untranslated("Unknown rpcserialversion requested.")); if (args.GetIntArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) == 0 && !IsDeprecatedRPCEnabled("serialversion")) { return InitError(Untranslated("-rpcserialversion=0 is deprecated and will be removed in the future. Specify -deprecatedrpc=serialversion to allow anyway.")); } // Also report errors from parsing before daemonization { kernel::Notifications notifications{}; ChainstateManager::Options chainman_opts_dummy{ .chainparams = chainparams, .datadir = args.GetDataDirNet(), .notifications = notifications, }; auto chainman_result{ApplyArgsManOptions(args, chainman_opts_dummy)}; if (!chainman_result) { return InitError(util::ErrorString(chainman_result)); } BlockManager::Options blockman_opts_dummy{ .chainparams = chainman_opts_dummy.chainparams, .blocks_dir = args.GetBlocksDirPath(), .notifications = chainman_opts_dummy.notifications, }; auto blockman_result{ApplyArgsManOptions(args, blockman_opts_dummy)}; if (!blockman_result) { return InitError(util::ErrorString(blockman_result)); } } return true; } static bool LockDataDirectory(bool probeOnly) { // Make sure only a single Bitcoin process is using the data directory. const fs::path& datadir = gArgs.GetDataDirNet(); switch (util::LockDirectory(datadir, ".lock", probeOnly)) { case util::LockResult::ErrorWrite: return InitError(strprintf(_("Cannot write to data directory '%s'; check permissions."), fs::PathToString(datadir))); case util::LockResult::ErrorLock: return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), fs::PathToString(datadir), PACKAGE_NAME)); case util::LockResult::Success: return true; } // no default case, so the compiler can warn about missing cases assert(false); } bool AppInitSanityChecks(const kernel::Context& kernel) { // ********************************************************* Step 4: sanity checks auto result{kernel::SanityChecks(kernel)}; if (!result) { InitError(util::ErrorString(result)); return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), PACKAGE_NAME)); } // Probe the data directory lock to give an early error message, if possible // We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened, // and a fork will cause weird behavior to it. return LockDataDirectory(true); } bool AppInitLockDataDirectory() { // After daemonization get the data directory lock again and hold on to it until exit // This creates a slight window for a race condition to happen, however this condition is harmless: it // will at most make us exit without printing a message to console. if (!LockDataDirectory(false)) { // Detailed error printed inside LockDataDirectory return false; } return true; } bool AppInitInterfaces(NodeContext& node) { node.chain = node.init->makeChain(); return true; } bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) { const ArgsManager& args = *Assert(node.args); const CChainParams& chainparams = Params(); auto opt_max_upload = ParseByteUnits(args.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET), ByteUnit::M); if (!opt_max_upload) { return InitError(strprintf(_("Unable to parse -maxuploadtarget: '%s'"), args.GetArg("-maxuploadtarget", ""))); } // ********************************************************* Step 4a: application initialization if (!CreatePidFile(args)) { // Detailed error printed inside CreatePidFile(). return false; } if (!init::StartLogging(args)) { // Detailed error printed inside StartLogging(). return false; } LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD); // Warn about relative -datadir path. if (args.IsArgSet("-datadir") && !args.GetPathArg("-datadir").is_absolute()) { LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the " "current working directory '%s'. This is fragile, because if bitcoin is started in the future " "from a different location, it will be unable to locate the current data files. There could " "also be data loss if bitcoin is started while in a temporary directory.\n", args.GetArg("-datadir", ""), fs::PathToString(fs::current_path())); } ValidationCacheSizes validation_cache_sizes{}; ApplyArgsManOptions(args, validation_cache_sizes); if (!InitSignatureCache(validation_cache_sizes.signature_cache_bytes) || !InitScriptExecutionCache(validation_cache_sizes.script_execution_cache_bytes)) { return InitError(strprintf(_("Unable to allocate memory for -maxsigcachesize: '%s' MiB"), args.GetIntArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_BYTES >> 20))); } assert(!node.scheduler); node.scheduler = std::make_unique<CScheduler>(); // Start the lightweight task scheduler thread node.scheduler->m_service_thread = std::thread(util::TraceThread, "scheduler", [&] { node.scheduler->serviceQueue(); }); // Gather some entropy once per minute. node.scheduler->scheduleEvery([]{ RandAddPeriodic(); }, std::chrono::minutes{1}); // Check disk space every 5 minutes to avoid db corruption. node.scheduler->scheduleEvery([&args, &node]{ constexpr uint64_t min_disk_space = 50 << 20; // 50 MB if (!CheckDiskSpace(args.GetBlocksDirPath(), min_disk_space)) { LogPrintf("Shutting down due to lack of disk space!\n"); if (!(*Assert(node.shutdown))()) { LogPrintf("Error: failed to send shutdown signal after disk space check\n"); } } }, std::chrono::minutes{5}); GetMainSignals().RegisterBackgroundSignalScheduler(*node.scheduler); // Create client interfaces for wallets that are supposed to be loaded // according to -wallet and -disablewallet options. This only constructs // the interfaces, it doesn't load wallet data. Wallets actually get loaded // when load() and start() interface methods are called below. g_wallet_init_interface.Construct(node); uiInterface.InitWallet(); /* Register RPC commands regardless of -server setting so they will be * available in the GUI RPC console even if external calls are disabled. */ RegisterAllCoreRPCCommands(tableRPC); for (const auto& client : node.chain_clients) { client->registerRpcs(); } #if ENABLE_ZMQ RegisterZMQRPCCommands(tableRPC); #endif /* Start the RPC server already. It will be started in "warmup" mode * and not really process calls already (but it will signify connections * that the server is there and will be ready later). Warmup mode will * be disabled when initialisation is finished. */ if (args.GetBoolArg("-server", false)) { uiInterface.InitMessage_connect(SetRPCWarmupStatus); if (!AppInitServers(node)) return InitError(_("Unable to start HTTP server. See debug log for details.")); } // ********************************************************* Step 5: verify wallet database integrity for (const auto& client : node.chain_clients) { if (!client->verify()) { return false; } } // ********************************************************* Step 6: network initialization // Note that we absolutely cannot open any actual connections // until the very end ("start node") as the UTXO/block state // is not yet setup and may end up being set up twice if we // need to reindex later. fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN); fDiscover = args.GetBoolArg("-discover", true); PeerManager::Options peerman_opts{}; ApplyArgsManOptions(args, peerman_opts); { // Read asmap file if configured std::vector<bool> asmap; if (args.IsArgSet("-asmap")) { fs::path asmap_path = args.GetPathArg("-asmap", DEFAULT_ASMAP_FILENAME); if (!asmap_path.is_absolute()) { asmap_path = args.GetDataDirNet() / asmap_path; } if (!fs::exists(asmap_path)) { InitError(strprintf(_("Could not find asmap file %s"), fs::quoted(fs::PathToString(asmap_path)))); return false; } asmap = DecodeAsmap(asmap_path); if (asmap.size() == 0) { InitError(strprintf(_("Could not parse asmap file %s"), fs::quoted(fs::PathToString(asmap_path)))); return false; } const uint256 asmap_version = (HashWriter{} << asmap).GetHash(); LogPrintf("Using asmap version %s for IP bucketing\n", asmap_version.ToString()); } else { LogPrintf("Using /16 prefix for IP bucketing\n"); } // Initialize netgroup manager assert(!node.netgroupman); node.netgroupman = std::make_unique<NetGroupManager>(std::move(asmap)); // Initialize addrman assert(!node.addrman); uiInterface.InitMessage(_("Loading P2P addresses…").translated); auto addrman{LoadAddrman(*node.netgroupman, args)}; if (!addrman) return InitError(util::ErrorString(addrman)); node.addrman = std::move(*addrman); } assert(!node.banman); node.banman = std::make_unique<BanMan>(args.GetDataDirNet() / "banlist", &uiInterface, args.GetIntArg("-bantime", DEFAULT_MISBEHAVING_BANTIME)); assert(!node.connman); node.connman = std::make_unique<CConnman>(GetRand<uint64_t>(), GetRand<uint64_t>(), *node.addrman, *node.netgroupman, chainparams, args.GetBoolArg("-networkactive", true)); assert(!node.fee_estimator); // Don't initialize fee estimation with old data if we don't relay transactions, // as they would never get updated. if (!peerman_opts.ignore_incoming_txs) { bool read_stale_estimates = args.GetBoolArg("-acceptstalefeeestimates", DEFAULT_ACCEPT_STALE_FEE_ESTIMATES); if (read_stale_estimates && (chainparams.GetChainType() != ChainType::REGTEST)) { return InitError(strprintf(_("acceptstalefeeestimates is not supported on %s chain."), chainparams.GetChainTypeString())); } node.fee_estimator = std::make_unique<CBlockPolicyEstimator>(FeeestPath(args), read_stale_estimates); // Flush estimates to disk periodically CBlockPolicyEstimator* fee_estimator = node.fee_estimator.get(); node.scheduler->scheduleEvery([fee_estimator] { fee_estimator->FlushFeeEstimates(); }, FEE_FLUSH_INTERVAL); RegisterValidationInterface(fee_estimator); } // Check port numbers for (const std::string port_option : { "-port", "-rpcport", }) { if (args.IsArgSet(port_option)) { const std::string port = args.GetArg(port_option, ""); uint16_t n; if (!ParseUInt16(port, &n) || n == 0) { return InitError(InvalidPortErrMsg(port_option, port)); } } } for (const std::string port_option : { "-i2psam", "-onion", "-proxy", "-rpcbind", "-torcontrol", "-whitebind", "-zmqpubhashblock", "-zmqpubhashtx", "-zmqpubrawblock", "-zmqpubrawtx", "-zmqpubsequence", }) { for (const std::string& socket_addr : args.GetArgs(port_option)) { std::string host_out; uint16_t port_out{0}; if (!SplitHostPort(socket_addr, port_out, host_out)) { return InitError(InvalidPortErrMsg(port_option, socket_addr)); } } } for (const std::string& socket_addr : args.GetArgs("-bind")) { std::string host_out; uint16_t port_out{0}; std::string bind_socket_addr = socket_addr.substr(0, socket_addr.rfind('=')); if (!SplitHostPort(bind_socket_addr, port_out, host_out)) { return InitError(InvalidPortErrMsg("-bind", socket_addr)); } } // sanitize comments per BIP-0014, format user agent and check total size std::vector<std::string> uacomments; for (const std::string& cmt : args.GetArgs("-uacomment")) { if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt)); uacomments.push_back(cmt); } strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments); if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) { return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."), strSubVersion.size(), MAX_SUBVERSION_LENGTH)); } if (args.IsArgSet("-onlynet")) { g_reachable_nets.RemoveAll(); for (const std::string& snet : args.GetArgs("-onlynet")) { enum Network net = ParseNetwork(snet); if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet)); g_reachable_nets.Add(net); } } if (!args.IsArgSet("-cjdnsreachable")) { if (args.IsArgSet("-onlynet") && g_reachable_nets.Contains(NET_CJDNS)) { return InitError( _("Outbound connections restricted to CJDNS (-onlynet=cjdns) but " "-cjdnsreachable is not provided")); } g_reachable_nets.Remove(NET_CJDNS); } // Now g_reachable_nets.Contains(NET_CJDNS) is true if: // 1. -cjdnsreachable is given and // 2.1. -onlynet is not given or // 2.2. -onlynet=cjdns is given // Requesting DNS seeds entails connecting to IPv4/IPv6, which -onlynet options may prohibit: // If -dnsseed=1 is explicitly specified, abort. If it's left unspecified by the user, we skip // the DNS seeds by adjusting -dnsseed in InitParameterInteraction. if (args.GetBoolArg("-dnsseed") == true && !g_reachable_nets.Contains(NET_IPV4) && !g_reachable_nets.Contains(NET_IPV6)) { return InitError(strprintf(_("Incompatible options: -dnsseed=1 was explicitly specified, but -onlynet forbids connections to IPv4/IPv6"))); }; // Check for host lookup allowed before parsing any network related parameters fNameLookup = args.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP); Proxy onion_proxy; bool proxyRandomize = args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE); // -proxy sets a proxy for all outgoing network traffic // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default std::string proxyArg = args.GetArg("-proxy", ""); if (proxyArg != "" && proxyArg != "0") { const std::optional<CService> proxyAddr{Lookup(proxyArg, 9050, fNameLookup)}; if (!proxyAddr.has_value()) { return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg)); } Proxy addrProxy = Proxy(proxyAddr.value(), proxyRandomize); if (!addrProxy.IsValid()) return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg)); SetProxy(NET_IPV4, addrProxy); SetProxy(NET_IPV6, addrProxy); SetProxy(NET_CJDNS, addrProxy); SetNameProxy(addrProxy); onion_proxy = addrProxy; } const bool onlynet_used_with_onion{args.IsArgSet("-onlynet") && g_reachable_nets.Contains(NET_ONION)}; // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses // -noonion (or -onion=0) disables connecting to .onion entirely // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none) std::string onionArg = args.GetArg("-onion", ""); if (onionArg != "") { if (onionArg == "0") { // Handle -noonion/-onion=0 onion_proxy = Proxy{}; if (onlynet_used_with_onion) { return InitError( _("Outbound connections restricted to Tor (-onlynet=onion) but the proxy for " "reaching the Tor network is explicitly forbidden: -onion=0")); } } else { const std::optional<CService> addr{Lookup(onionArg, 9050, fNameLookup)}; if (!addr.has_value() || !addr->IsValid()) { return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg)); } onion_proxy = Proxy{addr.value(), proxyRandomize}; } } if (onion_proxy.IsValid()) { SetProxy(NET_ONION, onion_proxy); } else { // If -listenonion is set, then we will (try to) connect to the Tor control port // later from the torcontrol thread and may retrieve the onion proxy from there. const bool listenonion_disabled{!args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)}; if (onlynet_used_with_onion && listenonion_disabled) { return InitError( _("Outbound connections restricted to Tor (-onlynet=onion) but the proxy for " "reaching the Tor network is not provided: none of -proxy, -onion or " "-listenonion is given")); } g_reachable_nets.Remove(NET_ONION); } for (const std::string& strAddr : args.GetArgs("-externalip")) { const std::optional<CService> addrLocal{Lookup(strAddr, GetListenPort(), fNameLookup)}; if (addrLocal.has_value() && addrLocal->IsValid()) AddLocal(addrLocal.value(), LOCAL_MANUAL); else return InitError(ResolveErrMsg("externalip", strAddr)); } #if ENABLE_ZMQ g_zmq_notification_interface = CZMQNotificationInterface::Create( [&chainman = node.chainman](CBlock& block, const CBlockIndex& index) { assert(chainman); return chainman->m_blockman.ReadBlockFromDisk(block, index); }); if (g_zmq_notification_interface) { RegisterValidationInterface(g_zmq_notification_interface.get()); } #endif // ********************************************************* Step 7: load block chain node.notifications = std::make_unique<KernelNotifications>(*Assert(node.shutdown), node.exit_status); ReadNotificationArgs(args, *node.notifications); fReindex = args.GetBoolArg("-reindex", false); bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false); ChainstateManager::Options chainman_opts{ .chainparams = chainparams, .datadir = args.GetDataDirNet(), .adjusted_time_callback = GetAdjustedTime, .notifications = *node.notifications, }; Assert(ApplyArgsManOptions(args, chainman_opts)); // no error can happen, already checked in AppInitParameterInteraction BlockManager::Options blockman_opts{ .chainparams = chainman_opts.chainparams, .blocks_dir = args.GetBlocksDirPath(), .notifications = chainman_opts.notifications, }; Assert(ApplyArgsManOptions(args, blockman_opts)); // no error can happen, already checked in AppInitParameterInteraction // cache size calculations CacheSizes cache_sizes = CalculateCacheSizes(args, g_enabled_filter_types.size()); LogPrintf("Cache configuration:\n"); LogPrintf("* Using %.1f MiB for block index database\n", cache_sizes.block_tree_db * (1.0 / 1024 / 1024)); if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) { LogPrintf("* Using %.1f MiB for transaction index database\n", cache_sizes.tx_index * (1.0 / 1024 / 1024)); } for (BlockFilterType filter_type : g_enabled_filter_types) { LogPrintf("* Using %.1f MiB for %s block filter index database\n", cache_sizes.filter_index * (1.0 / 1024 / 1024), BlockFilterTypeName(filter_type)); } LogPrintf("* Using %.1f MiB for chain state database\n", cache_sizes.coins_db * (1.0 / 1024 / 1024)); assert(!node.mempool); assert(!node.chainman); CTxMemPool::Options mempool_opts{ .check_ratio = chainparams.DefaultConsistencyChecks() ? 1 : 0, }; auto result{ApplyArgsManOptions(args, chainparams, mempool_opts)}; if (!result) { return InitError(util::ErrorString(result)); } mempool_opts.check_ratio = std::clamp<int>(mempool_opts.check_ratio, 0, 1'000'000); int64_t descendant_limit_bytes = mempool_opts.limits.descendant_size_vbytes * 40; if (mempool_opts.max_size_bytes < 0 || mempool_opts.max_size_bytes < descendant_limit_bytes) { return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(descendant_limit_bytes / 1'000'000.0))); } LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)\n", cache_sizes.coins * (1.0 / 1024 / 1024), mempool_opts.max_size_bytes * (1.0 / 1024 / 1024)); for (bool fLoaded = false; !fLoaded && !ShutdownRequested(node);) { node.mempool = std::make_unique<CTxMemPool>(mempool_opts); node.chainman = std::make_unique<ChainstateManager>(*Assert(node.shutdown), chainman_opts, blockman_opts); ChainstateManager& chainman = *node.chainman; // This is defined and set here instead of inline in validation.h to avoid a hard // dependency between validation and index/base, since the latter is not in // libbitcoinkernel. chainman.restart_indexes = [&node]() { LogPrintf("[snapshot] restarting indexes\n"); // Drain the validation interface queue to ensure that the old indexes // don't have any pending work. SyncWithValidationInterfaceQueue(); for (auto* index : node.indexes) { index->Interrupt(); index->Stop(); if (!(index->Init() && index->StartBackgroundSync())) { LogPrintf("[snapshot] WARNING failed to restart index %s on snapshot chain\n", index->GetName()); } } }; node::ChainstateLoadOptions options; options.mempool = Assert(node.mempool.get()); options.reindex = node::fReindex; options.reindex_chainstate = fReindexChainState; options.prune = chainman.m_blockman.IsPruneMode(); options.check_blocks = args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS); options.check_level = args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL); options.require_full_verification = args.IsArgSet("-checkblocks") || args.IsArgSet("-checklevel"); options.coins_error_cb = [] { uiInterface.ThreadSafeMessageBox( _("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR); }; uiInterface.InitMessage(_("Loading block index…").translated); const auto load_block_index_start_time{SteadyClock::now()}; auto catch_exceptions = [](auto&& f) { try { return f(); } catch (const std::exception& e) { LogPrintf("%s\n", e.what()); return std::make_tuple(node::ChainstateLoadStatus::FAILURE, _("Error opening block database")); } }; auto [status, error] = catch_exceptions([&]{ return LoadChainstate(chainman, cache_sizes, options); }); if (status == node::ChainstateLoadStatus::SUCCESS) { uiInterface.InitMessage(_("Verifying blocks…").translated); if (chainman.m_blockman.m_have_pruned && options.check_blocks > MIN_BLOCKS_TO_KEEP) { LogPrintfCategory(BCLog::PRUNE, "pruned datadir may not have more than %d blocks; only checking available blocks\n", MIN_BLOCKS_TO_KEEP); } std::tie(status, error) = catch_exceptions([&]{ return VerifyLoadedChainstate(chainman, options);}); if (status == node::ChainstateLoadStatus::SUCCESS) { fLoaded = true; LogPrintf(" block index %15dms\n", Ticks<std::chrono::milliseconds>(SteadyClock::now() - load_block_index_start_time)); } } if (status == node::ChainstateLoadStatus::FAILURE_FATAL || status == node::ChainstateLoadStatus::FAILURE_INCOMPATIBLE_DB || status == node::ChainstateLoadStatus::FAILURE_INSUFFICIENT_DBCACHE) { return InitError(error); } if (!fLoaded && !ShutdownRequested(node)) { // first suggest a reindex if (!options.reindex) { bool fRet = uiInterface.ThreadSafeQuestion( error + Untranslated(".\n\n") + _("Do you want to rebuild the block database now?"), error.original + ".\nPlease restart with -reindex or -reindex-chainstate to recover.", "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT); if (fRet) { fReindex = true; if (!Assert(node.shutdown)->reset()) { LogPrintf("Internal error: failed to reset shutdown signal.\n"); } } else { LogPrintf("Aborted block database rebuild. Exiting.\n"); return false; } } else { return InitError(error); } } } // As LoadBlockIndex can take several minutes, it's possible the user // requested to kill the GUI during the last operation. If so, exit. // As the program has not fully started yet, Shutdown() is possibly overkill. if (ShutdownRequested(node)) { LogPrintf("Shutdown requested. Exiting.\n"); return false; } ChainstateManager& chainman = *Assert(node.chainman); assert(!node.peerman); node.peerman = PeerManager::make(*node.connman, *node.addrman, node.banman.get(), chainman, *node.mempool, peerman_opts); RegisterValidationInterface(node.peerman.get()); // ********************************************************* Step 8: start indexers if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) { g_txindex = std::make_unique<TxIndex>(interfaces::MakeChain(node), cache_sizes.tx_index, false, fReindex); node.indexes.emplace_back(g_txindex.get()); } for (const auto& filter_type : g_enabled_filter_types) { InitBlockFilterIndex([&]{ return interfaces::MakeChain(node); }, filter_type, cache_sizes.filter_index, false, fReindex); node.indexes.emplace_back(GetBlockFilterIndex(filter_type)); } if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) { g_coin_stats_index = std::make_unique<CoinStatsIndex>(interfaces::MakeChain(node), /*cache_size=*/0, false, fReindex); node.indexes.emplace_back(g_coin_stats_index.get()); } // Init indexes for (auto index : node.indexes) if (!index->Init()) return false; // ********************************************************* Step 9: load wallet for (const auto& client : node.chain_clients) { if (!client->load()) { return false; } } // ********************************************************* Step 10: data directory maintenance // if pruning, perform the initial blockstore prune // after any wallet rescanning has taken place. if (chainman.m_blockman.IsPruneMode()) { if (!fReindex) { LOCK(cs_main); for (Chainstate* chainstate : chainman.GetAll()) { uiInterface.InitMessage(_("Pruning blockstore…").translated); chainstate->PruneAndFlush(); } } } else { LogPrintf("Setting NODE_NETWORK on non-prune mode\n"); nLocalServices = ServiceFlags(nLocalServices | NODE_NETWORK); } // ********************************************************* Step 11: import blocks if (!CheckDiskSpace(args.GetDataDirNet())) { InitError(strprintf(_("Error: Disk space is low for %s"), fs::quoted(fs::PathToString(args.GetDataDirNet())))); return false; } if (!CheckDiskSpace(args.GetBlocksDirPath())) { InitError(strprintf(_("Error: Disk space is low for %s"), fs::quoted(fs::PathToString(args.GetBlocksDirPath())))); return false; } int chain_active_height = WITH_LOCK(cs_main, return chainman.ActiveChain().Height()); // On first startup, warn on low block storage space if (!fReindex && !fReindexChainState && chain_active_height <= 1) { uint64_t assumed_chain_bytes{chainparams.AssumedBlockchainSize() * 1024 * 1024 * 1024}; uint64_t additional_bytes_needed{ chainman.m_blockman.IsPruneMode() ? std::min(chainman.m_blockman.GetPruneTarget(), assumed_chain_bytes) : assumed_chain_bytes}; if (!CheckDiskSpace(args.GetBlocksDirPath(), additional_bytes_needed)) { InitWarning(strprintf(_( "Disk space for %s may not accommodate the block files. " \ "Approximately %u GB of data will be stored in this directory." ), fs::quoted(fs::PathToString(args.GetBlocksDirPath())), chainparams.AssumedBlockchainSize() )); } } // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly. // No locking, as this happens before any background thread is started. boost::signals2::connection block_notify_genesis_wait_connection; if (WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip() == nullptr)) { block_notify_genesis_wait_connection = uiInterface.NotifyBlockTip_connect(std::bind(BlockNotifyGenesisWait, std::placeholders::_2)); } else { fHaveGenesis = true; } #if HAVE_SYSTEM const std::string block_notify = args.GetArg("-blocknotify", ""); if (!block_notify.empty()) { uiInterface.NotifyBlockTip_connect([block_notify](SynchronizationState sync_state, const CBlockIndex* pBlockIndex) { if (sync_state != SynchronizationState::POST_INIT || !pBlockIndex) return; std::string command = block_notify; ReplaceAll(command, "%s", pBlockIndex->GetBlockHash().GetHex()); std::thread t(runCommand, command); t.detach(); // thread runs free }); } #endif std::vector<fs::path> vImportFiles; for (const std::string& strFile : args.GetArgs("-loadblock")) { vImportFiles.push_back(fs::PathFromString(strFile)); } chainman.m_thread_load = std::thread(&util::TraceThread, "initload", [=, &chainman, &args, &node] { // Import blocks ImportBlocks(chainman, vImportFiles); if (args.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) { LogPrintf("Stopping after block import\n"); if (!(*Assert(node.shutdown))()) { LogPrintf("Error: failed to send shutdown signal after finishing block import\n"); } return; } // Start indexes initial sync if (!StartIndexBackgroundSync(node)) { bilingual_str err_str = _("Failed to start indexes, shutting down.."); chainman.GetNotifications().fatalError(err_str.original, err_str); return; } // Load mempool from disk if (auto* pool{chainman.ActiveChainstate().GetMempool()}) { LoadMempool(*pool, ShouldPersistMempool(args) ? MempoolPath(args) : fs::path{}, chainman.ActiveChainstate(), {}); pool->SetLoadTried(!chainman.m_interrupt); } }); // Wait for genesis block to be processed { WAIT_LOCK(g_genesis_wait_mutex, lock); // We previously could hang here if shutdown was requested prior to // ImportBlocks getting started, so instead we just wait on a timer to // check ShutdownRequested() regularly. while (!fHaveGenesis && !ShutdownRequested(node)) { g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500)); } block_notify_genesis_wait_connection.disconnect(); } if (ShutdownRequested(node)) { return false; } // ********************************************************* Step 12: start node //// debug print { LOCK(cs_main); LogPrintf("block tree size = %u\n", chainman.BlockIndex().size()); chain_active_height = chainman.ActiveChain().Height(); if (tip_info) { tip_info->block_height = chain_active_height; tip_info->block_time = chainman.ActiveChain().Tip() ? chainman.ActiveChain().Tip()->GetBlockTime() : chainman.GetParams().GenesisBlock().GetBlockTime(); tip_info->verification_progress = GuessVerificationProgress(chainman.GetParams().TxData(), chainman.ActiveChain().Tip()); } if (tip_info && chainman.m_best_header) { tip_info->header_height = chainman.m_best_header->nHeight; tip_info->header_time = chainman.m_best_header->GetBlockTime(); } } LogPrintf("nBestHeight = %d\n", chain_active_height); if (node.peerman) node.peerman->SetBestHeight(chain_active_height); // Map ports with UPnP or NAT-PMP. StartMapPort(args.GetBoolArg("-upnp", DEFAULT_UPNP), args.GetBoolArg("-natpmp", DEFAULT_NATPMP)); CConnman::Options connOptions; connOptions.nLocalServices = nLocalServices; connOptions.m_max_automatic_connections = nMaxConnections; connOptions.uiInterface = &uiInterface; connOptions.m_banman = node.banman.get(); connOptions.m_msgproc = node.peerman.get(); connOptions.nSendBufferMaxSize = 1000 * args.GetIntArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER); connOptions.nReceiveFloodSize = 1000 * args.GetIntArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER); connOptions.m_added_nodes = args.GetArgs("-addnode"); connOptions.nMaxOutboundLimit = *opt_max_upload; connOptions.m_peer_connect_timeout = peer_connect_timeout; // Port to bind to if `-bind=addr` is provided without a `:port` suffix. const uint16_t default_bind_port = static_cast<uint16_t>(args.GetIntArg("-port", Params().GetDefaultPort())); const auto BadPortWarning = [](const char* prefix, uint16_t port) { return strprintf(_("%s request to listen on port %u. This port is considered \"bad\" and " "thus it is unlikely that any peer will connect to it. See " "doc/p2p-bad-ports.md for details and a full list."), prefix, port); }; for (const std::string& bind_arg : args.GetArgs("-bind")) { std::optional<CService> bind_addr; const size_t index = bind_arg.rfind('='); if (index == std::string::npos) { bind_addr = Lookup(bind_arg, default_bind_port, /*fAllowLookup=*/false); if (bind_addr.has_value()) { connOptions.vBinds.push_back(bind_addr.value()); if (IsBadPort(bind_addr.value().GetPort())) { InitWarning(BadPortWarning("-bind", bind_addr.value().GetPort())); } continue; } } else { const std::string network_type = bind_arg.substr(index + 1); if (network_type == "onion") { const std::string truncated_bind_arg = bind_arg.substr(0, index); bind_addr = Lookup(truncated_bind_arg, BaseParams().OnionServiceTargetPort(), false); if (bind_addr.has_value()) { connOptions.onion_binds.push_back(bind_addr.value()); continue; } } } return InitError(ResolveErrMsg("bind", bind_arg)); } for (const std::string& strBind : args.GetArgs("-whitebind")) { NetWhitebindPermissions whitebind; bilingual_str error; if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) return InitError(error); connOptions.vWhiteBinds.push_back(whitebind); } // If the user did not specify -bind= or -whitebind= then we bind // on any address - 0.0.0.0 (IPv4) and :: (IPv6). connOptions.bind_on_any = args.GetArgs("-bind").empty() && args.GetArgs("-whitebind").empty(); // Emit a warning if a bad port is given to -port= but only if -bind and -whitebind are not // given, because if they are, then -port= is ignored. if (connOptions.bind_on_any && args.IsArgSet("-port")) { const uint16_t port_arg = args.GetIntArg("-port", 0); if (IsBadPort(port_arg)) { InitWarning(BadPortWarning("-port", port_arg)); } } CService onion_service_target; if (!connOptions.onion_binds.empty()) { onion_service_target = connOptions.onion_binds.front(); } else { onion_service_target = DefaultOnionServiceTarget(); connOptions.onion_binds.push_back(onion_service_target); } if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) { if (connOptions.onion_binds.size() > 1) { InitWarning(strprintf(_("More than one onion bind address is provided. Using %s " "for the automatically created Tor onion service."), onion_service_target.ToStringAddrPort())); } StartTorControl(onion_service_target); } if (connOptions.bind_on_any) { // Only add all IP addresses of the machine if we would be listening on // any address - 0.0.0.0 (IPv4) and :: (IPv6). Discover(); } for (const auto& net : args.GetArgs("-whitelist")) { NetWhitelistPermissions subnet; bilingual_str error; if (!NetWhitelistPermissions::TryParse(net, subnet, error)) return InitError(error); connOptions.vWhitelistedRange.push_back(subnet); } connOptions.vSeedNodes = args.GetArgs("-seednode"); // Initiate outbound connections unless connect=0 connOptions.m_use_addrman_outgoing = !args.IsArgSet("-connect"); if (!connOptions.m_use_addrman_outgoing) { const auto connect = args.GetArgs("-connect"); if (connect.size() != 1 || connect[0] != "0") { connOptions.m_specified_outgoing = connect; } if (!connOptions.m_specified_outgoing.empty() && !connOptions.vSeedNodes.empty()) { LogPrintf("-seednode is ignored when -connect is used\n"); } if (args.IsArgSet("-dnsseed") && args.GetBoolArg("-dnsseed", DEFAULT_DNSSEED) && args.IsArgSet("-proxy")) { LogPrintf("-dnsseed is ignored when -connect is used and -proxy is specified\n"); } } const std::string& i2psam_arg = args.GetArg("-i2psam", ""); if (!i2psam_arg.empty()) { const std::optional<CService> addr{Lookup(i2psam_arg, 7656, fNameLookup)}; if (!addr.has_value() || !addr->IsValid()) { return InitError(strprintf(_("Invalid -i2psam address or hostname: '%s'"), i2psam_arg)); } SetProxy(NET_I2P, Proxy{addr.value()}); } else { if (args.IsArgSet("-onlynet") && g_reachable_nets.Contains(NET_I2P)) { return InitError( _("Outbound connections restricted to i2p (-onlynet=i2p) but " "-i2psam is not provided")); } g_reachable_nets.Remove(NET_I2P); } connOptions.m_i2p_accept_incoming = args.GetBoolArg("-i2pacceptincoming", DEFAULT_I2P_ACCEPT_INCOMING); if (!node.connman->Start(*node.scheduler, connOptions)) { return false; } // ********************************************************* Step 13: finished // At this point, the RPC is "started", but still in warmup, which means it // cannot yet be called. Before we make it callable, we need to make sure // that the RPC's view of the best block is valid and consistent with // ChainstateManager's active tip. // // If we do not do this, RPC's view of the best block will be height=0 and // hash=0x0. This will lead to erroroneous responses for things like // waitforblockheight. RPCNotifyBlockChange(WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip())); SetRPCWarmupFinished(); uiInterface.InitMessage(_("Done loading").translated); for (const auto& client : node.chain_clients) { client->start(*node.scheduler); } BanMan* banman = node.banman.get(); node.scheduler->scheduleEvery([banman]{ banman->DumpBanlist(); }, DUMP_BANS_INTERVAL); if (node.peerman) node.peerman->StartScheduledTasks(*node.scheduler); #if HAVE_SYSTEM StartupNotify(args); #endif return true; } bool StartIndexBackgroundSync(NodeContext& node) { // Find the oldest block among all indexes. // This block is used to verify that we have the required blocks' data stored on disk, // starting from that point up to the current tip. // indexes_start_block='nullptr' means "start from height 0". std::optional<const CBlockIndex*> indexes_start_block; std::string older_index_name; ChainstateManager& chainman = *Assert(node.chainman); const Chainstate& chainstate = WITH_LOCK(::cs_main, return chainman.GetChainstateForIndexing()); const CChain& index_chain = chainstate.m_chain; for (auto index : node.indexes) { const IndexSummary& summary = index->GetSummary(); if (summary.synced) continue; // Get the last common block between the index best block and the active chain LOCK(::cs_main); const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(summary.best_block_hash); if (!index_chain.Contains(pindex)) { pindex = index_chain.FindFork(pindex); } if (!indexes_start_block || !pindex || pindex->nHeight < indexes_start_block.value()->nHeight) { indexes_start_block = pindex; older_index_name = summary.name; if (!pindex) break; // Starting from genesis so no need to look for earlier block. } }; // Verify all blocks needed to sync to current tip are present. if (indexes_start_block) { LOCK(::cs_main); const CBlockIndex* start_block = *indexes_start_block; if (!start_block) start_block = chainman.ActiveChain().Genesis(); if (!chainman.m_blockman.CheckBlockDataAvailability(*index_chain.Tip(), *Assert(start_block))) { return InitError(strprintf(Untranslated("%s best block of the index goes beyond pruned data. Please disable the index or reindex (which will download the whole blockchain again)"), older_index_name)); } } // Start threads for (auto index : node.indexes) if (!index->StartBackgroundSync()) return false; return true; }
0
bitcoin
bitcoin/src/bitcoind-res.rc
#include <windows.h> // needed for VERSIONINFO #include "clientversion.h" // holds the needed client version information #define VER_PRODUCTVERSION CLIENT_VERSION_MAJOR,CLIENT_VERSION_MINOR,CLIENT_VERSION_BUILD #define VER_FILEVERSION VER_PRODUCTVERSION VS_VERSION_INFO VERSIONINFO FILEVERSION VER_FILEVERSION PRODUCTVERSION VER_PRODUCTVERSION FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904E4" // U.S. English - multilingual (hex) BEGIN VALUE "CompanyName", "Bitcoin" VALUE "FileDescription", "bitcoind (Bitcoin node with a JSON-RPC server)" VALUE "FileVersion", PACKAGE_VERSION VALUE "InternalName", "bitcoind" VALUE "LegalCopyright", COPYRIGHT_STR VALUE "LegalTrademarks1", "Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php." VALUE "OriginalFilename", "bitcoind.exe" VALUE "ProductName", "bitcoind" VALUE "ProductVersion", PACKAGE_VERSION END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1252 // language neutral - multilingual (decimal) END END
0
bitcoin
bitcoin/src/core_io.h
// Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CORE_IO_H #define BITCOIN_CORE_IO_H #include <consensus/amount.h> #include <util/result.h> #include <string> #include <vector> class CBlock; class CBlockHeader; class CScript; class CTransaction; struct CMutableTransaction; class SigningProvider; class uint256; class UniValue; class CTxUndo; /** * Verbose level for block's transaction */ enum class TxVerbosity { SHOW_TXID, //!< Only TXID for each block's transaction SHOW_DETAILS, //!< Include TXID, inputs, outputs, and other common block's transaction information SHOW_DETAILS_AND_PREVOUT //!< The same as previous option with information about prevouts if available }; // core_read.cpp CScript ParseScript(const std::string& s); std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode = false); [[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); bool DecodeHexBlockHeader(CBlockHeader&, const std::string& hex_header); /** * Parse a hex string into 256 bits * @param[in] strHex a hex-formatted, 64-character string * @param[out] result the result of the parsing * @returns true if successful, false if not * * @see ParseHashV for an RPC-oriented version of this */ bool ParseHashStr(const std::string& strHex, uint256& result); [[nodiscard]] util::Result<int> SighashFromStr(const std::string& sighash); // core_write.cpp UniValue ValueFromAmount(const CAmount amount); std::string FormatScript(const CScript& script); std::string EncodeHexTx(const CTransaction& tx, const bool without_witness = false); std::string SighashToStr(unsigned char sighash_type); void ScriptToUniv(const CScript& script, UniValue& out, bool include_hex = true, bool include_address = false, const SigningProvider* provider = nullptr); void TxToUniv(const CTransaction& tx, const uint256& block_hash, UniValue& entry, bool include_hex = true, bool without_witness = false, const CTxUndo* txundo = nullptr, TxVerbosity verbosity = TxVerbosity::SHOW_DETAILS); #endif // BITCOIN_CORE_IO_H
0
bitcoin
bitcoin/src/torcontrol.cpp
// Copyright (c) 2015-2022 The Bitcoin Core developers // Copyright (c) 2017 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <torcontrol.h> #include <chainparams.h> #include <chainparamsbase.h> #include <common/args.h> #include <compat/compat.h> #include <crypto/hmac_sha256.h> #include <logging.h> #include <net.h> #include <netaddress.h> #include <netbase.h> #include <random.h> #include <tinyformat.h> #include <util/check.h> #include <util/fs.h> #include <util/readwritefile.h> #include <util/strencodings.h> #include <util/string.h> #include <util/thread.h> #include <util/time.h> #include <algorithm> #include <cassert> #include <cstdlib> #include <deque> #include <functional> #include <map> #include <optional> #include <set> #include <thread> #include <utility> #include <vector> #include <event2/buffer.h> #include <event2/bufferevent.h> #include <event2/event.h> #include <event2/thread.h> #include <event2/util.h> /** Default control ip and port */ const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:" + ToString(DEFAULT_TOR_CONTROL_PORT); /** Tor cookie size (from control-spec.txt) */ static const int TOR_COOKIE_SIZE = 32; /** Size of client/server nonce for SAFECOOKIE */ static const int TOR_NONCE_SIZE = 32; /** For computing serverHash in SAFECOOKIE */ static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash"; /** For computing clientHash in SAFECOOKIE */ static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash"; /** Exponential backoff configuration - initial timeout in seconds */ static const float RECONNECT_TIMEOUT_START = 1.0; /** Exponential backoff configuration - growth factor */ static const float RECONNECT_TIMEOUT_EXP = 1.5; /** Maximum length for lines received on TorControlConnection. * tor-control-spec.txt mentions that there is explicitly no limit defined to line length, * this is belt-and-suspenders sanity limit to prevent memory exhaustion. */ static const int MAX_LINE_LENGTH = 100000; static const uint16_t DEFAULT_TOR_SOCKS_PORT = 9050; /****** Low-level TorControlConnection ********/ TorControlConnection::TorControlConnection(struct event_base* _base) : base(_base) { } TorControlConnection::~TorControlConnection() { if (b_conn) bufferevent_free(b_conn); } void TorControlConnection::readcb(struct bufferevent *bev, void *ctx) { TorControlConnection *self = static_cast<TorControlConnection*>(ctx); struct evbuffer *input = bufferevent_get_input(bev); size_t n_read_out = 0; char *line; assert(input); // If there is not a whole line to read, evbuffer_readln returns nullptr while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr) { std::string s(line, n_read_out); free(line); if (s.size() < 4) // Short line continue; // <status>(-|+| )<data><CRLF> self->message.code = ToIntegral<int>(s.substr(0, 3)).value_or(0); self->message.lines.push_back(s.substr(4)); char ch = s[3]; // '-','+' or ' ' if (ch == ' ') { // Final line, dispatch reply and clean up if (self->message.code >= 600) { // (currently unused) // Dispatch async notifications to async handler // Synchronous and asynchronous messages are never interleaved } else { if (!self->reply_handlers.empty()) { // Invoke reply handler with message self->reply_handlers.front()(*self, self->message); self->reply_handlers.pop_front(); } else { LogPrint(BCLog::TOR, "Received unexpected sync reply %i\n", self->message.code); } } self->message.Clear(); } } // Check for size of buffer - protect against memory exhaustion with very long lines // Do this after evbuffer_readln to make sure all full lines have been // removed from the buffer. Everything left is an incomplete line. if (evbuffer_get_length(input) > MAX_LINE_LENGTH) { LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n"); self->Disconnect(); } } void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx) { TorControlConnection *self = static_cast<TorControlConnection*>(ctx); if (what & BEV_EVENT_CONNECTED) { LogPrint(BCLog::TOR, "Successfully connected!\n"); self->connected(*self); } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) { if (what & BEV_EVENT_ERROR) { LogPrint(BCLog::TOR, "Error connecting to Tor control socket\n"); } else { LogPrint(BCLog::TOR, "End of stream\n"); } self->Disconnect(); self->disconnected(*self); } } bool TorControlConnection::Connect(const std::string& tor_control_center, const ConnectionCB& _connected, const ConnectionCB& _disconnected) { if (b_conn) { Disconnect(); } const std::optional<CService> control_service{Lookup(tor_control_center, DEFAULT_TOR_CONTROL_PORT, fNameLookup)}; if (!control_service.has_value()) { LogPrintf("tor: Failed to look up control center %s\n", tor_control_center); return false; } struct sockaddr_storage control_address; socklen_t control_address_len = sizeof(control_address); if (!control_service.value().GetSockAddr(reinterpret_cast<struct sockaddr*>(&control_address), &control_address_len)) { LogPrintf("tor: Error parsing socket address %s\n", tor_control_center); return false; } // Create a new socket, set up callbacks and enable notification bits b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE); if (!b_conn) { return false; } bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this); bufferevent_enable(b_conn, EV_READ|EV_WRITE); this->connected = _connected; this->disconnected = _disconnected; // Finally, connect to tor_control_center if (bufferevent_socket_connect(b_conn, reinterpret_cast<struct sockaddr*>(&control_address), control_address_len) < 0) { LogPrintf("tor: Error connecting to address %s\n", tor_control_center); return false; } return true; } void TorControlConnection::Disconnect() { if (b_conn) bufferevent_free(b_conn); b_conn = nullptr; } bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler) { if (!b_conn) return false; struct evbuffer *buf = bufferevent_get_output(b_conn); if (!buf) return false; evbuffer_add(buf, cmd.data(), cmd.size()); evbuffer_add(buf, "\r\n", 2); reply_handlers.push_back(reply_handler); return true; } /****** General parsing utilities ********/ /* Split reply line in the form 'AUTH METHODS=...' into a type * 'AUTH' and arguments 'METHODS=...'. * Grammar is implicitly defined in https://spec.torproject.org/control-spec by * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24). */ std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s) { size_t ptr=0; std::string type; while (ptr < s.size() && s[ptr] != ' ') { type.push_back(s[ptr]); ++ptr; } if (ptr < s.size()) ++ptr; // skip ' ' return make_pair(type, s.substr(ptr)); } /** Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'. * Returns a map of keys to values, or an empty map if there was an error. * Grammar is implicitly defined in https://spec.torproject.org/control-spec by * the server reply formats for PROTOCOLINFO (S3.21), AUTHCHALLENGE (S3.24), * and ADD_ONION (S3.27). See also sections 2.1 and 2.3. */ std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s) { std::map<std::string,std::string> mapping; size_t ptr=0; while (ptr < s.size()) { std::string key, value; while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') { key.push_back(s[ptr]); ++ptr; } if (ptr == s.size()) // unexpected end of line return std::map<std::string,std::string>(); if (s[ptr] == ' ') // The remaining string is an OptArguments break; ++ptr; // skip '=' if (ptr < s.size() && s[ptr] == '"') { // Quoted string ++ptr; // skip opening '"' bool escape_next = false; while (ptr < s.size() && (escape_next || s[ptr] != '"')) { // Repeated backslashes must be interpreted as pairs escape_next = (s[ptr] == '\\' && !escape_next); value.push_back(s[ptr]); ++ptr; } if (ptr == s.size()) // unexpected end of line return std::map<std::string,std::string>(); ++ptr; // skip closing '"' /** * Unescape value. Per https://spec.torproject.org/control-spec section 2.1.1: * * For future-proofing, controller implementers MAY use the following * rules to be compatible with buggy Tor implementations and with * future ones that implement the spec as intended: * * Read \n \t \r and \0 ... \377 as C escapes. * Treat a backslash followed by any other character as that character. */ std::string escaped_value; for (size_t i = 0; i < value.size(); ++i) { if (value[i] == '\\') { // This will always be valid, because if the QuotedString // ended in an odd number of backslashes, then the parser // would already have returned above, due to a missing // terminating double-quote. ++i; if (value[i] == 'n') { escaped_value.push_back('\n'); } else if (value[i] == 't') { escaped_value.push_back('\t'); } else if (value[i] == 'r') { escaped_value.push_back('\r'); } else if ('0' <= value[i] && value[i] <= '7') { size_t j; // Octal escape sequences have a limit of three octal digits, // but terminate at the first character that is not a valid // octal digit if encountered sooner. for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {} // Tor restricts first digit to 0-3 for three-digit octals. // A leading digit of 4-7 would therefore be interpreted as // a two-digit octal. if (j == 3 && value[i] > '3') { j--; } const auto end{i + j}; uint8_t val{0}; while (i < end) { val *= 8; val += value[i++] - '0'; } escaped_value.push_back(char(val)); // Account for automatic incrementing at loop end --i; } else { escaped_value.push_back(value[i]); } } else { escaped_value.push_back(value[i]); } } value = escaped_value; } else { // Unquoted value. Note that values can contain '=' at will, just no spaces while (ptr < s.size() && s[ptr] != ' ') { value.push_back(s[ptr]); ++ptr; } } if (ptr < s.size() && s[ptr] == ' ') ++ptr; // skip ' ' after key=value mapping[key] = value; } return mapping; } TorController::TorController(struct event_base* _base, const std::string& tor_control_center, const CService& target): base(_base), m_tor_control_center(tor_control_center), conn(base), reconnect(true), reconnect_timeout(RECONNECT_TIMEOUT_START), m_target(target) { reconnect_ev = event_new(base, -1, 0, reconnect_cb, this); if (!reconnect_ev) LogPrintf("tor: Failed to create event for reconnection: out of memory?\n"); // Start connection attempts immediately if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1), std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) { LogPrintf("tor: Initiating connection to Tor control port %s failed\n", m_tor_control_center); } // Read service private key if cached std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile()); if (pkf.first) { LogPrint(BCLog::TOR, "Reading cached private key from %s\n", fs::PathToString(GetPrivateKeyFile())); private_key = pkf.second; } } TorController::~TorController() { if (reconnect_ev) { event_free(reconnect_ev); reconnect_ev = nullptr; } if (service.IsValid()) { RemoveLocal(service); } } void TorController::get_socks_cb(TorControlConnection& _conn, const TorControlReply& reply) { // NOTE: We can only get here if -onion is unset std::string socks_location; if (reply.code == 250) { for (const auto& line : reply.lines) { if (0 == line.compare(0, 20, "net/listeners/socks=")) { const std::string port_list_str = line.substr(20); std::vector<std::string> port_list = SplitString(port_list_str, ' '); for (auto& portstr : port_list) { if (portstr.empty()) continue; if ((portstr[0] == '"' || portstr[0] == '\'') && portstr.size() >= 2 && (*portstr.rbegin() == portstr[0])) { portstr = portstr.substr(1, portstr.size() - 2); if (portstr.empty()) continue; } socks_location = portstr; if (0 == portstr.compare(0, 10, "127.0.0.1:")) { // Prefer localhost - ignore other ports break; } } } } if (!socks_location.empty()) { LogPrint(BCLog::TOR, "Get SOCKS port command yielded %s\n", socks_location); } else { LogPrintf("tor: Get SOCKS port command returned nothing\n"); } } else if (reply.code == 510) { // 510 Unrecognized command LogPrintf("tor: Get SOCKS port command failed with unrecognized command (You probably should upgrade Tor)\n"); } else { LogPrintf("tor: Get SOCKS port command failed; error code %d\n", reply.code); } CService resolved; Assume(!resolved.IsValid()); if (!socks_location.empty()) { resolved = LookupNumeric(socks_location, DEFAULT_TOR_SOCKS_PORT); } if (!resolved.IsValid()) { // Fallback to old behaviour resolved = LookupNumeric("127.0.0.1", DEFAULT_TOR_SOCKS_PORT); } Assume(resolved.IsValid()); LogPrint(BCLog::TOR, "Configuring onion proxy for %s\n", resolved.ToStringAddrPort()); Proxy addrOnion = Proxy(resolved, true); SetProxy(NET_ONION, addrOnion); const auto onlynets = gArgs.GetArgs("-onlynet"); const bool onion_allowed_by_onlynet{ !gArgs.IsArgSet("-onlynet") || std::any_of(onlynets.begin(), onlynets.end(), [](const auto& n) { return ParseNetwork(n) == NET_ONION; })}; if (onion_allowed_by_onlynet) { // If NET_ONION is reachable, then the below is a noop. // // If NET_ONION is not reachable, then none of -proxy or -onion was given. // Since we are here, then -torcontrol and -torpassword were given. g_reachable_nets.Add(NET_ONION); } } void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlReply& reply) { if (reply.code == 250) { LogPrint(BCLog::TOR, "ADD_ONION successful\n"); for (const std::string &s : reply.lines) { std::map<std::string,std::string> m = ParseTorReplyMapping(s); std::map<std::string,std::string>::iterator i; if ((i = m.find("ServiceID")) != m.end()) service_id = i->second; if ((i = m.find("PrivateKey")) != m.end()) private_key = i->second; } if (service_id.empty()) { LogPrintf("tor: Error parsing ADD_ONION parameters:\n"); for (const std::string &s : reply.lines) { LogPrintf(" %s\n", SanitizeString(s)); } return; } service = LookupNumeric(std::string(service_id+".onion"), Params().GetDefaultPort()); LogPrintfCategory(BCLog::TOR, "Got service ID %s, advertising service %s\n", service_id, service.ToStringAddrPort()); if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) { LogPrint(BCLog::TOR, "Cached service private key to %s\n", fs::PathToString(GetPrivateKeyFile())); } else { LogPrintf("tor: Error writing service private key to %s\n", fs::PathToString(GetPrivateKeyFile())); } AddLocal(service, LOCAL_MANUAL); // ... onion requested - keep connection open } else if (reply.code == 510) { // 510 Unrecognized command LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n"); } else { LogPrintf("tor: Add onion failed; error code %d\n", reply.code); } } void TorController::auth_cb(TorControlConnection& _conn, const TorControlReply& reply) { if (reply.code == 250) { LogPrint(BCLog::TOR, "Authentication successful\n"); // Now that we know Tor is running setup the proxy for onion addresses // if -onion isn't set to something else. if (gArgs.GetArg("-onion", "") == "") { _conn.Command("GETINFO net/listeners/socks", std::bind(&TorController::get_socks_cb, this, std::placeholders::_1, std::placeholders::_2)); } // Finally - now create the service if (private_key.empty()) { // No private key, generate one private_key = "NEW:ED25519-V3"; // Explicitly request key type - see issue #9214 } // Request onion service, redirect port. // Note that the 'virtual' port is always the default port to avoid decloaking nodes using other ports. _conn.Command(strprintf("ADD_ONION %s Port=%i,%s", private_key, Params().GetDefaultPort(), m_target.ToStringAddrPort()), std::bind(&TorController::add_onion_cb, this, std::placeholders::_1, std::placeholders::_2)); } else { LogPrintf("tor: Authentication failed\n"); } } /** Compute Tor SAFECOOKIE response. * * ServerHash is computed as: * HMAC-SHA256("Tor safe cookie authentication server-to-controller hash", * CookieString | ClientNonce | ServerNonce) * (with the HMAC key as its first argument) * * After a controller sends a successful AUTHCHALLENGE command, the * next command sent on the connection must be an AUTHENTICATE command, * and the only authentication string which that AUTHENTICATE command * will accept is: * * HMAC-SHA256("Tor safe cookie authentication controller-to-server hash", * CookieString | ClientNonce | ServerNonce) * */ static std::vector<uint8_t> ComputeResponse(const std::string &key, const std::vector<uint8_t> &cookie, const std::vector<uint8_t> &clientNonce, const std::vector<uint8_t> &serverNonce) { CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size()); std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0); computeHash.Write(cookie.data(), cookie.size()); computeHash.Write(clientNonce.data(), clientNonce.size()); computeHash.Write(serverNonce.data(), serverNonce.size()); computeHash.Finalize(computedHash.data()); return computedHash; } void TorController::authchallenge_cb(TorControlConnection& _conn, const TorControlReply& reply) { if (reply.code == 250) { LogPrint(BCLog::TOR, "SAFECOOKIE authentication challenge successful\n"); std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]); if (l.first == "AUTHCHALLENGE") { std::map<std::string,std::string> m = ParseTorReplyMapping(l.second); if (m.empty()) { LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second)); return; } std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]); std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]); LogPrint(BCLog::TOR, "AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce)); if (serverNonce.size() != 32) { LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n"); return; } std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce); if (computedServerHash != serverHash) { LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash)); return; } std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce); _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2)); } else { LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n"); } } else { LogPrintf("tor: SAFECOOKIE authentication challenge failed\n"); } } void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorControlReply& reply) { if (reply.code == 250) { std::set<std::string> methods; std::string cookiefile; /* * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie" * 250-AUTH METHODS=NULL * 250-AUTH METHODS=HASHEDPASSWORD */ for (const std::string &s : reply.lines) { std::pair<std::string,std::string> l = SplitTorReplyLine(s); if (l.first == "AUTH") { std::map<std::string,std::string> m = ParseTorReplyMapping(l.second); std::map<std::string,std::string>::iterator i; if ((i = m.find("METHODS")) != m.end()) { std::vector<std::string> m_vec = SplitString(i->second, ','); methods = std::set<std::string>(m_vec.begin(), m_vec.end()); } if ((i = m.find("COOKIEFILE")) != m.end()) cookiefile = i->second; } else if (l.first == "VERSION") { std::map<std::string,std::string> m = ParseTorReplyMapping(l.second); std::map<std::string,std::string>::iterator i; if ((i = m.find("Tor")) != m.end()) { LogPrint(BCLog::TOR, "Connected to Tor version %s\n", i->second); } } } for (const std::string &s : methods) { LogPrint(BCLog::TOR, "Supported authentication method: %s\n", s); } // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD /* Authentication: * cookie: hex-encoded ~/.tor/control_auth_cookie * password: "password" */ std::string torpassword = gArgs.GetArg("-torpassword", ""); if (!torpassword.empty()) { if (methods.count("HASHEDPASSWORD")) { LogPrint(BCLog::TOR, "Using HASHEDPASSWORD authentication\n"); ReplaceAll(torpassword, "\"", "\\\""); _conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2)); } else { LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n"); } } else if (methods.count("NULL")) { LogPrint(BCLog::TOR, "Using NULL authentication\n"); _conn.Command("AUTHENTICATE", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2)); } else if (methods.count("SAFECOOKIE")) { // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie LogPrint(BCLog::TOR, "Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile); std::pair<bool,std::string> status_cookie = ReadBinaryFile(fs::PathFromString(cookiefile), TOR_COOKIE_SIZE); if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) { // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2)); cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end()); clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0); GetRandBytes(clientNonce); _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), std::bind(&TorController::authchallenge_cb, this, std::placeholders::_1, std::placeholders::_2)); } else { if (status_cookie.first) { LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE); } else { LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile); } } } else if (methods.count("HASHEDPASSWORD")) { LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n"); } else { LogPrintf("tor: No supported authentication method\n"); } } else { LogPrintf("tor: Requesting protocol info failed\n"); } } void TorController::connected_cb(TorControlConnection& _conn) { reconnect_timeout = RECONNECT_TIMEOUT_START; // First send a PROTOCOLINFO command to figure out what authentication is expected if (!_conn.Command("PROTOCOLINFO 1", std::bind(&TorController::protocolinfo_cb, this, std::placeholders::_1, std::placeholders::_2))) LogPrintf("tor: Error sending initial protocolinfo command\n"); } void TorController::disconnected_cb(TorControlConnection& _conn) { // Stop advertising service when disconnected if (service.IsValid()) RemoveLocal(service); service = CService(); if (!reconnect) return; LogPrint(BCLog::TOR, "Not connected to Tor control port %s, trying to reconnect\n", m_tor_control_center); // Single-shot timer for reconnect. Use exponential backoff. struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0)); if (reconnect_ev) event_add(reconnect_ev, &time); reconnect_timeout *= RECONNECT_TIMEOUT_EXP; } void TorController::Reconnect() { /* Try to reconnect and reestablish if we get booted - for example, Tor * may be restarting. */ if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1), std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) { LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", m_tor_control_center); } } fs::path TorController::GetPrivateKeyFile() { return gArgs.GetDataDirNet() / "onion_v3_private_key"; } void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg) { TorController *self = static_cast<TorController*>(arg); self->Reconnect(); } /****** Thread ********/ static struct event_base *gBase; static std::thread torControlThread; static void TorControlThread(CService onion_service_target) { TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL), onion_service_target); event_base_dispatch(gBase); } void StartTorControl(CService onion_service_target) { assert(!gBase); #ifdef WIN32 evthread_use_windows_threads(); #else evthread_use_pthreads(); #endif gBase = event_base_new(); if (!gBase) { LogPrintf("tor: Unable to create event_base\n"); return; } torControlThread = std::thread(&util::TraceThread, "torcontrol", [onion_service_target] { TorControlThread(onion_service_target); }); } void InterruptTorControl() { if (gBase) { LogPrintf("tor: Thread interrupt\n"); event_base_once(gBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) { event_base_loopbreak(gBase); }, nullptr, nullptr); } } void StopTorControl() { if (gBase) { torControlThread.join(); event_base_free(gBase); gBase = nullptr; } } CService DefaultOnionServiceTarget() { struct in_addr onion_service_target; onion_service_target.s_addr = htonl(INADDR_LOOPBACK); return {onion_service_target, BaseParams().OnionServiceTargetPort()}; }
0
bitcoin
bitcoin/src/external_signer.cpp
// Copyright (c) 2018-2022 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 <external_signer.h> #include <chainparams.h> #include <common/run_command.h> #include <core_io.h> #include <psbt.h> #include <util/strencodings.h> #include <algorithm> #include <stdexcept> #include <string> #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) {} std::string ExternalSigner::NetworkArg() const { return " --chain " + m_chain; } bool ExternalSigner::Enumerate(const std::string& command, std::vector<ExternalSigner>& signers, const std::string chain) { // Call <command> enumerate const UniValue result = RunCommandParseJSON(command + " enumerate"); if (!result.isArray()) { throw std::runtime_error(strprintf("'%s' received invalid response, expected array of signers", command)); } for (const UniValue& signer : result.getValues()) { // Check for error const UniValue& error = signer.find_value("error"); if (!error.isNull()) { if (!error.isStr()) { throw std::runtime_error(strprintf("'%s' error", command)); } throw std::runtime_error(strprintf("'%s' error: %s", command, error.getValStr())); } // Check if fingerprint is present const UniValue& fingerprint = signer.find_value("fingerprint"); if (fingerprint.isNull()) { throw std::runtime_error(strprintf("'%s' received invalid response, missing signer fingerprint", command)); } const std::string& fingerprintStr{fingerprint.get_str()}; // Skip duplicate signer bool duplicate = false; for (const ExternalSigner& signer : signers) { if (signer.m_fingerprint.compare(fingerprintStr) == 0) duplicate = true; } if (duplicate) break; std::string name; const UniValue& model_field = signer.find_value("model"); if (model_field.isStr() && model_field.getValStr() != "") { name += model_field.getValStr(); } signers.emplace_back(command, chain, fingerprintStr, name); } return true; } UniValue ExternalSigner::DisplayAddress(const std::string& descriptor) const { return RunCommandParseJSON(m_command + " --fingerprint \"" + m_fingerprint + "\"" + NetworkArg() + " displayaddress --desc \"" + descriptor + "\""); } UniValue ExternalSigner::GetDescriptors(const int account) { return RunCommandParseJSON(m_command + " --fingerprint \"" + m_fingerprint + "\"" + NetworkArg() + " getdescriptors --account " + strprintf("%d", account)); } bool ExternalSigner::SignTransaction(PartiallySignedTransaction& psbtx, std::string& error) { // Serialize the PSBT DataStream ssTx{}; ssTx << psbtx; // parse ExternalSigner master fingerprint std::vector<unsigned char> parsed_m_fingerprint = ParseHex(m_fingerprint); // Check if signer fingerprint matches any input master key fingerprint auto matches_signer_fingerprint = [&](const PSBTInput& input) { for (const auto& entry : input.hd_keypaths) { if (parsed_m_fingerprint == MakeUCharSpan(entry.second.fingerprint)) return true; } for (const auto& entry : input.m_tap_bip32_paths) { if (parsed_m_fingerprint == MakeUCharSpan(entry.second.second.fingerprint)) return true; } return false; }; if (!std::any_of(psbtx.inputs.begin(), psbtx.inputs.end(), matches_signer_fingerprint)) { error = "Signer fingerprint " + m_fingerprint + " does not match any of the inputs:\n" + EncodeBase64(ssTx.str()); return false; } const std::string command = m_command + " --stdin --fingerprint \"" + m_fingerprint + "\"" + NetworkArg(); const std::string stdinStr = "signtx \"" + EncodeBase64(ssTx.str()) + "\""; const UniValue signer_result = RunCommandParseJSON(command, stdinStr); if (signer_result.find_value("error").isStr()) { error = signer_result.find_value("error").get_str(); return false; } if (!signer_result.find_value("psbt").isStr()) { error = "Unexpected result from signer"; return false; } PartiallySignedTransaction signer_psbtx; std::string signer_psbt_error; if (!DecodeBase64PSBT(signer_psbtx, signer_result.find_value("psbt").get_str(), signer_psbt_error)) { error = strprintf("TX decode failed %s", signer_psbt_error); return false; } psbtx = signer_psbtx; return true; }
0
bitcoin
bitcoin/src/hash.cpp
// Copyright (c) 2013-2022 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 <hash.h> #include <span.h> #include <crypto/common.h> #include <crypto/hmac_sha512.h> #include <string> inline uint32_t ROTL32(uint32_t x, int8_t r) { return (x << r) | (x >> (32 - r)); } unsigned int MurmurHash3(unsigned int nHashSeed, Span<const unsigned char> vDataToHash) { // The following is MurmurHash3 (x86_32), see https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp uint32_t h1 = nHashSeed; const uint32_t c1 = 0xcc9e2d51; const uint32_t c2 = 0x1b873593; const int nblocks = vDataToHash.size() / 4; //---------- // body const uint8_t* blocks = vDataToHash.data(); for (int i = 0; i < nblocks; ++i) { uint32_t k1 = ReadLE32(blocks + i*4); k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; h1 = ROTL32(h1, 13); h1 = h1 * 5 + 0xe6546b64; } //---------- // tail const uint8_t* tail = vDataToHash.data() + nblocks * 4; uint32_t k1 = 0; switch (vDataToHash.size() & 3) { case 3: k1 ^= tail[2] << 16; [[fallthrough]]; case 2: k1 ^= tail[1] << 8; [[fallthrough]]; case 1: k1 ^= tail[0]; k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; } //---------- // finalization h1 ^= vDataToHash.size(); h1 ^= h1 >> 16; h1 *= 0x85ebca6b; h1 ^= h1 >> 13; h1 *= 0xc2b2ae35; h1 ^= h1 >> 16; return h1; } void BIP32Hash(const ChainCode &chainCode, unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]) { unsigned char num[4]; WriteBE32(num, nChild); CHMAC_SHA512(chainCode.begin(), chainCode.size()).Write(&header, 1).Write(data, 32).Write(num, 4).Finalize(output); } uint256 SHA256Uint256(const uint256& input) { uint256 result; CSHA256().Write(input.begin(), 32).Finalize(result.begin()); return result; } HashWriter TaggedHash(const std::string& tag) { HashWriter writer{}; uint256 taghash; CSHA256().Write((const unsigned char*)tag.data(), tag.size()).Finalize(taghash.begin()); writer << taghash << taghash; return writer; }
0
bitcoin
bitcoin/src/txdb.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TXDB_H #define BITCOIN_TXDB_H #include <coins.h> #include <dbwrapper.h> #include <kernel/cs_main.h> #include <sync.h> #include <util/fs.h> #include <cstddef> #include <cstdint> #include <memory> #include <optional> #include <vector> class COutPoint; class uint256; //! -dbcache default (MiB) static const int64_t nDefaultDbCache = 450; //! -dbbatchsize default (bytes) static const int64_t nDefaultDbBatchSize = 16 << 20; //! max. -dbcache (MiB) static const int64_t nMaxDbCache = sizeof(void*) > 4 ? 16384 : 1024; //! min. -dbcache (MiB) static const int64_t nMinDbCache = 4; //! Max memory allocated to block tree DB specific cache, if no -txindex (MiB) static const int64_t nMaxBlockDBCache = 2; //! Max memory allocated to block tree DB specific cache, if -txindex (MiB) // Unlike for the UTXO database, for the txindex scenario the leveldb cache make // a meaningful difference: https://github.com/bitcoin/bitcoin/pull/8273#issuecomment-229601991 static const int64_t nMaxTxIndexCache = 1024; //! Max memory allocated to all block filter index caches combined in MiB. static const int64_t max_filter_index_cache = 1024; //! Max memory allocated to coin DB specific cache (MiB) static const int64_t nMaxCoinsDBCache = 8; //! User-controlled performance and debug options. struct CoinsViewOptions { //! Maximum database write batch size in bytes. size_t batch_write_bytes = nDefaultDbBatchSize; //! If non-zero, randomly exit when the database is flushed with (1/ratio) //! probability. int simulate_crash_ratio = 0; }; /** CCoinsView backed by the coin database (chainstate/) */ class CCoinsViewDB final : public CCoinsView { protected: DBParams m_db_params; CoinsViewOptions m_options; std::unique_ptr<CDBWrapper> m_db; public: explicit CCoinsViewDB(DBParams db_params, CoinsViewOptions options); bool GetCoin(const COutPoint &outpoint, Coin &coin) const override; bool HaveCoin(const COutPoint &outpoint) const override; uint256 GetBestBlock() const override; std::vector<uint256> GetHeadBlocks() const override; bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase = true) override; std::unique_ptr<CCoinsViewCursor> Cursor() const override; //! Whether an unsupported database format is used. bool NeedsUpgrade(); size_t EstimateSize() const override; //! Dynamically alter the underlying leveldb cache size. void ResizeCache(size_t new_cache_size) EXCLUSIVE_LOCKS_REQUIRED(cs_main); //! @returns filesystem path to on-disk storage or std::nullopt if in memory. std::optional<fs::path> StoragePath() { return m_db->StoragePath(); } }; #endif // BITCOIN_TXDB_H
0
bitcoin
bitcoin/src/net_permissions.cpp
// Copyright (c) 2009-2021 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 <common/system.h> #include <net_permissions.h> #include <netbase.h> #include <util/error.h> #include <util/translation.h> const std::vector<std::string> NET_PERMISSIONS_DOC{ "bloomfilter (allow requesting BIP37 filtered blocks and transactions)", "noban (do not ban for misbehavior; implies download)", "forcerelay (relay transactions that are already in the mempool; implies relay)", "relay (relay even in -blocksonly mode, and unlimited transaction announcements)", "mempool (allow requesting BIP35 mempool contents)", "download (allow getheaders during IBD, no disconnect after maxuploadtarget limit)", "addr (responses to GETADDR avoid hitting the cache and contain random records with the most up-to-date info)" }; namespace { // Parse the following format: "perm1,perm2@xxxxxx" bool TryParsePermissionFlags(const std::string& str, NetPermissionFlags& output, size_t& readen, bilingual_str& error) { NetPermissionFlags flags = NetPermissionFlags::None; const auto atSeparator = str.find('@'); // if '@' is not found (ie, "xxxxx"), the caller should apply implicit permissions if (atSeparator == std::string::npos) { NetPermissions::AddFlag(flags, NetPermissionFlags::Implicit); readen = 0; } // else (ie, "perm1,perm2@xxxxx"), let's enumerate the permissions by splitting by ',' and calculate the flags else { readen = 0; // permissions == perm1,perm2 const auto permissions = str.substr(0, atSeparator); while (readen < permissions.length()) { const auto commaSeparator = permissions.find(',', readen); const auto len = commaSeparator == std::string::npos ? permissions.length() - readen : commaSeparator - readen; // permission == perm1 const auto permission = permissions.substr(readen, len); readen += len; // We read "perm1" if (commaSeparator != std::string::npos) readen++; // We read "," if (permission == "bloomfilter" || permission == "bloom") NetPermissions::AddFlag(flags, NetPermissionFlags::BloomFilter); else if (permission == "noban") NetPermissions::AddFlag(flags, NetPermissionFlags::NoBan); else if (permission == "forcerelay") NetPermissions::AddFlag(flags, NetPermissionFlags::ForceRelay); else if (permission == "mempool") NetPermissions::AddFlag(flags, NetPermissionFlags::Mempool); else if (permission == "download") NetPermissions::AddFlag(flags, NetPermissionFlags::Download); else if (permission == "all") NetPermissions::AddFlag(flags, NetPermissionFlags::All); else if (permission == "relay") NetPermissions::AddFlag(flags, NetPermissionFlags::Relay); else if (permission == "addr") NetPermissions::AddFlag(flags, NetPermissionFlags::Addr); else if (permission.length() == 0); // Allow empty entries else { error = strprintf(_("Invalid P2P permission: '%s'"), permission); return false; } } readen++; } output = flags; error = Untranslated(""); return true; } } std::vector<std::string> NetPermissions::ToStrings(NetPermissionFlags flags) { std::vector<std::string> strings; if (NetPermissions::HasFlag(flags, NetPermissionFlags::BloomFilter)) strings.emplace_back("bloomfilter"); if (NetPermissions::HasFlag(flags, NetPermissionFlags::NoBan)) strings.emplace_back("noban"); if (NetPermissions::HasFlag(flags, NetPermissionFlags::ForceRelay)) strings.emplace_back("forcerelay"); if (NetPermissions::HasFlag(flags, NetPermissionFlags::Relay)) strings.emplace_back("relay"); if (NetPermissions::HasFlag(flags, NetPermissionFlags::Mempool)) strings.emplace_back("mempool"); if (NetPermissions::HasFlag(flags, NetPermissionFlags::Download)) strings.emplace_back("download"); if (NetPermissions::HasFlag(flags, NetPermissionFlags::Addr)) strings.emplace_back("addr"); return strings; } bool NetWhitebindPermissions::TryParse(const std::string& str, NetWhitebindPermissions& output, bilingual_str& error) { NetPermissionFlags flags; size_t offset; if (!TryParsePermissionFlags(str, flags, offset, error)) return false; const std::string strBind = str.substr(offset); const std::optional<CService> addrBind{Lookup(strBind, 0, false)}; if (!addrBind.has_value()) { error = ResolveErrMsg("whitebind", strBind); return false; } if (addrBind.value().GetPort() == 0) { error = strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind); return false; } output.m_flags = flags; output.m_service = addrBind.value(); error = Untranslated(""); return true; } bool NetWhitelistPermissions::TryParse(const std::string& str, NetWhitelistPermissions& output, bilingual_str& error) { NetPermissionFlags flags; size_t offset; if (!TryParsePermissionFlags(str, flags, offset, error)) return false; const std::string net = str.substr(offset); const CSubNet subnet{LookupSubNet(net)}; if (!subnet.IsValid()) { error = strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net); return false; } output.m_flags = flags; output.m_subnet = subnet; error = Untranslated(""); return true; }
0
bitcoin
bitcoin/src/mapport.cpp
// Copyright (c) 2011-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <mapport.h> #include <clientversion.h> #include <common/system.h> #include <logging.h> #include <net.h> #include <netaddress.h> #include <netbase.h> #include <util/thread.h> #include <util/threadinterrupt.h> #ifdef USE_NATPMP #include <compat/compat.h> #include <natpmp.h> #endif // USE_NATPMP #ifdef USE_UPNP #include <miniupnpc/miniupnpc.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> // The minimum supported miniUPnPc API version is set to 17. This excludes // versions with known vulnerabilities. static_assert(MINIUPNPC_API_VERSION >= 17, "miniUPnPc API version >= 17 assumed"); #endif // USE_UPNP #include <atomic> #include <cassert> #include <chrono> #include <functional> #include <string> #include <thread> #if defined(USE_NATPMP) || defined(USE_UPNP) static CThreadInterrupt g_mapport_interrupt; static std::thread g_mapport_thread; static std::atomic_uint g_mapport_enabled_protos{MapPortProtoFlag::NONE}; static std::atomic<MapPortProtoFlag> g_mapport_current_proto{MapPortProtoFlag::NONE}; using namespace std::chrono_literals; static constexpr auto PORT_MAPPING_REANNOUNCE_PERIOD{20min}; static constexpr auto PORT_MAPPING_RETRY_PERIOD{5min}; #ifdef USE_NATPMP static uint16_t g_mapport_external_port = 0; static bool NatpmpInit(natpmp_t* natpmp) { const int r_init = initnatpmp(natpmp, /* detect gateway automatically */ 0, /* forced gateway - NOT APPLIED*/ 0); if (r_init == 0) return true; LogPrintf("natpmp: initnatpmp() failed with %d error.\n", r_init); return false; } static bool NatpmpDiscover(natpmp_t* natpmp, struct in_addr& external_ipv4_addr) { const int r_send = sendpublicaddressrequest(natpmp); if (r_send == 2 /* OK */) { int r_read; natpmpresp_t response; do { r_read = readnatpmpresponseorretry(natpmp, &response); } while (r_read == NATPMP_TRYAGAIN); if (r_read == 0) { external_ipv4_addr = response.pnu.publicaddress.addr; return true; } else if (r_read == NATPMP_ERR_NOGATEWAYSUPPORT) { LogPrintf("natpmp: The gateway does not support NAT-PMP.\n"); } else { LogPrintf("natpmp: readnatpmpresponseorretry() for public address failed with %d error.\n", r_read); } } else { LogPrintf("natpmp: sendpublicaddressrequest() failed with %d error.\n", r_send); } return false; } static bool NatpmpMapping(natpmp_t* natpmp, const struct in_addr& external_ipv4_addr, uint16_t private_port, bool& external_ip_discovered) { const uint16_t suggested_external_port = g_mapport_external_port ? g_mapport_external_port : private_port; const int r_send = sendnewportmappingrequest(natpmp, NATPMP_PROTOCOL_TCP, private_port, suggested_external_port, 3600 /*seconds*/); if (r_send == 12 /* OK */) { int r_read; natpmpresp_t response; do { r_read = readnatpmpresponseorretry(natpmp, &response); } while (r_read == NATPMP_TRYAGAIN); if (r_read == 0) { auto pm = response.pnu.newportmapping; if (private_port == pm.privateport && pm.lifetime > 0) { g_mapport_external_port = pm.mappedpublicport; const CService external{external_ipv4_addr, pm.mappedpublicport}; if (!external_ip_discovered && fDiscover) { AddLocal(external, LOCAL_MAPPED); external_ip_discovered = true; } LogPrintf("natpmp: Port mapping successful. External address = %s\n", external.ToStringAddrPort()); return true; } else { LogPrintf("natpmp: Port mapping failed.\n"); } } else if (r_read == NATPMP_ERR_NOGATEWAYSUPPORT) { LogPrintf("natpmp: The gateway does not support NAT-PMP.\n"); } else { LogPrintf("natpmp: readnatpmpresponseorretry() for port mapping failed with %d error.\n", r_read); } } else { LogPrintf("natpmp: sendnewportmappingrequest() failed with %d error.\n", r_send); } return false; } static bool ProcessNatpmp() { bool ret = false; natpmp_t natpmp; struct in_addr external_ipv4_addr; if (NatpmpInit(&natpmp) && NatpmpDiscover(&natpmp, external_ipv4_addr)) { bool external_ip_discovered = false; const uint16_t private_port = GetListenPort(); do { ret = NatpmpMapping(&natpmp, external_ipv4_addr, private_port, external_ip_discovered); } while (ret && g_mapport_interrupt.sleep_for(PORT_MAPPING_REANNOUNCE_PERIOD)); g_mapport_interrupt.reset(); const int r_send = sendnewportmappingrequest(&natpmp, NATPMP_PROTOCOL_TCP, private_port, g_mapport_external_port, /* remove a port mapping */ 0); g_mapport_external_port = 0; if (r_send == 12 /* OK */) { LogPrintf("natpmp: Port mapping removed successfully.\n"); } else { LogPrintf("natpmp: sendnewportmappingrequest(0) failed with %d error.\n", r_send); } } closenatpmp(&natpmp); return ret; } #endif // USE_NATPMP #ifdef USE_UPNP static bool ProcessUpnp() { bool ret = false; std::string port = strprintf("%u", GetListenPort()); const char * multicastif = nullptr; const char * minissdpdpath = nullptr; struct UPNPDev * devlist = nullptr; char lanaddr[64]; int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error); struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if (r != UPNPCOMMAND_SUCCESS) { LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r); } else { if (externalIPAddress[0]) { std::optional<CNetAddr> resolved{LookupHost(externalIPAddress, false)}; if (resolved.has_value()) { LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved->ToStringAddr()); AddLocal(resolved.value(), LOCAL_MAPPED); } } else { LogPrintf("UPnP: GetExternalIPAddress failed.\n"); } } } std::string strDesc = PACKAGE_NAME " " + FormatFullVersion(); do { r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", nullptr, "0"); if (r != UPNPCOMMAND_SUCCESS) { ret = false; LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port, port, lanaddr, r, strupnperror(r)); break; } else { ret = true; LogPrintf("UPnP Port Mapping successful.\n"); } } while (g_mapport_interrupt.sleep_for(PORT_MAPPING_REANNOUNCE_PERIOD)); g_mapport_interrupt.reset(); r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", nullptr); LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r); freeUPNPDevlist(devlist); devlist = nullptr; FreeUPNPUrls(&urls); } else { LogPrintf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = nullptr; if (r != 0) FreeUPNPUrls(&urls); } return ret; } #endif // USE_UPNP static void ThreadMapPort() { bool ok; do { ok = false; #ifdef USE_UPNP // High priority protocol. if (g_mapport_enabled_protos & MapPortProtoFlag::UPNP) { g_mapport_current_proto = MapPortProtoFlag::UPNP; ok = ProcessUpnp(); if (ok) continue; } #endif // USE_UPNP #ifdef USE_NATPMP // Low priority protocol. if (g_mapport_enabled_protos & MapPortProtoFlag::NAT_PMP) { g_mapport_current_proto = MapPortProtoFlag::NAT_PMP; ok = ProcessNatpmp(); if (ok) continue; } #endif // USE_NATPMP g_mapport_current_proto = MapPortProtoFlag::NONE; if (g_mapport_enabled_protos == MapPortProtoFlag::NONE) { return; } } while (ok || g_mapport_interrupt.sleep_for(PORT_MAPPING_RETRY_PERIOD)); } void StartThreadMapPort() { if (!g_mapport_thread.joinable()) { assert(!g_mapport_interrupt); g_mapport_thread = std::thread(&util::TraceThread, "mapport", &ThreadMapPort); } } static void DispatchMapPort() { if (g_mapport_current_proto == MapPortProtoFlag::NONE && g_mapport_enabled_protos == MapPortProtoFlag::NONE) { return; } if (g_mapport_current_proto == MapPortProtoFlag::NONE && g_mapport_enabled_protos != MapPortProtoFlag::NONE) { StartThreadMapPort(); return; } if (g_mapport_current_proto != MapPortProtoFlag::NONE && g_mapport_enabled_protos == MapPortProtoFlag::NONE) { InterruptMapPort(); StopMapPort(); return; } if (g_mapport_enabled_protos & g_mapport_current_proto) { // Enabling another protocol does not cause switching from the currently used one. return; } assert(g_mapport_thread.joinable()); assert(!g_mapport_interrupt); // Interrupt a protocol-specific loop in the ThreadUpnp() or in the ThreadNatpmp() // to force trying the next protocol in the ThreadMapPort() loop. g_mapport_interrupt(); } static void MapPortProtoSetEnabled(MapPortProtoFlag proto, bool enabled) { if (enabled) { g_mapport_enabled_protos |= proto; } else { g_mapport_enabled_protos &= ~proto; } } void StartMapPort(bool use_upnp, bool use_natpmp) { MapPortProtoSetEnabled(MapPortProtoFlag::UPNP, use_upnp); MapPortProtoSetEnabled(MapPortProtoFlag::NAT_PMP, use_natpmp); DispatchMapPort(); } void InterruptMapPort() { g_mapport_enabled_protos = MapPortProtoFlag::NONE; if (g_mapport_thread.joinable()) { g_mapport_interrupt(); } } void StopMapPort() { if (g_mapport_thread.joinable()) { g_mapport_thread.join(); g_mapport_interrupt.reset(); } } #else // #if defined(USE_NATPMP) || defined(USE_UPNP) void StartMapPort(bool use_upnp, bool use_natpmp) { // Intentionally left blank. } void InterruptMapPort() { // Intentionally left blank. } void StopMapPort() { // Intentionally left blank. } #endif // #if defined(USE_NATPMP) || defined(USE_UPNP)
0
bitcoin
bitcoin/src/checkqueue.h
// Copyright (c) 2012-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CHECKQUEUE_H #define BITCOIN_CHECKQUEUE_H #include <sync.h> #include <tinyformat.h> #include <util/threadnames.h> #include <algorithm> #include <iterator> #include <vector> /** * Queue for verifications that have to be performed. * The verifications are represented by a type T, which must provide an * operator(), returning a bool. * * One thread (the master) is assumed to push batches of verifications * onto the queue, where they are processed by N-1 worker threads. When * the master is done adding work, it temporarily joins the worker pool * as an N'th worker, until all jobs are done. */ template <typename T> class CCheckQueue { private: //! Mutex to protect the inner state Mutex m_mutex; //! Worker threads block on this when out of work std::condition_variable m_worker_cv; //! Master thread blocks on this when out of work std::condition_variable m_master_cv; //! The queue of elements to be processed. //! As the order of booleans doesn't matter, it is used as a LIFO (stack) std::vector<T> queue GUARDED_BY(m_mutex); //! The number of workers (including the master) that are idle. int nIdle GUARDED_BY(m_mutex){0}; //! The total number of workers (including the master). int nTotal GUARDED_BY(m_mutex){0}; //! The temporary evaluation result. bool fAllOk GUARDED_BY(m_mutex){true}; /** * Number of verifications that haven't completed yet. * This includes elements that are no longer queued, but still in the * worker's own batches. */ unsigned int nTodo GUARDED_BY(m_mutex){0}; //! The maximum number of elements to be processed in one batch const unsigned int nBatchSize; std::vector<std::thread> m_worker_threads; bool m_request_stop GUARDED_BY(m_mutex){false}; /** Internal function that does bulk of the verification work. */ bool Loop(bool fMaster) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) { std::condition_variable& cond = fMaster ? m_master_cv : m_worker_cv; std::vector<T> vChecks; vChecks.reserve(nBatchSize); unsigned int nNow = 0; bool fOk = true; do { { WAIT_LOCK(m_mutex, lock); // first do the clean-up of the previous loop run (allowing us to do it in the same critsect) if (nNow) { fAllOk &= fOk; nTodo -= nNow; if (nTodo == 0 && !fMaster) // We processed the last element; inform the master it can exit and return the result m_master_cv.notify_one(); } else { // first iteration nTotal++; } // logically, the do loop starts here while (queue.empty() && !m_request_stop) { if (fMaster && nTodo == 0) { nTotal--; bool fRet = fAllOk; // reset the status for new work later fAllOk = true; // return the current status return fRet; } nIdle++; cond.wait(lock); // wait nIdle--; } if (m_request_stop) { return false; } // Decide how many work units to process now. // * Do not try to do everything at once, but aim for increasingly smaller batches so // all workers finish approximately simultaneously. // * Try to account for idle jobs which will instantly start helping. // * Don't do batches smaller than 1 (duh), or larger than nBatchSize. nNow = std::max(1U, std::min(nBatchSize, (unsigned int)queue.size() / (nTotal + nIdle + 1))); auto start_it = queue.end() - nNow; vChecks.assign(std::make_move_iterator(start_it), std::make_move_iterator(queue.end())); queue.erase(start_it, queue.end()); // Check whether we need to do work at all fOk = fAllOk; } // execute work for (T& check : vChecks) if (fOk) fOk = check(); vChecks.clear(); } while (true); } public: //! Mutex to ensure only one concurrent CCheckQueueControl Mutex m_control_mutex; //! Create a new check queue explicit CCheckQueue(unsigned int batch_size, int worker_threads_num) : nBatchSize(batch_size) { m_worker_threads.reserve(worker_threads_num); for (int n = 0; n < worker_threads_num; ++n) { m_worker_threads.emplace_back([this, n]() { util::ThreadRename(strprintf("scriptch.%i", n)); Loop(false /* worker thread */); }); } } // Since this class manages its own resources, which is a thread // pool `m_worker_threads`, copy and move operations are not appropriate. CCheckQueue(const CCheckQueue&) = delete; CCheckQueue& operator=(const CCheckQueue&) = delete; CCheckQueue(CCheckQueue&&) = delete; CCheckQueue& operator=(CCheckQueue&&) = delete; //! Wait until execution finishes, and return whether all evaluations were successful. bool Wait() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) { return Loop(true /* master thread */); } //! Add a batch of checks to the queue void Add(std::vector<T>&& vChecks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) { if (vChecks.empty()) { return; } { LOCK(m_mutex); queue.insert(queue.end(), std::make_move_iterator(vChecks.begin()), std::make_move_iterator(vChecks.end())); nTodo += vChecks.size(); } if (vChecks.size() == 1) { m_worker_cv.notify_one(); } else { m_worker_cv.notify_all(); } } ~CCheckQueue() { WITH_LOCK(m_mutex, m_request_stop = true); m_worker_cv.notify_all(); for (std::thread& t : m_worker_threads) { t.join(); } } bool HasThreads() const { return !m_worker_threads.empty(); } }; /** * RAII-style controller object for a CCheckQueue that guarantees the passed * queue is finished before continuing. */ template <typename T> class CCheckQueueControl { private: CCheckQueue<T> * const pqueue; bool fDone; public: CCheckQueueControl() = delete; CCheckQueueControl(const CCheckQueueControl&) = delete; CCheckQueueControl& operator=(const CCheckQueueControl&) = delete; explicit CCheckQueueControl(CCheckQueue<T> * const pqueueIn) : pqueue(pqueueIn), fDone(false) { // passed queue is supposed to be unused, or nullptr if (pqueue != nullptr) { ENTER_CRITICAL_SECTION(pqueue->m_control_mutex); } } bool Wait() { if (pqueue == nullptr) return true; bool fRet = pqueue->Wait(); fDone = true; return fRet; } void Add(std::vector<T>&& vChecks) { if (pqueue != nullptr) { pqueue->Add(std::move(vChecks)); } } ~CCheckQueueControl() { if (!fDone) Wait(); if (pqueue != nullptr) { LEAVE_CRITICAL_SECTION(pqueue->m_control_mutex); } } }; #endif // BITCOIN_CHECKQUEUE_H
0
bitcoin
bitcoin/src/bitcoin-wallet-res.rc
#include <windows.h> // needed for VERSIONINFO #include "clientversion.h" // holds the needed client version information #define VER_PRODUCTVERSION CLIENT_VERSION_MAJOR,CLIENT_VERSION_MINOR,CLIENT_VERSION_BUILD #define VER_FILEVERSION VER_PRODUCTVERSION VS_VERSION_INFO VERSIONINFO FILEVERSION VER_FILEVERSION PRODUCTVERSION VER_PRODUCTVERSION FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904E4" // U.S. English - multilingual (hex) BEGIN VALUE "CompanyName", "Bitcoin" VALUE "FileDescription", "bitcoin-wallet (CLI tool for " PACKAGE_NAME " wallets)" VALUE "FileVersion", PACKAGE_VERSION VALUE "InternalName", "bitcoin-wallet" VALUE "LegalCopyright", COPYRIGHT_STR VALUE "LegalTrademarks1", "Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php." VALUE "OriginalFilename", "bitcoin-wallet.exe" VALUE "ProductName", "bitcoin-wallet" VALUE "ProductVersion", PACKAGE_VERSION END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1252 // language neutral - multilingual (decimal) END END
0
bitcoin
bitcoin/src/serialize.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_SERIALIZE_H #define BITCOIN_SERIALIZE_H #include <attributes.h> #include <compat/assumptions.h> // IWYU pragma: keep #include <compat/endian.h> #include <prevector.h> #include <span.h> #include <algorithm> #include <cstdint> #include <cstring> #include <ios> #include <limits> #include <map> #include <memory> #include <set> #include <string> #include <utility> #include <vector> /** * The maximum size of a serialized object in bytes or number of elements * (for eg vectors) when the size is encoded as CompactSize. */ static constexpr uint64_t MAX_SIZE = 0x02000000; /** Maximum amount of memory (in bytes) to allocate at once when deserializing vectors. */ static const unsigned int MAX_VECTOR_ALLOCATE = 5000000; /** * Dummy data type to identify deserializing constructors. * * By convention, a constructor of a type T with signature * * template <typename Stream> T::T(deserialize_type, Stream& s) * * is a deserializing constructor, which builds the type by * deserializing it from s. If T contains const fields, this * is likely the only way to do so. */ struct deserialize_type {}; constexpr deserialize_type deserialize {}; /* * Lowest-level serialization and conversion. */ template<typename Stream> inline void ser_writedata8(Stream &s, uint8_t obj) { s.write(AsBytes(Span{&obj, 1})); } template<typename Stream> inline void ser_writedata16(Stream &s, uint16_t obj) { obj = htole16(obj); s.write(AsBytes(Span{&obj, 1})); } template<typename Stream> inline void ser_writedata16be(Stream &s, uint16_t obj) { obj = htobe16(obj); s.write(AsBytes(Span{&obj, 1})); } template<typename Stream> inline void ser_writedata32(Stream &s, uint32_t obj) { obj = htole32(obj); s.write(AsBytes(Span{&obj, 1})); } template<typename Stream> inline void ser_writedata32be(Stream &s, uint32_t obj) { obj = htobe32(obj); s.write(AsBytes(Span{&obj, 1})); } template<typename Stream> inline void ser_writedata64(Stream &s, uint64_t obj) { obj = htole64(obj); s.write(AsBytes(Span{&obj, 1})); } template<typename Stream> inline uint8_t ser_readdata8(Stream &s) { uint8_t obj; s.read(AsWritableBytes(Span{&obj, 1})); return obj; } template<typename Stream> inline uint16_t ser_readdata16(Stream &s) { uint16_t obj; s.read(AsWritableBytes(Span{&obj, 1})); return le16toh(obj); } template<typename Stream> inline uint16_t ser_readdata16be(Stream &s) { uint16_t obj; s.read(AsWritableBytes(Span{&obj, 1})); return be16toh(obj); } template<typename Stream> inline uint32_t ser_readdata32(Stream &s) { uint32_t obj; s.read(AsWritableBytes(Span{&obj, 1})); return le32toh(obj); } template<typename Stream> inline uint32_t ser_readdata32be(Stream &s) { uint32_t obj; s.read(AsWritableBytes(Span{&obj, 1})); return be32toh(obj); } template<typename Stream> inline uint64_t ser_readdata64(Stream &s) { uint64_t obj; s.read(AsWritableBytes(Span{&obj, 1})); return le64toh(obj); } class SizeComputer; /** * Convert any argument to a reference to X, maintaining constness. * * This can be used in serialization code to invoke a base class's * serialization routines. * * Example use: * class Base { ... }; * class Child : public Base { * int m_data; * public: * SERIALIZE_METHODS(Child, obj) { * READWRITE(AsBase<Base>(obj), obj.m_data); * } * }; * * static_cast cannot easily be used here, as the type of Obj will be const Child& * during serialization and Child& during deserialization. AsBase will convert to * const Base& and Base& appropriately. */ template <class Out, class In> Out& AsBase(In& x) { static_assert(std::is_base_of_v<Out, In>); return x; } template <class Out, class In> const Out& AsBase(const In& x) { static_assert(std::is_base_of_v<Out, In>); return x; } #define READWRITE(...) (ser_action.SerReadWriteMany(s, __VA_ARGS__)) #define SER_READ(obj, code) ser_action.SerRead(s, obj, [&](Stream& s, typename std::remove_const<Type>::type& obj) { code; }) #define SER_WRITE(obj, code) ser_action.SerWrite(s, obj, [&](Stream& s, const Type& obj) { code; }) /** * Implement the Ser and Unser methods needed for implementing a formatter (see Using below). * * Both Ser and Unser are delegated to a single static method SerializationOps, which is polymorphic * in the serialized/deserialized type (allowing it to be const when serializing, and non-const when * deserializing). * * Example use: * struct FooFormatter { * FORMATTER_METHODS(Class, obj) { READWRITE(obj.val1, VARINT(obj.val2)); } * } * would define a class FooFormatter that defines a serialization of Class objects consisting * of serializing its val1 member using the default serialization, and its val2 member using * VARINT serialization. That FooFormatter can then be used in statements like * READWRITE(Using<FooFormatter>(obj.bla)). */ #define FORMATTER_METHODS(cls, obj) \ template<typename Stream> \ static void Ser(Stream& s, const cls& obj) { SerializationOps(obj, s, ActionSerialize{}); } \ template<typename Stream> \ static void Unser(Stream& s, cls& obj) { SerializationOps(obj, s, ActionUnserialize{}); } \ template<typename Stream, typename Type, typename Operation> \ static void SerializationOps(Type& obj, Stream& s, Operation ser_action) /** * Variant of FORMATTER_METHODS that supports a declared parameter type. * * If a formatter has a declared parameter type, it must be invoked directly or * indirectly with a parameter of that type. This permits making serialization * depend on run-time context in a type-safe way. * * Example use: * struct BarParameter { bool fancy; ... }; * struct Bar { ... }; * struct FooFormatter { * FORMATTER_METHODS(Bar, obj, BarParameter, param) { * if (param.fancy) { * READWRITE(VARINT(obj.value)); * } else { * READWRITE(obj.value); * } * } * }; * which would then be invoked as * READWRITE(BarParameter{...}(Using<FooFormatter>(obj.foo))) * * parameter(obj) can be invoked anywhere in the call stack; it is * passed down recursively into all serialization code, until another * serialization parameter overrides it. * * Parameters will be implicitly converted where appropriate. This means that * "parent" serialization code can use a parameter that derives from, or is * convertible to, a "child" formatter's parameter type. * * Compilation will fail in any context where serialization is invoked but * no parameter of a type convertible to BarParameter is provided. */ #define FORMATTER_METHODS_PARAMS(cls, obj, paramcls, paramobj) \ template <typename Stream> \ static void Ser(Stream& s, const cls& obj) { SerializationOps(obj, s, ActionSerialize{}, s.GetParams()); } \ template <typename Stream> \ static void Unser(Stream& s, cls& obj) { SerializationOps(obj, s, ActionUnserialize{}, s.GetParams()); } \ template <typename Stream, typename Type, typename Operation> \ static void SerializationOps(Type& obj, Stream& s, Operation ser_action, const paramcls& paramobj) #define BASE_SERIALIZE_METHODS(cls) \ template <typename Stream> \ void Serialize(Stream& s) const \ { \ static_assert(std::is_same<const cls&, decltype(*this)>::value, "Serialize type mismatch"); \ Ser(s, *this); \ } \ template <typename Stream> \ void Unserialize(Stream& s) \ { \ static_assert(std::is_same<cls&, decltype(*this)>::value, "Unserialize type mismatch"); \ Unser(s, *this); \ } /** * Implement the Serialize and Unserialize methods by delegating to a single templated * static method that takes the to-be-(de)serialized object as a parameter. This approach * has the advantage that the constness of the object becomes a template parameter, and * thus allows a single implementation that sees the object as const for serializing * and non-const for deserializing, without casts. */ #define SERIALIZE_METHODS(cls, obj) \ BASE_SERIALIZE_METHODS(cls) \ FORMATTER_METHODS(cls, obj) /** * Variant of SERIALIZE_METHODS that supports a declared parameter type. * * See FORMATTER_METHODS_PARAMS for more information on parameters. */ #define SERIALIZE_METHODS_PARAMS(cls, obj, paramcls, paramobj) \ BASE_SERIALIZE_METHODS(cls) \ FORMATTER_METHODS_PARAMS(cls, obj, paramcls, paramobj) // Templates for serializing to anything that looks like a stream, // i.e. anything that supports .read(Span<std::byte>) and .write(Span<const std::byte>) // // clang-format off #ifndef CHAR_EQUALS_INT8 template <typename Stream> void Serialize(Stream&, char) = delete; // char serialization forbidden. Use uint8_t or int8_t #endif template <typename Stream> void Serialize(Stream& s, std::byte a) { ser_writedata8(s, uint8_t(a)); } template<typename Stream> inline void Serialize(Stream& s, int8_t a ) { ser_writedata8(s, a); } template<typename Stream> inline void Serialize(Stream& s, uint8_t a ) { ser_writedata8(s, a); } template<typename Stream> inline void Serialize(Stream& s, int16_t a ) { ser_writedata16(s, a); } template<typename Stream> inline void Serialize(Stream& s, uint16_t a) { ser_writedata16(s, a); } template<typename Stream> inline void Serialize(Stream& s, int32_t a ) { ser_writedata32(s, a); } template<typename Stream> inline void Serialize(Stream& s, uint32_t a) { ser_writedata32(s, a); } template<typename Stream> inline void Serialize(Stream& s, int64_t a ) { ser_writedata64(s, a); } template<typename Stream> inline void Serialize(Stream& s, uint64_t a) { ser_writedata64(s, a); } template <typename Stream, BasicByte B, int N> void Serialize(Stream& s, const B (&a)[N]) { s.write(MakeByteSpan(a)); } template <typename Stream, BasicByte B, std::size_t N> void Serialize(Stream& s, const std::array<B, N>& a) { s.write(MakeByteSpan(a)); } template <typename Stream, BasicByte B> void Serialize(Stream& s, Span<B> span) { s.write(AsBytes(span)); } #ifndef CHAR_EQUALS_INT8 template <typename Stream> void Unserialize(Stream&, char) = delete; // char serialization forbidden. Use uint8_t or int8_t #endif template <typename Stream> void Unserialize(Stream& s, std::byte& a) { a = std::byte{ser_readdata8(s)}; } template<typename Stream> inline void Unserialize(Stream& s, int8_t& a ) { a = ser_readdata8(s); } template<typename Stream> inline void Unserialize(Stream& s, uint8_t& a ) { a = ser_readdata8(s); } template<typename Stream> inline void Unserialize(Stream& s, int16_t& a ) { a = ser_readdata16(s); } template<typename Stream> inline void Unserialize(Stream& s, uint16_t& a) { a = ser_readdata16(s); } template<typename Stream> inline void Unserialize(Stream& s, int32_t& a ) { a = ser_readdata32(s); } template<typename Stream> inline void Unserialize(Stream& s, uint32_t& a) { a = ser_readdata32(s); } template<typename Stream> inline void Unserialize(Stream& s, int64_t& a ) { a = ser_readdata64(s); } template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a) { a = ser_readdata64(s); } template <typename Stream, BasicByte B, int N> void Unserialize(Stream& s, B (&a)[N]) { s.read(MakeWritableByteSpan(a)); } template <typename Stream, BasicByte B, std::size_t N> void Unserialize(Stream& s, std::array<B, N>& a) { s.read(MakeWritableByteSpan(a)); } template <typename Stream, BasicByte B> void Unserialize(Stream& s, Span<B> span) { s.read(AsWritableBytes(span)); } template <typename Stream> inline void Serialize(Stream& s, bool a) { uint8_t f = a; ser_writedata8(s, f); } template <typename Stream> inline void Unserialize(Stream& s, bool& a) { uint8_t f = ser_readdata8(s); a = f; } // clang-format on /** * Compact Size * size < 253 -- 1 byte * size <= USHRT_MAX -- 3 bytes (253 + 2 bytes) * size <= UINT_MAX -- 5 bytes (254 + 4 bytes) * size > UINT_MAX -- 9 bytes (255 + 8 bytes) */ constexpr inline unsigned int GetSizeOfCompactSize(uint64_t nSize) { if (nSize < 253) return sizeof(unsigned char); else if (nSize <= std::numeric_limits<uint16_t>::max()) return sizeof(unsigned char) + sizeof(uint16_t); else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int); else return sizeof(unsigned char) + sizeof(uint64_t); } inline void WriteCompactSize(SizeComputer& os, uint64_t nSize); template<typename Stream> void WriteCompactSize(Stream& os, uint64_t nSize) { if (nSize < 253) { ser_writedata8(os, nSize); } else if (nSize <= std::numeric_limits<uint16_t>::max()) { ser_writedata8(os, 253); ser_writedata16(os, nSize); } else if (nSize <= std::numeric_limits<unsigned int>::max()) { ser_writedata8(os, 254); ser_writedata32(os, nSize); } else { ser_writedata8(os, 255); ser_writedata64(os, nSize); } return; } /** * Decode a CompactSize-encoded variable-length integer. * * As these are primarily used to encode the size of vector-like serializations, by default a range * check is performed. When used as a generic number encoding, range_check should be set to false. */ template<typename Stream> uint64_t ReadCompactSize(Stream& is, bool range_check = true) { uint8_t chSize = ser_readdata8(is); uint64_t nSizeRet = 0; if (chSize < 253) { nSizeRet = chSize; } else if (chSize == 253) { nSizeRet = ser_readdata16(is); if (nSizeRet < 253) throw std::ios_base::failure("non-canonical ReadCompactSize()"); } else if (chSize == 254) { nSizeRet = ser_readdata32(is); if (nSizeRet < 0x10000u) throw std::ios_base::failure("non-canonical ReadCompactSize()"); } else { nSizeRet = ser_readdata64(is); if (nSizeRet < 0x100000000ULL) throw std::ios_base::failure("non-canonical ReadCompactSize()"); } if (range_check && nSizeRet > MAX_SIZE) { throw std::ios_base::failure("ReadCompactSize(): size too large"); } return nSizeRet; } /** * Variable-length integers: bytes are a MSB base-128 encoding of the number. * The high bit in each byte signifies whether another digit follows. To make * 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] * 128: [0x80 0x00] 16511: [0xFF 0x7F] * 255: [0x80 0x7F] 65535: [0x82 0xFE 0x7F] * 2^32: [0x8E 0xFE 0xFE 0xFF 0x00] */ /** * Mode for encoding VarInts. * * Currently there is no support for signed encodings. The default mode will not * compile with signed values, and the legacy "nonnegative signed" mode will * accept signed values, but improperly encode and decode them if they are * negative. In the future, the DEFAULT mode could be extended to support * negative numbers in a backwards compatible way, and additional modes could be * added to support different varint formats (e.g. zigzag encoding). */ enum class VarIntMode { DEFAULT, NONNEGATIVE_SIGNED }; template <VarIntMode Mode, typename I> struct CheckVarIntMode { constexpr CheckVarIntMode() { static_assert(Mode != VarIntMode::DEFAULT || std::is_unsigned<I>::value, "Unsigned type required with mode DEFAULT."); static_assert(Mode != VarIntMode::NONNEGATIVE_SIGNED || std::is_signed<I>::value, "Signed type required with mode NONNEGATIVE_SIGNED."); } }; template<VarIntMode Mode, typename I> inline unsigned int GetSizeOfVarInt(I n) { CheckVarIntMode<Mode, I>(); int nRet = 0; while(true) { nRet++; if (n <= 0x7F) break; n = (n >> 7) - 1; } return nRet; } template<typename I> inline void WriteVarInt(SizeComputer& os, I n); template<typename Stream, VarIntMode Mode, typename I> void WriteVarInt(Stream& os, I n) { CheckVarIntMode<Mode, I>(); unsigned char tmp[(sizeof(n)*8+6)/7]; int len=0; while(true) { tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00); if (n <= 0x7F) break; n = (n >> 7) - 1; len++; } do { ser_writedata8(os, tmp[len]); } while(len--); } template<typename Stream, VarIntMode Mode, typename I> I ReadVarInt(Stream& is) { CheckVarIntMode<Mode, I>(); I n = 0; while(true) { unsigned char chData = ser_readdata8(is); if (n > (std::numeric_limits<I>::max() >> 7)) { throw std::ios_base::failure("ReadVarInt(): size too large"); } n = (n << 7) | (chData & 0x7F); if (chData & 0x80) { if (n == std::numeric_limits<I>::max()) { throw std::ios_base::failure("ReadVarInt(): size too large"); } n++; } else { return n; } } } /** Simple wrapper class to serialize objects using a formatter; used by Using(). */ template<typename Formatter, typename T> class Wrapper { static_assert(std::is_lvalue_reference<T>::value, "Wrapper needs an lvalue reference type T"); protected: T m_object; public: explicit Wrapper(T obj) : m_object(obj) {} template<typename Stream> void Serialize(Stream &s) const { Formatter().Ser(s, m_object); } template<typename Stream> void Unserialize(Stream &s) { Formatter().Unser(s, m_object); } }; /** Cause serialization/deserialization of an object to be done using a specified formatter class. * * To use this, you need a class Formatter that has public functions Ser(stream, const object&) for * serialization, and Unser(stream, object&) for deserialization. Serialization routines (inside * READWRITE, or directly with << and >> operators), can then use Using<Formatter>(object). * * This works by constructing a Wrapper<Formatter, T>-wrapped version of object, where T is * const during serialization, and non-const during deserialization, which maintains const * correctness. */ template<typename Formatter, typename T> static inline Wrapper<Formatter, T&> Using(T&& t) { return Wrapper<Formatter, T&>(t); } #define VARINT_MODE(obj, mode) Using<VarIntFormatter<mode>>(obj) #define VARINT(obj) Using<VarIntFormatter<VarIntMode::DEFAULT>>(obj) #define COMPACTSIZE(obj) Using<CompactSizeFormatter<true>>(obj) #define LIMITED_STRING(obj,n) Using<LimitedStringFormatter<n>>(obj) /** Serialization wrapper class for integers in VarInt format. */ template<VarIntMode Mode> struct VarIntFormatter { template<typename Stream, typename I> void Ser(Stream &s, I v) { WriteVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s, v); } template<typename Stream, typename I> void Unser(Stream& s, I& v) { v = ReadVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s); } }; /** Serialization wrapper class for custom integers and enums. * * It permits specifying the serialized size (1 to 8 bytes) and endianness. * * Use the big endian mode for values that are stored in memory in native * byte order, but serialized in big endian notation. This is only intended * to implement serializers that are compatible with existing formats, and * its use is not recommended for new data structures. */ template<int Bytes, bool BigEndian = false> struct CustomUintFormatter { static_assert(Bytes > 0 && Bytes <= 8, "CustomUintFormatter Bytes out of range"); static constexpr uint64_t MAX = 0xffffffffffffffff >> (8 * (8 - Bytes)); template <typename Stream, typename I> void Ser(Stream& s, I v) { if (v < 0 || v > MAX) throw std::ios_base::failure("CustomUintFormatter value out of range"); if (BigEndian) { uint64_t raw = htobe64(v); s.write(AsBytes(Span{&raw, 1}).last(Bytes)); } else { uint64_t raw = htole64(v); s.write(AsBytes(Span{&raw, 1}).first(Bytes)); } } template <typename Stream, typename I> void Unser(Stream& s, I& v) { using U = typename std::conditional<std::is_enum<I>::value, std::underlying_type<I>, std::common_type<I>>::type::type; static_assert(std::numeric_limits<U>::max() >= MAX && std::numeric_limits<U>::min() <= 0, "Assigned type too small"); uint64_t raw = 0; if (BigEndian) { s.read(AsWritableBytes(Span{&raw, 1}).last(Bytes)); v = static_cast<I>(be64toh(raw)); } else { s.read(AsWritableBytes(Span{&raw, 1}).first(Bytes)); v = static_cast<I>(le64toh(raw)); } } }; template<int Bytes> using BigEndianFormatter = CustomUintFormatter<Bytes, true>; /** Formatter for integers in CompactSize format. */ template<bool RangeCheck> struct CompactSizeFormatter { template<typename Stream, typename I> void Unser(Stream& s, I& v) { uint64_t n = ReadCompactSize<Stream>(s, RangeCheck); if (n < std::numeric_limits<I>::min() || n > std::numeric_limits<I>::max()) { throw std::ios_base::failure("CompactSize exceeds limit of type"); } v = n; } template<typename Stream, typename I> void Ser(Stream& s, I v) { static_assert(std::is_unsigned<I>::value, "CompactSize only supported for unsigned integers"); static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(), "CompactSize only supports 64-bit integers and below"); WriteCompactSize<Stream>(s, v); } }; template <typename U, bool LOSSY = false> struct ChronoFormatter { template <typename Stream, typename Tp> void Unser(Stream& s, Tp& tp) { U u; s >> u; // Lossy deserialization does not make sense, so force Wnarrowing tp = Tp{typename Tp::duration{typename Tp::duration::rep{u}}}; } template <typename Stream, typename Tp> void Ser(Stream& s, Tp tp) { if constexpr (LOSSY) { s << U(tp.time_since_epoch().count()); } else { s << U{tp.time_since_epoch().count()}; } } }; template <typename U> using LossyChronoFormatter = ChronoFormatter<U, true>; class CompactSizeWriter { protected: uint64_t n; public: explicit CompactSizeWriter(uint64_t n_in) : n(n_in) { } template<typename Stream> void Serialize(Stream &s) const { WriteCompactSize<Stream>(s, n); } }; template<size_t Limit> struct LimitedStringFormatter { template<typename Stream> void Unser(Stream& s, std::string& v) { size_t size = ReadCompactSize(s); if (size > Limit) { throw std::ios_base::failure("String length limit exceeded"); } v.resize(size); if (size != 0) s.read(MakeWritableByteSpan(v)); } template<typename Stream> void Ser(Stream& s, const std::string& v) { s << v; } }; /** Formatter to serialize/deserialize vector elements using another formatter * * Example: * struct X { * std::vector<uint64_t> v; * SERIALIZE_METHODS(X, obj) { READWRITE(Using<VectorFormatter<VarInt>>(obj.v)); } * }; * will define a struct that contains a vector of uint64_t, which is serialized * as a vector of VarInt-encoded integers. * * V is not required to be an std::vector type. It works for any class that * exposes a value_type, size, reserve, emplace_back, back, and const iterators. */ template<class Formatter> struct VectorFormatter { template<typename Stream, typename V> void Ser(Stream& s, const V& v) { Formatter formatter; WriteCompactSize(s, v.size()); for (const typename V::value_type& elem : v) { formatter.Ser(s, elem); } } template<typename Stream, typename V> void Unser(Stream& s, V& v) { Formatter formatter; v.clear(); size_t size = ReadCompactSize(s); size_t allocated = 0; while (allocated < size) { // For DoS prevention, do not blindly allocate as much as the stream claims to contain. // Instead, allocate in 5MiB batches, so that an attacker actually needs to provide // X MiB of data to make us allocate X+5 Mib. static_assert(sizeof(typename V::value_type) <= MAX_VECTOR_ALLOCATE, "Vector element size too large"); allocated = std::min(size, allocated + MAX_VECTOR_ALLOCATE / sizeof(typename V::value_type)); v.reserve(allocated); while (v.size() < allocated) { v.emplace_back(); formatter.Unser(s, v.back()); } } }; }; /** * Forward declarations */ /** * string */ template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str); template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str); /** * prevector * prevectors of unsigned char are a special case and are intended to be serialized as a single opaque blob. */ template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v); template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v); /** * vector * vectors of unsigned char are a special case and are intended to be serialized as a single opaque blob. */ template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v); template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v); /** * pair */ template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item); template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item); /** * map */ template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m); template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m); /** * set */ template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m); template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m); /** * shared_ptr */ template<typename Stream, typename T> void Serialize(Stream& os, const std::shared_ptr<const T>& p); template<typename Stream, typename T> void Unserialize(Stream& os, std::shared_ptr<const T>& p); /** * unique_ptr */ template<typename Stream, typename T> void Serialize(Stream& os, const std::unique_ptr<const T>& p); template<typename Stream, typename T> void Unserialize(Stream& os, std::unique_ptr<const T>& p); /** * If none of the specialized versions above matched, default to calling member function. */ template <class T, class Stream> concept Serializable = requires(T a, Stream s) { a.Serialize(s); }; template <typename Stream, typename T> requires Serializable<T, Stream> void Serialize(Stream& os, const T& a) { a.Serialize(os); } template <class T, class Stream> concept Unserializable = requires(T a, Stream s) { a.Unserialize(s); }; template <typename Stream, typename T> requires Unserializable<T, Stream> void Unserialize(Stream& is, T&& a) { a.Unserialize(is); } /** Default formatter. Serializes objects as themselves. * * The vector/prevector serialization code passes this to VectorFormatter * to enable reusing that logic. It shouldn't be needed elsewhere. */ struct DefaultFormatter { template<typename Stream, typename T> static void Ser(Stream& s, const T& t) { Serialize(s, t); } template<typename Stream, typename T> static void Unser(Stream& s, T& t) { Unserialize(s, t); } }; /** * string */ template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str) { WriteCompactSize(os, str.size()); if (!str.empty()) os.write(MakeByteSpan(str)); } template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str) { unsigned int nSize = ReadCompactSize(is); str.resize(nSize); if (nSize != 0) is.read(MakeWritableByteSpan(str)); } /** * prevector */ template <typename Stream, unsigned int N, typename T> void Serialize(Stream& os, const prevector<N, T>& v) { if constexpr (std::is_same_v<T, unsigned char>) { WriteCompactSize(os, v.size()); if (!v.empty()) os.write(MakeByteSpan(v)); } else { Serialize(os, Using<VectorFormatter<DefaultFormatter>>(v)); } } template <typename Stream, unsigned int N, typename T> void Unserialize(Stream& is, prevector<N, T>& v) { if constexpr (std::is_same_v<T, unsigned char>) { // Limit size per read so bogus size value won't cause out of memory v.clear(); unsigned int nSize = ReadCompactSize(is); unsigned int i = 0; while (i < nSize) { unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T))); v.resize_uninitialized(i + blk); is.read(AsWritableBytes(Span{&v[i], blk})); i += blk; } } else { Unserialize(is, Using<VectorFormatter<DefaultFormatter>>(v)); } } /** * vector */ template <typename Stream, typename T, typename A> void Serialize(Stream& os, const std::vector<T, A>& v) { if constexpr (std::is_same_v<T, unsigned char>) { WriteCompactSize(os, v.size()); if (!v.empty()) os.write(MakeByteSpan(v)); } else if constexpr (std::is_same_v<T, bool>) { // A special case for std::vector<bool>, as dereferencing // std::vector<bool>::const_iterator does not result in a const bool& // due to std::vector's special casing for bool arguments. WriteCompactSize(os, v.size()); for (bool elem : v) { ::Serialize(os, elem); } } else { Serialize(os, Using<VectorFormatter<DefaultFormatter>>(v)); } } template <typename Stream, typename T, typename A> void Unserialize(Stream& is, std::vector<T, A>& v) { if constexpr (std::is_same_v<T, unsigned char>) { // Limit size per read so bogus size value won't cause out of memory v.clear(); unsigned int nSize = ReadCompactSize(is); unsigned int i = 0; while (i < nSize) { unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T))); v.resize(i + blk); is.read(AsWritableBytes(Span{&v[i], blk})); i += blk; } } else { Unserialize(is, Using<VectorFormatter<DefaultFormatter>>(v)); } } /** * pair */ template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item) { Serialize(os, item.first); Serialize(os, item.second); } template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item) { Unserialize(is, item.first); Unserialize(is, item.second); } /** * map */ template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m) { WriteCompactSize(os, m.size()); for (const auto& entry : m) Serialize(os, entry); } template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m) { m.clear(); unsigned int nSize = ReadCompactSize(is); typename std::map<K, T, Pred, A>::iterator mi = m.begin(); for (unsigned int i = 0; i < nSize; i++) { std::pair<K, T> item; Unserialize(is, item); mi = m.insert(mi, item); } } /** * set */ template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m) { WriteCompactSize(os, m.size()); for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it) Serialize(os, (*it)); } template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m) { m.clear(); unsigned int nSize = ReadCompactSize(is); typename std::set<K, Pred, A>::iterator it = m.begin(); for (unsigned int i = 0; i < nSize; i++) { K key; Unserialize(is, key); it = m.insert(it, key); } } /** * unique_ptr */ template<typename Stream, typename T> void Serialize(Stream& os, const std::unique_ptr<const T>& p) { Serialize(os, *p); } template<typename Stream, typename T> void Unserialize(Stream& is, std::unique_ptr<const T>& p) { p.reset(new T(deserialize, is)); } /** * shared_ptr */ template<typename Stream, typename T> void Serialize(Stream& os, const std::shared_ptr<const T>& p) { Serialize(os, *p); } template<typename Stream, typename T> void Unserialize(Stream& is, std::shared_ptr<const T>& p) { p = std::make_shared<const T>(deserialize, is); } /** * Support for (un)serializing many things at once */ template <typename Stream, typename... Args> void SerializeMany(Stream& s, const Args&... args) { (::Serialize(s, args), ...); } template <typename Stream, typename... Args> inline void UnserializeMany(Stream& s, Args&&... args) { (::Unserialize(s, args), ...); } /** * Support for all macros providing or using the ser_action parameter of the SerializationOps method. */ struct ActionSerialize { static constexpr bool ForRead() { return false; } template<typename Stream, typename... Args> static void SerReadWriteMany(Stream& s, const Args&... args) { ::SerializeMany(s, args...); } template<typename Stream, typename Type, typename Fn> static void SerRead(Stream& s, Type&&, Fn&&) { } template<typename Stream, typename Type, typename Fn> static void SerWrite(Stream& s, Type&& obj, Fn&& fn) { fn(s, std::forward<Type>(obj)); } }; struct ActionUnserialize { static constexpr bool ForRead() { return true; } template<typename Stream, typename... Args> static void SerReadWriteMany(Stream& s, Args&&... args) { ::UnserializeMany(s, args...); } template<typename Stream, typename Type, typename Fn> static void SerRead(Stream& s, Type&& obj, Fn&& fn) { fn(s, std::forward<Type>(obj)); } template<typename Stream, typename Type, typename Fn> static void SerWrite(Stream& s, Type&&, Fn&&) { } }; /* ::GetSerializeSize implementations * * Computing the serialized size of objects is done through a special stream * object of type SizeComputer, which only records the number of bytes written * to it. * * If your Serialize or SerializationOp method has non-trivial overhead for * serialization, it may be worthwhile to implement a specialized version for * SizeComputer, which uses the s.seek() method to record bytes that would * be written instead. */ class SizeComputer { protected: size_t nSize{0}; public: SizeComputer() {} void write(Span<const std::byte> src) { this->nSize += src.size(); } /** Pretend _nSize bytes are written, without specifying them. */ void seek(size_t _nSize) { this->nSize += _nSize; } template<typename T> SizeComputer& operator<<(const T& obj) { ::Serialize(*this, obj); return (*this); } size_t size() const { return nSize; } }; template<typename I> inline void WriteVarInt(SizeComputer &s, I n) { s.seek(GetSizeOfVarInt<I>(n)); } inline void WriteCompactSize(SizeComputer &s, uint64_t nSize) { s.seek(GetSizeOfCompactSize(nSize)); } template <typename T> size_t GetSerializeSize(const T& t) { return (SizeComputer() << t).size(); } /** Wrapper that overrides the GetParams() function of a stream (and hides GetVersion/GetType). */ template <typename Params, typename SubStream> class ParamsStream { const Params& m_params; SubStream& m_substream; // private to avoid leaking version/type into serialization code that shouldn't see it public: ParamsStream(const Params& params LIFETIMEBOUND, SubStream& substream LIFETIMEBOUND) : m_params{params}, m_substream{substream} {} template <typename U> ParamsStream& operator<<(const U& obj) { ::Serialize(*this, obj); return *this; } template <typename U> ParamsStream& operator>>(U&& obj) { ::Unserialize(*this, obj); return *this; } void write(Span<const std::byte> src) { m_substream.write(src); } void read(Span<std::byte> dst) { m_substream.read(dst); } void ignore(size_t num) { m_substream.ignore(num); } bool eof() const { return m_substream.eof(); } size_t size() const { return m_substream.size(); } const Params& GetParams() const { return m_params; } int GetVersion() = delete; // Deprecated with Params usage int GetType() = delete; // Deprecated with Params usage }; /** Wrapper that serializes objects with the specified parameters. */ template <typename Params, typename T> class ParamsWrapper { const Params& m_params; T& m_object; public: explicit ParamsWrapper(const Params& params, T& obj) : m_params{params}, m_object{obj} {} template <typename Stream> void Serialize(Stream& s) const { ParamsStream ss{m_params, s}; ::Serialize(ss, m_object); } template <typename Stream> void Unserialize(Stream& s) { ParamsStream ss{m_params, s}; ::Unserialize(ss, m_object); } }; /** * Helper macro for SerParams structs * * Allows you define SerParams instances and then apply them directly * to an object via function call syntax, eg: * * constexpr SerParams FOO{....}; * ss << FOO(obj); */ #define SER_PARAMS_OPFUNC \ /** \ * Return a wrapper around t that (de)serializes it with specified parameter params. \ * \ * See FORMATTER_METHODS_PARAMS for more information on serialization parameters. \ */ \ template <typename T> \ auto operator()(T&& t) const \ { \ return ParamsWrapper{*this, t}; \ } #endif // BITCOIN_SERIALIZE_H
0
bitcoin
bitcoin/src/bitcoin-tx-res.rc
#include <windows.h> // needed for VERSIONINFO #include "clientversion.h" // holds the needed client version information #define VER_PRODUCTVERSION CLIENT_VERSION_MAJOR,CLIENT_VERSION_MINOR,CLIENT_VERSION_BUILD #define VER_FILEVERSION VER_PRODUCTVERSION VS_VERSION_INFO VERSIONINFO FILEVERSION VER_FILEVERSION PRODUCTVERSION VER_PRODUCTVERSION FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904E4" // U.S. English - multilingual (hex) BEGIN VALUE "CompanyName", "Bitcoin" VALUE "FileDescription", "bitcoin-tx (CLI Bitcoin transaction editor utility)" VALUE "FileVersion", PACKAGE_VERSION VALUE "InternalName", "bitcoin-tx" VALUE "LegalCopyright", COPYRIGHT_STR VALUE "LegalTrademarks1", "Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php." VALUE "OriginalFilename", "bitcoin-tx.exe" VALUE "ProductName", "bitcoin-tx" VALUE "ProductVersion", PACKAGE_VERSION END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1252 // language neutral - multilingual (decimal) END END
0
bitcoin
bitcoin/src/init.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_INIT_H #define BITCOIN_INIT_H #include <any> #include <memory> #include <string> //! Default value for -daemon option static constexpr bool DEFAULT_DAEMON = false; //! Default value for -daemonwait option static constexpr bool DEFAULT_DAEMONWAIT = false; class ArgsManager; namespace interfaces { struct BlockAndHeaderTipInfo; } namespace kernel { struct Context; } namespace node { struct NodeContext; } // namespace node /** Initialize node context shutdown and args variables. */ void InitContext(node::NodeContext& node); /** Return whether node shutdown was requested. */ bool ShutdownRequested(node::NodeContext& node); /** Interrupt threads */ void Interrupt(node::NodeContext& node); void Shutdown(node::NodeContext& node); //!Initialize the logging infrastructure void InitLogging(const ArgsManager& args); //!Parameter interaction: change current parameters depending on various rules void InitParameterInteraction(ArgsManager& args); /** Initialize bitcoin core: Basic context setup. * @note This can be done before daemonization. Do not call Shutdown() if this function fails. * @pre Parameters should be parsed and config file should be read. */ bool AppInitBasicSetup(const ArgsManager& args, std::atomic<int>& exit_status); /** * Initialization: parameter interaction. * @note This can be done before daemonization. Do not call Shutdown() if this function fails. * @pre Parameters should be parsed and config file should be read, AppInitBasicSetup should have been called. */ bool AppInitParameterInteraction(const ArgsManager& args); /** * Initialization sanity checks. * @note This can be done before daemonization. Do not call Shutdown() if this function fails. * @pre Parameters should be parsed and config file should be read, AppInitParameterInteraction should have been called. */ bool AppInitSanityChecks(const kernel::Context& kernel); /** * Lock bitcoin core data directory. * @note This should only be done after daemonization. Do not call Shutdown() if this function fails. * @pre Parameters should be parsed and config file should be read, AppInitSanityChecks should have been called. */ bool AppInitLockDataDirectory(); /** * Initialize node and wallet interface pointers. Has no prerequisites or side effects besides allocating memory. */ bool AppInitInterfaces(node::NodeContext& node); /** * Bitcoin core main initialization. * @note This should only be done after daemonization. Call Shutdown() if this function fails. * @pre Parameters should be parsed and config file should be read, AppInitLockDataDirectory should have been called. */ bool AppInitMain(node::NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info = nullptr); /** * Register all arguments with the ArgsManager */ void SetupServerArgs(ArgsManager& argsman); /** Validates requirements to run the indexes and spawns each index initial sync thread */ bool StartIndexBackgroundSync(node::NodeContext& node); #endif // BITCOIN_INIT_H
0
bitcoin
bitcoin/src/validationinterface.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 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 <validationinterface.h> #include <attributes.h> #include <chain.h> #include <consensus/validation.h> #include <kernel/chain.h> #include <kernel/mempool_entry.h> #include <logging.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <scheduler.h> #include <future> #include <unordered_map> #include <utility> std::string RemovalReasonToString(const MemPoolRemovalReason& r) noexcept; /** * MainSignalsImpl manages a list of shared_ptr<CValidationInterface> callbacks. * * A std::unordered_map is used to track what callbacks are currently * registered, and a std::list is used to store the callbacks that are * currently registered as well as any callbacks that are just unregistered * and about to be deleted when they are done executing. */ class MainSignalsImpl { private: Mutex m_mutex; //! List entries consist of a callback pointer and reference count. The //! count is equal to the number of current executions of that entry, plus 1 //! if it's registered. It cannot be 0 because that would imply it is //! unregistered and also not being executed (so shouldn't exist). struct ListEntry { std::shared_ptr<CValidationInterface> callbacks; int count = 1; }; std::list<ListEntry> m_list GUARDED_BY(m_mutex); std::unordered_map<CValidationInterface*, std::list<ListEntry>::iterator> m_map GUARDED_BY(m_mutex); public: // We are not allowed to assume the scheduler only runs in one thread, // but must ensure all callbacks happen in-order, so we end up creating // our own queue here :( SingleThreadedSchedulerClient m_schedulerClient; explicit MainSignalsImpl(CScheduler& scheduler LIFETIMEBOUND) : m_schedulerClient(scheduler) {} void Register(std::shared_ptr<CValidationInterface> callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) { LOCK(m_mutex); auto inserted = m_map.emplace(callbacks.get(), m_list.end()); if (inserted.second) inserted.first->second = m_list.emplace(m_list.end()); inserted.first->second->callbacks = std::move(callbacks); } void Unregister(CValidationInterface* callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) { LOCK(m_mutex); auto it = m_map.find(callbacks); if (it != m_map.end()) { if (!--it->second->count) m_list.erase(it->second); m_map.erase(it); } } //! Clear unregisters every previously registered callback, erasing every //! map entry. After this call, the list may still contain callbacks that //! are currently executing, but it will be cleared when they are done //! executing. void Clear() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) { LOCK(m_mutex); for (const auto& entry : m_map) { if (!--entry.second->count) m_list.erase(entry.second); } m_map.clear(); } template<typename F> void Iterate(F&& f) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) { WAIT_LOCK(m_mutex, lock); for (auto it = m_list.begin(); it != m_list.end();) { ++it->count; { REVERSE_LOCK(lock); f(*it->callbacks); } it = --it->count ? std::next(it) : m_list.erase(it); } } }; static CMainSignals g_signals; void CMainSignals::RegisterBackgroundSignalScheduler(CScheduler& scheduler) { assert(!m_internals); m_internals = std::make_unique<MainSignalsImpl>(scheduler); } void CMainSignals::UnregisterBackgroundSignalScheduler() { m_internals.reset(nullptr); } void CMainSignals::FlushBackgroundCallbacks() { if (m_internals) { m_internals->m_schedulerClient.EmptyQueue(); } } size_t CMainSignals::CallbacksPending() { if (!m_internals) return 0; return m_internals->m_schedulerClient.CallbacksPending(); } CMainSignals& GetMainSignals() { return g_signals; } void RegisterSharedValidationInterface(std::shared_ptr<CValidationInterface> callbacks) { // Each connection captures the shared_ptr to ensure that each callback is // executed before the subscriber is destroyed. For more details see #18338. g_signals.m_internals->Register(std::move(callbacks)); } void RegisterValidationInterface(CValidationInterface* callbacks) { // Create a shared_ptr with a no-op deleter - CValidationInterface lifecycle // is managed by the caller. RegisterSharedValidationInterface({callbacks, [](CValidationInterface*){}}); } void UnregisterSharedValidationInterface(std::shared_ptr<CValidationInterface> callbacks) { UnregisterValidationInterface(callbacks.get()); } void UnregisterValidationInterface(CValidationInterface* callbacks) { if (g_signals.m_internals) { g_signals.m_internals->Unregister(callbacks); } } void UnregisterAllValidationInterfaces() { if (!g_signals.m_internals) { return; } g_signals.m_internals->Clear(); } void CallFunctionInValidationInterfaceQueue(std::function<void()> func) { g_signals.m_internals->m_schedulerClient.AddToProcessQueue(std::move(func)); } void SyncWithValidationInterfaceQueue() { AssertLockNotHeld(cs_main); // Block until the validation queue drains std::promise<void> promise; CallFunctionInValidationInterfaceQueue([&promise] { promise.set_value(); }); promise.get_future().wait(); } // Use a macro instead of a function for conditional logging to prevent // evaluating arguments when logging is not enabled. // // NOTE: The lambda captures all local variables by value. #define ENQUEUE_AND_LOG_EVENT(event, fmt, name, ...) \ do { \ auto local_name = (name); \ LOG_EVENT("Enqueuing " fmt, local_name, __VA_ARGS__); \ m_internals->m_schedulerClient.AddToProcessQueue([=] { \ LOG_EVENT(fmt, local_name, __VA_ARGS__); \ event(); \ }); \ } while (0) #define LOG_EVENT(fmt, ...) \ LogPrint(BCLog::VALIDATION, fmt "\n", __VA_ARGS__) void CMainSignals::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) { // Dependencies exist that require UpdatedBlockTip events to be delivered in the order in which // the chain actually updates. One way to ensure this is for the caller to invoke this signal // in the same critical section where the chain is updated auto event = [pindexNew, pindexFork, fInitialDownload, this] { m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.UpdatedBlockTip(pindexNew, pindexFork, fInitialDownload); }); }; ENQUEUE_AND_LOG_EVENT(event, "%s: new block hash=%s fork block hash=%s (in IBD=%s)", __func__, pindexNew->GetBlockHash().ToString(), pindexFork ? pindexFork->GetBlockHash().ToString() : "null", fInitialDownload); } void CMainSignals::TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t mempool_sequence) { auto event = [tx, mempool_sequence, this] { m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.TransactionAddedToMempool(tx, mempool_sequence); }); }; ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s wtxid=%s", __func__, tx.info.m_tx->GetHash().ToString(), tx.info.m_tx->GetWitnessHash().ToString()); } void CMainSignals::TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) { auto event = [tx, reason, mempool_sequence, this] { m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.TransactionRemovedFromMempool(tx, reason, mempool_sequence); }); }; ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s wtxid=%s reason=%s", __func__, tx->GetHash().ToString(), tx->GetWitnessHash().ToString(), RemovalReasonToString(reason)); } void CMainSignals::BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock> &pblock, const CBlockIndex *pindex) { auto event = [role, pblock, pindex, this] { m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockConnected(role, pblock, pindex); }); }; ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s block height=%d", __func__, pblock->GetHash().ToString(), pindex->nHeight); } void CMainSignals::MempoolTransactionsRemovedForBlock(const std::vector<RemovedMempoolTransactionInfo>& txs_removed_for_block, unsigned int nBlockHeight) { auto event = [txs_removed_for_block, nBlockHeight, this] { m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight); }); }; ENQUEUE_AND_LOG_EVENT(event, "%s: block height=%s txs removed=%s", __func__, nBlockHeight, txs_removed_for_block.size()); } void CMainSignals::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex) { auto event = [pblock, pindex, this] { m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockDisconnected(pblock, pindex); }); }; ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s block height=%d", __func__, pblock->GetHash().ToString(), pindex->nHeight); } void CMainSignals::ChainStateFlushed(ChainstateRole role, const CBlockLocator &locator) { auto event = [role, locator, this] { m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.ChainStateFlushed(role, locator); }); }; ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__, locator.IsNull() ? "null" : locator.vHave.front().ToString()); } void CMainSignals::BlockChecked(const CBlock& block, const BlockValidationState& state) { LOG_EVENT("%s: block hash=%s state=%s", __func__, block.GetHash().ToString(), state.ToString()); m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockChecked(block, state); }); } void CMainSignals::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock> &block) { LOG_EVENT("%s: block hash=%s", __func__, block->GetHash().ToString()); m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.NewPoWValidBlock(pindex, block); }); }
0
bitcoin
bitcoin/src/versionbits.cpp
// Copyright (c) 2016-2022 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 <consensus/params.h> #include <util/check.h> #include <versionbits.h> ThresholdState AbstractThresholdConditionChecker::GetStateFor(const CBlockIndex* pindexPrev, const Consensus::Params& params, ThresholdConditionCache& cache) const { int nPeriod = Period(params); int nThreshold = Threshold(params); int min_activation_height = MinActivationHeight(params); int64_t nTimeStart = BeginTime(params); int64_t nTimeTimeout = EndTime(params); // Check if this deployment is always active. if (nTimeStart == Consensus::BIP9Deployment::ALWAYS_ACTIVE) { return ThresholdState::ACTIVE; } // Check if this deployment is never active. if (nTimeStart == Consensus::BIP9Deployment::NEVER_ACTIVE) { return ThresholdState::FAILED; } // A block's state is always the same as that of the first of its period, so it is computed based on a pindexPrev whose height equals a multiple of nPeriod - 1. if (pindexPrev != nullptr) { pindexPrev = pindexPrev->GetAncestor(pindexPrev->nHeight - ((pindexPrev->nHeight + 1) % nPeriod)); } // Walk backwards in steps of nPeriod to find a pindexPrev whose information is known std::vector<const CBlockIndex*> vToCompute; while (cache.count(pindexPrev) == 0) { if (pindexPrev == nullptr) { // The genesis block is by definition defined. cache[pindexPrev] = ThresholdState::DEFINED; break; } if (pindexPrev->GetMedianTimePast() < nTimeStart) { // Optimization: don't recompute down further, as we know every earlier block will be before the start time cache[pindexPrev] = ThresholdState::DEFINED; break; } vToCompute.push_back(pindexPrev); pindexPrev = pindexPrev->GetAncestor(pindexPrev->nHeight - nPeriod); } // At this point, cache[pindexPrev] is known assert(cache.count(pindexPrev)); ThresholdState state = cache[pindexPrev]; // Now walk forward and compute the state of descendants of pindexPrev while (!vToCompute.empty()) { ThresholdState stateNext = state; pindexPrev = vToCompute.back(); vToCompute.pop_back(); switch (state) { case ThresholdState::DEFINED: { if (pindexPrev->GetMedianTimePast() >= nTimeStart) { stateNext = ThresholdState::STARTED; } break; } case ThresholdState::STARTED: { // We need to count const CBlockIndex* pindexCount = pindexPrev; int count = 0; for (int i = 0; i < nPeriod; i++) { if (Condition(pindexCount, params)) { count++; } pindexCount = pindexCount->pprev; } if (count >= nThreshold) { stateNext = ThresholdState::LOCKED_IN; } else if (pindexPrev->GetMedianTimePast() >= nTimeTimeout) { stateNext = ThresholdState::FAILED; } break; } case ThresholdState::LOCKED_IN: { // Progresses into ACTIVE provided activation height will have been reached. if (pindexPrev->nHeight + 1 >= min_activation_height) { stateNext = ThresholdState::ACTIVE; } break; } case ThresholdState::FAILED: case ThresholdState::ACTIVE: { // Nothing happens, these are terminal states. break; } } cache[pindexPrev] = state = stateNext; } return state; } BIP9Stats AbstractThresholdConditionChecker::GetStateStatisticsFor(const CBlockIndex* pindex, const Consensus::Params& params, std::vector<bool>* signalling_blocks) const { BIP9Stats stats = {}; stats.period = Period(params); stats.threshold = Threshold(params); if (pindex == nullptr) return stats; // Find how many blocks are in the current period int blocks_in_period = 1 + (pindex->nHeight % stats.period); // Reset signalling_blocks if (signalling_blocks) { signalling_blocks->assign(blocks_in_period, false); } // Count from current block to beginning of period int elapsed = 0; int count = 0; const CBlockIndex* currentIndex = pindex; do { ++elapsed; --blocks_in_period; if (Condition(currentIndex, params)) { ++count; if (signalling_blocks) signalling_blocks->at(blocks_in_period) = true; } currentIndex = currentIndex->pprev; } while(blocks_in_period > 0); stats.elapsed = elapsed; stats.count = count; stats.possible = (stats.period - stats.threshold ) >= (stats.elapsed - count); return stats; } int AbstractThresholdConditionChecker::GetStateSinceHeightFor(const CBlockIndex* pindexPrev, const Consensus::Params& params, ThresholdConditionCache& cache) const { int64_t start_time = BeginTime(params); if (start_time == Consensus::BIP9Deployment::ALWAYS_ACTIVE || start_time == Consensus::BIP9Deployment::NEVER_ACTIVE) { return 0; } const ThresholdState initialState = GetStateFor(pindexPrev, params, cache); // BIP 9 about state DEFINED: "The genesis block is by definition in this state for each deployment." if (initialState == ThresholdState::DEFINED) { return 0; } const int nPeriod = Period(params); // A block's state is always the same as that of the first of its period, so it is computed based on a pindexPrev whose height equals a multiple of nPeriod - 1. // To ease understanding of the following height calculation, it helps to remember that // right now pindexPrev points to the block prior to the block that we are computing for, thus: // if we are computing for the last block of a period, then pindexPrev points to the second to last block of the period, and // if we are computing for the first block of a period, then pindexPrev points to the last block of the previous period. // The parent of the genesis block is represented by nullptr. pindexPrev = Assert(pindexPrev->GetAncestor(pindexPrev->nHeight - ((pindexPrev->nHeight + 1) % nPeriod))); const CBlockIndex* previousPeriodParent = pindexPrev->GetAncestor(pindexPrev->nHeight - nPeriod); while (previousPeriodParent != nullptr && GetStateFor(previousPeriodParent, params, cache) == initialState) { pindexPrev = previousPeriodParent; previousPeriodParent = pindexPrev->GetAncestor(pindexPrev->nHeight - nPeriod); } // Adjust the result because right now we point to the parent block. return pindexPrev->nHeight + 1; } namespace { /** * Class to implement versionbits logic. */ class VersionBitsConditionChecker : public AbstractThresholdConditionChecker { private: const Consensus::DeploymentPos id; protected: int64_t BeginTime(const Consensus::Params& params) const override { return params.vDeployments[id].nStartTime; } int64_t EndTime(const Consensus::Params& params) const override { return params.vDeployments[id].nTimeout; } int MinActivationHeight(const Consensus::Params& params) const override { return params.vDeployments[id].min_activation_height; } int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; } int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; } bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override { return (((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) && (pindex->nVersion & Mask(params)) != 0); } public: explicit VersionBitsConditionChecker(Consensus::DeploymentPos id_) : id(id_) {} uint32_t Mask(const Consensus::Params& params) const { return (uint32_t{1}) << params.vDeployments[id].bit; } }; } // namespace ThresholdState VersionBitsCache::State(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos) { LOCK(m_mutex); return VersionBitsConditionChecker(pos).GetStateFor(pindexPrev, params, m_caches[pos]); } BIP9Stats VersionBitsCache::Statistics(const CBlockIndex* pindex, const Consensus::Params& params, Consensus::DeploymentPos pos, std::vector<bool>* signalling_blocks) { return VersionBitsConditionChecker(pos).GetStateStatisticsFor(pindex, params, signalling_blocks); } int VersionBitsCache::StateSinceHeight(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos) { LOCK(m_mutex); return VersionBitsConditionChecker(pos).GetStateSinceHeightFor(pindexPrev, params, m_caches[pos]); } uint32_t VersionBitsCache::Mask(const Consensus::Params& params, Consensus::DeploymentPos pos) { return VersionBitsConditionChecker(pos).Mask(params); } int32_t VersionBitsCache::ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params) { LOCK(m_mutex); int32_t nVersion = VERSIONBITS_TOP_BITS; for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) { Consensus::DeploymentPos pos = static_cast<Consensus::DeploymentPos>(i); ThresholdState state = VersionBitsConditionChecker(pos).GetStateFor(pindexPrev, params, m_caches[pos]); if (state == ThresholdState::LOCKED_IN || state == ThresholdState::STARTED) { nVersion |= Mask(params, pos); } } return nVersion; } void VersionBitsCache::Clear() { LOCK(m_mutex); for (unsigned int d = 0; d < Consensus::MAX_VERSION_BITS_DEPLOYMENTS; d++) { m_caches[d].clear(); } }
0
bitcoin
bitcoin/src/compressor.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_COMPRESSOR_H #define BITCOIN_COMPRESSOR_H #include <prevector.h> #include <primitives/transaction.h> #include <script/script.h> #include <serialize.h> #include <span.h> /** * This saves us from making many heap allocations when serializing * and deserializing compressed scripts. * * This prevector size is determined by the largest .resize() in the * CompressScript function. The largest compressed script format is a * compressed public key, which is 33 bytes. */ using CompressedScript = prevector<33, unsigned char>; bool CompressScript(const CScript& script, CompressedScript& out); unsigned int GetSpecialScriptSize(unsigned int nSize); bool DecompressScript(CScript& script, unsigned int nSize, const CompressedScript& in); /** * Compress amount. * * nAmount is of type uint64_t and thus cannot be negative. If you're passing in * a CAmount (int64_t), make sure to properly handle the case where the amount * is negative before calling CompressAmount(...). * * @pre Function defined only for 0 <= nAmount <= MAX_MONEY. */ uint64_t CompressAmount(uint64_t nAmount); uint64_t DecompressAmount(uint64_t nAmount); /** Compact serializer for scripts. * * It detects common cases and encodes them much more efficiently. * 3 special cases are defined: * * Pay to pubkey hash (encoded as 21 bytes) * * Pay to script hash (encoded as 21 bytes) * * Pay to pubkey starting with 0x02, 0x03 or 0x04 (encoded as 33 bytes) * * Other scripts up to 121 bytes require 1 byte + script length. Above * that, scripts up to 16505 bytes require 2 bytes + script length. */ struct ScriptCompression { /** * make this static for now (there are only 6 special scripts defined) * this can potentially be extended together with a new nVersion for * transactions, in which case this value becomes dependent on nVersion * and nHeight of the enclosing transaction. */ static const unsigned int nSpecialScripts = 6; template<typename Stream> void Ser(Stream &s, const CScript& script) { CompressedScript compr; if (CompressScript(script, compr)) { s << Span{compr}; return; } unsigned int nSize = script.size() + nSpecialScripts; s << VARINT(nSize); s << Span{script}; } template<typename Stream> void Unser(Stream &s, CScript& script) { unsigned int nSize = 0; s >> VARINT(nSize); if (nSize < nSpecialScripts) { CompressedScript vch(GetSpecialScriptSize(nSize), 0x00); s >> Span{vch}; DecompressScript(script, nSize, vch); return; } nSize -= nSpecialScripts; if (nSize > MAX_SCRIPT_SIZE) { // Overly long script, replace with a short invalid one script << OP_RETURN; s.ignore(nSize); } else { script.resize(nSize); s >> Span{script}; } } }; struct AmountCompression { template<typename Stream, typename I> void Ser(Stream& s, I val) { s << VARINT(CompressAmount(val)); } template<typename Stream, typename I> void Unser(Stream& s, I& val) { uint64_t v; s >> VARINT(v); val = DecompressAmount(v); } }; /** wrapper for CTxOut that provides a more compact serialization */ struct TxOutCompression { FORMATTER_METHODS(CTxOut, obj) { READWRITE(Using<AmountCompression>(obj.nValue), Using<ScriptCompression>(obj.scriptPubKey)); } }; #endif // BITCOIN_COMPRESSOR_H
0
bitcoin
bitcoin/src/pow.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_POW_H #define BITCOIN_POW_H #include <consensus/params.h> #include <stdint.h> class CBlockHeader; class CBlockIndex; class uint256; unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params&); unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params&); /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */ bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params&); /** * Return false if the proof-of-work requirement specified by new_nbits at a * given height is not possible, given the proof-of-work on the prior block as * specified by old_nbits. * * This function only checks that the new value is within a factor of 4 of the * old value for blocks at the difficulty adjustment interval, and otherwise * requires the values to be the same. * * Always returns true on networks where min difficulty blocks are allowed, * such as regtest/testnet. */ bool PermittedDifficultyTransition(const Consensus::Params& params, int64_t height, uint32_t old_nbits, uint32_t new_nbits); #endif // BITCOIN_POW_H
0
bitcoin
bitcoin/src/external_signer.h
// Copyright (c) 2018-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_EXTERNAL_SIGNER_H #define BITCOIN_EXTERNAL_SIGNER_H #include <common/system.h> #include <univalue.h> #include <string> #include <vector> struct PartiallySignedTransaction; //! Enables interaction with an external signing device or service, such as //! a hardware wallet. See doc/external-signer.md class ExternalSigner { private: //! The command which handles interaction with the external signer. std::string m_command; //! Bitcoin mainnet, testnet, etc std::string m_chain; std::string NetworkArg() const; public: //! @param[in] command the command which handles interaction with the external signer //! @param[in] fingerprint master key fingerprint of the signer //! @param[in] chain "main", "test", "regtest" or "signet" //! @param[in] name device name ExternalSigner(const std::string& command, const std::string chain, const std::string& fingerprint, const std::string name); //! Master key fingerprint of the signer std::string m_fingerprint; //! Name of signer std::string m_name; //! Obtain a list of signers. Calls `<command> enumerate`. //! @param[in] command the command which handles interaction with the external signer //! @param[in,out] signers vector to which new signers (with a unique master key fingerprint) are added //! @param chain "main", "test", "regtest" or "signet" //! @returns success 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>`. //! @param[in] descriptor Descriptor specifying which address to display. //! Must include a public key or xpub, as well as key origin. UniValue DisplayAddress(const std::string& descriptor) const; //! Get receive and change Descriptor(s) from device for a given account. //! Calls `<command> getdescriptors --account <account>` //! @param[in] account which BIP32 account to use (e.g. `m/44'/0'/account'`) //! @returns see doc/external-signer.md UniValue GetDescriptors(const int account); //! Sign PartiallySignedTransaction on the device. //! Calls `<command> signtransaction` and passes the PSBT via stdin. //! @param[in,out] psbt PartiallySignedTransaction to be signed bool SignTransaction(PartiallySignedTransaction& psbt, std::string& error); }; #endif // BITCOIN_EXTERNAL_SIGNER_H
0
bitcoin
bitcoin/src/key.cpp
// Copyright (c) 2009-2022 The Bitcoin Core developers // Copyright (c) 2017 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <key.h> #include <crypto/common.h> #include <crypto/hmac_sha512.h> #include <hash.h> #include <random.h> #include <secp256k1.h> #include <secp256k1_ellswift.h> #include <secp256k1_extrakeys.h> #include <secp256k1_recovery.h> #include <secp256k1_schnorrsig.h> static secp256k1_context* secp256k1_context_sign = nullptr; /** These functions are taken from the libsecp256k1 distribution and are very ugly. */ /** * This parses a format loosely based on a DER encoding of the ECPrivateKey type from * section C.4 of SEC 1 <https://www.secg.org/sec1-v2.pdf>, with the following caveats: * * * The octet-length of the SEQUENCE must be encoded as 1 or 2 octets. It is not * required to be encoded as one octet if it is less than 256, as DER would require. * * The octet-length of the SEQUENCE must not be greater than the remaining * length of the key encoding, but need not match it (i.e. the encoding may contain * junk after the encoded SEQUENCE). * * The privateKey OCTET STRING is zero-filled on the left to 32 octets. * * Anything after the encoding of the privateKey OCTET STRING is ignored, whether * or not it is validly encoded DER. * * out32 must point to an output buffer of length at least 32 bytes. */ int ec_seckey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *seckey, size_t seckeylen) { const unsigned char *end = seckey + seckeylen; memset(out32, 0, 32); /* sequence header */ if (end - seckey < 1 || *seckey != 0x30u) { return 0; } seckey++; /* sequence length constructor */ if (end - seckey < 1 || !(*seckey & 0x80u)) { return 0; } ptrdiff_t lenb = *seckey & ~0x80u; seckey++; if (lenb < 1 || lenb > 2) { return 0; } if (end - seckey < lenb) { return 0; } /* sequence length */ ptrdiff_t len = seckey[lenb-1] | (lenb > 1 ? seckey[lenb-2] << 8 : 0u); seckey += lenb; if (end - seckey < len) { return 0; } /* sequence element 0: version number (=1) */ if (end - seckey < 3 || seckey[0] != 0x02u || seckey[1] != 0x01u || seckey[2] != 0x01u) { return 0; } seckey += 3; /* sequence element 1: octet string, up to 32 bytes */ if (end - seckey < 2 || seckey[0] != 0x04u) { return 0; } ptrdiff_t oslen = seckey[1]; seckey += 2; if (oslen > 32 || end - seckey < oslen) { return 0; } memcpy(out32 + (32 - oslen), seckey, oslen); if (!secp256k1_ec_seckey_verify(ctx, out32)) { memset(out32, 0, 32); return 0; } return 1; } /** * This serializes to a DER encoding of the ECPrivateKey type from section C.4 of SEC 1 * <https://www.secg.org/sec1-v2.pdf>. The optional parameters and publicKey fields are * included. * * seckey must point to an output buffer of length at least CKey::SIZE bytes. * seckeylen must initially be set to the size of the seckey buffer. Upon return it * will be set to the number of bytes used in the buffer. * key32 must point to a 32-byte raw private key. */ int ec_seckey_export_der(const secp256k1_context *ctx, unsigned char *seckey, size_t *seckeylen, const unsigned char *key32, bool compressed) { assert(*seckeylen >= CKey::SIZE); secp256k1_pubkey pubkey; size_t pubkeylen = 0; if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) { *seckeylen = 0; return 0; } if (compressed) { static const unsigned char begin[] = { 0x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20 }; static const unsigned char middle[] = { 0xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48, 0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04, 0x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87, 0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8, 0x17,0x98,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E, 0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00 }; unsigned char *ptr = seckey; memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin); memcpy(ptr, key32, 32); ptr += 32; memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle); pubkeylen = CPubKey::COMPRESSED_SIZE; secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED); ptr += pubkeylen; *seckeylen = ptr - seckey; assert(*seckeylen == CKey::COMPRESSED_SIZE); } else { static const unsigned char begin[] = { 0x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20 }; static const unsigned char middle[] = { 0xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48, 0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04, 0x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87, 0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8, 0x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11, 0x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10, 0xD4,0xB8,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E, 0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00 }; unsigned char *ptr = seckey; memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin); memcpy(ptr, key32, 32); ptr += 32; memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle); pubkeylen = CPubKey::SIZE; secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED); ptr += pubkeylen; *seckeylen = ptr - seckey; assert(*seckeylen == CKey::SIZE); } return 1; } bool CKey::Check(const unsigned char *vch) { return secp256k1_ec_seckey_verify(secp256k1_context_sign, vch); } void CKey::MakeNewKey(bool fCompressedIn) { MakeKeyData(); do { GetStrongRandBytes(*keydata); } while (!Check(keydata->data())); fCompressed = fCompressedIn; } bool CKey::Negate() { assert(keydata); return secp256k1_ec_seckey_negate(secp256k1_context_sign, keydata->data()); } CPrivKey CKey::GetPrivKey() const { assert(keydata); CPrivKey seckey; int ret; size_t seckeylen; seckey.resize(SIZE); seckeylen = SIZE; ret = ec_seckey_export_der(secp256k1_context_sign, seckey.data(), &seckeylen, begin(), fCompressed); assert(ret); seckey.resize(seckeylen); return seckey; } CPubKey CKey::GetPubKey() const { assert(keydata); secp256k1_pubkey pubkey; size_t clen = CPubKey::SIZE; CPubKey result; int ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pubkey, begin()); assert(ret); secp256k1_ec_pubkey_serialize(secp256k1_context_sign, (unsigned char*)result.begin(), &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED); assert(result.size() == clen); assert(result.IsValid()); return result; } // Check that the sig has a low R value and will be less than 71 bytes bool SigHasLowR(const secp256k1_ecdsa_signature* sig) { unsigned char compact_sig[64]; secp256k1_ecdsa_signature_serialize_compact(secp256k1_context_sign, compact_sig, sig); // In DER serialization, all values are interpreted as big-endian, signed integers. The highest bit in the integer indicates // its signed-ness; 0 is positive, 1 is negative. When the value is interpreted as a negative integer, it must be converted // to a positive value by prepending a 0x00 byte so that the highest bit is 0. We can avoid this prepending by ensuring that // our highest bit is always 0, and thus we must check that the first byte is less than 0x80. return compact_sig[0] < 0x80; } bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, bool grind, uint32_t test_case) const { if (!keydata) return false; vchSig.resize(CPubKey::SIGNATURE_SIZE); size_t nSigLen = CPubKey::SIGNATURE_SIZE; unsigned char extra_entropy[32] = {0}; WriteLE32(extra_entropy, test_case); secp256k1_ecdsa_signature sig; uint32_t counter = 0; int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, (!grind && test_case) ? extra_entropy : nullptr); // Grind for low R while (ret && !SigHasLowR(&sig) && grind) { WriteLE32(extra_entropy, ++counter); ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, extra_entropy); } assert(ret); secp256k1_ecdsa_signature_serialize_der(secp256k1_context_sign, vchSig.data(), &nSigLen, &sig); vchSig.resize(nSigLen); // Additional verification step to prevent using a potentially corrupted signature secp256k1_pubkey pk; ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pk, begin()); assert(ret); ret = secp256k1_ecdsa_verify(secp256k1_context_static, &sig, hash.begin(), &pk); assert(ret); return true; } bool CKey::VerifyPubKey(const CPubKey& pubkey) const { if (pubkey.IsCompressed() != fCompressed) { return false; } unsigned char rnd[8]; std::string str = "Bitcoin key verification\n"; GetRandBytes(rnd); uint256 hash{Hash(str, rnd)}; std::vector<unsigned char> vchSig; Sign(hash, vchSig); return pubkey.Verify(hash, vchSig); } bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const { if (!keydata) return false; vchSig.resize(CPubKey::COMPACT_SIGNATURE_SIZE); int rec = -1; secp256k1_ecdsa_recoverable_signature rsig; int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &rsig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, nullptr); assert(ret); ret = secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_sign, &vchSig[1], &rec, &rsig); assert(ret); assert(rec != -1); vchSig[0] = 27 + rec + (fCompressed ? 4 : 0); // Additional verification step to prevent using a potentially corrupted signature secp256k1_pubkey epk, rpk; ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &epk, begin()); assert(ret); ret = secp256k1_ecdsa_recover(secp256k1_context_static, &rpk, &rsig, hash.begin()); assert(ret); ret = secp256k1_ec_pubkey_cmp(secp256k1_context_static, &epk, &rpk); assert(ret == 0); return true; } bool CKey::SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const { assert(sig.size() == 64); secp256k1_keypair keypair; if (!secp256k1_keypair_create(secp256k1_context_sign, &keypair, begin())) return false; if (merkle_root) { secp256k1_xonly_pubkey pubkey; if (!secp256k1_keypair_xonly_pub(secp256k1_context_sign, &pubkey, nullptr, &keypair)) return false; unsigned char pubkey_bytes[32]; if (!secp256k1_xonly_pubkey_serialize(secp256k1_context_sign, pubkey_bytes, &pubkey)) return false; uint256 tweak = XOnlyPubKey(pubkey_bytes).ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root); if (!secp256k1_keypair_xonly_tweak_add(secp256k1_context_static, &keypair, tweak.data())) return false; } bool ret = secp256k1_schnorrsig_sign32(secp256k1_context_sign, sig.data(), hash.data(), &keypair, aux.data()); if (ret) { // Additional verification step to prevent using a potentially corrupted signature secp256k1_xonly_pubkey pubkey_verify; ret = secp256k1_keypair_xonly_pub(secp256k1_context_static, &pubkey_verify, nullptr, &keypair); ret &= secp256k1_schnorrsig_verify(secp256k1_context_static, sig.data(), hash.begin(), 32, &pubkey_verify); } if (!ret) memory_cleanse(sig.data(), sig.size()); memory_cleanse(&keypair, sizeof(keypair)); return ret; } bool CKey::Load(const CPrivKey &seckey, const CPubKey &vchPubKey, bool fSkipCheck=false) { MakeKeyData(); if (!ec_seckey_import_der(secp256k1_context_sign, (unsigned char*)begin(), seckey.data(), seckey.size())) { ClearKeyData(); return false; } fCompressed = vchPubKey.IsCompressed(); if (fSkipCheck) return true; return VerifyPubKey(vchPubKey); } bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const { assert(IsValid()); assert(IsCompressed()); std::vector<unsigned char, secure_allocator<unsigned char>> vout(64); if ((nChild >> 31) == 0) { CPubKey pubkey = GetPubKey(); assert(pubkey.size() == CPubKey::COMPRESSED_SIZE); BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, vout.data()); } else { assert(size() == 32); BIP32Hash(cc, nChild, 0, begin(), vout.data()); } memcpy(ccChild.begin(), vout.data()+32, 32); keyChild.Set(begin(), begin() + 32, true); bool ret = secp256k1_ec_seckey_tweak_add(secp256k1_context_sign, (unsigned char*)keyChild.begin(), vout.data()); if (!ret) keyChild.ClearKeyData(); return ret; } EllSwiftPubKey CKey::EllSwiftCreate(Span<const std::byte> ent32) const { assert(keydata); assert(ent32.size() == 32); std::array<std::byte, EllSwiftPubKey::size()> encoded_pubkey; auto success = secp256k1_ellswift_create(secp256k1_context_sign, UCharCast(encoded_pubkey.data()), keydata->data(), UCharCast(ent32.data())); // Should always succeed for valid keys (asserted above). assert(success); return {encoded_pubkey}; } ECDHSecret CKey::ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift, const EllSwiftPubKey& our_ellswift, bool initiating) const { assert(keydata); ECDHSecret output; // BIP324 uses the initiator as party A, and the responder as party B. Remap the inputs // accordingly: bool success = secp256k1_ellswift_xdh(secp256k1_context_sign, UCharCast(output.data()), UCharCast(initiating ? our_ellswift.data() : their_ellswift.data()), UCharCast(initiating ? their_ellswift.data() : our_ellswift.data()), keydata->data(), initiating ? 0 : 1, secp256k1_ellswift_xdh_hash_function_bip324, nullptr); // Should always succeed for valid keys (assert above). assert(success); return output; } bool CExtKey::Derive(CExtKey &out, unsigned int _nChild) const { if (nDepth == std::numeric_limits<unsigned char>::max()) return false; out.nDepth = nDepth + 1; CKeyID id = key.GetPubKey().GetID(); memcpy(out.vchFingerprint, &id, 4); out.nChild = _nChild; return key.Derive(out.key, out.chaincode, _nChild, chaincode); } void CExtKey::SetSeed(Span<const std::byte> seed) { static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'}; std::vector<unsigned char, secure_allocator<unsigned char>> vout(64); CHMAC_SHA512{hashkey, sizeof(hashkey)}.Write(UCharCast(seed.data()), seed.size()).Finalize(vout.data()); key.Set(vout.data(), vout.data() + 32, true); memcpy(chaincode.begin(), vout.data() + 32, 32); nDepth = 0; nChild = 0; memset(vchFingerprint, 0, sizeof(vchFingerprint)); } CExtPubKey CExtKey::Neuter() const { CExtPubKey ret; ret.nDepth = nDepth; memcpy(ret.vchFingerprint, vchFingerprint, 4); ret.nChild = nChild; ret.pubkey = key.GetPubKey(); ret.chaincode = chaincode; return ret; } void CExtKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const { code[0] = nDepth; memcpy(code+1, vchFingerprint, 4); WriteBE32(code+5, nChild); memcpy(code+9, chaincode.begin(), 32); code[41] = 0; assert(key.size() == 32); memcpy(code+42, key.begin(), 32); } void CExtKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) { nDepth = code[0]; memcpy(vchFingerprint, code+1, 4); nChild = ReadBE32(code+5); memcpy(chaincode.begin(), code+9, 32); key.Set(code+42, code+BIP32_EXTKEY_SIZE, true); if ((nDepth == 0 && (nChild != 0 || ReadLE32(vchFingerprint) != 0)) || code[41] != 0) key = CKey(); } bool ECC_InitSanityCheck() { CKey key; key.MakeNewKey(true); CPubKey pubkey = key.GetPubKey(); return key.VerifyPubKey(pubkey); } void ECC_Start() { assert(secp256k1_context_sign == nullptr); secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE); assert(ctx != nullptr); { // Pass in a random blinding seed to the secp256k1 context. std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32); GetRandBytes(vseed); bool ret = secp256k1_context_randomize(ctx, vseed.data()); assert(ret); } secp256k1_context_sign = ctx; } void ECC_Stop() { secp256k1_context *ctx = secp256k1_context_sign; secp256k1_context_sign = nullptr; if (ctx) { secp256k1_context_destroy(ctx); } }
0
bitcoin
bitcoin/src/bech32.h
// Copyright (c) 2017, 2021 Pieter Wuille // Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Bech32 and Bech32m are string encoding formats used in newer // address types. The outputs consist of a human-readable part // (alphanumeric), a separator character (1), and a base32 data // section, the last 6 characters of which are a checksum. The // module is namespaced under bech32 for historical reasons. // // For more information, see BIP 173 and BIP 350. #ifndef BITCOIN_BECH32_H #define BITCOIN_BECH32_H #include <stdint.h> #include <string> #include <vector> namespace bech32 { enum class Encoding { INVALID, //!< Failed decoding BECH32, //!< Bech32 encoding as defined in BIP173 BECH32M, //!< Bech32m encoding as defined in BIP350 }; /** Encode a Bech32 or Bech32m string. If hrp contains uppercase characters, this will cause an * assertion error. Encoding must be one of BECH32 or BECH32M. */ std::string Encode(Encoding encoding, const std::string& hrp, const std::vector<uint8_t>& values); struct DecodeResult { Encoding encoding; //!< What encoding was detected in the result; Encoding::INVALID if failed. std::string hrp; //!< The human readable part std::vector<uint8_t> data; //!< The payload (excluding checksum) DecodeResult() : encoding(Encoding::INVALID) {} DecodeResult(Encoding enc, std::string&& h, std::vector<uint8_t>&& d) : encoding(enc), hrp(std::move(h)), data(std::move(d)) {} }; /** Decode a Bech32 or Bech32m string. */ DecodeResult Decode(const std::string& str); /** Return the positions of errors in a Bech32 string. */ std::pair<std::string, std::vector<int>> LocateErrors(const std::string& str); } // namespace bech32 #endif // BITCOIN_BECH32_H
0
bitcoin
bitcoin/src/signet.cpp
// Copyright (c) 2019-2021 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 <signet.h> #include <array> #include <cstdint> #include <vector> #include <common/system.h> #include <consensus/merkle.h> #include <consensus/params.h> #include <consensus/validation.h> #include <core_io.h> #include <hash.h> #include <logging.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <script/interpreter.h> #include <span.h> #include <streams.h> #include <uint256.h> #include <util/strencodings.h> static constexpr uint8_t SIGNET_HEADER[4] = {0xec, 0xc7, 0xda, 0xa2}; static constexpr unsigned int BLOCK_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_NULLDUMMY; static bool FetchAndClearCommitmentSection(const Span<const uint8_t> header, CScript& witness_commitment, std::vector<uint8_t>& result) { CScript replacement; bool found_header = false; result.clear(); opcodetype opcode; CScript::const_iterator pc = witness_commitment.begin(); std::vector<uint8_t> pushdata; while (witness_commitment.GetOp(pc, opcode, pushdata)) { if (pushdata.size() > 0) { if (!found_header && pushdata.size() > (size_t)header.size() && Span{pushdata}.first(header.size()) == header) { // pushdata only counts if it has the header _and_ some data result.insert(result.end(), pushdata.begin() + header.size(), pushdata.end()); pushdata.erase(pushdata.begin() + header.size(), pushdata.end()); found_header = true; } replacement << pushdata; } else { replacement << opcode; } } if (found_header) witness_commitment = replacement; return found_header; } static uint256 ComputeModifiedMerkleRoot(const CMutableTransaction& cb, const CBlock& block) { std::vector<uint256> leaves; leaves.resize(block.vtx.size()); leaves[0] = cb.GetHash(); for (size_t s = 1; s < block.vtx.size(); ++s) { leaves[s] = block.vtx[s]->GetHash(); } return ComputeMerkleRoot(std::move(leaves)); } std::optional<SignetTxs> SignetTxs::Create(const CBlock& block, const CScript& challenge) { CMutableTransaction tx_to_spend; tx_to_spend.nVersion = 0; tx_to_spend.nLockTime = 0; tx_to_spend.vin.emplace_back(COutPoint(), CScript(OP_0), 0); tx_to_spend.vout.emplace_back(0, challenge); CMutableTransaction tx_spending; tx_spending.nVersion = 0; tx_spending.nLockTime = 0; tx_spending.vin.emplace_back(COutPoint(), CScript(), 0); tx_spending.vout.emplace_back(0, CScript(OP_RETURN)); // can't fill any other fields before extracting signet // responses from block coinbase tx // find and delete signet signature if (block.vtx.empty()) return std::nullopt; // no coinbase tx in block; invalid CMutableTransaction modified_cb(*block.vtx.at(0)); const int cidx = GetWitnessCommitmentIndex(block); if (cidx == NO_WITNESS_COMMITMENT) { return std::nullopt; // require a witness commitment } CScript& witness_commitment = modified_cb.vout.at(cidx).scriptPubKey; std::vector<uint8_t> signet_solution; if (!FetchAndClearCommitmentSection(SIGNET_HEADER, witness_commitment, signet_solution)) { // no signet solution -- allow this to support OP_TRUE as trivial block challenge } else { try { SpanReader v{signet_solution}; v >> tx_spending.vin[0].scriptSig; v >> tx_spending.vin[0].scriptWitness.stack; if (!v.empty()) return std::nullopt; // extraneous data encountered } catch (const std::exception&) { return std::nullopt; // parsing error } } uint256 signet_merkle = ComputeModifiedMerkleRoot(modified_cb, block); std::vector<uint8_t> block_data; VectorWriter writer{block_data, 0}; writer << block.nVersion; writer << block.hashPrevBlock; writer << signet_merkle; writer << block.nTime; tx_to_spend.vin[0].scriptSig << block_data; tx_spending.vin[0].prevout = COutPoint(tx_to_spend.GetHash(), 0); return SignetTxs{tx_to_spend, tx_spending}; } // Signet block solution checker bool CheckSignetBlockSolution(const CBlock& block, const Consensus::Params& consensusParams) { if (block.GetHash() == consensusParams.hashGenesisBlock) { // genesis block solution is always valid return true; } const CScript challenge(consensusParams.signet_challenge.begin(), consensusParams.signet_challenge.end()); const std::optional<SignetTxs> signet_txs = SignetTxs::Create(block, challenge); if (!signet_txs) { LogPrint(BCLog::VALIDATION, "CheckSignetBlockSolution: Errors in block (block solution parse failure)\n"); return false; } const CScript& scriptSig = signet_txs->m_to_sign.vin[0].scriptSig; const CScriptWitness& witness = signet_txs->m_to_sign.vin[0].scriptWitness; PrecomputedTransactionData txdata; txdata.Init(signet_txs->m_to_sign, {signet_txs->m_to_spend.vout[0]}); TransactionSignatureChecker sigcheck(&signet_txs->m_to_sign, /* nInIn= */ 0, /* amountIn= */ signet_txs->m_to_spend.vout[0].nValue, txdata, MissingDataBehavior::ASSERT_FAIL); if (!VerifyScript(scriptSig, signet_txs->m_to_spend.vout[0].scriptPubKey, &witness, BLOCK_SCRIPT_VERIFY_FLAGS, sigcheck)) { LogPrint(BCLog::VALIDATION, "CheckSignetBlockSolution: Errors in block (block solution invalid)\n"); return false; } return true; }
0
bitcoin
bitcoin/src/banman.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 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 <banman.h> #include <common/system.h> #include <logging.h> #include <netaddress.h> #include <node/interface_ui.h> #include <sync.h> #include <util/time.h> #include <util/translation.h> BanMan::BanMan(fs::path ban_file, CClientUIInterface* client_interface, int64_t default_ban_time) : m_client_interface(client_interface), m_ban_db(std::move(ban_file)), m_default_ban_time(default_ban_time) { LoadBanlist(); DumpBanlist(); } BanMan::~BanMan() { DumpBanlist(); } void BanMan::LoadBanlist() { LOCK(m_banned_mutex); if (m_client_interface) m_client_interface->InitMessage(_("Loading banlist…").translated); const auto start{SteadyClock::now()}; if (m_ban_db.Read(m_banned)) { SweepBanned(); // sweep out unused entries LogPrint(BCLog::NET, "Loaded %d banned node addresses/subnets %dms\n", m_banned.size(), Ticks<std::chrono::milliseconds>(SteadyClock::now() - start)); } else { LogPrintf("Recreating the banlist database\n"); m_banned = {}; m_is_dirty = true; } } void BanMan::DumpBanlist() { static Mutex dump_mutex; LOCK(dump_mutex); banmap_t banmap; { LOCK(m_banned_mutex); SweepBanned(); if (!m_is_dirty) return; banmap = m_banned; m_is_dirty = false; } const auto start{SteadyClock::now()}; if (!m_ban_db.Write(banmap)) { LOCK(m_banned_mutex); m_is_dirty = true; } LogPrint(BCLog::NET, "Flushed %d banned node addresses/subnets to disk %dms\n", banmap.size(), Ticks<std::chrono::milliseconds>(SteadyClock::now() - start)); } void BanMan::ClearBanned() { { LOCK(m_banned_mutex); m_banned.clear(); m_is_dirty = true; } DumpBanlist(); //store banlist to disk if (m_client_interface) m_client_interface->BannedListChanged(); } bool BanMan::IsDiscouraged(const CNetAddr& net_addr) { LOCK(m_banned_mutex); return m_discouraged.contains(net_addr.GetAddrBytes()); } bool BanMan::IsBanned(const CNetAddr& net_addr) { auto current_time = GetTime(); LOCK(m_banned_mutex); for (const auto& it : m_banned) { CSubNet sub_net = it.first; CBanEntry ban_entry = it.second; if (current_time < ban_entry.nBanUntil && sub_net.Match(net_addr)) { return true; } } return false; } bool BanMan::IsBanned(const CSubNet& sub_net) { auto current_time = GetTime(); LOCK(m_banned_mutex); banmap_t::iterator i = m_banned.find(sub_net); if (i != m_banned.end()) { CBanEntry ban_entry = (*i).second; if (current_time < ban_entry.nBanUntil) { return true; } } return false; } void BanMan::Ban(const CNetAddr& net_addr, int64_t ban_time_offset, bool since_unix_epoch) { CSubNet sub_net(net_addr); Ban(sub_net, ban_time_offset, since_unix_epoch); } void BanMan::Discourage(const CNetAddr& net_addr) { LOCK(m_banned_mutex); m_discouraged.insert(net_addr.GetAddrBytes()); } void BanMan::Ban(const CSubNet& sub_net, int64_t ban_time_offset, bool since_unix_epoch) { CBanEntry ban_entry(GetTime()); int64_t normalized_ban_time_offset = ban_time_offset; bool normalized_since_unix_epoch = since_unix_epoch; if (ban_time_offset <= 0) { normalized_ban_time_offset = m_default_ban_time; normalized_since_unix_epoch = false; } ban_entry.nBanUntil = (normalized_since_unix_epoch ? 0 : GetTime()) + normalized_ban_time_offset; { LOCK(m_banned_mutex); if (m_banned[sub_net].nBanUntil < ban_entry.nBanUntil) { m_banned[sub_net] = ban_entry; m_is_dirty = true; } else return; } if (m_client_interface) m_client_interface->BannedListChanged(); //store banlist to disk immediately DumpBanlist(); } bool BanMan::Unban(const CNetAddr& net_addr) { CSubNet sub_net(net_addr); return Unban(sub_net); } bool BanMan::Unban(const CSubNet& sub_net) { { LOCK(m_banned_mutex); if (m_banned.erase(sub_net) == 0) return false; m_is_dirty = true; } if (m_client_interface) m_client_interface->BannedListChanged(); DumpBanlist(); //store banlist to disk immediately return true; } void BanMan::GetBanned(banmap_t& banmap) { LOCK(m_banned_mutex); // Sweep the banlist so expired bans are not returned SweepBanned(); banmap = m_banned; //create a thread safe copy } void BanMan::SweepBanned() { AssertLockHeld(m_banned_mutex); int64_t now = GetTime(); bool notify_ui = false; banmap_t::iterator it = m_banned.begin(); while (it != m_banned.end()) { CSubNet sub_net = (*it).first; CBanEntry ban_entry = (*it).second; if (!sub_net.IsValid() || now > ban_entry.nBanUntil) { m_banned.erase(it++); m_is_dirty = true; notify_ui = true; LogPrint(BCLog::NET, "Removed banned node address/subnet: %s\n", sub_net.ToString()); } else { ++it; } } // update UI if (notify_ui && m_client_interface) { m_client_interface->BannedListChanged(); } }
0
bitcoin
bitcoin/src/addrman.cpp
// Copyright (c) 2012 Pieter Wuille // Copyright (c) 2012-2022 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 <addrman.h> #include <addrman_impl.h> #include <hash.h> #include <logging.h> #include <logging/timer.h> #include <netaddress.h> #include <protocol.h> #include <random.h> #include <serialize.h> #include <streams.h> #include <tinyformat.h> #include <uint256.h> #include <util/check.h> #include <util/time.h> #include <cmath> #include <optional> /** Over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread */ static constexpr uint32_t ADDRMAN_TRIED_BUCKETS_PER_GROUP{8}; /** Over how many buckets entries with new addresses originating from a single group are spread */ static constexpr uint32_t ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP{64}; /** Maximum number of times an address can occur in the new table */ static constexpr int32_t ADDRMAN_NEW_BUCKETS_PER_ADDRESS{8}; /** How old addresses can maximally be */ static constexpr auto ADDRMAN_HORIZON{30 * 24h}; /** After how many failed attempts we give up on a new node */ static constexpr int32_t ADDRMAN_RETRIES{3}; /** How many successive failures are allowed ... */ static constexpr int32_t ADDRMAN_MAX_FAILURES{10}; /** ... in at least this duration */ static constexpr auto ADDRMAN_MIN_FAIL{7 * 24h}; /** How recent a successful connection should be before we allow an address to be evicted from tried */ static constexpr auto ADDRMAN_REPLACEMENT{4h}; /** The maximum number of tried addr collisions to store */ static constexpr size_t ADDRMAN_SET_TRIED_COLLISION_SIZE{10}; /** The maximum time we'll spend trying to resolve a tried table collision */ static constexpr auto ADDRMAN_TEST_WINDOW{40min}; int AddrInfo::GetTriedBucket(const uint256& nKey, const NetGroupManager& netgroupman) const { uint64_t hash1 = (HashWriter{} << nKey << GetKey()).GetCheapHash(); uint64_t hash2 = (HashWriter{} << nKey << netgroupman.GetGroup(*this) << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetCheapHash(); return hash2 % ADDRMAN_TRIED_BUCKET_COUNT; } int AddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src, const NetGroupManager& netgroupman) const { std::vector<unsigned char> vchSourceGroupKey = netgroupman.GetGroup(src); uint64_t hash1 = (HashWriter{} << nKey << netgroupman.GetGroup(*this) << vchSourceGroupKey).GetCheapHash(); uint64_t hash2 = (HashWriter{} << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetCheapHash(); return hash2 % ADDRMAN_NEW_BUCKET_COUNT; } int AddrInfo::GetBucketPosition(const uint256& nKey, bool fNew, int bucket) const { uint64_t hash1 = (HashWriter{} << nKey << (fNew ? uint8_t{'N'} : uint8_t{'K'}) << bucket << GetKey()).GetCheapHash(); return hash1 % ADDRMAN_BUCKET_SIZE; } bool AddrInfo::IsTerrible(NodeSeconds now) const { if (now - m_last_try <= 1min) { // never remove things tried in the last minute return false; } if (nTime > now + 10min) { // came in a flying DeLorean return true; } if (now - nTime > ADDRMAN_HORIZON) { // not seen in recent history return true; } if (TicksSinceEpoch<std::chrono::seconds>(m_last_success) == 0 && nAttempts >= ADDRMAN_RETRIES) { // tried N times and never a success return true; } if (now - m_last_success > ADDRMAN_MIN_FAIL && nAttempts >= ADDRMAN_MAX_FAILURES) { // N successive failures in the last week return true; } return false; } double AddrInfo::GetChance(NodeSeconds now) const { double fChance = 1.0; // deprioritize very recent attempts away if (now - m_last_try < 10min) { fChance *= 0.01; } // deprioritize 66% after each failed attempt, but at most 1/28th to avoid the search taking forever or overly penalizing outages. fChance *= pow(0.66, std::min(nAttempts, 8)); return fChance; } AddrManImpl::AddrManImpl(const NetGroupManager& netgroupman, bool deterministic, int32_t consistency_check_ratio) : insecure_rand{deterministic} , nKey{deterministic ? uint256{1} : insecure_rand.rand256()} , m_consistency_check_ratio{consistency_check_ratio} , m_netgroupman{netgroupman} { for (auto& bucket : vvNew) { for (auto& entry : bucket) { entry = -1; } } for (auto& bucket : vvTried) { for (auto& entry : bucket) { entry = -1; } } } AddrManImpl::~AddrManImpl() { nKey.SetNull(); } template <typename Stream> void AddrManImpl::Serialize(Stream& s_) const { LOCK(cs); /** * Serialized format. * * format version byte (@see `Format`) * * lowest compatible format version byte. This is used to help old software decide * whether to parse the file. For example: * * Bitcoin Core version N knows how to parse up to format=3. If a new format=4 is * introduced in version N+1 that is compatible with format=3 and it is known that * version N will be able to parse it, then version N+1 will write * (format=4, lowest_compatible=3) in the first two bytes of the file, and so * version N will still try to parse it. * * Bitcoin Core version N+2 introduces a new incompatible format=5. It will write * (format=5, lowest_compatible=5) and so any versions that do not know how to parse * format=5 will not try to read the file. * * nKey * * nNew * * nTried * * number of "new" buckets XOR 2**30 * * all new addresses (total count: nNew) * * all tried addresses (total count: nTried) * * for each new bucket: * * number of elements * * for each element: index in the serialized "all new addresses" * * asmap checksum * * 2**30 is xorred with the number of buckets to make addrman deserializer v0 detect it * as incompatible. This is necessary because it did not check the version number on * deserialization. * * vvNew, vvTried, mapInfo, mapAddr and vRandom are never encoded explicitly; * they are instead reconstructed from the other information. * * This format is more complex, but significantly smaller (at most 1.5 MiB), and supports * changes to the ADDRMAN_ parameters without breaking the on-disk structure. * * We don't use SERIALIZE_METHODS since the serialization and deserialization code has * very little in common. */ // Always serialize in the latest version (FILE_FORMAT). ParamsStream s{CAddress::V2_DISK, s_}; s << static_cast<uint8_t>(FILE_FORMAT); // Increment `lowest_compatible` iff a newly introduced format is incompatible with // the previous one. static constexpr uint8_t lowest_compatible = Format::V4_MULTIPORT; s << static_cast<uint8_t>(INCOMPATIBILITY_BASE + lowest_compatible); s << nKey; s << nNew; s << nTried; int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30); s << nUBuckets; std::unordered_map<int, int> mapUnkIds; int nIds = 0; for (const auto& entry : mapInfo) { mapUnkIds[entry.first] = nIds; const AddrInfo& info = entry.second; if (info.nRefCount) { assert(nIds != nNew); // this means nNew was wrong, oh ow s << info; nIds++; } } nIds = 0; for (const auto& entry : mapInfo) { const AddrInfo& info = entry.second; if (info.fInTried) { assert(nIds != nTried); // this means nTried was wrong, oh ow s << info; nIds++; } } for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) { int nSize = 0; for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvNew[bucket][i] != -1) nSize++; } s << nSize; for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvNew[bucket][i] != -1) { int nIndex = mapUnkIds[vvNew[bucket][i]]; s << nIndex; } } } // Store asmap checksum after bucket entries so that it // can be ignored by older clients for backward compatibility. s << m_netgroupman.GetAsmapChecksum(); } template <typename Stream> void AddrManImpl::Unserialize(Stream& s_) { LOCK(cs); assert(vRandom.empty()); Format format; s_ >> Using<CustomUintFormatter<1>>(format); const auto ser_params = (format >= Format::V3_BIP155 ? CAddress::V2_DISK : CAddress::V1_DISK); ParamsStream s{ser_params, s_}; uint8_t compat; s >> compat; if (compat < INCOMPATIBILITY_BASE) { throw std::ios_base::failure(strprintf( "Corrupted addrman database: The compat value (%u) " "is lower than the expected minimum value %u.", compat, INCOMPATIBILITY_BASE)); } const uint8_t lowest_compatible = compat - INCOMPATIBILITY_BASE; if (lowest_compatible > FILE_FORMAT) { throw InvalidAddrManVersionError(strprintf( "Unsupported format of addrman database: %u. It is compatible with formats >=%u, " "but the maximum supported by this version of %s is %u.", uint8_t{format}, lowest_compatible, PACKAGE_NAME, uint8_t{FILE_FORMAT})); } s >> nKey; s >> nNew; s >> nTried; int nUBuckets = 0; s >> nUBuckets; if (format >= Format::V1_DETERMINISTIC) { nUBuckets ^= (1 << 30); } if (nNew > ADDRMAN_NEW_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE || nNew < 0) { throw std::ios_base::failure( strprintf("Corrupt AddrMan serialization: nNew=%d, should be in [0, %d]", nNew, ADDRMAN_NEW_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE)); } if (nTried > ADDRMAN_TRIED_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE || nTried < 0) { throw std::ios_base::failure( strprintf("Corrupt AddrMan serialization: nTried=%d, should be in [0, %d]", nTried, ADDRMAN_TRIED_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE)); } // Deserialize entries from the new table. for (int n = 0; n < nNew; n++) { AddrInfo& info = mapInfo[n]; s >> info; mapAddr[info] = n; info.nRandomPos = vRandom.size(); vRandom.push_back(n); m_network_counts[info.GetNetwork()].n_new++; } nIdCount = nNew; // Deserialize entries from the tried table. int nLost = 0; for (int n = 0; n < nTried; n++) { AddrInfo info; s >> info; int nKBucket = info.GetTriedBucket(nKey, m_netgroupman); int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket); if (info.IsValid() && vvTried[nKBucket][nKBucketPos] == -1) { info.nRandomPos = vRandom.size(); info.fInTried = true; vRandom.push_back(nIdCount); mapInfo[nIdCount] = info; mapAddr[info] = nIdCount; vvTried[nKBucket][nKBucketPos] = nIdCount; nIdCount++; m_network_counts[info.GetNetwork()].n_tried++; } else { nLost++; } } nTried -= nLost; // Store positions in the new table buckets to apply later (if possible). // An entry may appear in up to ADDRMAN_NEW_BUCKETS_PER_ADDRESS buckets, // so we store all bucket-entry_index pairs to iterate through later. std::vector<std::pair<int, int>> bucket_entries; for (int bucket = 0; bucket < nUBuckets; ++bucket) { int num_entries{0}; s >> num_entries; for (int n = 0; n < num_entries; ++n) { int entry_index{0}; s >> entry_index; if (entry_index >= 0 && entry_index < nNew) { bucket_entries.emplace_back(bucket, entry_index); } } } // If the bucket count and asmap checksum haven't changed, then attempt // to restore the entries to the buckets/positions they were in before // serialization. uint256 supplied_asmap_checksum{m_netgroupman.GetAsmapChecksum()}; uint256 serialized_asmap_checksum; if (format >= Format::V2_ASMAP) { s >> serialized_asmap_checksum; } const bool restore_bucketing{nUBuckets == ADDRMAN_NEW_BUCKET_COUNT && serialized_asmap_checksum == supplied_asmap_checksum}; if (!restore_bucketing) { LogPrint(BCLog::ADDRMAN, "Bucketing method was updated, re-bucketing addrman entries from disk\n"); } for (auto bucket_entry : bucket_entries) { int bucket{bucket_entry.first}; const int entry_index{bucket_entry.second}; AddrInfo& info = mapInfo[entry_index]; // Don't store the entry in the new bucket if it's not a valid address for our addrman if (!info.IsValid()) continue; // The entry shouldn't appear in more than // ADDRMAN_NEW_BUCKETS_PER_ADDRESS. If it has already, just skip // this bucket_entry. if (info.nRefCount >= ADDRMAN_NEW_BUCKETS_PER_ADDRESS) continue; int bucket_position = info.GetBucketPosition(nKey, true, bucket); if (restore_bucketing && vvNew[bucket][bucket_position] == -1) { // Bucketing has not changed, using existing bucket positions for the new table vvNew[bucket][bucket_position] = entry_index; ++info.nRefCount; } else { // In case the new table data cannot be used (bucket count wrong or new asmap), // try to give them a reference based on their primary source address. bucket = info.GetNewBucket(nKey, m_netgroupman); bucket_position = info.GetBucketPosition(nKey, true, bucket); if (vvNew[bucket][bucket_position] == -1) { vvNew[bucket][bucket_position] = entry_index; ++info.nRefCount; } } } // Prune new entries with refcount 0 (as a result of collisions or invalid address). int nLostUnk = 0; for (auto it = mapInfo.cbegin(); it != mapInfo.cend(); ) { if (it->second.fInTried == false && it->second.nRefCount == 0) { const auto itCopy = it++; Delete(itCopy->first); ++nLostUnk; } else { ++it; } } if (nLost + nLostUnk > 0) { LogPrint(BCLog::ADDRMAN, "addrman lost %i new and %i tried addresses due to collisions or invalid addresses\n", nLostUnk, nLost); } const int check_code{CheckAddrman()}; if (check_code != 0) { throw std::ios_base::failure(strprintf( "Corrupt data. Consistency check failed with code %s", check_code)); } } AddrInfo* AddrManImpl::Find(const CService& addr, int* pnId) { AssertLockHeld(cs); const auto it = mapAddr.find(addr); if (it == mapAddr.end()) return nullptr; if (pnId) *pnId = (*it).second; const auto it2 = mapInfo.find((*it).second); if (it2 != mapInfo.end()) return &(*it2).second; return nullptr; } AddrInfo* AddrManImpl::Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId) { AssertLockHeld(cs); int nId = nIdCount++; mapInfo[nId] = AddrInfo(addr, addrSource); mapAddr[addr] = nId; mapInfo[nId].nRandomPos = vRandom.size(); vRandom.push_back(nId); nNew++; m_network_counts[addr.GetNetwork()].n_new++; if (pnId) *pnId = nId; return &mapInfo[nId]; } void AddrManImpl::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2) const { AssertLockHeld(cs); if (nRndPos1 == nRndPos2) return; assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size()); int nId1 = vRandom[nRndPos1]; int nId2 = vRandom[nRndPos2]; const auto it_1{mapInfo.find(nId1)}; const auto it_2{mapInfo.find(nId2)}; assert(it_1 != mapInfo.end()); assert(it_2 != mapInfo.end()); it_1->second.nRandomPos = nRndPos2; it_2->second.nRandomPos = nRndPos1; vRandom[nRndPos1] = nId2; vRandom[nRndPos2] = nId1; } void AddrManImpl::Delete(int nId) { AssertLockHeld(cs); assert(mapInfo.count(nId) != 0); AddrInfo& info = mapInfo[nId]; assert(!info.fInTried); assert(info.nRefCount == 0); SwapRandom(info.nRandomPos, vRandom.size() - 1); m_network_counts[info.GetNetwork()].n_new--; vRandom.pop_back(); mapAddr.erase(info); mapInfo.erase(nId); nNew--; } void AddrManImpl::ClearNew(int nUBucket, int nUBucketPos) { AssertLockHeld(cs); // if there is an entry in the specified bucket, delete it. if (vvNew[nUBucket][nUBucketPos] != -1) { int nIdDelete = vvNew[nUBucket][nUBucketPos]; AddrInfo& infoDelete = mapInfo[nIdDelete]; assert(infoDelete.nRefCount > 0); infoDelete.nRefCount--; vvNew[nUBucket][nUBucketPos] = -1; LogPrint(BCLog::ADDRMAN, "Removed %s from new[%i][%i]\n", infoDelete.ToStringAddrPort(), nUBucket, nUBucketPos); if (infoDelete.nRefCount == 0) { Delete(nIdDelete); } } } void AddrManImpl::MakeTried(AddrInfo& info, int nId) { AssertLockHeld(cs); // remove the entry from all new buckets const int start_bucket{info.GetNewBucket(nKey, m_netgroupman)}; for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; ++n) { const int bucket{(start_bucket + n) % ADDRMAN_NEW_BUCKET_COUNT}; const int pos{info.GetBucketPosition(nKey, true, bucket)}; if (vvNew[bucket][pos] == nId) { vvNew[bucket][pos] = -1; info.nRefCount--; if (info.nRefCount == 0) break; } } nNew--; m_network_counts[info.GetNetwork()].n_new--; assert(info.nRefCount == 0); // which tried bucket to move the entry to int nKBucket = info.GetTriedBucket(nKey, m_netgroupman); int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket); // first make space to add it (the existing tried entry there is moved to new, deleting whatever is there). if (vvTried[nKBucket][nKBucketPos] != -1) { // find an item to evict int nIdEvict = vvTried[nKBucket][nKBucketPos]; assert(mapInfo.count(nIdEvict) == 1); AddrInfo& infoOld = mapInfo[nIdEvict]; // Remove the to-be-evicted item from the tried set. infoOld.fInTried = false; vvTried[nKBucket][nKBucketPos] = -1; nTried--; m_network_counts[infoOld.GetNetwork()].n_tried--; // find which new bucket it belongs to int nUBucket = infoOld.GetNewBucket(nKey, m_netgroupman); int nUBucketPos = infoOld.GetBucketPosition(nKey, true, nUBucket); ClearNew(nUBucket, nUBucketPos); assert(vvNew[nUBucket][nUBucketPos] == -1); // Enter it into the new set again. infoOld.nRefCount = 1; vvNew[nUBucket][nUBucketPos] = nIdEvict; nNew++; m_network_counts[infoOld.GetNetwork()].n_new++; LogPrint(BCLog::ADDRMAN, "Moved %s from tried[%i][%i] to new[%i][%i] to make space\n", infoOld.ToStringAddrPort(), nKBucket, nKBucketPos, nUBucket, nUBucketPos); } assert(vvTried[nKBucket][nKBucketPos] == -1); vvTried[nKBucket][nKBucketPos] = nId; nTried++; info.fInTried = true; m_network_counts[info.GetNetwork()].n_tried++; } bool AddrManImpl::AddSingle(const CAddress& addr, const CNetAddr& source, std::chrono::seconds time_penalty) { AssertLockHeld(cs); if (!addr.IsRoutable()) return false; int nId; AddrInfo* pinfo = Find(addr, &nId); // Do not set a penalty for a source's self-announcement if (addr == source) { time_penalty = 0s; } if (pinfo) { // periodically update nTime const bool currently_online{NodeClock::now() - addr.nTime < 24h}; const auto update_interval{currently_online ? 1h : 24h}; if (pinfo->nTime < addr.nTime - update_interval - time_penalty) { pinfo->nTime = std::max(NodeSeconds{0s}, addr.nTime - time_penalty); } // add services pinfo->nServices = ServiceFlags(pinfo->nServices | addr.nServices); // do not update if no new information is present if (addr.nTime <= pinfo->nTime) { return false; } // do not update if the entry was already in the "tried" table if (pinfo->fInTried) return false; // do not update if the max reference count is reached if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return false; // stochastic test: previous nRefCount == N: 2^N times harder to increase it int nFactor = 1; for (int n = 0; n < pinfo->nRefCount; n++) nFactor *= 2; if (nFactor > 1 && (insecure_rand.randrange(nFactor) != 0)) return false; } else { pinfo = Create(addr, source, &nId); pinfo->nTime = std::max(NodeSeconds{0s}, pinfo->nTime - time_penalty); } int nUBucket = pinfo->GetNewBucket(nKey, source, m_netgroupman); int nUBucketPos = pinfo->GetBucketPosition(nKey, true, nUBucket); bool fInsert = vvNew[nUBucket][nUBucketPos] == -1; if (vvNew[nUBucket][nUBucketPos] != nId) { if (!fInsert) { AddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]]; if (infoExisting.IsTerrible() || (infoExisting.nRefCount > 1 && pinfo->nRefCount == 0)) { // Overwrite the existing new table entry. fInsert = true; } } if (fInsert) { ClearNew(nUBucket, nUBucketPos); pinfo->nRefCount++; vvNew[nUBucket][nUBucketPos] = nId; const auto mapped_as{m_netgroupman.GetMappedAS(addr)}; LogPrint(BCLog::ADDRMAN, "Added %s%s to new[%i][%i]\n", addr.ToStringAddrPort(), (mapped_as ? strprintf(" mapped to AS%i", mapped_as) : ""), nUBucket, nUBucketPos); } else { if (pinfo->nRefCount == 0) { Delete(nId); } } } return fInsert; } bool AddrManImpl::Good_(const CService& addr, bool test_before_evict, NodeSeconds time) { AssertLockHeld(cs); int nId; m_last_good = time; AddrInfo* pinfo = Find(addr, &nId); // if not found, bail out if (!pinfo) return false; AddrInfo& info = *pinfo; // update info info.m_last_success = time; info.m_last_try = time; info.nAttempts = 0; // nTime is not updated here, to avoid leaking information about // currently-connected peers. // if it is already in the tried set, don't do anything else if (info.fInTried) return false; // if it is not in new, something bad happened if (!Assume(info.nRefCount > 0)) return false; // which tried bucket to move the entry to int tried_bucket = info.GetTriedBucket(nKey, m_netgroupman); int tried_bucket_pos = info.GetBucketPosition(nKey, false, tried_bucket); // Will moving this address into tried evict another entry? if (test_before_evict && (vvTried[tried_bucket][tried_bucket_pos] != -1)) { if (m_tried_collisions.size() < ADDRMAN_SET_TRIED_COLLISION_SIZE) { m_tried_collisions.insert(nId); } // Output the entry we'd be colliding with, for debugging purposes auto colliding_entry = mapInfo.find(vvTried[tried_bucket][tried_bucket_pos]); LogPrint(BCLog::ADDRMAN, "Collision with %s while attempting to move %s to tried table. Collisions=%d\n", colliding_entry != mapInfo.end() ? colliding_entry->second.ToStringAddrPort() : "", addr.ToStringAddrPort(), m_tried_collisions.size()); return false; } else { // move nId to the tried tables MakeTried(info, nId); const auto mapped_as{m_netgroupman.GetMappedAS(addr)}; LogPrint(BCLog::ADDRMAN, "Moved %s%s to tried[%i][%i]\n", addr.ToStringAddrPort(), (mapped_as ? strprintf(" mapped to AS%i", mapped_as) : ""), tried_bucket, tried_bucket_pos); return true; } } bool AddrManImpl::Add_(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty) { int added{0}; for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++) { added += AddSingle(*it, source, time_penalty) ? 1 : 0; } if (added > 0) { LogPrint(BCLog::ADDRMAN, "Added %i addresses (of %i) from %s: %i tried, %i new\n", added, vAddr.size(), source.ToStringAddr(), nTried, nNew); } return added > 0; } void AddrManImpl::Attempt_(const CService& addr, bool fCountFailure, NodeSeconds time) { AssertLockHeld(cs); AddrInfo* pinfo = Find(addr); // if not found, bail out if (!pinfo) return; AddrInfo& info = *pinfo; // update info info.m_last_try = time; if (fCountFailure && info.m_last_count_attempt < m_last_good) { info.m_last_count_attempt = time; info.nAttempts++; } } std::pair<CAddress, NodeSeconds> AddrManImpl::Select_(bool new_only, std::optional<Network> network) const { AssertLockHeld(cs); if (vRandom.empty()) return {}; size_t new_count = nNew; size_t tried_count = nTried; if (network.has_value()) { auto it = m_network_counts.find(*network); if (it == m_network_counts.end()) return {}; auto counts = it->second; new_count = counts.n_new; tried_count = counts.n_tried; } if (new_only && new_count == 0) return {}; if (new_count + tried_count == 0) return {}; // Decide if we are going to search the new or tried table // If either option is viable, use a 50% chance to choose bool search_tried; if (new_only || tried_count == 0) { search_tried = false; } else if (new_count == 0) { search_tried = true; } else { search_tried = insecure_rand.randbool(); } const int bucket_count{search_tried ? ADDRMAN_TRIED_BUCKET_COUNT : ADDRMAN_NEW_BUCKET_COUNT}; // Loop through the addrman table until we find an appropriate entry double chance_factor = 1.0; while (1) { // Pick a bucket, and an initial position in that bucket. int bucket = insecure_rand.randrange(bucket_count); int initial_position = insecure_rand.randrange(ADDRMAN_BUCKET_SIZE); // Iterate over the positions of that bucket, starting at the initial one, // and looping around. int i, position, node_id; for (i = 0; i < ADDRMAN_BUCKET_SIZE; ++i) { position = (initial_position + i) % ADDRMAN_BUCKET_SIZE; node_id = GetEntry(search_tried, bucket, position); if (node_id != -1) { if (network.has_value()) { const auto it{mapInfo.find(node_id)}; if (Assume(it != mapInfo.end()) && it->second.GetNetwork() == *network) break; } else { break; } } } // If the bucket is entirely empty, start over with a (likely) different one. if (i == ADDRMAN_BUCKET_SIZE) continue; // Find the entry to return. const auto it_found{mapInfo.find(node_id)}; assert(it_found != mapInfo.end()); const AddrInfo& info{it_found->second}; // With probability GetChance() * chance_factor, return the entry. if (insecure_rand.randbits(30) < chance_factor * info.GetChance() * (1 << 30)) { LogPrint(BCLog::ADDRMAN, "Selected %s from %s\n", info.ToStringAddrPort(), search_tried ? "tried" : "new"); return {info, info.m_last_try}; } // Otherwise start over with a (likely) different bucket, and increased chance factor. chance_factor *= 1.2; } } int AddrManImpl::GetEntry(bool use_tried, size_t bucket, size_t position) const { AssertLockHeld(cs); if (use_tried) { if (Assume(position < ADDRMAN_BUCKET_SIZE) && Assume(bucket < ADDRMAN_TRIED_BUCKET_COUNT)) { return vvTried[bucket][position]; } } else { if (Assume(position < ADDRMAN_BUCKET_SIZE) && Assume(bucket < ADDRMAN_NEW_BUCKET_COUNT)) { return vvNew[bucket][position]; } } return -1; } std::vector<CAddress> AddrManImpl::GetAddr_(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const { AssertLockHeld(cs); size_t nNodes = vRandom.size(); if (max_pct != 0) { nNodes = max_pct * nNodes / 100; } if (max_addresses != 0) { nNodes = std::min(nNodes, max_addresses); } // gather a list of random nodes, skipping those of low quality const auto now{Now<NodeSeconds>()}; std::vector<CAddress> addresses; for (unsigned int n = 0; n < vRandom.size(); n++) { if (addresses.size() >= nNodes) break; int nRndPos = insecure_rand.randrange(vRandom.size() - n) + n; SwapRandom(n, nRndPos); const auto it{mapInfo.find(vRandom[n])}; assert(it != mapInfo.end()); const AddrInfo& ai{it->second}; // Filter by network (optional) if (network != std::nullopt && ai.GetNetClass() != network) continue; // Filter for quality if (ai.IsTerrible(now) && filtered) continue; addresses.push_back(ai); } LogPrint(BCLog::ADDRMAN, "GetAddr returned %d random addresses\n", addresses.size()); return addresses; } std::vector<std::pair<AddrInfo, AddressPosition>> AddrManImpl::GetEntries_(bool from_tried) const { AssertLockHeld(cs); const int bucket_count = from_tried ? ADDRMAN_TRIED_BUCKET_COUNT : ADDRMAN_NEW_BUCKET_COUNT; std::vector<std::pair<AddrInfo, AddressPosition>> infos; for (int bucket = 0; bucket < bucket_count; ++bucket) { for (int position = 0; position < ADDRMAN_BUCKET_SIZE; ++position) { int id = GetEntry(from_tried, bucket, position); if (id >= 0) { AddrInfo info = mapInfo.at(id); AddressPosition location = AddressPosition( from_tried, /*multiplicity_in=*/from_tried ? 1 : info.nRefCount, bucket, position); infos.emplace_back(info, location); } } } return infos; } void AddrManImpl::Connected_(const CService& addr, NodeSeconds time) { AssertLockHeld(cs); AddrInfo* pinfo = Find(addr); // if not found, bail out if (!pinfo) return; AddrInfo& info = *pinfo; // update info const auto update_interval{20min}; if (time - info.nTime > update_interval) { info.nTime = time; } } void AddrManImpl::SetServices_(const CService& addr, ServiceFlags nServices) { AssertLockHeld(cs); AddrInfo* pinfo = Find(addr); // if not found, bail out if (!pinfo) return; AddrInfo& info = *pinfo; // update info info.nServices = nServices; } void AddrManImpl::ResolveCollisions_() { AssertLockHeld(cs); for (std::set<int>::iterator it = m_tried_collisions.begin(); it != m_tried_collisions.end();) { int id_new = *it; bool erase_collision = false; // If id_new not found in mapInfo remove it from m_tried_collisions if (mapInfo.count(id_new) != 1) { erase_collision = true; } else { AddrInfo& info_new = mapInfo[id_new]; // Which tried bucket to move the entry to. int tried_bucket = info_new.GetTriedBucket(nKey, m_netgroupman); int tried_bucket_pos = info_new.GetBucketPosition(nKey, false, tried_bucket); if (!info_new.IsValid()) { // id_new may no longer map to a valid address erase_collision = true; } else if (vvTried[tried_bucket][tried_bucket_pos] != -1) { // The position in the tried bucket is not empty // Get the to-be-evicted address that is being tested int id_old = vvTried[tried_bucket][tried_bucket_pos]; AddrInfo& info_old = mapInfo[id_old]; const auto current_time{Now<NodeSeconds>()}; // Has successfully connected in last X hours if (current_time - info_old.m_last_success < ADDRMAN_REPLACEMENT) { erase_collision = true; } else if (current_time - info_old.m_last_try < ADDRMAN_REPLACEMENT) { // attempted to connect and failed in last X hours // Give address at least 60 seconds to successfully connect if (current_time - info_old.m_last_try > 60s) { LogPrint(BCLog::ADDRMAN, "Replacing %s with %s in tried table\n", info_old.ToStringAddrPort(), info_new.ToStringAddrPort()); // Replaces an existing address already in the tried table with the new address Good_(info_new, false, current_time); erase_collision = true; } } else if (current_time - info_new.m_last_success > ADDRMAN_TEST_WINDOW) { // If the collision hasn't resolved in some reasonable amount of time, // just evict the old entry -- we must not be able to // connect to it for some reason. LogPrint(BCLog::ADDRMAN, "Unable to test; replacing %s with %s in tried table anyway\n", info_old.ToStringAddrPort(), info_new.ToStringAddrPort()); Good_(info_new, false, current_time); erase_collision = true; } } else { // Collision is not actually a collision anymore Good_(info_new, false, Now<NodeSeconds>()); erase_collision = true; } } if (erase_collision) { m_tried_collisions.erase(it++); } else { it++; } } } std::pair<CAddress, NodeSeconds> AddrManImpl::SelectTriedCollision_() { AssertLockHeld(cs); if (m_tried_collisions.size() == 0) return {}; std::set<int>::iterator it = m_tried_collisions.begin(); // Selects a random element from m_tried_collisions std::advance(it, insecure_rand.randrange(m_tried_collisions.size())); int id_new = *it; // If id_new not found in mapInfo remove it from m_tried_collisions if (mapInfo.count(id_new) != 1) { m_tried_collisions.erase(it); return {}; } const AddrInfo& newInfo = mapInfo[id_new]; // which tried bucket to move the entry to int tried_bucket = newInfo.GetTriedBucket(nKey, m_netgroupman); int tried_bucket_pos = newInfo.GetBucketPosition(nKey, false, tried_bucket); const AddrInfo& info_old = mapInfo[vvTried[tried_bucket][tried_bucket_pos]]; return {info_old, info_old.m_last_try}; } std::optional<AddressPosition> AddrManImpl::FindAddressEntry_(const CAddress& addr) { AssertLockHeld(cs); AddrInfo* addr_info = Find(addr); if (!addr_info) return std::nullopt; if(addr_info->fInTried) { int bucket{addr_info->GetTriedBucket(nKey, m_netgroupman)}; return AddressPosition(/*tried_in=*/true, /*multiplicity_in=*/1, /*bucket_in=*/bucket, /*position_in=*/addr_info->GetBucketPosition(nKey, false, bucket)); } else { int bucket{addr_info->GetNewBucket(nKey, m_netgroupman)}; return AddressPosition(/*tried_in=*/false, /*multiplicity_in=*/addr_info->nRefCount, /*bucket_in=*/bucket, /*position_in=*/addr_info->GetBucketPosition(nKey, true, bucket)); } } size_t AddrManImpl::Size_(std::optional<Network> net, std::optional<bool> in_new) const { AssertLockHeld(cs); if (!net.has_value()) { if (in_new.has_value()) { return *in_new ? nNew : nTried; } else { return vRandom.size(); } } if (auto it = m_network_counts.find(*net); it != m_network_counts.end()) { auto net_count = it->second; if (in_new.has_value()) { return *in_new ? net_count.n_new : net_count.n_tried; } else { return net_count.n_new + net_count.n_tried; } } return 0; } void AddrManImpl::Check() const { AssertLockHeld(cs); // Run consistency checks 1 in m_consistency_check_ratio times if enabled if (m_consistency_check_ratio == 0) return; if (insecure_rand.randrange(m_consistency_check_ratio) >= 1) return; const int err{CheckAddrman()}; if (err) { LogPrintf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err); assert(false); } } int AddrManImpl::CheckAddrman() const { AssertLockHeld(cs); LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE( strprintf("new %i, tried %i, total %u", nNew, nTried, vRandom.size()), BCLog::ADDRMAN); std::unordered_set<int> setTried; std::unordered_map<int, int> mapNew; std::unordered_map<Network, NewTriedCount> local_counts; if (vRandom.size() != (size_t)(nTried + nNew)) return -7; for (const auto& entry : mapInfo) { int n = entry.first; const AddrInfo& info = entry.second; if (info.fInTried) { if (!TicksSinceEpoch<std::chrono::seconds>(info.m_last_success)) { return -1; } if (info.nRefCount) return -2; setTried.insert(n); local_counts[info.GetNetwork()].n_tried++; } else { if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return -3; if (!info.nRefCount) return -4; mapNew[n] = info.nRefCount; local_counts[info.GetNetwork()].n_new++; } const auto it{mapAddr.find(info)}; if (it == mapAddr.end() || it->second != n) { return -5; } if (info.nRandomPos < 0 || (size_t)info.nRandomPos >= vRandom.size() || vRandom[info.nRandomPos] != n) return -14; if (info.m_last_try < NodeSeconds{0s}) { return -6; } if (info.m_last_success < NodeSeconds{0s}) { return -8; } } if (setTried.size() != (size_t)nTried) return -9; if (mapNew.size() != (size_t)nNew) return -10; for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) { for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvTried[n][i] != -1) { if (!setTried.count(vvTried[n][i])) return -11; const auto it{mapInfo.find(vvTried[n][i])}; if (it == mapInfo.end() || it->second.GetTriedBucket(nKey, m_netgroupman) != n) { return -17; } if (it->second.GetBucketPosition(nKey, false, n) != i) { return -18; } setTried.erase(vvTried[n][i]); } } } for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) { for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvNew[n][i] != -1) { if (!mapNew.count(vvNew[n][i])) return -12; const auto it{mapInfo.find(vvNew[n][i])}; if (it == mapInfo.end() || it->second.GetBucketPosition(nKey, true, n) != i) { return -19; } if (--mapNew[vvNew[n][i]] == 0) mapNew.erase(vvNew[n][i]); } } } if (setTried.size()) return -13; if (mapNew.size()) return -15; if (nKey.IsNull()) return -16; // It's possible that m_network_counts may have all-zero entries that local_counts // doesn't have if addrs from a network were being added and then removed again in the past. if (m_network_counts.size() < local_counts.size()) { return -20; } for (const auto& [net, count] : m_network_counts) { if (local_counts[net].n_new != count.n_new || local_counts[net].n_tried != count.n_tried) { return -21; } } return 0; } size_t AddrManImpl::Size(std::optional<Network> net, std::optional<bool> in_new) const { LOCK(cs); Check(); auto ret = Size_(net, in_new); Check(); return ret; } bool AddrManImpl::Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty) { LOCK(cs); Check(); auto ret = Add_(vAddr, source, time_penalty); Check(); return ret; } bool AddrManImpl::Good(const CService& addr, NodeSeconds time) { LOCK(cs); Check(); auto ret = Good_(addr, /*test_before_evict=*/true, time); Check(); return ret; } void AddrManImpl::Attempt(const CService& addr, bool fCountFailure, NodeSeconds time) { LOCK(cs); Check(); Attempt_(addr, fCountFailure, time); Check(); } void AddrManImpl::ResolveCollisions() { LOCK(cs); Check(); ResolveCollisions_(); Check(); } std::pair<CAddress, NodeSeconds> AddrManImpl::SelectTriedCollision() { LOCK(cs); Check(); auto ret = SelectTriedCollision_(); Check(); return ret; } std::pair<CAddress, NodeSeconds> AddrManImpl::Select(bool new_only, std::optional<Network> network) const { LOCK(cs); Check(); auto addrRet = Select_(new_only, network); Check(); return addrRet; } std::vector<CAddress> AddrManImpl::GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const { LOCK(cs); Check(); auto addresses = GetAddr_(max_addresses, max_pct, network, filtered); Check(); return addresses; } std::vector<std::pair<AddrInfo, AddressPosition>> AddrManImpl::GetEntries(bool from_tried) const { LOCK(cs); Check(); auto addrInfos = GetEntries_(from_tried); Check(); return addrInfos; } void AddrManImpl::Connected(const CService& addr, NodeSeconds time) { LOCK(cs); Check(); Connected_(addr, time); Check(); } void AddrManImpl::SetServices(const CService& addr, ServiceFlags nServices) { LOCK(cs); Check(); SetServices_(addr, nServices); Check(); } std::optional<AddressPosition> AddrManImpl::FindAddressEntry(const CAddress& addr) { LOCK(cs); Check(); auto entry = FindAddressEntry_(addr); Check(); return entry; } AddrMan::AddrMan(const NetGroupManager& netgroupman, bool deterministic, int32_t consistency_check_ratio) : m_impl(std::make_unique<AddrManImpl>(netgroupman, deterministic, consistency_check_ratio)) {} AddrMan::~AddrMan() = default; template <typename Stream> void AddrMan::Serialize(Stream& s_) const { m_impl->Serialize<Stream>(s_); } template <typename Stream> void AddrMan::Unserialize(Stream& s_) { m_impl->Unserialize<Stream>(s_); } // explicit instantiation template void AddrMan::Serialize(HashedSourceWriter<AutoFile>&) const; template void AddrMan::Serialize(DataStream&) const; template void AddrMan::Unserialize(AutoFile&); template void AddrMan::Unserialize(HashVerifier<AutoFile>&); template void AddrMan::Unserialize(DataStream&); template void AddrMan::Unserialize(HashVerifier<DataStream>&); size_t AddrMan::Size(std::optional<Network> net, std::optional<bool> in_new) const { return m_impl->Size(net, in_new); } bool AddrMan::Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty) { return m_impl->Add(vAddr, source, time_penalty); } bool AddrMan::Good(const CService& addr, NodeSeconds time) { return m_impl->Good(addr, time); } void AddrMan::Attempt(const CService& addr, bool fCountFailure, NodeSeconds time) { m_impl->Attempt(addr, fCountFailure, time); } void AddrMan::ResolveCollisions() { m_impl->ResolveCollisions(); } std::pair<CAddress, NodeSeconds> AddrMan::SelectTriedCollision() { return m_impl->SelectTriedCollision(); } std::pair<CAddress, NodeSeconds> AddrMan::Select(bool new_only, std::optional<Network> network) const { return m_impl->Select(new_only, network); } std::vector<CAddress> AddrMan::GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const { return m_impl->GetAddr(max_addresses, max_pct, network, filtered); } std::vector<std::pair<AddrInfo, AddressPosition>> AddrMan::GetEntries(bool use_tried) const { return m_impl->GetEntries(use_tried); } void AddrMan::Connected(const CService& addr, NodeSeconds time) { m_impl->Connected(addr, time); } void AddrMan::SetServices(const CService& addr, ServiceFlags nServices) { m_impl->SetServices(addr, nServices); } std::optional<AddressPosition> AddrMan::FindAddressEntry(const CAddress& addr) { return m_impl->FindAddressEntry(addr); }
0
bitcoin
bitcoin/src/txmempool.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TXMEMPOOL_H #define BITCOIN_TXMEMPOOL_H #include <coins.h> #include <consensus/amount.h> #include <indirectmap.h> #include <kernel/cs_main.h> #include <kernel/mempool_entry.h> // IWYU pragma: export #include <kernel/mempool_limits.h> // IWYU pragma: export #include <kernel/mempool_options.h> // IWYU pragma: export #include <kernel/mempool_removal_reason.h> // IWYU pragma: export #include <policy/feerate.h> #include <policy/packages.h> #include <primitives/transaction.h> #include <sync.h> #include <util/epochguard.h> #include <util/hasher.h> #include <util/result.h> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/identity.hpp> #include <boost/multi_index/indexed_by.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/multi_index/tag.hpp> #include <boost/multi_index_container.hpp> #include <atomic> #include <map> #include <optional> #include <set> #include <string> #include <string_view> #include <utility> #include <vector> class CChain; /** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */ static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF; /** * Test whether the LockPoints height and time are still valid on the current chain */ bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main); // extracts a transaction hash from CTxMemPoolEntry or CTransactionRef struct mempoolentry_txid { typedef uint256 result_type; result_type operator() (const CTxMemPoolEntry &entry) const { return entry.GetTx().GetHash(); } result_type operator() (const CTransactionRef& tx) const { return tx->GetHash(); } }; // extracts a transaction witness-hash from CTxMemPoolEntry or CTransactionRef struct mempoolentry_wtxid { typedef uint256 result_type; result_type operator() (const CTxMemPoolEntry &entry) const { return entry.GetTx().GetWitnessHash(); } result_type operator() (const CTransactionRef& tx) const { return tx->GetWitnessHash(); } }; /** \class CompareTxMemPoolEntryByDescendantScore * * Sort an entry by max(score/size of entry's tx, score/size with all descendants). */ class CompareTxMemPoolEntryByDescendantScore { public: bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const { double a_mod_fee, a_size, b_mod_fee, b_size; GetModFeeAndSize(a, a_mod_fee, a_size); GetModFeeAndSize(b, b_mod_fee, b_size); // Avoid division by rewriting (a/b > c/d) as (a*d > c*b). double f1 = a_mod_fee * b_size; double f2 = a_size * b_mod_fee; if (f1 == f2) { return a.GetTime() >= b.GetTime(); } return f1 < f2; } // Return the fee/size we're using for sorting this entry. void GetModFeeAndSize(const CTxMemPoolEntry &a, double &mod_fee, double &size) const { // Compare feerate with descendants to feerate of the transaction, and // return the fee/size for the max. double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants(); double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize(); if (f2 > f1) { mod_fee = a.GetModFeesWithDescendants(); size = a.GetSizeWithDescendants(); } else { mod_fee = a.GetModifiedFee(); size = a.GetTxSize(); } } }; /** \class CompareTxMemPoolEntryByScore * * Sort by feerate of entry (fee/size) in descending order * This is only used for transaction relay, so we use GetFee() * instead of GetModifiedFee() to avoid leaking prioritization * information via the sort order. */ class CompareTxMemPoolEntryByScore { public: bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const { double f1 = (double)a.GetFee() * b.GetTxSize(); double f2 = (double)b.GetFee() * a.GetTxSize(); if (f1 == f2) { return b.GetTx().GetHash() < a.GetTx().GetHash(); } return f1 > f2; } }; class CompareTxMemPoolEntryByEntryTime { public: bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const { return a.GetTime() < b.GetTime(); } }; /** \class CompareTxMemPoolEntryByAncestorScore * * Sort an entry by min(score/size of entry's tx, score/size with all ancestors). */ class CompareTxMemPoolEntryByAncestorFee { public: template<typename T> bool operator()(const T& a, const T& b) const { double a_mod_fee, a_size, b_mod_fee, b_size; GetModFeeAndSize(a, a_mod_fee, a_size); GetModFeeAndSize(b, b_mod_fee, b_size); // Avoid division by rewriting (a/b > c/d) as (a*d > c*b). double f1 = a_mod_fee * b_size; double f2 = a_size * b_mod_fee; if (f1 == f2) { return a.GetTx().GetHash() < b.GetTx().GetHash(); } return f1 > f2; } // Return the fee/size we're using for sorting this entry. template <typename T> void GetModFeeAndSize(const T &a, double &mod_fee, double &size) const { // Compare feerate with ancestors to feerate of the transaction, and // return the fee/size for the min. double f1 = (double)a.GetModifiedFee() * a.GetSizeWithAncestors(); double f2 = (double)a.GetModFeesWithAncestors() * a.GetTxSize(); if (f1 > f2) { mod_fee = a.GetModFeesWithAncestors(); size = a.GetSizeWithAncestors(); } else { mod_fee = a.GetModifiedFee(); size = a.GetTxSize(); } } }; // Multi_index tag names struct descendant_score {}; struct entry_time {}; struct ancestor_score {}; struct index_by_wtxid {}; /** * Information about a mempool transaction. */ struct TxMempoolInfo { /** The transaction itself */ CTransactionRef tx; /** Time the transaction entered the mempool. */ std::chrono::seconds m_time; /** Fee of the transaction. */ CAmount fee; /** Virtual size of the transaction. */ int32_t vsize; /** The fee delta. */ int64_t nFeeDelta; }; /** * CTxMemPool stores valid-according-to-the-current-best-chain transactions * that may be included in the next block. * * Transactions are added when they are seen on the network (or created by the * local node), but not all transactions seen are added to the pool. For * example, the following new transactions will not be added to the mempool: * - a transaction which doesn't meet the minimum fee requirements. * - a new transaction that double-spends an input of a transaction already in * the pool where the new transaction does not meet the Replace-By-Fee * requirements as defined in doc/policy/mempool-replacements.md. * - a non-standard transaction. * * CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping: * * mapTx is a boost::multi_index that sorts the mempool on 5 criteria: * - transaction hash (txid) * - witness-transaction hash (wtxid) * - descendant feerate [we use max(feerate of tx, feerate of tx with all descendants)] * - time in mempool * - ancestor feerate [we use min(feerate of tx, feerate of tx with all unconfirmed ancestors)] * * Note: the term "descendant" refers to in-mempool transactions that depend on * this one, while "ancestor" refers to in-mempool transactions that a given * transaction depends on. * * In order for the feerate sort to remain correct, we must update transactions * in the mempool when new descendants arrive. To facilitate this, we track * the set of in-mempool direct parents and direct children in mapLinks. Within * each CTxMemPoolEntry, we track the size and fees of all descendants. * * Usually when a new transaction is added to the mempool, it has no in-mempool * children (because any such children would be an orphan). So in * addUnchecked(), we: * - update a new entry's setMemPoolParents to include all in-mempool parents * - update the new entry's direct parents to include the new tx as a child * - update all ancestors of the transaction to include the new tx's size/fee * * When a transaction is removed from the mempool, we must: * - update all in-mempool parents to not track the tx in setMemPoolChildren * - update all ancestors to not include the tx's size/fees in descendant state * - update all in-mempool children to not include it as a parent * * These happen in UpdateForRemoveFromMempool(). (Note that when removing a * transaction along with its descendants, we must calculate that set of * transactions to be removed before doing the removal, or else the mempool can * be in an inconsistent state where it's impossible to walk the ancestors of * a transaction.) * * In the event of a reorg, the assumption that a newly added tx has no * in-mempool children is false. In particular, the mempool is in an * inconsistent state while new transactions are being added, because there may * be descendant transactions of a tx coming from a disconnected block that are * unreachable from just looking at transactions in the mempool (the linking * transactions may also be in the disconnected block, waiting to be added). * Because of this, there's not much benefit in trying to search for in-mempool * children in addUnchecked(). Instead, in the special case of transactions * being added from a disconnected block, we require the caller to clean up the * state, to account for in-mempool, out-of-block descendants for all the * in-block transactions by calling UpdateTransactionsFromBlock(). Note that * until this is called, the mempool state is not consistent, and in particular * mapLinks may not be correct (and therefore functions like * CalculateMemPoolAncestors() and CalculateDescendants() that rely * on them to walk the mempool are not generally safe to use). * * Computational limits: * * Updating all in-mempool ancestors of a newly added transaction can be slow, * if no bound exists on how many in-mempool ancestors there may be. * CalculateMemPoolAncestors() takes configurable limits that are designed to * prevent these calculations from being too CPU intensive. * */ class CTxMemPool { protected: const int m_check_ratio; //!< Value n means that 1 times in n we check. std::atomic<unsigned int> nTransactionsUpdated{0}; //!< Used by getblocktemplate to trigger CreateNewBlock() invocation uint64_t totalTxSize GUARDED_BY(cs){0}; //!< sum of all mempool tx's virtual sizes. Differs from serialized tx size since witness data is discounted. Defined in BIP 141. CAmount m_total_fee GUARDED_BY(cs){0}; //!< sum of all mempool tx's fees (NOT modified fee) uint64_t cachedInnerUsage GUARDED_BY(cs){0}; //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves) mutable int64_t lastRollingFeeUpdate GUARDED_BY(cs){GetTime()}; mutable bool blockSinceLastRollingFeeBump GUARDED_BY(cs){false}; mutable double rollingMinimumFeeRate GUARDED_BY(cs){0}; //!< minimum fee to get into the pool, decreases exponentially mutable Epoch m_epoch GUARDED_BY(cs){}; // In-memory counter for external mempool tracking purposes. // This number is incremented once every time a transaction // is added or removed from the mempool for any reason. mutable uint64_t m_sequence_number GUARDED_BY(cs){1}; void trackPackageRemoved(const CFeeRate& rate) EXCLUSIVE_LOCKS_REQUIRED(cs); bool m_load_tried GUARDED_BY(cs){false}; CFeeRate GetMinFee(size_t sizelimit) const; public: static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing typedef boost::multi_index_container< CTxMemPoolEntry, boost::multi_index::indexed_by< // sorted by txid boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>, // sorted by wtxid boost::multi_index::hashed_unique< boost::multi_index::tag<index_by_wtxid>, mempoolentry_wtxid, SaltedTxidHasher >, // sorted by fee rate boost::multi_index::ordered_non_unique< boost::multi_index::tag<descendant_score>, boost::multi_index::identity<CTxMemPoolEntry>, CompareTxMemPoolEntryByDescendantScore >, // sorted by entry time boost::multi_index::ordered_non_unique< boost::multi_index::tag<entry_time>, boost::multi_index::identity<CTxMemPoolEntry>, CompareTxMemPoolEntryByEntryTime >, // sorted by fee rate with ancestors boost::multi_index::ordered_non_unique< boost::multi_index::tag<ancestor_score>, boost::multi_index::identity<CTxMemPoolEntry>, CompareTxMemPoolEntryByAncestorFee > > > indexed_transaction_set; /** * This mutex needs to be locked when accessing `mapTx` or other members * that are guarded by it. * * @par Consistency guarantees * * By design, it is guaranteed that: * * 1. Locking both `cs_main` and `mempool.cs` will give a view of mempool * that is consistent with current chain tip (`ActiveChain()` and * `CoinsTip()`) and is fully populated. Fully populated means that if the * current active chain is missing transactions that were present in a * previously active chain, all the missing transactions will have been * re-added to the mempool and should be present if they meet size and * consistency constraints. * * 2. Locking `mempool.cs` without `cs_main` will give a view of a mempool * consistent with some chain that was active since `cs_main` was last * locked, and that is fully populated as described above. It is ok for * code that only needs to query or remove transactions from the mempool * to lock just `mempool.cs` without `cs_main`. * * To provide these guarantees, it is necessary to lock both `cs_main` and * `mempool.cs` whenever adding transactions to the mempool and whenever * changing the chain tip. It's necessary to keep both mutexes locked until * the mempool is consistent with the new chain tip and fully populated. */ mutable RecursiveMutex cs; indexed_transaction_set mapTx GUARDED_BY(cs); using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator; std::vector<CTransactionRef> txns_randomized GUARDED_BY(cs); //!< All transactions in mapTx, in random order typedef std::set<txiter, CompareIteratorByHash> setEntries; using Limits = kernel::MemPoolLimits; uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs); private: typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap; void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs); void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs); std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs); /** * Track locally submitted transactions to periodically retry initial broadcast. */ std::set<uint256> m_unbroadcast_txids GUARDED_BY(cs); /** * Helper function to calculate all in-mempool ancestors of staged_ancestors and apply ancestor * and descendant limits (including staged_ancestors themselves, entry_size and entry_count). * * @param[in] entry_size Virtual size to include in the limits. * @param[in] entry_count How many entries to include in the limits. * @param[in] staged_ancestors Should contain entries in the mempool. * @param[in] limits Maximum number and size of ancestors and descendants * * @return all in-mempool ancestors, or an error if any ancestor or descendant limits were hit */ util::Result<setEntries> CalculateAncestorsAndCheckLimits(int64_t entry_size, size_t entry_count, CTxMemPoolEntry::Parents &staged_ancestors, const Limits& limits ) const EXCLUSIVE_LOCKS_REQUIRED(cs); public: indirectmap<COutPoint, const CTransaction*> mapNextTx GUARDED_BY(cs); std::map<uint256, CAmount> mapDeltas GUARDED_BY(cs); using Options = kernel::MemPoolOptions; const int64_t m_max_size_bytes; const std::chrono::seconds m_expiry; const CFeeRate m_incremental_relay_feerate; const CFeeRate m_min_relay_feerate; const CFeeRate m_dust_relay_feerate; const bool m_permit_bare_multisig; const std::optional<unsigned> m_max_datacarrier_bytes; const bool m_require_standard; const bool m_full_rbf; const bool m_persist_v1_dat; const Limits m_limits; /** Create a new CTxMemPool. * Sanity checks will be off by default for performance, because otherwise * accepting transactions becomes O(N^2) where N is the number of transactions * in the pool. */ explicit CTxMemPool(const Options& opts); /** * If sanity-checking is turned on, check makes sure the pool is * consistent (does not contain two transactions that spend the same inputs, * all inputs are in the mapNextTx array). If sanity-checking is turned off, * check does nothing. */ void check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main); // addUnchecked must updated state for all ancestors of a given transaction, // to track size/count of descendant transactions. First version of // addUnchecked can be used to have it call CalculateMemPoolAncestors(), and // then invoke the second version. // Note that addUnchecked is ONLY called from ATMP outside of tests // and any other callers may break wallet's in-mempool tracking (due to // lack of CValidationInterface::TransactionAddedToMempool callbacks). void addUnchecked(const CTxMemPoolEntry& entry) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main); void addUnchecked(const CTxMemPoolEntry& entry, setEntries& setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main); void removeRecursive(const CTransaction& tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs); /** After reorg, filter the entries that would no longer be valid in the next block, and update * the entries' cached LockPoints if needed. The mempool does not have any knowledge of * consensus rules. It just applies the callable function and removes the ones for which it * returns true. * @param[in] filter_final_and_mature Predicate that checks the relevant validation rules * and updates an entry's LockPoints. * */ void removeForReorg(CChain& chain, std::function<bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main); void removeConflicts(const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(cs); void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs); bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb, bool wtxid=false); void queryHashes(std::vector<uint256>& vtxid) const; bool isSpent(const COutPoint& outpoint) const; unsigned int GetTransactionsUpdated() const; void AddTransactionsUpdated(unsigned int n); /** * Check that none of this transactions inputs are in the mempool, and thus * the tx is not dependent on other mempool transactions to be included in a block. */ bool HasNoInputsOf(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs); /** Affect CreateNewBlock prioritisation of transactions */ void PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta); void ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs); void ClearPrioritisation(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs); struct delta_info { /** Whether this transaction is in the mempool. */ const bool in_mempool; /** The fee delta added using PrioritiseTransaction(). */ const CAmount delta; /** The modified fee (base fee + delta) of this entry. Only present if in_mempool=true. */ std::optional<CAmount> modified_fee; /** The prioritised transaction's txid. */ const uint256 txid; }; /** Return a vector of all entries in mapDeltas with their corresponding delta_info. */ std::vector<delta_info> GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs); /** Get the transaction in the pool that spends the same prevout */ const CTransaction* GetConflictTx(const COutPoint& prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs); /** Returns an iterator to the given hash, if found */ std::optional<txiter> GetIter(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs); /** Translate a set of hashes into a set of pool iterators to avoid repeated lookups. * Does not require that all of the hashes correspond to actual transactions in the mempool, * only returns the ones that exist. */ setEntries GetIterSet(const std::set<uint256>& hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs); /** Translate a list of hashes into a list of mempool iterators to avoid repeated lookups. * The nth element in txids becomes the nth element in the returned vector. If any of the txids * don't actually exist in the mempool, returns an empty vector. */ std::vector<txiter> GetIterVec(const std::vector<uint256>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs); /** Remove a set of transactions from the mempool. * If a transaction is in this set, then all in-mempool descendants must * also be in the set, unless this transaction is being removed for being * in a block. * Set updateDescendants to true when removing a tx that was in a block, so * that any in-mempool descendants have their ancestor state updated. */ void RemoveStaged(setEntries& stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs); /** UpdateTransactionsFromBlock is called when adding transactions from a * disconnected block back to the mempool, new mempool entries may have * children in the mempool (which is generally not the case when otherwise * adding transactions). * @post updated descendant state for descendants of each transaction in * vHashesToUpdate (excluding any child transactions present in * vHashesToUpdate, which are already accounted for). Updated state * includes add fee/size information for such descendants to the * parent and updated ancestor state to include the parent. * * @param[in] vHashesToUpdate The set of txids from the * disconnected block that have been accepted back into the mempool. */ void UpdateTransactionsFromBlock(const std::vector<uint256>& vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main) LOCKS_EXCLUDED(m_epoch); /** * Try to calculate all in-mempool ancestors of entry. * (these are all calculated including the tx itself) * * @param[in] entry CTxMemPoolEntry of which all in-mempool ancestors are calculated * @param[in] limits Maximum number and size of ancestors and descendants * @param[in] fSearchForParents Whether to search a tx's vin for in-mempool parents, or look * up parents from mapLinks. Must be true for entries not in * the mempool * * @return all in-mempool ancestors, or an error if any ancestor or descendant limits were hit */ util::Result<setEntries> CalculateMemPoolAncestors(const CTxMemPoolEntry& entry, const Limits& limits, bool fSearchForParents = true) const EXCLUSIVE_LOCKS_REQUIRED(cs); /** * Same as CalculateMemPoolAncestors, but always returns a (non-optional) setEntries. * Should only be used when it is assumed CalculateMemPoolAncestors would not fail. If * CalculateMemPoolAncestors does unexpectedly fail, an empty setEntries is returned and the * error is logged to BCLog::MEMPOOL with level BCLog::Level::Error. In debug builds, failure * of CalculateMemPoolAncestors will lead to shutdown due to assertion failure. * * @param[in] calling_fn_name Name of calling function so we can properly log the call site * * @return a setEntries corresponding to the result of CalculateMemPoolAncestors or an empty * setEntries if it failed * * @see CTXMemPool::CalculateMemPoolAncestors() */ setEntries AssumeCalculateMemPoolAncestors( std::string_view calling_fn_name, const CTxMemPoolEntry &entry, const Limits& limits, bool fSearchForParents = true) const EXCLUSIVE_LOCKS_REQUIRED(cs); /** Collect the entire cluster of connected transactions for each transaction in txids. * All txids must correspond to transaction entries in the mempool, otherwise this returns an * empty vector. This call will also exit early and return an empty vector if it collects 500 or * more transactions as a DoS protection. */ std::vector<txiter> GatherClusters(const std::vector<uint256>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs); /** Calculate all in-mempool ancestors of a set of transactions not already in the mempool and * check ancestor and descendant limits. Heuristics are used to estimate the ancestor and * descendant count of all entries if the package were to be added to the mempool. The limits * are applied to the union of all package transactions. For example, if the package has 3 * transactions and limits.ancestor_count = 25, the union of all 3 sets of ancestors (including the * transactions themselves) must be <= 22. * @param[in] package Transaction package being evaluated for acceptance * to mempool. The transactions need not be direct * ancestors/descendants of each other. * @param[in] total_vsize Sum of virtual sizes for all transactions in package. * @returns {} or the error reason if a limit is hit. */ util::Result<void> CheckPackageLimits(const Package& package, int64_t total_vsize) const EXCLUSIVE_LOCKS_REQUIRED(cs); /** Populate setDescendants with all in-mempool descendants of hash. * Assumes that setDescendants includes all in-mempool descendants of anything * already in it. */ void CalculateDescendants(txiter it, setEntries& setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs); /** The minimum fee to get into the mempool, which may itself not be enough * for larger-sized transactions. * The m_incremental_relay_feerate policy variable is used to bound the time it * takes the fee rate to go back down all the way to 0. When the feerate * would otherwise be half of this, it is set to 0 instead. */ CFeeRate GetMinFee() const { return GetMinFee(m_max_size_bytes); } /** Remove transactions from the mempool until its dynamic size is <= sizelimit. * pvNoSpendsRemaining, if set, will be populated with the list of outpoints * which are not in mempool which no longer have any spends in this mempool. */ void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs); /** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */ int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs); /** * Calculate the ancestor and descendant count for the given transaction. * The counts include the transaction itself. * When ancestors is non-zero (ie, the transaction itself is in the mempool), * ancestorsize and ancestorfees will also be set to the appropriate values. */ void GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) const; /** * @returns true if an initial attempt to load the persisted mempool was made, regardless of * whether the attempt was successful or not */ bool GetLoadTried() const; /** * Set whether or not an initial attempt to load the persisted mempool was made (regardless * of whether the attempt was successful or not) */ void SetLoadTried(bool load_tried); unsigned long size() const { LOCK(cs); return mapTx.size(); } uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs) { AssertLockHeld(cs); return totalTxSize; } CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs) { AssertLockHeld(cs); return m_total_fee; } bool exists(const GenTxid& gtxid) const { LOCK(cs); if (gtxid.IsWtxid()) { return (mapTx.get<index_by_wtxid>().count(gtxid.GetHash()) != 0); } return (mapTx.count(gtxid.GetHash()) != 0); } const CTxMemPoolEntry* GetEntry(const Txid& txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs); CTransactionRef get(const uint256& hash) const; txiter get_iter_from_wtxid(const uint256& wtxid) const EXCLUSIVE_LOCKS_REQUIRED(cs) { AssertLockHeld(cs); return mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid)); } TxMempoolInfo info(const GenTxid& gtxid) const; /** Returns info for a transaction if its entry_sequence < last_sequence */ TxMempoolInfo info_for_relay(const GenTxid& gtxid, uint64_t last_sequence) const; std::vector<CTxMemPoolEntryRef> entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs); std::vector<TxMempoolInfo> infoAll() const; size_t DynamicMemoryUsage() const; /** Adds a transaction to the unbroadcast set */ void AddUnbroadcastTx(const uint256& txid) { LOCK(cs); // Sanity check the transaction is in the mempool & insert into // unbroadcast set. if (exists(GenTxid::Txid(txid))) m_unbroadcast_txids.insert(txid); }; /** Removes a transaction from the unbroadcast set */ void RemoveUnbroadcastTx(const uint256& txid, const bool unchecked = false); /** Returns transactions in unbroadcast set */ std::set<uint256> GetUnbroadcastTxs() const { LOCK(cs); return m_unbroadcast_txids; } /** Returns whether a txid is in the unbroadcast set */ bool IsUnbroadcastTx(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs) { AssertLockHeld(cs); return m_unbroadcast_txids.count(txid) != 0; } /** Guards this internal counter for external reporting */ uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) { return m_sequence_number++; } uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) { return m_sequence_number; } private: /** UpdateForDescendants is used by UpdateTransactionsFromBlock to update * the descendants for a single transaction that has been added to the * mempool but may have child transactions in the mempool, eg during a * chain reorg. * * @pre CTxMemPoolEntry::m_children is correct for the given tx and all * descendants. * @pre cachedDescendants is an accurate cache where each entry has all * descendants of the corresponding key, including those that should * be removed for violation of ancestor limits. * @post if updateIt has any non-excluded descendants, cachedDescendants has * a new cache line for updateIt. * @post descendants_to_remove has a new entry for any descendant which exceeded * ancestor limits relative to updateIt. * * @param[in] updateIt the entry to update for its descendants * @param[in,out] cachedDescendants a cache where each line corresponds to all * descendants. It will be updated with the descendants of the transaction * being updated, so that future invocations don't need to walk the same * transaction again, if encountered in another transaction chain. * @param[in] setExclude the set of descendant transactions in the mempool * that must not be accounted for (because any descendants in setExclude * were added to the mempool after the transaction being updated and hence * their state is already reflected in the parent state). * @param[out] descendants_to_remove Populated with the txids of entries that * exceed ancestor limits. It's the responsibility of the caller to * removeRecursive them. */ void UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants, const std::set<uint256>& setExclude, std::set<uint256>& descendants_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs); /** Update ancestors of hash to add/remove it as a descendant transaction. */ void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs); /** Set ancestor state for an entry */ void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs); /** For each transaction being removed, update ancestors and any direct children. * If updateDescendants is true, then also update in-mempool descendants' * ancestor state. */ void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants) EXCLUSIVE_LOCKS_REQUIRED(cs); /** Sever link between specified transaction and direct children. */ void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs); /** Before calling removeUnchecked for a given transaction, * UpdateForRemoveFromMempool must be called on the entire (dependent) set * of transactions being removed at the same time. We use each * CTxMemPoolEntry's setMemPoolParents in order to walk ancestors of a * given transaction that is removed, so we can't remove intermediate * transactions in a chain before we've updated all the state for the * removal. */ void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs); public: /** visited marks a CTxMemPoolEntry as having been traversed * during the lifetime of the most recently created Epoch::Guard * and returns false if we are the first visitor, true otherwise. * * An Epoch::Guard must be held when visited is called or an assert will be * triggered. * */ bool visited(const txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch) { return m_epoch.visited(it->m_epoch_marker); } bool visited(std::optional<txiter> it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch) { assert(m_epoch.guarded()); // verify guard even when it==nullopt return !it || visited(*it); } }; /** * 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 * base CCoinsView, are outputs from any mempool transaction, or are * tracked temporarily to allow transaction dependencies in package validation. * This allows transaction replacement to work as expected, as you want to * have all inputs "available" to check signatures, and any cycles in the * dependency graph are checked directly in AcceptToMemoryPool. * It also allows you to sign a double-spend directly in * signrawtransactionwithkey and signrawtransactionwithwallet, * as long as the conflicting transaction is not yet confirmed. */ class CCoinsViewMemPool : public CCoinsViewBacked { /** * Coins made available by transactions being validated. Tracking these allows for package * validation, since we can access transaction outputs without submitting them to mempool. */ std::unordered_map<COutPoint, Coin, SaltedOutpointHasher> m_temp_added; /** * Set of all coins that have been fetched from mempool or created using PackageAddTransaction * (not base). Used to track the origin of a coin, see GetNonBaseCoins(). */ mutable std::unordered_set<COutPoint, SaltedOutpointHasher> m_non_base_coins; protected: const CTxMemPool& mempool; public: CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn); /** GetCoin, returning whether it exists and is not spent. Also updates m_non_base_coins if the * coin is not fetched from base. */ bool GetCoin(const COutPoint &outpoint, Coin &coin) const override; /** Add the coins created by this transaction. These coins are only temporarily stored in * m_temp_added and cannot be flushed to the back end. Only used for package validation. */ void PackageAddTransaction(const CTransactionRef& tx); /** Get all coins in m_non_base_coins. */ std::unordered_set<COutPoint, SaltedOutpointHasher> GetNonBaseCoins() const { return m_non_base_coins; } /** Clear m_temp_added and m_non_base_coins. */ void Reset(); }; #endif // BITCOIN_TXMEMPOOL_H
0
bitcoin
bitcoin/src/hash.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_HASH_H #define BITCOIN_HASH_H #include <attributes.h> #include <crypto/common.h> #include <crypto/ripemd160.h> #include <crypto/sha256.h> #include <prevector.h> #include <serialize.h> #include <span.h> #include <uint256.h> #include <string> #include <vector> typedef uint256 ChainCode; /** A hasher class for Bitcoin's 256-bit hash (double SHA-256). */ class CHash256 { private: CSHA256 sha; public: static const size_t OUTPUT_SIZE = CSHA256::OUTPUT_SIZE; void Finalize(Span<unsigned char> output) { assert(output.size() == OUTPUT_SIZE); unsigned char buf[CSHA256::OUTPUT_SIZE]; sha.Finalize(buf); sha.Reset().Write(buf, CSHA256::OUTPUT_SIZE).Finalize(output.data()); } CHash256& Write(Span<const unsigned char> input) { sha.Write(input.data(), input.size()); return *this; } CHash256& Reset() { sha.Reset(); return *this; } }; /** A hasher class for Bitcoin's 160-bit hash (SHA-256 + RIPEMD-160). */ class CHash160 { private: CSHA256 sha; public: static const size_t OUTPUT_SIZE = CRIPEMD160::OUTPUT_SIZE; void Finalize(Span<unsigned char> output) { assert(output.size() == OUTPUT_SIZE); unsigned char buf[CSHA256::OUTPUT_SIZE]; sha.Finalize(buf); CRIPEMD160().Write(buf, CSHA256::OUTPUT_SIZE).Finalize(output.data()); } CHash160& Write(Span<const unsigned char> input) { sha.Write(input.data(), input.size()); return *this; } CHash160& Reset() { sha.Reset(); return *this; } }; /** Compute the 256-bit hash of an object. */ template<typename T> inline uint256 Hash(const T& in1) { uint256 result; CHash256().Write(MakeUCharSpan(in1)).Finalize(result); return result; } /** Compute the 256-bit hash of the concatenation of two objects. */ template<typename T1, typename T2> inline uint256 Hash(const T1& in1, const T2& in2) { uint256 result; CHash256().Write(MakeUCharSpan(in1)).Write(MakeUCharSpan(in2)).Finalize(result); return result; } /** Compute the 160-bit hash an object. */ template<typename T1> inline uint160 Hash160(const T1& in1) { uint160 result; CHash160().Write(MakeUCharSpan(in1)).Finalize(result); return result; } /** A writer stream (for serialization) that computes a 256-bit hash. */ class HashWriter { private: CSHA256 ctx; public: void write(Span<const std::byte> src) { ctx.Write(UCharCast(src.data()), src.size()); } /** Compute the double-SHA256 hash of all data written to this object. * * Invalidates this object. */ uint256 GetHash() { uint256 result; ctx.Finalize(result.begin()); ctx.Reset().Write(result.begin(), CSHA256::OUTPUT_SIZE).Finalize(result.begin()); return result; } /** Compute the SHA256 hash of all data written to this object. * * Invalidates this object. */ uint256 GetSHA256() { uint256 result; ctx.Finalize(result.begin()); return result; } /** * Returns the first 64 bits from the resulting hash. */ inline uint64_t GetCheapHash() { uint256 result = GetHash(); return ReadLE64(result.begin()); } template <typename T> HashWriter& operator<<(const T& obj) { ::Serialize(*this, obj); return *this; } }; /** Reads data from an underlying stream, while hashing the read data. */ template <typename Source> class HashVerifier : public HashWriter { private: Source& m_source; public: explicit HashVerifier(Source& source LIFETIMEBOUND) : m_source{source} {} void read(Span<std::byte> dst) { m_source.read(dst); this->write(dst); } void ignore(size_t num_bytes) { std::byte data[1024]; while (num_bytes > 0) { size_t now = std::min<size_t>(num_bytes, 1024); read({data, now}); num_bytes -= now; } } template <typename T> HashVerifier<Source>& operator>>(T&& obj) { ::Unserialize(*this, obj); return *this; } }; /** Writes data to an underlying source stream, while hashing the written data. */ template <typename Source> class HashedSourceWriter : public HashWriter { private: Source& m_source; public: explicit HashedSourceWriter(Source& source LIFETIMEBOUND) : HashWriter{}, m_source{source} {} void write(Span<const std::byte> src) { m_source.write(src); HashWriter::write(src); } template <typename T> HashedSourceWriter& operator<<(const T& obj) { ::Serialize(*this, obj); return *this; } }; /** Single-SHA256 a 32-byte input (represented as uint256). */ [[nodiscard]] uint256 SHA256Uint256(const uint256& input); unsigned int MurmurHash3(unsigned int nHashSeed, Span<const unsigned char> vDataToHash); void BIP32Hash(const ChainCode &chainCode, unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]); /** Return a HashWriter primed for tagged hashes (as specified in BIP 340). * * The returned object will have SHA256(tag) written to it twice (= 64 bytes). * A tagged hash can be computed by feeding the message into this object, and * then calling HashWriter::GetSHA256(). */ HashWriter TaggedHash(const std::string& tag); /** Compute the 160-bit RIPEMD-160 hash of an array. */ inline uint160 RIPEMD160(Span<const unsigned char> data) { uint160 result; CRIPEMD160().Write(data.data(), data.size()).Finalize(result.begin()); return result; } #endif // BITCOIN_HASH_H
0
bitcoin
bitcoin/src/dbwrapper.cpp
// Copyright (c) 2012-2022 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 <dbwrapper.h> #include <logging.h> #include <random.h> #include <serialize.h> #include <span.h> #include <streams.h> #include <util/fs.h> #include <util/fs_helpers.h> #include <util/strencodings.h> #include <algorithm> #include <cassert> #include <cstdarg> #include <cstdint> #include <cstdio> #include <leveldb/cache.h> #include <leveldb/db.h> #include <leveldb/env.h> #include <leveldb/filter_policy.h> #include <leveldb/helpers/memenv/memenv.h> #include <leveldb/iterator.h> #include <leveldb/options.h> #include <leveldb/slice.h> #include <leveldb/status.h> #include <leveldb/write_batch.h> #include <memory> #include <optional> #include <utility> static auto CharCast(const std::byte* data) { return reinterpret_cast<const char*>(data); } bool DestroyDB(const std::string& path_str) { return leveldb::DestroyDB(path_str, {}).ok(); } /** Handle database error by throwing dbwrapper_error exception. */ static void HandleError(const leveldb::Status& status) { if (status.ok()) return; const std::string errmsg = "Fatal LevelDB error: " + status.ToString(); LogPrintf("%s\n", errmsg); LogPrintf("You can use -debug=leveldb to get more complete diagnostic messages\n"); throw dbwrapper_error(errmsg); } class CBitcoinLevelDBLogger : public leveldb::Logger { public: // This code is adapted from posix_logger.h, which is why it is using vsprintf. // Please do not do this in normal code void Logv(const char * format, va_list ap) override { if (!LogAcceptCategory(BCLog::LEVELDB, BCLog::Level::Debug)) { return; } char buffer[500]; for (int iter = 0; iter < 2; iter++) { char* base; int bufsize; if (iter == 0) { bufsize = sizeof(buffer); base = buffer; } else { bufsize = 30000; base = new char[bufsize]; } char* p = base; char* limit = base + bufsize; // Print the message if (p < limit) { va_list backup_ap; va_copy(backup_ap, ap); // Do not use vsnprintf elsewhere in bitcoin source code, see above. p += vsnprintf(p, limit - p, format, backup_ap); va_end(backup_ap); } // Truncate to available space if necessary if (p >= limit) { if (iter == 0) { continue; // Try again with larger buffer } else { p = limit - 1; } } // Add newline if necessary if (p == base || p[-1] != '\n') { *p++ = '\n'; } assert(p <= limit); base[std::min(bufsize - 1, (int)(p - base))] = '\0'; LogPrintLevel(BCLog::LEVELDB, BCLog::Level::Debug, "%s", base); // NOLINT(bitcoin-unterminated-logprintf) if (base != buffer) { delete[] base; } break; } } }; static void SetMaxOpenFiles(leveldb::Options *options) { // On most platforms the default setting of max_open_files (which is 1000) // is optimal. On Windows using a large file count is OK because the handles // do not interfere with select() loops. On 64-bit Unix hosts this value is // also OK, because up to that amount LevelDB will use an mmap // implementation that does not use extra file descriptors (the fds are // closed after being mmap'ed). // // Increasing the value beyond the default is dangerous because LevelDB will // fall back to a non-mmap implementation when the file count is too large. // On 32-bit Unix host we should decrease the value because the handles use // up real fds, and we want to avoid fd exhaustion issues. // // See PR #12495 for further discussion. int default_open_files = options->max_open_files; #ifndef WIN32 if (sizeof(void*) < 8) { options->max_open_files = 64; } #endif LogPrint(BCLog::LEVELDB, "LevelDB using max_open_files=%d (default=%d)\n", options->max_open_files, default_open_files); } static leveldb::Options GetOptions(size_t nCacheSize) { leveldb::Options options; options.block_cache = leveldb::NewLRUCache(nCacheSize / 2); options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously options.filter_policy = leveldb::NewBloomFilterPolicy(10); options.compression = leveldb::kNoCompression; options.info_log = new CBitcoinLevelDBLogger(); if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) { // LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error // on corruption in later versions. options.paranoid_checks = true; } SetMaxOpenFiles(&options); return options; } struct CDBBatch::WriteBatchImpl { leveldb::WriteBatch batch; }; CDBBatch::CDBBatch(const CDBWrapper& _parent) : parent{_parent}, m_impl_batch{std::make_unique<CDBBatch::WriteBatchImpl>()} {}; CDBBatch::~CDBBatch() = default; void CDBBatch::Clear() { m_impl_batch->batch.Clear(); size_estimate = 0; } void CDBBatch::WriteImpl(Span<const std::byte> key, DataStream& ssValue) { leveldb::Slice slKey(CharCast(key.data()), key.size()); ssValue.Xor(dbwrapper_private::GetObfuscateKey(parent)); leveldb::Slice slValue(CharCast(ssValue.data()), ssValue.size()); m_impl_batch->batch.Put(slKey, slValue); // LevelDB serializes writes as: // - byte: header // - varint: key length (1 byte up to 127B, 2 bytes up to 16383B, ...) // - byte[]: key // - varint: value length // - byte[]: value // The formula below assumes the key and value are both less than 16k. size_estimate += 3 + (slKey.size() > 127) + slKey.size() + (slValue.size() > 127) + slValue.size(); } void CDBBatch::EraseImpl(Span<const std::byte> key) { leveldb::Slice slKey(CharCast(key.data()), key.size()); m_impl_batch->batch.Delete(slKey); // LevelDB serializes erases as: // - byte: header // - varint: key length // - byte[]: key // The formula below assumes the key is less than 16kB. size_estimate += 2 + (slKey.size() > 127) + slKey.size(); } struct LevelDBContext { //! custom environment this database is using (may be nullptr in case of default environment) leveldb::Env* penv; //! database options used leveldb::Options options; //! options used when reading from the database leveldb::ReadOptions readoptions; //! options used when iterating over values of the database leveldb::ReadOptions iteroptions; //! options used when writing to the database leveldb::WriteOptions writeoptions; //! options used when sync writing to the database leveldb::WriteOptions syncoptions; //! the database itself leveldb::DB* pdb; }; CDBWrapper::CDBWrapper(const DBParams& params) : m_db_context{std::make_unique<LevelDBContext>()}, m_name{fs::PathToString(params.path.stem())}, m_path{params.path}, m_is_memory{params.memory_only} { DBContext().penv = nullptr; DBContext().readoptions.verify_checksums = true; DBContext().iteroptions.verify_checksums = true; DBContext().iteroptions.fill_cache = false; DBContext().syncoptions.sync = true; DBContext().options = GetOptions(params.cache_bytes); DBContext().options.create_if_missing = true; if (params.memory_only) { DBContext().penv = leveldb::NewMemEnv(leveldb::Env::Default()); DBContext().options.env = DBContext().penv; } else { if (params.wipe_data) { LogPrintf("Wiping LevelDB in %s\n", fs::PathToString(params.path)); leveldb::Status result = leveldb::DestroyDB(fs::PathToString(params.path), DBContext().options); HandleError(result); } TryCreateDirectories(params.path); LogPrintf("Opening LevelDB in %s\n", fs::PathToString(params.path)); } // PathToString() return value is safe to pass to leveldb open function, // because on POSIX leveldb passes the byte string directly to ::open(), and // on Windows it converts from UTF-8 to UTF-16 before calling ::CreateFileW // (see env_posix.cc and env_windows.cc). leveldb::Status status = leveldb::DB::Open(DBContext().options, fs::PathToString(params.path), &DBContext().pdb); HandleError(status); LogPrintf("Opened LevelDB successfully\n"); if (params.options.force_compact) { LogPrintf("Starting database compaction of %s\n", fs::PathToString(params.path)); DBContext().pdb->CompactRange(nullptr, nullptr); LogPrintf("Finished database compaction of %s\n", fs::PathToString(params.path)); } // The base-case obfuscation key, which is a noop. obfuscate_key = std::vector<unsigned char>(OBFUSCATE_KEY_NUM_BYTES, '\000'); bool key_exists = Read(OBFUSCATE_KEY_KEY, obfuscate_key); if (!key_exists && params.obfuscate && IsEmpty()) { // Initialize non-degenerate obfuscation if it won't upset // existing, non-obfuscated data. std::vector<unsigned char> new_key = CreateObfuscateKey(); // Write `new_key` so we don't obfuscate the key with itself Write(OBFUSCATE_KEY_KEY, new_key); obfuscate_key = new_key; LogPrintf("Wrote new obfuscate key for %s: %s\n", fs::PathToString(params.path), HexStr(obfuscate_key)); } LogPrintf("Using obfuscation key for %s: %s\n", fs::PathToString(params.path), HexStr(obfuscate_key)); } CDBWrapper::~CDBWrapper() { delete DBContext().pdb; DBContext().pdb = nullptr; delete DBContext().options.filter_policy; DBContext().options.filter_policy = nullptr; delete DBContext().options.info_log; DBContext().options.info_log = nullptr; delete DBContext().options.block_cache; DBContext().options.block_cache = nullptr; delete DBContext().penv; DBContext().options.env = nullptr; } bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync) { const bool log_memory = LogAcceptCategory(BCLog::LEVELDB, BCLog::Level::Debug); double mem_before = 0; if (log_memory) { mem_before = DynamicMemoryUsage() / 1024.0 / 1024; } leveldb::Status status = DBContext().pdb->Write(fSync ? DBContext().syncoptions : DBContext().writeoptions, &batch.m_impl_batch->batch); HandleError(status); if (log_memory) { double mem_after = DynamicMemoryUsage() / 1024.0 / 1024; LogPrint(BCLog::LEVELDB, "WriteBatch memory usage: db=%s, before=%.1fMiB, after=%.1fMiB\n", m_name, mem_before, mem_after); } return true; } size_t CDBWrapper::DynamicMemoryUsage() const { std::string memory; std::optional<size_t> parsed; if (!DBContext().pdb->GetProperty("leveldb.approximate-memory-usage", &memory) || !(parsed = ToIntegral<size_t>(memory))) { LogPrint(BCLog::LEVELDB, "Failed to get approximate-memory-usage property\n"); return 0; } return parsed.value(); } // Prefixed with null character to avoid collisions with other keys // // We must use a string constructor which specifies length so that we copy // past the null-terminator. const std::string CDBWrapper::OBFUSCATE_KEY_KEY("\000obfuscate_key", 14); const unsigned int CDBWrapper::OBFUSCATE_KEY_NUM_BYTES = 8; /** * Returns a string (consisting of 8 random bytes) suitable for use as an * obfuscating XOR key. */ std::vector<unsigned char> CDBWrapper::CreateObfuscateKey() const { std::vector<uint8_t> ret(OBFUSCATE_KEY_NUM_BYTES); GetRandBytes(ret); return ret; } std::optional<std::string> CDBWrapper::ReadImpl(Span<const std::byte> key) const { leveldb::Slice slKey(CharCast(key.data()), key.size()); std::string strValue; leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue); if (!status.ok()) { if (status.IsNotFound()) return std::nullopt; LogPrintf("LevelDB read failure: %s\n", status.ToString()); HandleError(status); } return strValue; } bool CDBWrapper::ExistsImpl(Span<const std::byte> key) const { leveldb::Slice slKey(CharCast(key.data()), key.size()); std::string strValue; leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue); if (!status.ok()) { if (status.IsNotFound()) return false; LogPrintf("LevelDB read failure: %s\n", status.ToString()); HandleError(status); } return true; } size_t CDBWrapper::EstimateSizeImpl(Span<const std::byte> key1, Span<const std::byte> key2) const { leveldb::Slice slKey1(CharCast(key1.data()), key1.size()); leveldb::Slice slKey2(CharCast(key2.data()), key2.size()); uint64_t size = 0; leveldb::Range range(slKey1, slKey2); DBContext().pdb->GetApproximateSizes(&range, 1, &size); return size; } bool CDBWrapper::IsEmpty() { std::unique_ptr<CDBIterator> it(NewIterator()); it->SeekToFirst(); return !(it->Valid()); } struct CDBIterator::IteratorImpl { const std::unique_ptr<leveldb::Iterator> iter; explicit IteratorImpl(leveldb::Iterator* _iter) : iter{_iter} {} }; CDBIterator::CDBIterator(const CDBWrapper& _parent, std::unique_ptr<IteratorImpl> _piter) : parent(_parent), m_impl_iter(std::move(_piter)) {} CDBIterator* CDBWrapper::NewIterator() { return new CDBIterator{*this, std::make_unique<CDBIterator::IteratorImpl>(DBContext().pdb->NewIterator(DBContext().iteroptions))}; } void CDBIterator::SeekImpl(Span<const std::byte> key) { leveldb::Slice slKey(CharCast(key.data()), key.size()); m_impl_iter->iter->Seek(slKey); } Span<const std::byte> CDBIterator::GetKeyImpl() const { return MakeByteSpan(m_impl_iter->iter->key()); } Span<const std::byte> CDBIterator::GetValueImpl() const { return MakeByteSpan(m_impl_iter->iter->value()); } CDBIterator::~CDBIterator() = default; bool CDBIterator::Valid() const { return m_impl_iter->iter->Valid(); } void CDBIterator::SeekToFirst() { m_impl_iter->iter->SeekToFirst(); } void CDBIterator::Next() { m_impl_iter->iter->Next(); } namespace dbwrapper_private { const std::vector<unsigned char>& GetObfuscateKey(const CDBWrapper &w) { return w.obfuscate_key; } } // namespace dbwrapper_private
0
bitcoin
bitcoin/src/random.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_RANDOM_H #define BITCOIN_RANDOM_H #include <crypto/chacha20.h> #include <crypto/common.h> #include <span.h> #include <uint256.h> #include <cassert> #include <chrono> #include <cstdint> #include <limits> #include <vector> /** * Overall design of the RNG and entropy sources. * * We maintain a single global 256-bit RNG state for all high-quality randomness. * The following (classes of) functions interact with that state by mixing in new * entropy, and optionally extracting random output from it: * * - The GetRand*() class of functions, as well as construction of FastRandomContext objects, * perform 'fast' seeding, consisting of mixing in: * - A stack pointer (indirectly committing to calling thread and call stack) * - A high-precision timestamp (rdtsc when available, c++ high_resolution_clock otherwise) * - 64 bits from the hardware RNG (rdrand) when available. * These entropy sources are very fast, and only designed to protect against situations * where a VM state restore/copy results in multiple systems with the same randomness. * FastRandomContext on the other hand does not protect against this once created, but * is even faster (and acceptable to use inside tight loops). * * - The GetStrongRand*() class of function perform 'slow' seeding, including everything * that fast seeding includes, but additionally: * - OS entropy (/dev/urandom, getrandom(), ...). The application will terminate if * this entropy source fails. * - Another high-precision timestamp (indirectly committing to a benchmark of all the * previous sources). * These entropy sources are slower, but designed to make sure the RNG state contains * fresh data that is unpredictable to attackers. * * - RandAddPeriodic() seeds everything that fast seeding includes, but additionally: * - A high-precision timestamp * - Dynamic environment data (performance monitoring, ...) * - Strengthen the entropy for 10 ms using repeated SHA512. * This is run once every minute. * * On first use of the RNG (regardless of what function is called first), all entropy * sources used in the 'slow' seeder are included, but also: * - 256 bits from the hardware RNG (rdseed or rdrand) when available. * - Dynamic environment data (performance monitoring, ...) * - Static environment data * - Strengthen the entropy for 100 ms using repeated SHA512. * * When mixing in new entropy, H = SHA512(entropy || old_rng_state) is computed, and * (up to) the first 32 bytes of H are produced as output, while the last 32 bytes * become the new RNG state. */ /** * Generate random data via the internal PRNG. * * These functions are designed to be fast (sub microsecond), but do not necessarily * meaningfully add entropy to the PRNG state. * * Thread-safe. */ void GetRandBytes(Span<unsigned char> bytes) noexcept; /** Generate a uniform random integer in the range [0..range). Precondition: range > 0 */ uint64_t GetRandInternal(uint64_t nMax) noexcept; /** Generate a uniform random integer of type T in the range [0..nMax) * nMax defaults to std::numeric_limits<T>::max() * Precondition: nMax > 0, T is an integral type, no larger than uint64_t */ template<typename T> T GetRand(T nMax=std::numeric_limits<T>::max()) noexcept { static_assert(std::is_integral<T>(), "T must be integral"); static_assert(std::numeric_limits<T>::max() <= std::numeric_limits<uint64_t>::max(), "GetRand only supports up to uint64_t"); return T(GetRandInternal(nMax)); } /** Generate a uniform random duration in the range [0..max). Precondition: max.count() > 0 */ template <typename D> D GetRandomDuration(typename std::common_type<D>::type max) noexcept // Having the compiler infer the template argument from the function argument // is dangerous, because the desired return value generally has a different // type than the function argument. So std::common_type is used to force the // call site to specify the type of the return value. { assert(max.count() > 0); return D{GetRand(max.count())}; }; constexpr auto GetRandMicros = GetRandomDuration<std::chrono::microseconds>; constexpr auto GetRandMillis = GetRandomDuration<std::chrono::milliseconds>; /** * Return a timestamp in the future sampled from an exponential distribution * (https://en.wikipedia.org/wiki/Exponential_distribution). This distribution * is memoryless and should be used for repeated network events (e.g. sending a * certain type of message) to minimize leaking information to observers. * * The probability of an event occurring before time x is 1 - e^-(x/a) where a * is the average interval between events. * */ std::chrono::microseconds GetExponentialRand(std::chrono::microseconds now, std::chrono::seconds average_interval); uint256 GetRandHash() noexcept; /** * Gather entropy from various sources, feed it into the internal PRNG, and * generate random data using it. * * This function will cause failure whenever the OS RNG fails. * * Thread-safe. */ void GetStrongRandBytes(Span<unsigned char> bytes) noexcept; /** * Gather entropy from various expensive sources, and feed them to the PRNG state. * * Thread-safe. */ void RandAddPeriodic() noexcept; /** * Gathers entropy from the low bits of the time at which events occur. Should * be called with a uint32_t describing the event at the time an event occurs. * * Thread-safe. */ void RandAddEvent(const uint32_t event_info) noexcept; /** * Fast randomness source. This is seeded once with secure random data, but * is completely deterministic and does not gather more entropy after that. * * This class is not thread-safe. */ class FastRandomContext { private: bool requires_seed; ChaCha20 rng; uint64_t bitbuf; int bitbuf_size; void RandomSeed(); void FillBitBuffer() { bitbuf = rand64(); bitbuf_size = 64; } public: explicit FastRandomContext(bool fDeterministic = false) noexcept; /** Initialize with explicit seed (only for testing) */ explicit FastRandomContext(const uint256& seed) noexcept; // Do not permit copying a FastRandomContext (move it, or create a new one to get reseeded). FastRandomContext(const FastRandomContext&) = delete; FastRandomContext(FastRandomContext&&) = delete; FastRandomContext& operator=(const FastRandomContext&) = delete; /** Move a FastRandomContext. If the original one is used again, it will be reseeded. */ FastRandomContext& operator=(FastRandomContext&& from) noexcept; /** Generate a random 64-bit integer. */ uint64_t rand64() noexcept { if (requires_seed) RandomSeed(); std::array<std::byte, 8> buf; rng.Keystream(buf); return ReadLE64(UCharCast(buf.data())); } /** Generate a random (bits)-bit integer. */ uint64_t randbits(int bits) noexcept { if (bits == 0) { return 0; } else if (bits > 32) { return rand64() >> (64 - bits); } else { if (bitbuf_size < bits) FillBitBuffer(); uint64_t ret = bitbuf & (~uint64_t{0} >> (64 - bits)); bitbuf >>= bits; bitbuf_size -= bits; return ret; } } /** Generate a random integer in the range [0..range). * Precondition: range > 0. */ uint64_t randrange(uint64_t range) noexcept { assert(range); --range; int bits = CountBits(range); while (true) { uint64_t ret = randbits(bits); if (ret <= range) return ret; } } /** Generate random bytes. */ template <typename B = unsigned char> std::vector<B> randbytes(size_t len); /** Fill a byte Span with random bytes. */ void fillrand(Span<std::byte> output); /** Generate a random 32-bit integer. */ uint32_t rand32() noexcept { return randbits(32); } /** generate a random uint256. */ uint256 rand256() noexcept; /** Generate a random boolean. */ bool randbool() noexcept { return randbits(1); } /** Return the time point advanced by a uniform random duration. */ template <typename Tp> Tp rand_uniform_delay(const Tp& time, typename Tp::duration range) { return time + rand_uniform_duration<Tp>(range); } /** Generate a uniform random duration in the range from 0 (inclusive) to range (exclusive). */ template <typename Chrono> typename Chrono::duration rand_uniform_duration(typename Chrono::duration range) noexcept { using Dur = typename Chrono::duration; return range.count() > 0 ? /* interval [0..range) */ Dur{randrange(range.count())} : range.count() < 0 ? /* interval (range..0] */ -Dur{randrange(-range.count())} : /* interval [0..0] */ Dur{0}; }; // Compatibility with the UniformRandomBitGenerator concept typedef uint64_t result_type; static constexpr uint64_t min() { return 0; } static constexpr uint64_t max() { return std::numeric_limits<uint64_t>::max(); } inline uint64_t operator()() noexcept { return rand64(); } }; /** More efficient than using std::shuffle on a FastRandomContext. * * This is more efficient as std::shuffle will consume entropy in groups of * 64 bits at the time and throw away most. * * This also works around a bug in libstdc++ std::shuffle that may cause * type::operator=(type&&) to be invoked on itself, which the library's * debug mode detects and panics on. This is a known issue, see * https://stackoverflow.com/questions/22915325/avoiding-self-assignment-in-stdshuffle */ template <typename I, typename R> void Shuffle(I first, I last, R&& rng) { while (first != last) { size_t j = rng.randrange(last - first); if (j) { using std::swap; swap(*first, *(first + j)); } ++first; } } /* Number of random bytes returned by GetOSRand. * When changing this constant make sure to change all call sites, and make * sure that the underlying OS APIs for all platforms support the number. * (many cap out at 256 bytes). */ static const int NUM_OS_RANDOM_BYTES = 32; /** Get 32 bytes of system entropy. Do not use this in application code: use * GetStrongRandBytes instead. */ void GetOSRand(unsigned char* ent32); /** Check that OS randomness is available and returning the requested number * of bytes. */ bool Random_SanityCheck(); /** * Initialize global RNG state and log any CPU features that are used. * * Calling this function is optional. RNG state will be initialized when first * needed if it is not called. */ void RandomInit(); #endif // BITCOIN_RANDOM_H
0
bitcoin
bitcoin/src/net_types.cpp
// Copyright (c) 2021-2022 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 <net_types.h> #include <logging.h> #include <netaddress.h> #include <netbase.h> #include <univalue.h> static const char* BANMAN_JSON_VERSION_KEY{"version"}; CBanEntry::CBanEntry(const UniValue& json) : nVersion(json[BANMAN_JSON_VERSION_KEY].getInt<int>()), nCreateTime(json["ban_created"].getInt<int64_t>()), nBanUntil(json["banned_until"].getInt<int64_t>()) { } UniValue CBanEntry::ToJson() const { UniValue json(UniValue::VOBJ); json.pushKV(BANMAN_JSON_VERSION_KEY, nVersion); json.pushKV("ban_created", nCreateTime); json.pushKV("banned_until", nBanUntil); return json; } static const char* BANMAN_JSON_ADDR_KEY = "address"; /** * Convert a `banmap_t` object to a JSON array. * @param[in] bans Bans list to convert. * @return a JSON array, similar to the one returned by the `listbanned` RPC. Suitable for * passing to `BanMapFromJson()`. */ UniValue BanMapToJson(const banmap_t& bans) { UniValue bans_json(UniValue::VARR); for (const auto& it : bans) { const auto& address = it.first; const auto& ban_entry = it.second; UniValue j = ban_entry.ToJson(); j.pushKV(BANMAN_JSON_ADDR_KEY, address.ToString()); bans_json.push_back(j); } return bans_json; } /** * Convert a JSON array to a `banmap_t` object. * @param[in] bans_json JSON to convert, must be as returned by `BanMapToJson()`. * @param[out] bans Bans list to create from the JSON. * @throws std::runtime_error if the JSON does not have the expected fields or they contain * unparsable values. */ void BanMapFromJson(const UniValue& bans_json, banmap_t& bans) { for (const auto& ban_entry_json : bans_json.getValues()) { const int version{ban_entry_json[BANMAN_JSON_VERSION_KEY].getInt<int>()}; if (version != CBanEntry::CURRENT_VERSION) { LogPrintf("Dropping entry with unknown version (%s) from ban list\n", version); continue; } const auto& subnet_str = ban_entry_json[BANMAN_JSON_ADDR_KEY].get_str(); const CSubNet subnet{LookupSubNet(subnet_str)}; if (!subnet.IsValid()) { LogPrintf("Dropping entry with unparseable address or subnet (%s) from ban list\n", subnet_str); continue; } bans.insert_or_assign(subnet, CBanEntry{ban_entry_json}); } }
0
bitcoin
bitcoin/src/Makefile.leveldb.include
# Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. LIBLEVELDB_INT = leveldb/libleveldb.la LIBMEMENV_INT = leveldb/libmemenv.la noinst_LTLIBRARIES += $(LIBLEVELDB_INT) noinst_LTLIBRARIES += $(LIBMEMENV_INT) LIBLEVELDB = $(LIBLEVELDB_INT) $(LIBCRC32C) LIBMEMENV = $(LIBMEMENV_INT) LEVELDB_CPPFLAGS = LEVELDB_CPPFLAGS += -I$(srcdir)/leveldb/include LEVELDB_CPPFLAGS_INT = LEVELDB_CPPFLAGS_INT += -I$(srcdir)/leveldb LEVELDB_CPPFLAGS_INT += -I$(srcdir)/crc32c/include LEVELDB_CPPFLAGS_INT += -D__STDC_LIMIT_MACROS LEVELDB_CPPFLAGS_INT += -DHAVE_SNAPPY=0 -DHAVE_CRC32C=1 LEVELDB_CPPFLAGS_INT += -DHAVE_FDATASYNC=@HAVE_FDATASYNC@ LEVELDB_CPPFLAGS_INT += -DHAVE_FULLFSYNC=@HAVE_FULLFSYNC@ LEVELDB_CPPFLAGS_INT += -DHAVE_O_CLOEXEC=@HAVE_O_CLOEXEC@ LEVELDB_CPPFLAGS_INT += -DFALLTHROUGH_INTENDED=[[fallthrough]] if WORDS_BIGENDIAN LEVELDB_CPPFLAGS_INT += -DLEVELDB_IS_BIG_ENDIAN=1 else LEVELDB_CPPFLAGS_INT += -DLEVELDB_IS_BIG_ENDIAN=0 endif if TARGET_WINDOWS LEVELDB_CPPFLAGS_INT += -DLEVELDB_PLATFORM_WINDOWS -D_UNICODE -DUNICODE -D__USE_MINGW_ANSI_STDIO=1 else LEVELDB_CPPFLAGS_INT += -DLEVELDB_PLATFORM_POSIX endif leveldb_libleveldb_la_CPPFLAGS = $(AM_CPPFLAGS) $(LEVELDB_CPPFLAGS_INT) $(LEVELDB_CPPFLAGS) # Specify -static in both CXXFLAGS and LDFLAGS so libtool will only build a # static version of this library. We don't need a dynamic version, and a dynamic # version can't be used on windows anyway because the library doesn't currently # export DLL symbols. leveldb_libleveldb_la_CXXFLAGS = $(filter-out -Wconditional-uninitialized -Werror=conditional-uninitialized -Wsuggest-override -Werror=suggest-override, $(AM_CXXFLAGS)) $(PIE_FLAGS) -static leveldb_libleveldb_la_LDFLAGS = $(AM_LDFLAGS) -static leveldb_libleveldb_la_SOURCES= leveldb_libleveldb_la_SOURCES += leveldb/port/port_stdcxx.h leveldb_libleveldb_la_SOURCES += leveldb/port/port.h leveldb_libleveldb_la_SOURCES += leveldb/port/thread_annotations.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/db.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/options.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/comparator.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/filter_policy.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/slice.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/table_builder.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/env.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/export.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/c.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/iterator.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/cache.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/dumpfile.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/table.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/write_batch.h leveldb_libleveldb_la_SOURCES += leveldb/include/leveldb/status.h leveldb_libleveldb_la_SOURCES += leveldb/db/log_format.h leveldb_libleveldb_la_SOURCES += leveldb/db/memtable.h leveldb_libleveldb_la_SOURCES += leveldb/db/version_set.h leveldb_libleveldb_la_SOURCES += leveldb/db/write_batch_internal.h leveldb_libleveldb_la_SOURCES += leveldb/db/filename.h leveldb_libleveldb_la_SOURCES += leveldb/db/version_edit.h leveldb_libleveldb_la_SOURCES += leveldb/db/dbformat.h leveldb_libleveldb_la_SOURCES += leveldb/db/builder.h leveldb_libleveldb_la_SOURCES += leveldb/db/log_writer.h leveldb_libleveldb_la_SOURCES += leveldb/db/db_iter.h leveldb_libleveldb_la_SOURCES += leveldb/db/skiplist.h leveldb_libleveldb_la_SOURCES += leveldb/db/db_impl.h leveldb_libleveldb_la_SOURCES += leveldb/db/table_cache.h leveldb_libleveldb_la_SOURCES += leveldb/db/snapshot.h leveldb_libleveldb_la_SOURCES += leveldb/db/log_reader.h leveldb_libleveldb_la_SOURCES += leveldb/table/filter_block.h leveldb_libleveldb_la_SOURCES += leveldb/table/block_builder.h leveldb_libleveldb_la_SOURCES += leveldb/table/block.h leveldb_libleveldb_la_SOURCES += leveldb/table/two_level_iterator.h leveldb_libleveldb_la_SOURCES += leveldb/table/merger.h leveldb_libleveldb_la_SOURCES += leveldb/table/format.h leveldb_libleveldb_la_SOURCES += leveldb/table/iterator_wrapper.h leveldb_libleveldb_la_SOURCES += leveldb/util/crc32c.h leveldb_libleveldb_la_SOURCES += leveldb/util/env_posix_test_helper.h leveldb_libleveldb_la_SOURCES += leveldb/util/env_windows_test_helper.h leveldb_libleveldb_la_SOURCES += leveldb/util/arena.h leveldb_libleveldb_la_SOURCES += leveldb/util/random.h leveldb_libleveldb_la_SOURCES += leveldb/util/posix_logger.h leveldb_libleveldb_la_SOURCES += leveldb/util/hash.h leveldb_libleveldb_la_SOURCES += leveldb/util/histogram.h leveldb_libleveldb_la_SOURCES += leveldb/util/coding.h leveldb_libleveldb_la_SOURCES += leveldb/util/testutil.h leveldb_libleveldb_la_SOURCES += leveldb/util/mutexlock.h leveldb_libleveldb_la_SOURCES += leveldb/util/logging.h leveldb_libleveldb_la_SOURCES += leveldb/util/no_destructor.h leveldb_libleveldb_la_SOURCES += leveldb/util/testharness.h leveldb_libleveldb_la_SOURCES += leveldb/util/windows_logger.h leveldb_libleveldb_la_SOURCES += leveldb/db/builder.cc leveldb_libleveldb_la_SOURCES += leveldb/db/c.cc leveldb_libleveldb_la_SOURCES += leveldb/db/dbformat.cc leveldb_libleveldb_la_SOURCES += leveldb/db/db_impl.cc leveldb_libleveldb_la_SOURCES += leveldb/db/db_iter.cc leveldb_libleveldb_la_SOURCES += leveldb/db/dumpfile.cc leveldb_libleveldb_la_SOURCES += leveldb/db/filename.cc leveldb_libleveldb_la_SOURCES += leveldb/db/log_reader.cc leveldb_libleveldb_la_SOURCES += leveldb/db/log_writer.cc leveldb_libleveldb_la_SOURCES += leveldb/db/memtable.cc leveldb_libleveldb_la_SOURCES += leveldb/db/repair.cc leveldb_libleveldb_la_SOURCES += leveldb/db/table_cache.cc leveldb_libleveldb_la_SOURCES += leveldb/db/version_edit.cc leveldb_libleveldb_la_SOURCES += leveldb/db/version_set.cc leveldb_libleveldb_la_SOURCES += leveldb/db/write_batch.cc leveldb_libleveldb_la_SOURCES += leveldb/table/block_builder.cc leveldb_libleveldb_la_SOURCES += leveldb/table/block.cc leveldb_libleveldb_la_SOURCES += leveldb/table/filter_block.cc leveldb_libleveldb_la_SOURCES += leveldb/table/format.cc leveldb_libleveldb_la_SOURCES += leveldb/table/iterator.cc leveldb_libleveldb_la_SOURCES += leveldb/table/merger.cc leveldb_libleveldb_la_SOURCES += leveldb/table/table_builder.cc leveldb_libleveldb_la_SOURCES += leveldb/table/table.cc leveldb_libleveldb_la_SOURCES += leveldb/table/two_level_iterator.cc leveldb_libleveldb_la_SOURCES += leveldb/util/arena.cc leveldb_libleveldb_la_SOURCES += leveldb/util/bloom.cc leveldb_libleveldb_la_SOURCES += leveldb/util/cache.cc leveldb_libleveldb_la_SOURCES += leveldb/util/coding.cc leveldb_libleveldb_la_SOURCES += leveldb/util/comparator.cc leveldb_libleveldb_la_SOURCES += leveldb/util/crc32c.cc leveldb_libleveldb_la_SOURCES += leveldb/util/env.cc leveldb_libleveldb_la_SOURCES += leveldb/util/filter_policy.cc leveldb_libleveldb_la_SOURCES += leveldb/util/hash.cc leveldb_libleveldb_la_SOURCES += leveldb/util/histogram.cc leveldb_libleveldb_la_SOURCES += leveldb/util/logging.cc leveldb_libleveldb_la_SOURCES += leveldb/util/options.cc leveldb_libleveldb_la_SOURCES += leveldb/util/status.cc if TARGET_WINDOWS leveldb_libleveldb_la_SOURCES += leveldb/util/env_windows.cc else leveldb_libleveldb_la_SOURCES += leveldb/util/env_posix.cc endif leveldb_libmemenv_la_CPPFLAGS = $(leveldb_libleveldb_la_CPPFLAGS) leveldb_libmemenv_la_CXXFLAGS = $(leveldb_libleveldb_la_CXXFLAGS) leveldb_libmemenv_la_LDFLAGS = $(leveldb_libleveldb_la_LDFLAGS) leveldb_libmemenv_la_SOURCES = leveldb/helpers/memenv/memenv.cc leveldb_libmemenv_la_SOURCES += leveldb/helpers/memenv/memenv.h
0