diff options
30 files changed, 379 insertions, 117 deletions
diff --git a/ci/test/00_setup_env_native_fuzz_with_valgrind.sh b/ci/test/00_setup_env_native_fuzz_with_valgrind.sh index b2213e2f77..abc3854762 100755 --- a/ci/test/00_setup_env_native_fuzz_with_valgrind.sh +++ b/ci/test/00_setup_env_native_fuzz_with_valgrind.sh @@ -16,5 +16,5 @@ export RUN_FUZZ_TESTS=true export FUZZ_TESTS_CONFIG="--valgrind" export GOAL="install" # Temporarily pin dwarf 4, until using Valgrind 3.20 or later -export BITCOIN_CONFIG="--enable-fuzz --with-sanitizers=fuzzer CC=clang CXX=clang++ CFLAGS='-gdwarf-4' CXXFLAGS='-gdwarf-4'" +export BITCOIN_CONFIG="--enable-fuzz --with-sanitizers=fuzzer CC='clang -gdwarf-4' CXX='clang++ -gdwarf-4'" export CCACHE_SIZE=200M diff --git a/ci/test/00_setup_env_native_valgrind.sh b/ci/test/00_setup_env_native_valgrind.sh index d6dcf73182..fa2ae81fdd 100755 --- a/ci/test/00_setup_env_native_valgrind.sh +++ b/ci/test/00_setup_env_native_valgrind.sh @@ -14,4 +14,4 @@ export NO_DEPENDS=1 export TEST_RUNNER_EXTRA="--exclude feature_init,rpc_bind,feature_bind_extra" # Excluded for now, see https://github.com/bitcoin/bitcoin/issues/17765#issuecomment-602068547 export GOAL="install" # Temporarily pin dwarf 4, until using Valgrind 3.20 or later -export BITCOIN_CONFIG="--enable-zmq --with-incompatible-bdb --with-gui=no CC=clang CXX=clang++ CFLAGS='-gdwarf-4' CXXFLAGS='-gdwarf-4'" # TODO enable GUI +export BITCOIN_CONFIG="--enable-zmq --with-incompatible-bdb --with-gui=no CC='clang -gdwarf-4' CXX='clang++ -gdwarf-4'" # TODO enable GUI diff --git a/configure.ac b/configure.ac index 29ac8e3805..912201696b 100644 --- a/configure.ac +++ b/configure.ac @@ -958,7 +958,8 @@ if test "$use_hardening" != "no"; then case $host in *mingw*) - dnl stack-clash-protection doesn't currently work, and likely should just be skipped for Windows. + dnl stack-clash-protection doesn't compile with GCC 10 and earlier. + dnl In any case, it is a no-op for Windows. dnl See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90458 for more details. ;; *) diff --git a/src/Makefile.am b/src/Makefile.am index 4e9c161c57..e1ae049b15 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -956,7 +956,6 @@ libbitcoinkernel_la_SOURCES = \ script/script_error.cpp \ script/sigcache.cpp \ script/standard.cpp \ - shutdown.cpp \ signet.cpp \ support/cleanse.cpp \ support/lockedpool.cpp \ diff --git a/src/bench/chacha20.cpp b/src/bench/chacha20.cpp index 115cd064bd..3b57e29f39 100644 --- a/src/bench/chacha20.cpp +++ b/src/bench/chacha20.cpp @@ -15,8 +15,7 @@ static void CHACHA20(benchmark::Bench& bench, size_t buffersize) { std::vector<uint8_t> key(32,0); ChaCha20 ctx(key.data()); - ctx.SetIV(0); - ctx.Seek64(0); + ctx.Seek64({0, 0}, 0); std::vector<uint8_t> in(buffersize,0); std::vector<uint8_t> out(buffersize,0); bench.batch(in.size()).unit("byte").run([&] { diff --git a/src/bitcoin-chainstate.cpp b/src/bitcoin-chainstate.cpp index 45fd239e20..580a6badd6 100644 --- a/src/bitcoin-chainstate.cpp +++ b/src/bitcoin-chainstate.cpp @@ -81,9 +81,10 @@ int main(int argc, char* argv[]) class KernelNotifications : public kernel::Notifications { public: - void blockTip(SynchronizationState, CBlockIndex&) override + kernel::InterruptResult blockTip(SynchronizationState, CBlockIndex&) override { std::cout << "Block tip changed" << std::endl; + return {}; } void headerTip(SynchronizationState, int64_t height, int64_t timestamp, bool presync) override { diff --git a/src/crypto/chacha20.cpp b/src/crypto/chacha20.cpp index 6934cef163..fafd783ab1 100644 --- a/src/crypto/chacha20.cpp +++ b/src/crypto/chacha20.cpp @@ -47,16 +47,12 @@ ChaCha20Aligned::ChaCha20Aligned(const unsigned char* key32) SetKey32(key32); } -void ChaCha20Aligned::SetIV(uint64_t iv) +void ChaCha20Aligned::Seek64(Nonce96 nonce, uint32_t block_counter) { - input[10] = iv; - input[11] = iv >> 32; -} - -void ChaCha20Aligned::Seek64(uint64_t pos) -{ - input[8] = pos; - input[9] = pos >> 32; + input[8] = block_counter; + input[9] = nonce.first; + input[10] = nonce.second; + input[11] = nonce.second >> 32; } inline void ChaCha20Aligned::Keystream64(unsigned char* c, size_t blocks) diff --git a/src/crypto/chacha20.h b/src/crypto/chacha20.h index b286ef59fe..f2ec21d82e 100644 --- a/src/crypto/chacha20.h +++ b/src/crypto/chacha20.h @@ -7,9 +7,15 @@ #include <cstdlib> #include <stdint.h> +#include <utility> // classes for ChaCha20 256-bit stream cipher developed by Daniel J. Bernstein -// https://cr.yp.to/chacha/chacha-20080128.pdf */ +// https://cr.yp.to/chacha/chacha-20080128.pdf. +// +// The 128-bit input is here implemented as a 96-bit nonce and a 32-bit block +// counter, as in RFC8439 Section 2.3. When the 32-bit block counter overflows +// the first 32-bit part of the nonce is automatically incremented, making it +// conceptually compatible with variants that use a 64/64 split instead. /** ChaCha20 cipher that only operates on multiples of 64 bytes. */ class ChaCha20Aligned @@ -26,11 +32,22 @@ public: /** set 32-byte key. */ void SetKey32(const unsigned char* key32); - /** set the 64-bit nonce. */ - void SetIV(uint64_t iv); + /** Type for 96-bit nonces used by the Set function below. + * + * The first field corresponds to the LE32-encoded first 4 bytes of the nonce, also referred + * to as the '32-bit fixed-common part' in Example 2.8.2 of RFC8439. + * + * The second field corresponds to the LE64-encoded last 8 bytes of the nonce. + * + */ + using Nonce96 = std::pair<uint32_t, uint64_t>; - /** set the 64bit block counter (pos seeks to byte position 64*pos). */ - void Seek64(uint64_t pos); + /** Set the 96-bit nonce and 32-bit block counter. + * + * Block_counter selects a position to seek to (to byte 64*block_counter). After 256 GiB, the + * block counter overflows, and nonce.first is incremented. + */ + void Seek64(Nonce96 nonce, uint32_t block_counter); /** outputs the keystream of size <64*blocks> into <c> */ void Keystream64(unsigned char* c, size_t blocks); @@ -62,13 +79,13 @@ public: m_bufleft = 0; } - /** set the 64-bit nonce. */ - void SetIV(uint64_t iv) { m_aligned.SetIV(iv); } + /** 96-bit nonce type. */ + using Nonce96 = ChaCha20Aligned::Nonce96; - /** set the 64bit block counter (pos seeks to byte position 64*pos). */ - void Seek64(uint64_t pos) + /** Set the 96-bit nonce and 32-bit block counter. */ + void Seek64(Nonce96 nonce, uint32_t block_counter) { - m_aligned.Seek64(pos); + m_aligned.Seek64(nonce, block_counter); m_bufleft = 0; } diff --git a/src/crypto/chacha_poly_aead.cpp b/src/crypto/chacha_poly_aead.cpp index 119ad6902f..d15f2f4ea6 100644 --- a/src/crypto/chacha_poly_aead.cpp +++ b/src/crypto/chacha_poly_aead.cpp @@ -58,12 +58,11 @@ bool ChaCha20Poly1305AEAD::Crypt(uint64_t seqnr_payload, uint64_t seqnr_aad, int unsigned char expected_tag[POLY1305_TAGLEN], poly_key[POLY1305_KEYLEN]; memset(poly_key, 0, sizeof(poly_key)); - m_chacha_main.SetIV(seqnr_payload); // block counter 0 for the poly1305 key // use lower 32bytes for the poly1305 key // (throws away 32 unused bytes (upper 32) from this ChaCha20 round) - m_chacha_main.Seek64(0); + m_chacha_main.Seek64({0, seqnr_payload}, 0); m_chacha_main.Crypt(poly_key, poly_key, sizeof(poly_key)); // if decrypting, verify the tag prior to decryption @@ -85,8 +84,7 @@ bool ChaCha20Poly1305AEAD::Crypt(uint64_t seqnr_payload, uint64_t seqnr_aad, int // calculate and cache the next 64byte keystream block if requested sequence number is not yet the cache if (m_cached_aad_seqnr != seqnr_aad) { m_cached_aad_seqnr = seqnr_aad; - m_chacha_header.SetIV(seqnr_aad); - m_chacha_header.Seek64(0); + m_chacha_header.Seek64({0, seqnr_aad}, 0); m_chacha_header.Keystream(m_aad_keystream_buffer, CHACHA20_ROUND_OUTPUT); } // crypt the AAD (3 bytes message length) with given position in AAD cipher instance keystream @@ -95,7 +93,7 @@ bool ChaCha20Poly1305AEAD::Crypt(uint64_t seqnr_payload, uint64_t seqnr_aad, int dest[2] = src[2] ^ m_aad_keystream_buffer[aad_pos + 2]; // Set the playload ChaCha instance block counter to 1 and crypt the payload - m_chacha_main.Seek64(1); + m_chacha_main.Seek64({0, seqnr_payload}, 1); m_chacha_main.Crypt(src + CHACHA20_POLY1305_AEAD_AAD_LEN, dest + CHACHA20_POLY1305_AEAD_AAD_LEN, src_len - CHACHA20_POLY1305_AEAD_AAD_LEN); // If encrypting, calculate and append tag @@ -117,8 +115,7 @@ bool ChaCha20Poly1305AEAD::GetLength(uint32_t* len24_out, uint64_t seqnr_aad, in if (m_cached_aad_seqnr != seqnr_aad) { // we need to calculate the 64 keystream bytes since we reached a new aad sequence number m_cached_aad_seqnr = seqnr_aad; - m_chacha_header.SetIV(seqnr_aad); // use LE for the nonce - m_chacha_header.Seek64(0); // block counter 0 + m_chacha_header.Seek64({0, seqnr_aad}, 0); // use LE for the nonce m_chacha_header.Keystream(m_aad_keystream_buffer, CHACHA20_ROUND_OUTPUT); // write keystream to the cache } diff --git a/src/init.cpp b/src/init.cpp index 2f4eec060b..f726fe54ca 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -123,6 +123,7 @@ 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; @@ -1408,6 +1409,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) // ********************************************************* Step 7: load block chain node.notifications = std::make_unique<KernelNotifications>(node.exit_status); + ReadNotificationArgs(args, *node.notifications); fReindex = args.GetBoolArg("-reindex", false); bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false); ChainstateManager::Options chainman_opts{ diff --git a/src/kernel/chainstatemanager_opts.h b/src/kernel/chainstatemanager_opts.h index 035a913d10..917f7d226c 100644 --- a/src/kernel/chainstatemanager_opts.h +++ b/src/kernel/chainstatemanager_opts.h @@ -21,7 +21,6 @@ class CChainParams; static constexpr bool DEFAULT_CHECKPOINTS_ENABLED{true}; static constexpr auto DEFAULT_MAX_TIP_AGE{24h}; -static constexpr int DEFAULT_STOPATHEIGHT{0}; namespace kernel { @@ -46,7 +45,6 @@ struct ChainstateManagerOpts { DBOptions coins_db{}; CoinsViewOptions coins_view{}; Notifications& notifications; - int stop_at_height{DEFAULT_STOPATHEIGHT}; }; } // namespace kernel diff --git a/src/kernel/notifications_interface.h b/src/kernel/notifications_interface.h index e596a144a8..c5e77b0df9 100644 --- a/src/kernel/notifications_interface.h +++ b/src/kernel/notifications_interface.h @@ -9,12 +9,25 @@ #include <cstdint> #include <string> +#include <variant> class CBlockIndex; enum class SynchronizationState; namespace kernel { +//! Result type for use with std::variant to indicate that an operation should be interrupted. +struct Interrupted{}; + +//! Simple result type for functions that need to propagate an interrupt status and don't have other return values. +using InterruptResult = std::variant<std::monostate, Interrupted>; + +template <typename T> +bool IsInterrupted(const T& result) +{ + return std::holds_alternative<kernel::Interrupted>(result); +} + /** * A base class defining functions for notifying about certain kernel * events. @@ -24,7 +37,7 @@ class Notifications public: virtual ~Notifications(){}; - virtual void blockTip(SynchronizationState state, CBlockIndex& index) {} + [[nodiscard]] virtual InterruptResult blockTip(SynchronizationState state, CBlockIndex& index) { return {}; } virtual void headerTip(SynchronizationState state, int64_t height, int64_t timestamp, bool presync) {} virtual void progress(const bilingual_str& title, int progress_percent, bool resume_possible) {} virtual void warning(const bilingual_str& warning) {} diff --git a/src/net.cpp b/src/net.cpp index 7601a6ea84..1b1b540417 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -146,7 +146,7 @@ uint16_t GetListenPort() } // find 'best' local address for a particular peer -bool GetLocal(CService& addr, const CNetAddr *paddrPeer) +bool GetLocal(CService& addr, const CNode& peer) { if (!fListen) return false; @@ -157,8 +157,18 @@ bool GetLocal(CService& addr, const CNetAddr *paddrPeer) LOCK(g_maplocalhost_mutex); for (const auto& entry : 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. + const Network our_net{entry.first.GetNetwork()}; + const Network peers_net{peer.ConnectedThroughNetwork()}; + if (our_net != peers_net && + (our_net == NET_ONION || our_net == NET_I2P || + peers_net == NET_ONION || peers_net == NET_I2P)) { + continue; + } int nScore = entry.second.nScore; - int nReachability = entry.first.GetReachabilityFrom(paddrPeer); + int nReachability = entry.first.GetReachabilityFrom(peer.addr); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService(entry.first, entry.second.nPort); @@ -196,10 +206,10 @@ static std::vector<CAddress> ConvertSeeds(const std::vector<uint8_t> &vSeedsIn) // Otherwise, 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 CNetAddr& addrPeer) +CService GetLocalAddress(const CNode& peer) { CService addr; - if (GetLocal(addr, &addrPeer)) { + if (GetLocal(addr, peer)) { return addr; } return CService{CNetAddr(), GetListenPort()}; @@ -222,7 +232,7 @@ bool IsPeerAddrLocalGood(CNode *pnode) std::optional<CService> GetLocalAddrForPeer(CNode& node) { - CService addrLocal{GetLocalAddress(node.addr)}; + CService addrLocal{GetLocalAddress(node)}; if (gArgs.GetBoolArg("-addrmantest", false)) { // use IPv4 loopback during addrmantest addrLocal = CService(LookupNumeric("127.0.0.1", GetListenPort())); @@ -164,8 +164,8 @@ bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE); void RemoveLocal(const CService& addr); bool SeenLocal(const CService& addr); bool IsLocal(const CService& addr); -bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr); -CService GetLocalAddress(const CNetAddr& addrPeer); +bool GetLocal(CService& addr, const CNode& peer); +CService GetLocalAddress(const CNode& peer); CService MaybeFlipIPv6toCJDNS(const CService& service); diff --git a/src/netaddress.cpp b/src/netaddress.cpp index 85ae8fab36..4758f24680 100644 --- a/src/netaddress.cpp +++ b/src/netaddress.cpp @@ -723,19 +723,16 @@ std::vector<unsigned char> CNetAddr::GetAddrBytes() const // private extensions to enum Network, only returned by GetExtNetwork, // and only used in GetReachabilityFrom -static const int NET_UNKNOWN = NET_MAX + 0; -static const int NET_TEREDO = NET_MAX + 1; -int static GetExtNetwork(const CNetAddr *addr) +static const int NET_TEREDO = NET_MAX; +int static GetExtNetwork(const CNetAddr& addr) { - if (addr == nullptr) - return NET_UNKNOWN; - if (addr->IsRFC4380()) + if (addr.IsRFC4380()) return NET_TEREDO; - return addr->GetNetwork(); + return addr.GetNetwork(); } /** Calculates a metric for how reachable (*this) is from a given partner */ -int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const +int CNetAddr::GetReachabilityFrom(const CNetAddr& paddrPartner) const { enum Reachability { REACH_UNREACHABLE, @@ -750,7 +747,7 @@ int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const if (!IsRoutable() || IsInternal()) return REACH_UNREACHABLE; - int ourNet = GetExtNetwork(this); + int ourNet = GetExtNetwork(*this); int theirNet = GetExtNetwork(paddrPartner); bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145(); @@ -790,7 +787,6 @@ int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const case NET_IPV6: return REACH_IPV6_WEAK; case NET_IPV4: return REACH_IPV4; } - case NET_UNKNOWN: case NET_UNROUTABLE: default: switch(ourNet) { diff --git a/src/netaddress.h b/src/netaddress.h index 3d15b0b123..36dc886406 100644 --- a/src/netaddress.h +++ b/src/netaddress.h @@ -203,7 +203,7 @@ public: bool HasLinkedIPv4() const; std::vector<unsigned char> GetAddrBytes() const; - int GetReachabilityFrom(const CNetAddr* paddrPartner = nullptr) 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; diff --git a/src/node/chainstatemanager_args.cpp b/src/node/chainstatemanager_args.cpp index a7f7303348..87d9238c18 100644 --- a/src/node/chainstatemanager_args.cpp +++ b/src/node/chainstatemanager_args.cpp @@ -37,8 +37,6 @@ util::Result<void> ApplyArgsManOptions(const ArgsManager& args, ChainstateManage if (auto value{args.GetIntArg("-maxtipage")}) opts.max_tip_age = std::chrono::seconds{*value}; - if (auto value{args.GetIntArg("-stopatheight")}) opts.stop_at_height = *value; - ReadDatabaseArgs(args, opts.block_tree_db); ReadDatabaseArgs(args, opts.coins_db); ReadCoinsViewArgs(args, opts.coins_view); diff --git a/src/node/kernel_notifications.cpp b/src/node/kernel_notifications.cpp index 0be7d51afb..7224127c72 100644 --- a/src/node/kernel_notifications.cpp +++ b/src/node/kernel_notifications.cpp @@ -8,6 +8,7 @@ #include <config/bitcoin-config.h> #endif +#include <chain.h> #include <common/args.h> #include <common/system.h> #include <kernel/context.h> @@ -57,9 +58,14 @@ static void DoWarning(const bilingual_str& warning) namespace node { -void KernelNotifications::blockTip(SynchronizationState state, CBlockIndex& index) +kernel::InterruptResult KernelNotifications::blockTip(SynchronizationState state, CBlockIndex& index) { uiInterface.NotifyBlockTip(state, &index); + if (m_stop_at_height && index.nHeight >= m_stop_at_height) { + StartShutdown(); + return kernel::Interrupted{}; + } + return {}; } void KernelNotifications::headerTip(SynchronizationState state, int64_t height, int64_t timestamp, bool presync) @@ -87,4 +93,9 @@ void KernelNotifications::fatalError(const std::string& debug_message, const bil node::AbortNode(m_exit_status, debug_message, user_message, m_shutdown_on_fatal_error); } +void ReadNotificationArgs(const ArgsManager& args, KernelNotifications& notifications) +{ + if (auto value{args.GetIntArg("-stopatheight")}) notifications.m_stop_at_height = *value; +} + } // namespace node diff --git a/src/node/kernel_notifications.h b/src/node/kernel_notifications.h index d35b6ecca5..b2dfc03398 100644 --- a/src/node/kernel_notifications.h +++ b/src/node/kernel_notifications.h @@ -11,17 +11,21 @@ #include <cstdint> #include <string> +class ArgsManager; class CBlockIndex; enum class SynchronizationState; struct bilingual_str; namespace node { + +static constexpr int DEFAULT_STOPATHEIGHT{0}; + class KernelNotifications : public kernel::Notifications { public: KernelNotifications(std::atomic<int>& exit_status) : m_exit_status{exit_status} {} - void blockTip(SynchronizationState state, CBlockIndex& index) override; + [[nodiscard]] kernel::InterruptResult blockTip(SynchronizationState state, CBlockIndex& index) override; void headerTip(SynchronizationState state, int64_t height, int64_t timestamp, bool presync) override; @@ -33,11 +37,16 @@ public: void fatalError(const std::string& debug_message, const bilingual_str& user_message = {}) override; + //! Block height after which blockTip notification will return Interrupted{}, if >0. + int m_stop_at_height{DEFAULT_STOPATHEIGHT}; //! Useful for tests, can be set to false to avoid shutdown on fatal error. bool m_shutdown_on_fatal_error{true}; private: std::atomic<int>& m_exit_status; }; + +void ReadNotificationArgs(const ArgsManager& args, KernelNotifications& notifications); + } // namespace node #endif // BITCOIN_NODE_KERNEL_NOTIFICATIONS_H diff --git a/src/qt/psbtoperationsdialog.cpp b/src/qt/psbtoperationsdialog.cpp index fe52e11157..26f1696de1 100644 --- a/src/qt/psbtoperationsdialog.cpp +++ b/src/qt/psbtoperationsdialog.cpp @@ -182,6 +182,8 @@ std::string PSBTOperationsDialog::renderTransaction(const PartiallySignedTransac tx_description.append(tr(" * Sends %1 to %2") .arg(BitcoinUnits::formatWithUnit(BitcoinUnit::BTC, out.nValue)) .arg(QString::fromStdString(EncodeDestination(address)))); + // Check if the address is one of ours + if (m_wallet_model != nullptr && m_wallet_model->wallet().txoutIsMine(out)) tx_description.append(" (" + tr("own address") + ")"); tx_description.append("<br>"); } diff --git a/src/test/crypto_tests.cpp b/src/test/crypto_tests.cpp index e4e8596a5d..b29df832b4 100644 --- a/src/test/crypto_tests.cpp +++ b/src/test/crypto_tests.cpp @@ -131,14 +131,13 @@ static void TestAES256CBC(const std::string &hexkey, const std::string &hexiv, b } } -static void TestChaCha20(const std::string &hex_message, const std::string &hexkey, uint64_t nonce, uint64_t seek, const std::string& hexout) +static void TestChaCha20(const std::string &hex_message, const std::string &hexkey, ChaCha20::Nonce96 nonce, uint32_t seek, const std::string& hexout) { std::vector<unsigned char> key = ParseHex(hexkey); assert(key.size() == 32); std::vector<unsigned char> m = ParseHex(hex_message); ChaCha20 rng(key.data()); - rng.SetIV(nonce); - rng.Seek64(seek); + rng.Seek64(nonce, seek); std::vector<unsigned char> outres; outres.resize(hexout.size() / 2); assert(hex_message.empty() || m.size() * 2 == hexout.size()); @@ -152,8 +151,7 @@ static void TestChaCha20(const std::string &hex_message, const std::string &hexk BOOST_CHECK_EQUAL(hexout, HexStr(outres)); if (!hex_message.empty()) { // Manually XOR with the keystream and compare the output - rng.SetIV(nonce); - rng.Seek64(seek); + rng.Seek64(nonce, seek); std::vector<unsigned char> only_keystream(outres.size()); rng.Keystream(only_keystream.data(), only_keystream.size()); for (size_t i = 0; i != m.size(); i++) { @@ -169,7 +167,7 @@ static void TestChaCha20(const std::string &hex_message, const std::string &hexk lens[1] = InsecureRandRange(hexout.size() / 2U + 1U - lens[0]); lens[2] = hexout.size() / 2U - lens[0] - lens[1]; - rng.Seek64(seek); + rng.Seek64(nonce, seek); outres.assign(hexout.size() / 2U, 0); size_t pos = 0; for (int j = 0; j < 3; ++j) { @@ -482,38 +480,57 @@ BOOST_AUTO_TEST_CASE(aes_cbc_testvectors) { BOOST_AUTO_TEST_CASE(chacha20_testvector) { + /* Example from RFC8439 section 2.3.2. */ + TestChaCha20("", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + {0x09000000, 0x4a000000}, 1, + "10f1e7e4d13b5915500fdd1fa32071c4c7d1f4c733c068030422aa9ac3d46c4e" + "d2826446079faa0914c2d705d98b02a2b5129cd1de164eb9cbd083e8a2503c4e"); + + /* Example from RFC8439 section 2.4.2. */ + TestChaCha20("4c616469657320616e642047656e746c656d656e206f662074686520636c6173" + "73206f66202739393a204966204920636f756c64206f6666657220796f75206f" + "6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73" + "637265656e20776f756c642062652069742e", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + {0, 0x4a000000}, 1, + "6e2e359a2568f98041ba0728dd0d6981e97e7aec1d4360c20a27afccfd9fae0b" + "f91b65c5524733ab8f593dabcd62b3571639d624e65152ab8f530c359f0861d8" + "07ca0dbf500d6a6156a38e088a22b65e52bc514d16ccf806818ce91ab7793736" + "5af90bbf74a35be6b40b8eedf2785e42874d"); + // RFC 7539/8439 A.1 Test Vector #1: TestChaCha20("", "0000000000000000000000000000000000000000000000000000000000000000", - 0, 0, + {0, 0}, 0, "76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7" "da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586"); // RFC 7539/8439 A.1 Test Vector #2: TestChaCha20("", "0000000000000000000000000000000000000000000000000000000000000000", - 0, 1, + {0, 0}, 1, "9f07e7be5551387a98ba977c732d080dcb0f29a048e3656912c6533e32ee7aed" "29b721769ce64e43d57133b074d839d531ed1f28510afb45ace10a1f4b794d6f"); // RFC 7539/8439 A.1 Test Vector #3: TestChaCha20("", "0000000000000000000000000000000000000000000000000000000000000001", - 0, 1, + {0, 0}, 1, "3aeb5224ecf849929b9d828db1ced4dd832025e8018b8160b82284f3c949aa5a" "8eca00bbb4a73bdad192b5c42f73f2fd4e273644c8b36125a64addeb006c13a0"); // RFC 7539/8439 A.1 Test Vector #4: TestChaCha20("", "00ff000000000000000000000000000000000000000000000000000000000000", - 0, 2, + {0, 0}, 2, "72d54dfbf12ec44b362692df94137f328fea8da73990265ec1bbbea1ae9af0ca" "13b25aa26cb4a648cb9b9d1be65b2c0924a66c54d545ec1b7374f4872e99f096"); // RFC 7539/8439 A.1 Test Vector #5: TestChaCha20("", "0000000000000000000000000000000000000000000000000000000000000000", - 0x200000000000000, 0, + {0, 0x200000000000000}, 0, "c2c64d378cd536374ae204b9ef933fcd1a8b2288b3dfa49672ab765b54ee27c7" "8a970e0e955c14f3a88e741b97c286f75f8fc299e8148362fa198a39531bed6d"); @@ -521,7 +538,7 @@ BOOST_AUTO_TEST_CASE(chacha20_testvector) TestChaCha20("0000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", - 0, 0, + {0, 0}, 0, "76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7" "da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586"); @@ -539,7 +556,7 @@ BOOST_AUTO_TEST_CASE(chacha20_testvector) "74696f6e73206d61646520617420616e792074696d65206f7220706c6163652c" "207768696368206172652061646472657373656420746f", "0000000000000000000000000000000000000000000000000000000000000001", - 0x200000000000000, 1, + {0, 0x200000000000000}, 1, "a3fbf07df3fa2fde4f376ca23e82737041605d9f4f4f57bd8cff2c1d4b7955ec" "2a97948bd3722915c8f3d337f7d370050e9e96d647b7c39f56e031ca5eb6250d" "4042e02785ececfa4b4bb5e8ead0440e20b6e8db09d881a7c6132f420e527950" @@ -559,27 +576,93 @@ BOOST_AUTO_TEST_CASE(chacha20_testvector) "6162653a0a416c6c206d696d737920776572652074686520626f726f676f7665" "732c0a416e6420746865206d6f6d65207261746873206f757467726162652e", "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0", - 0x200000000000000, 42, + {0, 0x200000000000000}, 42, "62e6347f95ed87a45ffae7426f27a1df5fb69110044c0d73118effa95b01e5cf" "166d3df2d721caf9b21e5fb14c616871fd84c54f9d65b283196c7fe4f60553eb" "f39c6402c42234e32a356b3e764312a61a5532055716ead6962568f87d3f3f77" "04c6a8d1bcd1bf4d50d6154b6da731b187b58dfd728afa36757a797ac188d1"); + // RFC 7539/8439 A.4 Test Vector #1: + TestChaCha20("", + "0000000000000000000000000000000000000000000000000000000000000000", + {0, 0}, 0, + "76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7"); + + // RFC 7539/8439 A.4 Test Vector #2: + TestChaCha20("", + "0000000000000000000000000000000000000000000000000000000000000001", + {0, 0x200000000000000}, 0, + "ecfa254f845f647473d3cb140da9e87606cb33066c447b87bc2666dde3fbb739"); + + // RFC 7539/8439 A.4 Test Vector #3: + TestChaCha20("", + "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0", + {0, 0x200000000000000}, 0, + "965e3bc6f9ec7ed9560808f4d229f94b137ff275ca9b3fcbdd59deaad23310ae"); + // test encryption TestChaCha20("4c616469657320616e642047656e746c656d656e206f662074686520636c617373206f66202739393a204966204920636f756" "c64206f6666657220796f75206f6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73637265656e" "20776f756c642062652069742e", - "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", 0x4a000000UL, 1, + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", {0, 0x4a000000UL}, 1, "6e2e359a2568f98041ba0728dd0d6981e97e7aec1d4360c20a27afccfd9fae0bf91b65c5524733ab8f593dabcd62b3571639d" "624e65152ab8f530c359f0861d807ca0dbf500d6a6156a38e088a22b65e52bc514d16ccf806818ce91ab77937365af90bbf74" "a35be6b40b8eedf2785e42874d" ); // test keystream output - TestChaCha20("", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", 0x4a000000UL, 1, + TestChaCha20("", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", {0, 0x4a000000UL}, 1, "224f51f3401bd9e12fde276fb8631ded8c131f823d2c06e27e4fcaec9ef3cf788a3b0aa372600a92b57974cded2b9334794cb" "a40c63e34cdea212c4cf07d41b769a6749f3f630f4122cafe28ec4dc47e26d4346d70b98c73f3e9c53ac40c5945398b6eda1a" "832c89c167eacd901d7e2bf363"); + + // Test vectors from https://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-7 + // The first one is identical to the above one from the RFC8439 A.1 vectors, but repeated here + // for completeness. + TestChaCha20("", + "0000000000000000000000000000000000000000000000000000000000000000", + {0, 0}, 0, + "76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7" + "da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586"); + TestChaCha20("", + "0000000000000000000000000000000000000000000000000000000000000001", + {0, 0}, 0, + "4540f05a9f1fb296d7736e7b208e3c96eb4fe1834688d2604f450952ed432d41" + "bbe2a0b6ea7566d2a5d1e7e20d42af2c53d792b1c43fea817e9ad275ae546963"); + TestChaCha20("", + "0000000000000000000000000000000000000000000000000000000000000000", + {0, 0x0100000000000000ULL}, 0, + "de9cba7bf3d69ef5e786dc63973f653a0b49e015adbff7134fcb7df137821031" + "e85a050278a7084527214f73efc7fa5b5277062eb7a0433e445f41e3"); + TestChaCha20("", + "0000000000000000000000000000000000000000000000000000000000000000", + {0, 1}, 0, + "ef3fdfd6c61578fbf5cf35bd3dd33b8009631634d21e42ac33960bd138e50d32" + "111e4caf237ee53ca8ad6426194a88545ddc497a0b466e7d6bbdb0041b2f586b"); + TestChaCha20("", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + {0, 0x0706050403020100ULL}, 0, + "f798a189f195e66982105ffb640bb7757f579da31602fc93ec01ac56f85ac3c1" + "34a4547b733b46413042c9440049176905d3be59ea1c53f15916155c2be8241a" + "38008b9a26bc35941e2444177c8ade6689de95264986d95889fb60e84629c9bd" + "9a5acb1cc118be563eb9b3a4a472f82e09a7e778492b562ef7130e88dfe031c7" + "9db9d4f7c7a899151b9a475032b63fc385245fe054e3dd5a97a5f576fe064025" + "d3ce042c566ab2c507b138db853e3d6959660996546cc9c4a6eafdc777c040d7" + "0eaf46f76dad3979e5c5360c3317166a1c894c94a371876a94df7628fe4eaaf2" + "ccb27d5aaae0ad7ad0f9d4b6ad3b54098746d4524d38407a6deb3ab78fab78c9"); + + // Test overflow of 32-bit block counter, should increment the first 32-bit + // part of the nonce to retain compatibility with >256 GiB output. + // The test data was generated with an implementation that uses a 64-bit + // counter and a 64-bit initialization vector (PyCryptodome's ChaCha20 class + // with 8 bytes nonce length). + TestChaCha20("", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + {0, 0xdeadbeef12345678}, 0xffffffff, + "2d292c880513397b91221c3a647cfb0765a4815894715f411e3df5e0dd0ba9df" + "fd565dea5addbdb914208fde7950f23e0385f9a727143f6a6ac51d84b1c0fb3e" + "2e3b00b63d6841a1cc6d1538b1d3a74bef1eb2f54c7b7281e36e484dba89b351" + "c8f572617e61e342879f211b0e4c515df50ea9d0771518fad96cd0baee62deb6"); } BOOST_AUTO_TEST_CASE(chacha20_midblock) @@ -730,8 +813,7 @@ static void TestChaCha20Poly1305AEAD(bool must_succeed, unsigned int expected_aa BOOST_CHECK(memcmp(ciphertext_buf.data(), expected_ciphertext_and_mac.data(), ciphertext_buf.size()) == 0); // manually construct the AAD keystream - cmp_ctx.SetIV(seqnr_aad); - cmp_ctx.Seek64(0); + cmp_ctx.Seek64({0, seqnr_aad}, 0); cmp_ctx.Keystream(cmp_ctx_buffer.data(), 64); BOOST_CHECK(memcmp(expected_aad_keystream.data(), cmp_ctx_buffer.data(), expected_aad_keystream.size()) == 0); // crypt the 3 length bytes and compare the length @@ -758,8 +840,7 @@ static void TestChaCha20Poly1305AEAD(bool must_succeed, unsigned int expected_aa BOOST_CHECK(memcmp(ciphertext_buf.data(), expected_ciphertext_and_mac_sequence999.data(), expected_ciphertext_and_mac_sequence999.size()) == 0); } // set nonce and block counter, output the keystream - cmp_ctx.SetIV(seqnr_aad); - cmp_ctx.Seek64(0); + cmp_ctx.Seek64({0, seqnr_aad}, 0); cmp_ctx.Keystream(cmp_ctx_buffer.data(), 64); // crypt the 3 length bytes and compare the length diff --git a/src/test/fuzz/FuzzedDataProvider.h b/src/test/fuzz/FuzzedDataProvider.h index 6cbfc39bc2..8a8214bd99 100644 --- a/src/test/fuzz/FuzzedDataProvider.h +++ b/src/test/fuzz/FuzzedDataProvider.h @@ -209,7 +209,7 @@ T FuzzedDataProvider::ConsumeIntegralInRange(T min, T max) { abort(); // Use the biggest type possible to hold the range and the result. - uint64_t range = static_cast<uint64_t>(max) - min; + uint64_t range = static_cast<uint64_t>(max) - static_cast<uint64_t>(min); uint64_t result = 0; size_t offset = 0; @@ -230,7 +230,7 @@ T FuzzedDataProvider::ConsumeIntegralInRange(T min, T max) { if (range != std::numeric_limits<decltype(range)>::max()) result = result % (range + 1); - return static_cast<T>(min + result); + return static_cast<T>(static_cast<uint64_t>(min) + result); } // Returns a floating point value in the range [Type's lowest, Type's max] by @@ -390,7 +390,7 @@ TS FuzzedDataProvider::ConvertUnsignedToSigned(TU value) { return static_cast<TS>(value); } else { constexpr auto TS_min = std::numeric_limits<TS>::min(); - return TS_min + static_cast<char>(value - TS_min); + return TS_min + static_cast<TS>(value - TS_min); } } diff --git a/src/test/fuzz/addrman.cpp b/src/test/fuzz/addrman.cpp index e0fa7ae908..f0035ddf21 100644 --- a/src/test/fuzz/addrman.cpp +++ b/src/test/fuzz/addrman.cpp @@ -300,12 +300,20 @@ FUZZ_TARGET(addrman, .init = initialize_addrman) }); } const AddrMan& const_addr_man{addr_man}; + std::optional<Network> network; + if (fuzzed_data_provider.ConsumeBool()) { + network = fuzzed_data_provider.PickValueInArray(ALL_NETWORKS); + } (void)const_addr_man.GetAddr( /*max_addresses=*/fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096), /*max_pct=*/fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096), - /*network=*/std::nullopt); - (void)const_addr_man.Select(fuzzed_data_provider.ConsumeBool()); - (void)const_addr_man.Size(); + network); + (void)const_addr_man.Select(fuzzed_data_provider.ConsumeBool(), network); + std::optional<bool> in_new; + if (fuzzed_data_provider.ConsumeBool()) { + in_new = fuzzed_data_provider.ConsumeBool(); + } + (void)const_addr_man.Size(network, in_new); CDataStream data_stream(SER_NETWORK, PROTOCOL_VERSION); data_stream << const_addr_man; } diff --git a/src/test/fuzz/crypto_chacha20.cpp b/src/test/fuzz/crypto_chacha20.cpp index 3fa445096a..63c7bf3b45 100644 --- a/src/test/fuzz/crypto_chacha20.cpp +++ b/src/test/fuzz/crypto_chacha20.cpp @@ -28,10 +28,11 @@ FUZZ_TARGET(crypto_chacha20) chacha20.SetKey32(key.data()); }, [&] { - chacha20.SetIV(fuzzed_data_provider.ConsumeIntegral<uint64_t>()); - }, - [&] { - chacha20.Seek64(fuzzed_data_provider.ConsumeIntegral<uint64_t>()); + chacha20.Seek64( + { + fuzzed_data_provider.ConsumeIntegral<uint32_t>(), + fuzzed_data_provider.ConsumeIntegral<uint64_t>() + }, fuzzed_data_provider.ConsumeIntegral<uint32_t>()); }, [&] { std::vector<uint8_t> output(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096)); @@ -63,17 +64,16 @@ void ChaCha20SplitFuzz(FuzzedDataProvider& provider) auto key_bytes = provider.ConsumeBytes<unsigned char>(32); std::copy(key_bytes.begin(), key_bytes.end(), key); uint64_t iv = provider.ConsumeIntegral<uint64_t>(); + uint32_t iv_prefix = provider.ConsumeIntegral<uint32_t>(); uint64_t total_bytes = provider.ConsumeIntegralInRange<uint64_t>(0, 1000000); - /* ~x = 2^64 - 1 - x, so ~(total_bytes >> 6) is the maximal seek position. */ - uint64_t seek = provider.ConsumeIntegralInRange<uint64_t>(0, ~(total_bytes >> 6)); + /* ~x = 2^BITS - 1 - x, so ~(total_bytes >> 6) is the maximal seek position. */ + uint32_t seek = provider.ConsumeIntegralInRange<uint32_t>(0, ~(uint32_t)(total_bytes >> 6)); // Initialize two ChaCha20 ciphers, with the same key/iv/position. ChaCha20 crypt1(key); ChaCha20 crypt2(key); - crypt1.SetIV(iv); - crypt1.Seek64(seek); - crypt2.SetIV(iv); - crypt2.Seek64(seek); + crypt1.Seek64({iv_prefix, iv}, seek); + crypt2.Seek64({iv_prefix, iv}, seek); // Construct vectors with data. std::vector<unsigned char> data1, data2; diff --git a/src/test/fuzz/crypto_diff_fuzz_chacha20.cpp b/src/test/fuzz/crypto_diff_fuzz_chacha20.cpp index 78fee48de6..285ea2dfe0 100644 --- a/src/test/fuzz/crypto_diff_fuzz_chacha20.cpp +++ b/src/test/fuzz/crypto_diff_fuzz_chacha20.cpp @@ -284,6 +284,8 @@ FUZZ_TARGET(crypto_diff_fuzz_chacha20) // ECRYPT_keysetup() doesn't set the counter and nonce to 0 while SetKey32() does static const uint8_t iv[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + ChaCha20::Nonce96 nonce{0, 0}; + uint32_t counter{0}; ECRYPT_ivsetup(&ctx, iv); LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), 3000) { @@ -292,45 +294,56 @@ FUZZ_TARGET(crypto_diff_fuzz_chacha20) [&] { const std::vector<unsigned char> key = ConsumeFixedLengthByteVector(fuzzed_data_provider, 32); chacha20.SetKey32(key.data()); + nonce = {0, 0}; + counter = 0; ECRYPT_keysetup(&ctx, key.data(), key.size() * 8, 0); // ECRYPT_keysetup() doesn't set the counter and nonce to 0 while SetKey32() does uint8_t iv[8] = {0, 0, 0, 0, 0, 0, 0, 0}; ECRYPT_ivsetup(&ctx, iv); }, [&] { + uint32_t iv_prefix = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); uint64_t iv = fuzzed_data_provider.ConsumeIntegral<uint64_t>(); - chacha20.SetIV(iv); + nonce = {iv_prefix, iv}; + counter = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); + chacha20.Seek64(nonce, counter); + ctx.input[12] = counter; + ctx.input[13] = iv_prefix; ctx.input[14] = iv; ctx.input[15] = iv >> 32; }, [&] { - uint64_t counter = fuzzed_data_provider.ConsumeIntegral<uint64_t>(); - chacha20.Seek64(counter); - ctx.input[12] = counter; - ctx.input[13] = counter >> 32; - }, - [&] { uint32_t integralInRange = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096); - // DJB's version seeks forward to a multiple of 64 bytes after every operation. Correct for that. - uint64_t pos = ctx.input[12] + (((uint64_t)ctx.input[13]) << 32) + ((integralInRange + 63) >> 6); std::vector<uint8_t> output(integralInRange); chacha20.Keystream(output.data(), output.size()); std::vector<uint8_t> djb_output(integralInRange); ECRYPT_keystream_bytes(&ctx, djb_output.data(), djb_output.size()); assert(output == djb_output); - chacha20.Seek64(pos); + // DJB's version seeks forward to a multiple of 64 bytes after every operation. Correct for that. + uint32_t old_counter = counter; + counter += (integralInRange + 63) >> 6; + if (counter < old_counter) ++nonce.first; + if (integralInRange & 63) { + chacha20.Seek64(nonce, counter); + } + assert(counter == ctx.input[12]); }, [&] { uint32_t integralInRange = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096); - // DJB's version seeks forward to a multiple of 64 bytes after every operation. Correct for that. - uint64_t pos = ctx.input[12] + (((uint64_t)ctx.input[13]) << 32) + ((integralInRange + 63) >> 6); std::vector<uint8_t> output(integralInRange); const std::vector<uint8_t> input = ConsumeFixedLengthByteVector(fuzzed_data_provider, output.size()); chacha20.Crypt(input.data(), output.data(), input.size()); std::vector<uint8_t> djb_output(integralInRange); ECRYPT_encrypt_bytes(&ctx, input.data(), djb_output.data(), input.size()); assert(output == djb_output); - chacha20.Seek64(pos); + // DJB's version seeks forward to a multiple of 64 bytes after every operation. Correct for that. + uint32_t old_counter = counter; + counter += (integralInRange + 63) >> 6; + if (counter < old_counter) ++nonce.first; + if (integralInRange & 63) { + chacha20.Seek64(nonce, counter); + } + assert(counter == ctx.input[12]); }); } } diff --git a/src/test/fuzz/netaddress.cpp b/src/test/fuzz/netaddress.cpp index 049ae02f4d..5141d3362d 100644 --- a/src/test/fuzz/netaddress.cpp +++ b/src/test/fuzz/netaddress.cpp @@ -84,7 +84,7 @@ FUZZ_TARGET(netaddress) (void)CServiceHash(0, 0)(service); const CNetAddr other_net_addr = ConsumeNetAddr(fuzzed_data_provider); - (void)net_addr.GetReachabilityFrom(&other_net_addr); + (void)net_addr.GetReachabilityFrom(other_net_addr); (void)sub_net.Match(other_net_addr); const CService other_service{net_addr, fuzzed_data_provider.ConsumeIntegral<uint16_t>()}; diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp index aa577f7b27..ead604598e 100644 --- a/src/test/net_tests.cpp +++ b/src/test/net_tests.cpp @@ -904,4 +904,109 @@ BOOST_AUTO_TEST_CASE(initial_advertise_from_version_message) TestOnlyResetTimeData(); } + +BOOST_AUTO_TEST_CASE(advertise_local_address) +{ + auto CreatePeer = [](const CAddress& addr) { + return std::make_unique<CNode>(/*id=*/0, + /*sock=*/nullptr, + addr, + /*nKeyedNetGroupIn=*/0, + /*nLocalHostNonceIn=*/0, + CAddress{}, + /*pszDest=*/std::string{}, + ConnectionType::OUTBOUND_FULL_RELAY, + /*inbound_onion=*/false); + }; + SetReachable(NET_CJDNS, true); + + CAddress addr_ipv4{Lookup("1.2.3.4", 8333, false).value(), NODE_NONE}; + BOOST_REQUIRE(addr_ipv4.IsValid()); + BOOST_REQUIRE(addr_ipv4.IsIPv4()); + + CAddress addr_ipv6{Lookup("1122:3344:5566:7788:9900:aabb:ccdd:eeff", 8333, false).value(), NODE_NONE}; + BOOST_REQUIRE(addr_ipv6.IsValid()); + BOOST_REQUIRE(addr_ipv6.IsIPv6()); + + CAddress addr_ipv6_tunnel{Lookup("2002:3344:5566:7788:9900:aabb:ccdd:eeff", 8333, false).value(), NODE_NONE}; + BOOST_REQUIRE(addr_ipv6_tunnel.IsValid()); + BOOST_REQUIRE(addr_ipv6_tunnel.IsIPv6()); + BOOST_REQUIRE(addr_ipv6_tunnel.IsRFC3964()); + + CAddress addr_teredo{Lookup("2001:0000:5566:7788:9900:aabb:ccdd:eeff", 8333, false).value(), NODE_NONE}; + BOOST_REQUIRE(addr_teredo.IsValid()); + BOOST_REQUIRE(addr_teredo.IsIPv6()); + BOOST_REQUIRE(addr_teredo.IsRFC4380()); + + CAddress addr_onion; + BOOST_REQUIRE(addr_onion.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion")); + BOOST_REQUIRE(addr_onion.IsValid()); + BOOST_REQUIRE(addr_onion.IsTor()); + + CAddress addr_i2p; + BOOST_REQUIRE(addr_i2p.SetSpecial("udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna.b32.i2p")); + BOOST_REQUIRE(addr_i2p.IsValid()); + BOOST_REQUIRE(addr_i2p.IsI2P()); + + CService service_cjdns{Lookup("fc00:3344:5566:7788:9900:aabb:ccdd:eeff", 8333, false).value(), NODE_NONE}; + CAddress addr_cjdns{MaybeFlipIPv6toCJDNS(service_cjdns), NODE_NONE}; + BOOST_REQUIRE(addr_cjdns.IsValid()); + BOOST_REQUIRE(addr_cjdns.IsCJDNS()); + + const auto peer_ipv4{CreatePeer(addr_ipv4)}; + const auto peer_ipv6{CreatePeer(addr_ipv6)}; + const auto peer_ipv6_tunnel{CreatePeer(addr_ipv6_tunnel)}; + const auto peer_teredo{CreatePeer(addr_teredo)}; + const auto peer_onion{CreatePeer(addr_onion)}; + const auto peer_i2p{CreatePeer(addr_i2p)}; + const auto peer_cjdns{CreatePeer(addr_cjdns)}; + + // one local clearnet address - advertise to all but privacy peers + AddLocal(addr_ipv4); + BOOST_CHECK(GetLocalAddress(*peer_ipv4) == addr_ipv4); + BOOST_CHECK(GetLocalAddress(*peer_ipv6) == addr_ipv4); + BOOST_CHECK(GetLocalAddress(*peer_ipv6_tunnel) == addr_ipv4); + BOOST_CHECK(GetLocalAddress(*peer_teredo) == addr_ipv4); + BOOST_CHECK(GetLocalAddress(*peer_cjdns) == addr_ipv4); + BOOST_CHECK(!GetLocalAddress(*peer_onion).IsValid()); + BOOST_CHECK(!GetLocalAddress(*peer_i2p).IsValid()); + RemoveLocal(addr_ipv4); + + // local privacy addresses - don't advertise to clearnet peers + AddLocal(addr_onion); + AddLocal(addr_i2p); + BOOST_CHECK(!GetLocalAddress(*peer_ipv4).IsValid()); + BOOST_CHECK(!GetLocalAddress(*peer_ipv6).IsValid()); + BOOST_CHECK(!GetLocalAddress(*peer_ipv6_tunnel).IsValid()); + BOOST_CHECK(!GetLocalAddress(*peer_teredo).IsValid()); + BOOST_CHECK(!GetLocalAddress(*peer_cjdns).IsValid()); + BOOST_CHECK(GetLocalAddress(*peer_onion) == addr_onion); + BOOST_CHECK(GetLocalAddress(*peer_i2p) == addr_i2p); + RemoveLocal(addr_onion); + RemoveLocal(addr_i2p); + + // local addresses from all networks + AddLocal(addr_ipv4); + AddLocal(addr_ipv6); + AddLocal(addr_ipv6_tunnel); + AddLocal(addr_teredo); + AddLocal(addr_onion); + AddLocal(addr_i2p); + AddLocal(addr_cjdns); + BOOST_CHECK(GetLocalAddress(*peer_ipv4) == addr_ipv4); + BOOST_CHECK(GetLocalAddress(*peer_ipv6) == addr_ipv6); + BOOST_CHECK(GetLocalAddress(*peer_ipv6_tunnel) == addr_ipv6); + BOOST_CHECK(GetLocalAddress(*peer_teredo) == addr_ipv4); + BOOST_CHECK(GetLocalAddress(*peer_onion) == addr_onion); + BOOST_CHECK(GetLocalAddress(*peer_i2p) == addr_i2p); + BOOST_CHECK(GetLocalAddress(*peer_cjdns) == addr_cjdns); + RemoveLocal(addr_ipv4); + RemoveLocal(addr_ipv6); + RemoveLocal(addr_ipv6_tunnel); + RemoveLocal(addr_teredo); + RemoveLocal(addr_onion); + RemoveLocal(addr_i2p); + RemoveLocal(addr_cjdns); +} + BOOST_AUTO_TEST_SUITE_END() diff --git a/src/validation.cpp b/src/validation.cpp index be6afbd320..5bf8bd70e2 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -37,7 +37,6 @@ #include <reverse_iterator.h> #include <script/script.h> #include <script/sigcache.h> -#include <shutdown.h> #include <signet.h> #include <tinyformat.h> #include <txdb.h> @@ -3172,13 +3171,17 @@ bool Chainstate::ActivateBestChain(BlockValidationState& state, std::shared_ptr< GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload); // Always notify the UI if a new block tip was connected - m_chainman.GetNotifications().blockTip(GetSynchronizationState(fInitialDownload), *pindexNewTip); + if (kernel::IsInterrupted(m_chainman.GetNotifications().blockTip(GetSynchronizationState(fInitialDownload), *pindexNewTip))) { + // Just breaking and returning success for now. This could + // be changed to bubble up the kernel::Interrupted value to + // the caller so the caller could distinguish between + // completed and interrupted operations. + break; + } } } // When we reach this point, we switched to a new tip (stored in pindexNewTip). - if (m_chainman.StopAtHeight() && pindexNewTip && pindexNewTip->nHeight >= m_chainman.StopAtHeight()) StartShutdown(); - if (WITH_LOCK(::cs_main, return m_disabled)) { // Background chainstate has reached the snapshot base block, so exit. break; @@ -3369,7 +3372,14 @@ bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* pinde // Only notify about a new block tip if the active chain was modified. if (pindex_was_in_chain) { - m_chainman.GetNotifications().blockTip(GetSynchronizationState(IsInitialBlockDownload()), *to_mark_failed->pprev); + // Ignoring return value for now, this could be changed to bubble up + // kernel::Interrupted value to the caller so the caller could + // distinguish between completed and interrupted operations. It might + // also make sense for the blockTip notification to have an enum + // parameter indicating the source of the tip change so hooks can + // distinguish user-initiated invalidateblock changes from other + // changes. + (void)m_chainman.GetNotifications().blockTip(GetSynchronizationState(IsInitialBlockDownload()), *to_mark_failed->pprev); } return true; } diff --git a/src/validation.h b/src/validation.h index 49860f2d6a..af8ceb5dfa 100644 --- a/src/validation.h +++ b/src/validation.h @@ -23,7 +23,6 @@ #include <policy/packages.h> #include <policy/policy.h> #include <script/script_error.h> -#include <shutdown.h> #include <sync.h> #include <txdb.h> #include <txmempool.h> // For CTxMemPool::cs @@ -970,7 +969,6 @@ public: 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; }; - int StopAtHeight() const { return m_options.stop_at_height; }; /** * Alias for ::cs_main. diff --git a/test/sanitizer_suppressions/ubsan b/test/sanitizer_suppressions/ubsan index 74703b04ec..1ec97f7563 100644 --- a/test/sanitizer_suppressions/ubsan +++ b/test/sanitizer_suppressions/ubsan @@ -20,8 +20,6 @@ implicit-integer-sign-change:*/include/boost/ implicit-integer-sign-change:*/include/c++/ implicit-integer-sign-change:*/new_allocator.h implicit-integer-sign-change:crc32c/ -# implicit-integer-sign-change in FuzzedDataProvider's ConsumeIntegralInRange -implicit-integer-sign-change:FuzzedDataProvider.h implicit-integer-sign-change:minisketch/ implicit-signed-integer-truncation:*/include/c++/ implicit-signed-integer-truncation:leveldb/ |