From 4152190f1586568dcd6acffa69bbb30974535841 Mon Sep 17 00:00:00 2001 From: Konstantin Akimov Date: Thu, 28 Apr 2022 14:56:27 +0100 Subject: [PATCH 01/12] Merge bitcoin/bitcoin#24322: [kernel 1/n] Introduce initial `libbitcoinkernel` BACKPORT NOTE: build: Don't add unrelated libs to LIBTEST_* --- done via a3c11b679bea0e84f2bf96ac76e998b50b66eab8 035fa1f07aacb7bce74c0884ae28c8cf00fe3b1b build: Remove LIBTOOL_APP_LDFLAGS for bitcoin-chainstate (Cory Fields) 3f0595095dd6d230dc661641227937e3ab4ca8d3 docs: Add libbitcoinkernel_la_SOURCES explanation (Carl Dong) 94ad45deb257a95b4e98aa85da0371fb072fcd4c ci: Build libbitcoinkernel (Carl Dong) 26b2e7ffb3471a4712e5b9e50e066e0e3218f0dd build: Extract the libbitcoinkernel library (Carl Dong) 1df44dd20ca9e6e55eb353824b27d11bd1878c59 b-cs: Define G_TRANSLATION_FUN in bitcoinkernel.cpp (Carl Dong) 83a0bb7cc9907dbe089409ed5a417277ed63ed95 build: Separate lib_LTLIBRARIES initialization (Carl Dong) c1e16cb31f4d8edde8fea310011189b8b272cb07 build: Create .la library for bitcoincrypto (Carl Dong) 8bdfe057c796dde1cd2e5a37a73e87a879e9fe56 build: Create .la library for leveldb (Carl Dong) 05d1525b6d4412f68ff4c5460cd1daa6fb49969b build: Create .la library for crc32c (Carl Dong) 64caf944797bc35c3044fe5675389656f9511a41 build: Remove vestigial LIBLEVELDB_SSE42 (Carl Dong) 1392e8e2d8cfe4115f0a152aca16ffe3f0f4573a build: Don't add unrelated libs to LIBTEST_* (Carl Dong) Pull request description: Part of: #24303 This PR introduces a `libbitcoinkernel` static library linking in the minimal list of files necessary to use our consensus engine as-is. `bitcoin-chainstate` introduced in #24304 now will link against `libbitcoinkernel`. Most of the changes are related to the build system. Please read the commit messages for more details. ACKs for top commit: theuni: This may be my favorite PR ever. It's a privilege to ACK 035fa1f07aacb7bce74c0884ae28c8cf00fe3b1b. Tree-SHA512: b755edc3471c7c1098847e9b16ab182a6abb7582563d9da516de376a770ac7543c6fdb24238ddd4d3d2d458f905a0c0614b8667aab182aa7e6b80c1cca7090bc Co-authored-by: fanquake --- ...up_env_native_nowallet_libbitcoinkernel.sh | 2 +- configure.ac | 16 ++++- src/Makefile.am | 70 ++++++++++++++----- src/bitcoin-chainstate.cpp | 34 --------- src/bls/bls.h | 2 - src/bls/bls_worker.cpp | 2 + src/bls/bls_worker.h | 2 + src/kernel/bitcoinkernel.cpp | 45 ++++++++++++ 8 files changed, 118 insertions(+), 55 deletions(-) create mode 100644 src/kernel/bitcoinkernel.cpp diff --git a/ci/test/00_setup_env_native_nowallet_libbitcoinkernel.sh b/ci/test/00_setup_env_native_nowallet_libbitcoinkernel.sh index ef228c677fef..291e949631c2 100755 --- a/ci/test/00_setup_env_native_nowallet_libbitcoinkernel.sh +++ b/ci/test/00_setup_env_native_nowallet_libbitcoinkernel.sh @@ -11,4 +11,4 @@ export HOST=x86_64-pc-linux-gnu export PACKAGES="python3-zmq" export DEP_OPTS="NO_WALLET=1 CC=gcc-14 CXX=g++-14" export GOAL="install" -export BITCOIN_CONFIG="--enable-reduce-exports CC=gcc-14 CXX=g++-14 --enable-experimental-util-chainstate" +export BITCOIN_CONFIG="--enable-reduce-exports CC=gcc-14 CXX=g++-14 --enable-experimental-util-chainstate --with-experimental-kernel-lib --enable-shared" diff --git a/configure.ac b/configure.ac index 0c97af58e657..f523915a855b 100644 --- a/configure.ac +++ b/configure.ac @@ -783,6 +783,12 @@ AC_ARG_WITH([libs], [build_bitcoin_libs=$withval], [build_bitcoin_libs=yes]) +AC_ARG_WITH([experimental-kernel-lib], + [AS_HELP_STRING([--with-experimental-kernel-lib], + [build experimental dashkernel library (default is to build if we're building libraries and the experimental build-chainstate executable)])], + [build_experimental_kernel_lib=$withval], + [build_experimental_kernel_lib=auto]) + AC_ARG_WITH([daemon], [AS_HELP_STRING([--with-daemon], [build dashd daemon (default=yes)])], @@ -1791,15 +1797,23 @@ AM_CONDITIONAL([BUILD_BITCOIN_UTIL], [test $build_bitcoin_util = "yes"]) AC_MSG_RESULT($build_bitcoin_util) AC_MSG_CHECKING([whether to build experimental dash-chainstate]) -AM_CONDITIONAL([BUILD_BITCOIN_CHAINSTATE], [test $build_bitcoin_chainstate = "yes"]) +if test "$build_experimental_kernel_lib" = "no"; then +AC_MSG_ERROR([experimental dash-chainstate cannot be built without the experimental dashkernel library. Use --with-experimental-kernel-lib]); +else + AM_CONDITIONAL([BUILD_BITCOIN_CHAINSTATE], [test $build_bitcoin_chainstate = "yes"]) +fi AC_MSG_RESULT($build_bitcoin_chainstate) AC_MSG_CHECKING([whether to build libraries]) AM_CONDITIONAL([BUILD_BITCOIN_LIBS], [test $build_bitcoin_libs = "yes"]) + if test "$build_bitcoin_libs" = "yes"; then AC_DEFINE([HAVE_CONSENSUS_LIB], [1], [Define this symbol if the consensus lib has been built]) AC_CONFIG_FILES([libdashconsensus.pc:libdashconsensus.pc.in]) fi + +AM_CONDITIONAL([BUILD_BITCOIN_KERNEL_LIB], [test "$build_experimental_kernel_lib" != "no" && ( test "$build_experimental_kernel_lib" = "yes" || test "$build_bitcoin_chainstate" = "yes" )]) + AC_MSG_RESULT($build_bitcoin_libs) AC_LANG_POP diff --git a/src/Makefile.am b/src/Makefile.am index 5137d940baef..3431cbc53509 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -18,7 +18,7 @@ AM_LIBTOOLFLAGS = --preserve-dup-deps PTHREAD_FLAGS = $(PTHREAD_CFLAGS) $(PTHREAD_LIBS) EXTRA_LIBRARIES = -lib_LTLIBRARIES = $(LIBBITCOINCONSENSUS) +lib_LTLIBRARIES = noinst_LTLIBRARIES = bin_PROGRAMS = @@ -49,6 +49,7 @@ LIBBITCOIN_NODE=libbitcoin_node.a LIBBITCOIN_COMMON=libbitcoin_common.a LIBBITCOIN_CONSENSUS=libbitcoin_consensus.a LIBBITCOIN_CLI=libbitcoin_cli.a +LIBBITCOIN_KERNEL=libbitcoin_kernel.a LIBBITCOIN_UTIL=libbitcoin_util.a LIBBITCOIN_CRYPTO_BASE=crypto/libbitcoin_crypto_base.la LIBBITCOINQT=qt/libbitcoinqt.a @@ -61,6 +62,9 @@ endif if BUILD_BITCOIN_LIBS LIBBITCOINCONSENSUS=libdashconsensus.la endif +if BUILD_BITCOIN_KERNEL_LIB +LIBBITCOINKERNEL=libdashkernel.la +endif if ENABLE_WALLET LIBBITCOIN_WALLET=libbitcoin_wallet.a LIBBITCOIN_WALLET_TOOL=libbitcoin_wallet_tool.a @@ -1163,10 +1167,48 @@ dash_util_LDADD = \ dash_util_LDADD += $(BOOST_LIBS) # dash-chainstate binary # -dash_chainstate_SOURCES = \ - bitcoin-chainstate.cpp \ - index/addressindex.cpp \ - index/addressindex_util.cpp \ +dash_chainstate_SOURCES = bitcoin-chainstate.cpp +dash_chainstate_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BOOST_CPPFLAGS) +dash_chainstate_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) + +# $(LIBTOOL_APP_LDFLAGS) deliberately omitted here so that we can test linking +# dash-chainstate against libdashkernel as a shared or static library by +# setting --{en,dis}able-shared. +dash_chainstate_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(PTHREAD_FLAGS) +dash_chainstate_LDADD = $(LIBBITCOINKERNEL) +# + +# dashkernel library # +if BUILD_BITCOIN_KERNEL_LIB +lib_LTLIBRARIES += $(LIBBITCOINKERNEL) + +libdashkernel_la_LDFLAGS = $(AM_LDFLAGS) -no-undefined $(RELDFLAGS) $(PTHREAD_FLAGS) +libdashkernel_la_LIBADD = $(LIBBITCOIN_CRYPTO) $(LIBUNIVALUE) $(LIBLEVELDB) $(LIBMEMENV) $(LIBSECP256K1) $(LIBDASHBLS) $(GMP_LIBS) +libdashkernel_la_CPPFLAGS = $(AM_CPPFLAGS) -I$(builddir)/obj -I$(srcdir)/secp256k1/include -DBUILD_BITCOIN_INTERNAL -isystem$(srcdir)/dashbls/include -isystem$(srcdir)/dashbls/depends/relic/include -isystem$(srcdir)/dashbls/depends/minialloc/include -isystem$(srcdir)/immer $(BOOST_CPPFLAGS) $(LEVELDB_CPPFLAGS) -I$(srcdir)/$(UNIVALUE_INCLUDE_DIR_INT) + +# libdashkernel 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. +libdashkernel_la_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) -fvisibility=default + +# TODO: For now, Specify -static in both CXXFLAGS and LDFLAGS when building for +# windows targets so libtool will only build a static version of this +# library. There are unresolved problems when building dll's for mingw-w64 +# and attempting to statically embed libstdc++, libpthread, etc. +if TARGET_WINDOWS +libdashkernel_la_LDFLAGS += -static +libdashkernel_la_CXXFLAGS += -static +endif + +# TODO: libdashkernel 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. For example, things +# like index/*.cpp will be removed. +libdashkernel_la_SOURCES = \ + kernel/bitcoinkernel.cpp \ arith_uint256.cpp \ base58.cpp \ batchedlogger.cpp \ @@ -1214,6 +1256,8 @@ dash_chainstate_SOURCES = \ governance/votedb.cpp \ gsl/assert.cpp \ hash.cpp \ + index/addressindex.cpp \ + index/addressindex_util.cpp \ index/base.cpp \ index/blockfilterindex.cpp \ index/coinstatsindex.cpp \ @@ -1303,25 +1347,17 @@ dash_chainstate_SOURCES = \ validationinterface.cpp \ versionbits.cpp \ warnings.cpp -dash_chainstate_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BOOST_CPPFLAGS) -dash_chainstate_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) -dash_chainstate_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) $(PTHREAD_FLAGS) -dash_chainstate_LDADD = \ - $(LIBBITCOIN_CRYPTO) \ - $(LIBUNIVALUE) \ - $(LIBSECP256K1) \ - $(LIBDASHBLS) \ - $(LIBLEVELDB) \ - $(LIBMEMENV) \ - $(GMP_LIBS) # Required for obj/build.h to be generated first. # More details: https://www.gnu.org/software/automake/manual/html_node/Built-Sources-Example.html -dash_chainstate-clientversion.$(OBJEXT): obj/build.h +libdashkernel_la-clientversion.l$(OBJEXT): obj/build.h +endif # BUILD_BITCOIN_KERNEL_LIB # # dashconsensus library # if BUILD_BITCOIN_LIBS +lib_LTLIBRARIES += $(LIBBITCOINCONSENSUS) + include_HEADERS = script/bitcoinconsensus.h libdashconsensus_la_SOURCES = support/cleanse.cpp $(crypto_libbitcoin_crypto_base_la_SOURCES) $(crypto_libbitcoin_crypto_sph_la_SOURCES) $(libbitcoin_consensus_a_SOURCES) diff --git a/src/bitcoin-chainstate.cpp b/src/bitcoin-chainstate.cpp index d9a4a4d0ace1..4fca32f7b16b 100644 --- a/src/bitcoin-chainstate.cpp +++ b/src/bitcoin-chainstate.cpp @@ -36,40 +36,6 @@ #include #include -const std::function G_TRANSLATION_FUN = nullptr; - -//---------------- -// symbols g_stats_client, ValueFromAmount, GetPrettyExceptionStr are re-defined -// here especially for dash-chainstate binary (kernel), because adding sources -// containing them pulls too many extra dependencies recursively -#include -std::unique_ptr g_stats_client{std::make_unique()}; - -UniValue ValueFromAmount(const CAmount amount) -{ - static_assert(COIN > 1); - int64_t quotient = amount / COIN; - int64_t remainder = amount % COIN; - if (amount < 0) { - quotient = -quotient; - remainder = -remainder; - } - return UniValue(UniValue::VNUM, - strprintf("%s%d.%08d", amount < 0 ? "-" : "", quotient, remainder)); -} -std::string GetPrettyExceptionStr(const std::exception_ptr& e) -{ - try { - // rethrow and catch the exception as there is no other way to reliably cast to the real type (not possible with RTTI) - std::rethrow_exception(e); - } catch (const std::exception& e2) { - return e2.what(); - } catch (...) { - throw; - } -} -////////////////////// - int main(int argc, char* argv[]) { // SETUP: Argument parsing and handling diff --git a/src/bls/bls.h b/src/bls/bls.h index 5be483b9b334..02a3bbefa5bf 100644 --- a/src/bls/bls.h +++ b/src/bls/bls.h @@ -386,7 +386,6 @@ class CBLSSignatureVersionWrapper { } }; -#ifndef BUILD_BITCOIN_INTERNAL template class CBLSLazyWrapper { @@ -592,7 +591,6 @@ class CBLSLazyPublicKeyVersionWrapper { obj.Unserialize(s, legacy); } }; -#endif using BLSVerificationVectorPtr = std::shared_ptr>; diff --git a/src/bls/bls_worker.cpp b/src/bls/bls_worker.cpp index 70e778c62df4..ddd32543ca3d 100644 --- a/src/bls/bls_worker.cpp +++ b/src/bls/bls_worker.cpp @@ -69,6 +69,7 @@ void CBLSWorker::Stop() workerPool.stop(true); } +#ifndef BUILD_BITCOIN_INTERNAL bool CBLSWorker::GenerateContributions(int quorumThreshold, Span ids, BLSVerificationVectorPtr& vvecRet, std::vector& skSharesRet) { auto svec = std::vector((size_t)quorumThreshold); @@ -109,6 +110,7 @@ bool CBLSWorker::GenerateContributions(int quorumThreshold, Span ids, BL } return std::ranges::all_of(futures, [](auto& f) { return f.get(); }); } +#endif // aggregates a single vector of BLS objects in parallel // the input vector is split into batches and each batch is aggregated in parallel diff --git a/src/bls/bls_worker.h b/src/bls/bls_worker.h index 529c9427baad..1ffa1ebfc34d 100644 --- a/src/bls/bls_worker.h +++ b/src/bls/bls_worker.h @@ -57,7 +57,9 @@ class CBLSWorker void Start(int16_t worker_count); void Stop(); +#ifndef BUILD_BITCOIN_INTERNAL bool GenerateContributions(int threshold, Span ids, BLSVerificationVectorPtr& vvecRet, std::vector& skSharesRet); +#endif // The following functions are all used to aggregate verification (public key) vectors // Inputs are in the following form: diff --git a/src/kernel/bitcoinkernel.cpp b/src/kernel/bitcoinkernel.cpp new file mode 100644 index 000000000000..d31335751185 --- /dev/null +++ b/src/kernel/bitcoinkernel.cpp @@ -0,0 +1,45 @@ +// 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 +#include +#include + +// Define G_TRANSLATION_FUN symbol in libbitcoinkernel library so users of the +// library aren't required to export this symbol +extern const std::function G_TRANSLATION_FUN = nullptr; + +//---------------- +// symbols g_stats_client, ValueFromAmount, GetPrettyExceptionStr are re-defined +// here because adding relevant sources files will pull too many extra dependencies recursively +#include +#include +#include +std::unique_ptr g_stats_client{std::make_unique()}; + +UniValue ValueFromAmount(const CAmount amount) +{ + static_assert(COIN > 1); + int64_t quotient = amount / COIN; + int64_t remainder = amount % COIN; + if (amount < 0) { + quotient = -quotient; + remainder = -remainder; + } + return UniValue(UniValue::VNUM, + strprintf("%s%d.%08d", amount < 0 ? "-" : "", quotient, remainder)); +} +////////////////////// + +std::string GetPrettyExceptionStr(const std::exception_ptr& e) +{ + try { + // rethrow and catch the exception as there is no other way to reliably cast to the real type (not possible with RTTI) + std::rethrow_exception(e); + } catch (const std::exception& e2) { + return e2.what(); + } catch (...) { + throw; + } +} From df61afc409847d18527bc2949818c24443318b88 Mon Sep 17 00:00:00 2001 From: Konstantin Akimov Date: Mon, 15 Jun 2026 02:28:27 +0700 Subject: [PATCH 02/12] Merge bitcoin/bitcoin#26003: build: fix configuring with `--without-experimental-kernel-lib` e531e34b4146792fb61e178c5a1370ab223e9c3a build: fix configuring with --without-experimental-kernel-lib (fanquake) Pull request description: Fixes #25994. ACKs for top commit: Rspigler: tACK e531e34b4146792fb61e178c5a1370ab223e9c3a ryanofsky: Code review ACK e531e34b4146792fb61e178c5a1370ab223e9c3a Tree-SHA512: 029b58ec02aef2b96d3300085db8fce7653720482c65a1af6a2fb729b0546515579d2bb4676ceb2796ac12d5ccc4224f3990852bd68bcc9a59bb9b310976224f --- configure.ac | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/configure.ac b/configure.ac index f523915a855b..9e9d21be5fd0 100644 --- a/configure.ac +++ b/configure.ac @@ -1797,11 +1797,12 @@ AM_CONDITIONAL([BUILD_BITCOIN_UTIL], [test $build_bitcoin_util = "yes"]) AC_MSG_RESULT($build_bitcoin_util) AC_MSG_CHECKING([whether to build experimental dash-chainstate]) -if test "$build_experimental_kernel_lib" = "no"; then -AC_MSG_ERROR([experimental dash-chainstate cannot be built without the experimental dashkernel library. Use --with-experimental-kernel-lib]); -else - AM_CONDITIONAL([BUILD_BITCOIN_CHAINSTATE], [test $build_bitcoin_chainstate = "yes"]) +if test "$build_bitcoin_chainstate" = "yes"; then + if test "$build_experimental_kernel_lib" = "no"; then + AC_MSG_ERROR([experimental dash-chainstate cannot be built without the experimental dashkernel library. Use --with-experimental-kernel-lib]); + fi fi +AM_CONDITIONAL([BUILD_BITCOIN_CHAINSTATE], [test $build_bitcoin_chainstate = "yes"]) AC_MSG_RESULT($build_bitcoin_chainstate) AC_MSG_CHECKING([whether to build libraries]) From 26986650acca8fea3fab7d5695a0df6bd3270cee Mon Sep 17 00:00:00 2001 From: Konstantin Akimov Date: Sat, 16 May 2026 16:57:17 +0700 Subject: [PATCH 03/12] refactor: add 2 new helpers DeploymentActiveAt and DeploymentActiveAfter for burried deployments --- src/deploymentstatus.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/deploymentstatus.h b/src/deploymentstatus.h index 2651baac7349..6d613d1ec6ea 100644 --- a/src/deploymentstatus.h +++ b/src/deploymentstatus.h @@ -17,6 +17,13 @@ inline bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const Consensus return (pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1) >= params.DeploymentHeight(dep); } +/** 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)); @@ -30,6 +37,12 @@ inline bool DeploymentActiveAt(const CBlockIndex& index, const Consensus::Params return index.nHeight >= params.DeploymentHeight(dep); } +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)); From 0afc9ea6ebdafe4ea39afd160ce31c5607746a1e Mon Sep 17 00:00:00 2001 From: Konstantin Akimov Date: Fri, 20 May 2022 13:35:09 +0100 Subject: [PATCH 04/12] Merge bitcoin/bitcoin#25168: refactor: Avoid passing params where not needed fa1b76aeb064b315a3767a8f59836ca18aeb117e Do not call global Params() when chainman is in scope (MacroFake) fa30234be81b6f49ae8150478a9255daa1611083 Do not pass CChainParams& to PeerManager::make (MacroFake) fafe5c0ca2927642cbcec63ac73994737e1653d6 Do not pass CChainParams& to BlockAssembler constructor (MacroFake) faf012b438b451dced785e7f031e07c0c55665e1 Do not pass Consensus::Params& to Chainstate helpers (MacroFake) fa4ee53dca5ccf1b87f019f372ffc10528add943 Do not pass time getter to Chainstate helpers (MacroFake) Pull request description: It seems confusing to pass chain params, consensus params, or a time function around when it is not needed. Fix this by: * Inlining the passed time getter function. I don't see a use case why this should be mockable. * Using `chainman.GetConsensus()` or `chainman.GetParams()`, where possible. ACKs for top commit: promag: Code review ACK fa1b76aeb064b315a3767a8f59836ca18aeb117e. vincenzopalazzo: ACK https://github.com/bitcoin/bitcoin/pull/25168/commits/fa1b76aeb064b315a3767a8f59836ca18aeb117e Tree-SHA512: 1abff5cba4b4871d97f17dbcdf67bc9255ff21fa4150a79a74e39b28f0610eab3e7dee24d56872dd6e111f003b55e288958cdd467e6218368d896f191e4ec9cd Co-authored-by: MacroFake --- src/bitcoin-chainstate.cpp | 5 +---- src/evo/mnhftx.cpp | 3 +-- src/init.cpp | 13 +++++------ src/net_processing.cpp | 18 +++++++-------- src/net_processing.h | 2 +- src/node/chainstate.cpp | 22 ++++++++----------- src/node/chainstate.h | 9 +------- src/node/interfaces.cpp | 18 +++++++-------- src/node/miner.cpp | 12 +++++----- src/node/miner.h | 5 ++--- src/rest.cpp | 2 +- src/rpc/blockchain.cpp | 16 +++++++------- src/rpc/mining.cpp | 20 +++++++---------- src/rpc/rawtransaction.cpp | 4 ++-- src/rpc/txoutproof.cpp | 4 ++-- src/test/block_reward_reallocation_tests.cpp | 14 ++++++------ src/test/blockfilter_index_tests.cpp | 5 ++--- src/test/denialofservice_tests.cpp | 14 +++++------- .../dynamic_activation_thresholds_tests.cpp | 2 +- src/test/fuzz/tx_pool.cpp | 2 +- src/test/miner_tests.cpp | 2 +- src/test/net_peer_connection_tests.cpp | 3 +-- src/test/util/mining.cpp | 2 +- src/test/util/setup_common.cpp | 21 +++++------------- src/test/util/setup_common.h | 5 +---- src/test/validation_block_tests.cpp | 2 +- .../validation_chainstatemanager_tests.cpp | 5 ++--- 27 files changed, 93 insertions(+), 137 deletions(-) diff --git a/src/bitcoin-chainstate.cpp b/src/bitcoin-chainstate.cpp index 4fca32f7b16b..4d5a57f274ad 100644 --- a/src/bitcoin-chainstate.cpp +++ b/src/bitcoin-chainstate.cpp @@ -102,7 +102,6 @@ int main(int argc, char* argv[]) /*mempool=*/nullptr, gArgs.GetDataDirNet(), /*fPruneMode=*/false, - chainparams.GetConsensus(), /*fReindexChainState=*/false, 2 << 20, 2 << 22, @@ -123,10 +122,8 @@ int main(int argc, char* argv[]) *evodb, false, false, - chainparams.GetConsensus(), DEFAULT_CHECKBLOCKS, - DEFAULT_CHECKLEVEL, - /*get_unix_time_seconds=*/static_cast(GetTime)); + DEFAULT_CHECKLEVEL); if (maybe_verify_error.has_value()) { std::cerr << "Failed to verify loaded Chain state from your datadir." << std::endl; goto epilogue; diff --git a/src/evo/mnhftx.cpp b/src/evo/mnhftx.cpp index 9e7c6f60abf7..e0d52bde2f80 100644 --- a/src/evo/mnhftx.cpp +++ b/src/evo/mnhftx.cpp @@ -285,14 +285,13 @@ CMNHFManager::Signals CMNHFManager::GetForBlock(const CBlockIndex* pindex) pindex = pindex->pprev; } - const Consensus::Params& consensusParams{Params().GetConsensus()}; while (!to_calculate.empty()) { const CBlockIndex* pindex_top{to_calculate.top()}; if (pindex_top->nHeight % 1000 == 0) { LogPrintf("re-index EHF signals at block %d\n", pindex_top->nHeight); } CBlock block; - if (!ReadBlockFromDisk(block, pindex_top, consensusParams)) { + if (!ReadBlockFromDisk(block, pindex_top, m_chainman.GetConsensus())) { throw std::runtime_error("failed-getehfforblock-read"); } BlockValidationState state; diff --git a/src/init.cpp b/src/init.cpp index c6f641e7e407..a160b48f5117 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -2017,7 +2017,6 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) Assert(node.mempool.get()), args.GetDataDirNet(), fPruneMode, - chainparams.GetConsensus(), fReindexChainState, cache_sizes.block_tree_db, cache_sizes.coins_db, @@ -2102,10 +2101,8 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) *Assert(node.evodb.get()), fReset, fReindexChainState, - chainparams.GetConsensus(), check_blocks, args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL), - /*get_unix_time_seconds=*/static_cast(GetTime), [](bool bls_state) { LogPrintf("%s: bls_legacy_scheme=%d\n", __func__, bls_state); }); @@ -2176,7 +2173,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) node.govman = std::make_unique(*node.mn_metaman, *node.chainman, *node.chain_helper->superblocks, *node.dmnman, *node.mn_sync); assert(!node.peerman); - node.peerman = PeerManager::make(chainparams, *node.connman, *node.addrman, node.banman.get(), *node.dstxman, + node.peerman = PeerManager::make(*node.connman, *node.addrman, node.banman.get(), *node.dstxman, chainman, *node.mempool, *node.mn_metaman, *node.mn_sync, *node.sporkman, *node.chainlocks, *node.clhandler, node.active_ctx, node.dmnman, node.cj_walletman, node.llmq_ctx, node.observer_ctx, ignores_incoming_txs); @@ -2586,9 +2583,9 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) 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() : Params().GenesisBlock().GetBlockTime(); - tip_info->block_hash = chainman.ActiveChain().Tip() ? chainman.ActiveChain().Tip()->GetBlockHash() : Params().GenesisBlock().GetHash(); - tip_info->verification_progress = GuessVerificationProgress(Params().TxData(), chainman.ActiveChain().Tip()); + tip_info->block_time = chainman.ActiveChain().Tip() ? chainman.ActiveChain().Tip()->GetBlockTime() : chainman.GetParams().GenesisBlock().GetBlockTime(); + tip_info->block_hash = chainman.ActiveChain().Tip() ? chainman.ActiveChain().Tip()->GetBlockHash() : chainman.GetParams().GenesisBlock().GetHash(); + 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; @@ -2622,7 +2619,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) // Port to bind to if `-bind=addr` is provided without a `:port` suffix. const uint16_t default_bind_port = - static_cast(args.GetIntArg("-port", Params().GetDefaultPort())); + static_cast(args.GetIntArg("-port", chainman.GetParams().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 " diff --git a/src/net_processing.cpp b/src/net_processing.cpp index 015408b9306a..0d2c0b895e53 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -583,7 +583,7 @@ struct CNodeState { class PeerManagerImpl final : public PeerManager { public: - PeerManagerImpl(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman, BanMan* banman, + PeerManagerImpl(CConnman& connman, AddrMan& addrman, BanMan* banman, CDSTXManager& dstxman, ChainstateManager& chainman, CTxMemPool& pool, CMasternodeMetaMan& mn_metaman, CMasternodeSync& mn_sync, CSporkManager& sporkman, const chainlock::Chainlocks& chainlocks, @@ -1512,8 +1512,6 @@ void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int co void PeerManagerImpl::PushNodeVersion(CNode& pnode, const Peer& peer) { - const auto& params = Params(); - uint64_t my_services{peer.m_our_services}; const int64_t nTime{count_seconds(GetTime())}; uint64_t nonce = pnode.GetLocalNonce(); @@ -1529,7 +1527,7 @@ void PeerManagerImpl::PushNodeVersion(CNode& pnode, const Peer& peer) pnode.SetSentMNAuthChallenge(mnauthChallenge); int nProtocolVersion = PROTOCOL_VERSION; - if (params.NetworkIDString() != CBaseChainParams::MAIN && gArgs.IsArgSet("-pushversion")) { + if (m_chainparams.NetworkIDString() != CBaseChainParams::MAIN && gArgs.IsArgSet("-pushversion")) { nProtocolVersion = gArgs.GetIntArg("-pushversion", PROTOCOL_VERSION); } @@ -2055,7 +2053,7 @@ std::optional PeerManagerImpl::FetchBlock(NodeId peer_id, const CBl return std::nullopt; } -std::unique_ptr PeerManager::make(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman, +std::unique_ptr PeerManager::make(CConnman& connman, AddrMan& addrman, BanMan* banman, CDSTXManager& dstxman, ChainstateManager& chainman, CTxMemPool& pool, CMasternodeMetaMan& mn_metaman, CMasternodeSync& mn_sync, @@ -2067,10 +2065,10 @@ std::unique_ptr PeerManager::make(const CChainParams& chainparams, const std::unique_ptr& llmq_ctx, const std::unique_ptr& observer_ctx, bool ignore_incoming_txs) { - return std::make_unique(chainparams, connman, addrman, banman, dstxman, chainman, pool, mn_metaman, mn_sync, sporkman, chainlocks, clhandler, active_ctx, dmnman, cj_walletman, llmq_ctx, observer_ctx, ignore_incoming_txs); + return std::make_unique(connman, addrman, banman, dstxman, chainman, pool, mn_metaman, mn_sync, sporkman, chainlocks, clhandler, active_ctx, dmnman, cj_walletman, llmq_ctx, observer_ctx, ignore_incoming_txs); } -PeerManagerImpl::PeerManagerImpl(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman, BanMan* banman, +PeerManagerImpl::PeerManagerImpl(CConnman& connman, AddrMan& addrman, BanMan* banman, CDSTXManager& dstxman, ChainstateManager& chainman, CTxMemPool& pool, CMasternodeMetaMan& mn_metaman, CMasternodeSync& mn_sync, CSporkManager& sporkman, @@ -2081,7 +2079,7 @@ PeerManagerImpl::PeerManagerImpl(const CChainParams& chainparams, CConnman& conn const std::unique_ptr& cj_walletman, const std::unique_ptr& llmq_ctx, const std::unique_ptr& observer_ctx, bool ignore_incoming_txs) - : m_chainparams(chainparams), + : m_chainparams(chainman.GetParams()), m_connman(connman), m_addrman(addrman), m_banman(banman), @@ -3684,7 +3682,7 @@ MessageProcessingResult PeerManagerImpl::ProcessPlatformBanMessage(NodeId node, return ret; } - Consensus::LLMQType llmq_type = Params().GetConsensus().llmqTypePlatform; + Consensus::LLMQType llmq_type = m_chainparams.GetConsensus().llmqTypePlatform; auto quorum = m_llmq_ctx->qman->GetQuorum(llmq_type, ban_msg.m_quorum_hash); if (!quorum) { LogPrintf("PLATFORMBAN -- hash: %s protx_hash: %s missing quorum_hash: %s llmq_type: %d\n", hash.ToString(), ban_msg.m_protx_hash.ToString(), ban_msg.m_quorum_hash.ToString(), std23::to_underlying(llmq_type)); @@ -3828,7 +3826,7 @@ void PeerManagerImpl::ProcessMessage( PushNodeVersion(pfrom, *peer); } - if (Params().NetworkIDString() == CBaseChainParams::DEVNET) { + if (m_chainparams.NetworkIDString() == CBaseChainParams::DEVNET) { if (cleanSubVer.find(strprintf("devnet.%s", gArgs.GetDevNetName())) == std::string::npos) { LogPrintf("connected to wrong devnet. Reported version is %s, expected devnet name is %s\n", cleanSubVer, gArgs.GetDevNetName()); if (!pfrom.IsInboundConn()) diff --git a/src/net_processing.h b/src/net_processing.h index e5f5132925f6..3e9d4302e203 100644 --- a/src/net_processing.h +++ b/src/net_processing.h @@ -107,7 +107,7 @@ class NetHandler class PeerManager : public CValidationInterface, public NetEventsInterface, public PeerManagerInternal { public: - static std::unique_ptr make(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman, + static std::unique_ptr make(CConnman& connman, AddrMan& addrman, BanMan* banman, CDSTXManager& dstxman, ChainstateManager& chainman, CTxMemPool& pool, CMasternodeMetaMan& mn_metaman, CMasternodeSync& mn_sync, CSporkManager& sporkman, diff --git a/src/node/chainstate.cpp b/src/node/chainstate.cpp index 75a474a439ff..9a741f291c3e 100644 --- a/src/node/chainstate.cpp +++ b/src/node/chainstate.cpp @@ -46,7 +46,6 @@ std::optional LoadChainstate(bool fReset, CTxMemPool* mempool, const fs::path& data_dir, bool fPruneMode, - const Consensus::Params& consensus_params, bool fReindexChainState, int64_t nBlockTreeDBCache, int64_t nCoinDBCache, @@ -82,7 +81,7 @@ std::optional LoadChainstate(bool fReset, DashChainstateSetup(chainman, mn_metaman, sporkman, chainlocks, mn_sync, chain_helper, dmnman, *evodb, llmq_ctx, mempool, data_dir, dash_dbs_in_memory, /*llmq_dbs_wipe=*/fReset || fReindexChainState, bls_threads, worker_count, - max_recsigs_age, consensus_params); + max_recsigs_age); if (fReset) { pblocktree->WriteReindexing(true); @@ -103,12 +102,12 @@ std::optional LoadChainstate(bool fReset, } if (!chainman.BlockIndex().empty() && - !chainman.m_blockman.LookupBlockIndex(consensus_params.hashGenesisBlock)) { + !chainman.m_blockman.LookupBlockIndex(chainman.GetConsensus().hashGenesisBlock)) { return ChainstateLoadingError::ERROR_BAD_GENESIS_BLOCK; } - if (!consensus_params.hashDevnetGenesisBlock.IsNull() && !chainman.BlockIndex().empty() && - !chainman.m_blockman.LookupBlockIndex(consensus_params.hashDevnetGenesisBlock)) { + if (!chainman.GetConsensus().hashDevnetGenesisBlock.IsNull() && !chainman.BlockIndex().empty() && + !chainman.m_blockman.LookupBlockIndex(chainman.GetConsensus().hashDevnetGenesisBlock)) { return ChainstateLoadingError::ERROR_BAD_DEVNET_GENESIS_BLOCK; } @@ -198,8 +197,7 @@ void DashChainstateSetup(ChainstateManager& chainman, bool llmq_dbs_wipe, int8_t bls_threads, int16_t worker_count, - int64_t max_recsigs_age, - const Consensus::Params& consensus_params) + int64_t max_recsigs_age) { // Same logic as pblocktree dmnman.reset(); @@ -214,7 +212,7 @@ void DashChainstateSetup(ChainstateManager& chainman, } chain_helper.reset(); chain_helper = std::make_unique(evodb, *dmnman, mn_sync, *(llmq_ctx->isman), *(llmq_ctx->quorum_block_processor), - *(llmq_ctx->qsnapman), chainman, consensus_params, chainlocks, + *(llmq_ctx->qsnapman), chainman, chainman.GetConsensus(), chainlocks, *(llmq_ctx->qman)); } @@ -236,10 +234,8 @@ std::optional VerifyLoadedChainstate(ChainstateManage CEvoDB& evodb, bool fReset, bool fReindexChainState, - const Consensus::Params& consensus_params, int check_blocks, int check_level, - std::function get_unix_time_seconds, std::function notify_bls_state) { auto is_coinsview_empty = [&](CChainState* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { @@ -251,17 +247,17 @@ std::optional VerifyLoadedChainstate(ChainstateManage for (CChainState* chainstate : chainman.GetAll()) { if (!is_coinsview_empty(chainstate)) { const CBlockIndex* tip = chainstate->m_chain.Tip(); - if (tip && tip->nTime > get_unix_time_seconds() + MAX_FUTURE_BLOCK_TIME) { + if (tip && tip->nTime > GetTime() + MAX_FUTURE_BLOCK_TIME) { return ChainstateLoadVerifyError::ERROR_BLOCK_FROM_FUTURE; } - const bool v19active{DeploymentActiveAfter(tip, consensus_params, Consensus::DEPLOYMENT_V19)}; + const bool v19active{DeploymentActiveAfter(tip, chainman, Consensus::DEPLOYMENT_V19)}; if (v19active) { bls::bls_legacy_scheme.store(false); if (notify_bls_state) notify_bls_state(bls::bls_legacy_scheme.load()); } if (!CVerifyDB().VerifyDB( - *chainstate, consensus_params, chainstate->CoinsDB(), + *chainstate, chainman.GetConsensus(), chainstate->CoinsDB(), evodb, check_level, check_blocks)) { diff --git a/src/node/chainstate.h b/src/node/chainstate.h index bbddf1f72ea5..2e3a830ea445 100644 --- a/src/node/chainstate.h +++ b/src/node/chainstate.h @@ -22,9 +22,6 @@ class CTxMemPool; struct LLMQContext; namespace chainlock { class Chainlocks; } -namespace Consensus { -struct Params; -} // namespace Consensus namespace fs { class path; } // namespace fs @@ -85,7 +82,6 @@ std::optional LoadChainstate(bool fReset, CTxMemPool* mempool, const fs::path& data_dir, bool fPruneMode, - const Consensus::Params& consensus_params, bool fReindexChainState, int64_t nBlockTreeDBCache, int64_t nCoinDBCache, @@ -115,8 +111,7 @@ void DashChainstateSetup(ChainstateManager& chainman, bool llmq_dbs_wipe, int8_t bls_threads, int16_t worker_count, - int64_t max_recsigs_age, - const Consensus::Params& consensus_params); + int64_t max_recsigs_age); void DashChainstateSetupClose(std::unique_ptr& chain_helper, std::unique_ptr& dmnman, @@ -134,10 +129,8 @@ std::optional VerifyLoadedChainstate(ChainstateManage CEvoDB& evodb, bool fReset, bool fReindexChainState, - const Consensus::Params& consensus_params, int check_blocks, int check_level, - std::function get_unix_time_seconds, std::function notify_bls_state = nullptr); } // namespace node diff --git a/src/node/interfaces.cpp b/src/node/interfaces.cpp index d9fe93f70e41..fbbd3a89a6f0 100644 --- a/src/node/interfaces.cpp +++ b/src/node/interfaces.cpp @@ -289,19 +289,19 @@ class GOVImpl : public GOV GovernanceInfo getGovernanceInfo() override { GovernanceInfo info; - const Consensus::Params& consensusParams = Params().GetConsensus(); if (context().chainman) { + const Consensus::Params& consensusParams = context().chainman->GetConsensus(); LOCK(::cs_main); CSuperblock::GetNearestSuperblocksHeights(context().chainman->ActiveHeight(), info.lastsuperblock, info.nextsuperblock); info.governancebudget = CSuperblock::GetPaymentsLimit(context().chainman->ActiveChain(), info.nextsuperblock); if (context().dmnman) { info.fundingthreshold = static_cast(context().dmnman->GetListAtChainTip().GetCounts().m_valid_weighted / 10); } + info.superblockcycle = consensusParams.nSuperblockCycle; + info.superblockmaturitywindow = consensusParams.nSuperblockMaturityWindow; + info.targetSpacing = consensusParams.nPowTargetSpacing; } info.proposalfee = GOVERNANCE_PROPOSAL_FEE_TX; - info.superblockcycle = consensusParams.nSuperblockCycle; - info.superblockmaturitywindow = consensusParams.nSuperblockMaturityWindow; - info.targetSpacing = consensusParams.nPowTargetSpacing; info.relayRequiredConfs = GOVERNANCE_MIN_RELAY_FEE_CONFIRMATIONS; info.requiredConfs = GOVERNANCE_FEE_CONFIRMATIONS; return info; @@ -877,7 +877,7 @@ class NodeImpl : public Node uint256 getBestBlockHash() override { const CBlockIndex* tip = WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()); - return tip ? tip->GetBlockHash() : Params().GenesisBlock().GetHash(); + return tip ? tip->GetBlockHash() : chainman().GetParams().GenesisBlock().GetHash(); } int64_t getLastBlockTime() override { @@ -885,7 +885,7 @@ class NodeImpl : public Node if (chainman().ActiveChain().Tip()) { return chainman().ActiveChain().Tip()->GetBlockTime(); } - return Params().GenesisBlock().GetBlockTime(); // Genesis block's time of current network + return chainman().GetParams().GenesisBlock().GetBlockTime(); // Genesis block's time of current network } std::string getLastBlockHash() override { @@ -893,7 +893,7 @@ class NodeImpl : public Node if (m_context->chainman->ActiveChain().Tip()) { return m_context->chainman->ActiveChain().Tip()->GetBlockHash().ToString(); } - return Params().GenesisBlock().GetHash().ToString(); // Genesis block's hash of current network + return chainman().GetParams().GenesisBlock().GetHash().ToString(); // Genesis block's hash of current network } double getVerificationProgress() override { @@ -902,7 +902,7 @@ class NodeImpl : public Node LOCK(::cs_main); tip = chainman().ActiveChain().Tip(); } - return GuessVerificationProgress(Params().TxData(), tip); + return GuessVerificationProgress(chainman().GetParams().TxData(), tip); } bool isInitialBlockDownload() override { return chainman().ActiveChainstate().IsInitialBlockDownload(); @@ -1318,7 +1318,7 @@ class ChainImpl : public Chain double guessVerificationProgress(const uint256& block_hash) override { LOCK(::cs_main); - return GuessVerificationProgress(Params().TxData(), chainman().m_blockman.LookupBlockIndex(block_hash)); + return GuessVerificationProgress(chainman().GetParams().TxData(), chainman().m_blockman.LookupBlockIndex(block_hash)); } bool hasBlocks(const uint256& block_hash, int min_height, std::optional max_height) override { diff --git a/src/node/miner.cpp b/src/node/miner.cpp index 6b267353cd5f..0bbb1ff2fcfd 100644 --- a/src/node/miner.cpp +++ b/src/node/miner.cpp @@ -69,7 +69,7 @@ BlockAssembler::Options::Options() nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE; } -BlockAssembler::BlockAssembler(CChainState& chainstate, const NodeContext& node, const CTxMemPool* mempool, const CChainParams& params, const Options& options) : +BlockAssembler::BlockAssembler(CChainState& chainstate, const NodeContext& node, const CTxMemPool* mempool, const Options& options) : m_blockman(chainstate.m_blockman), m_chain_helper(chainstate.ChainHelper()), m_chainstate(chainstate), @@ -77,7 +77,7 @@ BlockAssembler::BlockAssembler(CChainState& chainstate, const NodeContext& node, m_chainlocks(*Assert(node.chainlocks)), m_clhandler(*Assert(node.clhandler)), m_isman(*Assert(Assert(node.llmq_ctx)->isman)), - chainparams(params), + chainparams(chainstate.m_chainman.GetParams()), m_mempool(mempool), m_quorum_block_processor(*Assert(Assert(node.llmq_ctx)->quorum_block_processor)), m_qman(*Assert(Assert(node.llmq_ctx)->qman)) @@ -103,8 +103,8 @@ static BlockAssembler::Options DefaultOptions() return options; } -BlockAssembler::BlockAssembler(CChainState& chainstate, const NodeContext& node, const CTxMemPool* mempool, const CChainParams& params) - : BlockAssembler(chainstate, node, mempool, params, DefaultOptions()) {} +BlockAssembler::BlockAssembler(CChainState& chainstate, const NodeContext& node, const CTxMemPool* mempool) + : BlockAssembler(chainstate, node, mempool, DefaultOptions()) {} void BlockAssembler::resetBlock() { @@ -214,7 +214,7 @@ std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& sc pblock->nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus()); // Non-mainnet only: allow overriding block.nVersion with // -blockversion=N to test forking scenarios - if (Params().NetworkIDString() != CBaseChainParams::MAIN) { + if (chainparams.NetworkIDString() != CBaseChainParams::MAIN) { pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion); } @@ -259,7 +259,7 @@ std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& sc coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn; // NOTE: unlike in bitcoin, we need to pass PREVIOUS block height here - CAmount blockSubsidy = GetBlockSubsidyInner(pindexPrev->nBits, pindexPrev->nHeight, Params().GetConsensus(), fV20Active_context); + CAmount blockSubsidy = GetBlockSubsidyInner(pindexPrev->nBits, pindexPrev->nHeight, chainparams.GetConsensus(), fV20Active_context); CAmount blockReward = blockSubsidy + nFees; // Compute regular coinbase transaction. diff --git a/src/node/miner.h b/src/node/miner.h index f16bb8ef5d94..18d9520d0061 100644 --- a/src/node/miner.h +++ b/src/node/miner.h @@ -187,9 +187,8 @@ class BlockAssembler CFeeRate blockMinFeeRate; }; - explicit BlockAssembler(CChainState& chainstate, const node::NodeContext& node, const CTxMemPool* mempool, const CChainParams& params); - explicit BlockAssembler(CChainState& chainstate, const node::NodeContext& node, const CTxMemPool* mempool, const CChainParams& params, - const Options& options); + explicit BlockAssembler(CChainState& chainstate, const node::NodeContext& node, const CTxMemPool* mempool); + explicit BlockAssembler(CChainState& chainstate, const node::NodeContext& node, const CTxMemPool* mempool, const Options& options); /** Construct a new block template with coinbase to scriptPubKeyIn */ std::unique_ptr CreateNewBlock(const CScript& scriptPubKeyIn); diff --git a/src/rest.cpp b/src/rest.cpp index 70c61e40fe25..87f5671cf000 100644 --- a/src/rest.cpp +++ b/src/rest.cpp @@ -333,7 +333,7 @@ static bool rest_block(const CoreContext& context, return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (pruned data)"); } - if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) { + if (!ReadBlockFromDisk(block, pblockindex, chainman.GetParams().GetConsensus())) { return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found"); } diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index eca003933174..97f28f5bd8a6 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -1090,11 +1090,11 @@ static RPCHelpMan pruneblockchain() unsigned int height = (unsigned int) heightParam; unsigned int chainHeight = (unsigned int) active_chain.Height(); - if (chainHeight < Params().PruneAfterHeight()) + if (chainHeight < chainman.GetParams().PruneAfterHeight()) { throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning."); - else if (height > chainHeight) + } else if (height > chainHeight) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height."); - else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) { + } else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) { LogPrint(BCLog::RPC, "Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.\n"); height = chainHeight - MIN_BLOCKS_TO_KEEP; } @@ -1409,7 +1409,7 @@ static RPCHelpMan verifychain() CChainState& active_chainstate = chainman.ActiveChainstate(); return CVerifyDB().VerifyDB( - active_chainstate, Params().GetConsensus(), active_chainstate.CoinsTip(), *CHECK_NONFATAL(node.evodb), check_level, check_depth); + active_chainstate, chainman.GetParams().GetConsensus(), active_chainstate.CoinsTip(), *CHECK_NONFATAL(node.evodb), check_level, check_depth); }, }; } @@ -1563,7 +1563,7 @@ RPCHelpMan getblockchaininfo() if (args.IsArgSet("-devnet")) { obj.pushKV("chain", args.GetDevNetName()); } else { - obj.pushKV("chain", Params().NetworkIDString()); + obj.pushKV("chain", chainman.GetParams().NetworkIDString()); } obj.pushKV("blocks", height); obj.pushKV("headers", chainman.m_best_header ? chainman.m_best_header->nHeight : -1); @@ -1571,7 +1571,7 @@ RPCHelpMan getblockchaininfo() obj.pushKV("difficulty", GetDifficulty(&tip)); obj.pushKV("time", tip.GetBlockTime()); obj.pushKV("mediantime", tip.GetMedianTimePast()); - obj.pushKV("verificationprogress", GuessVerificationProgress(Params().TxData(), &tip)); + obj.pushKV("verificationprogress", GuessVerificationProgress(chainman.GetParams().TxData(), &tip)); obj.pushKV("initialblockdownload", active_chainstate.IsInitialBlockDownload()); obj.pushKV("chainwork", tip.nChainWork.GetHex()); obj.pushKV("size_on_disk", chainman.m_blockman.CalculateCurrentUsage()); @@ -1912,7 +1912,7 @@ static RPCHelpMan getchaintxstats() CChain& active_chain = chainman.ActiveChain(); const CBlockIndex* pindex; - int blockcount = 30 * 24 * 60 * 60 / Params().GetConsensus().nPowTargetSpacing; // By default: 1 month + int blockcount = 30 * 24 * 60 * 60 / chainman.GetParams().GetConsensus().nPowTargetSpacing; // By default: 1 month if (request.params[1].isNull()) { LOCK(cs_main); @@ -2232,7 +2232,7 @@ static RPCHelpMan getblockstats() ret_all.pushKV("minfeerate", (minfeerate == MAX_MONEY) ? 0 : minfeerate); ret_all.pushKV("mintxsize", mintxsize == MaxBlockSize() ? 0 : mintxsize); ret_all.pushKV("outs", outputs); - ret_all.pushKV("subsidy", GetBlockSubsidy(&pindex, Params().GetConsensus())); + ret_all.pushKV("subsidy", GetBlockSubsidy(&pindex, chainman.GetParams().GetConsensus())); ret_all.pushKV("time", pindex.GetBlockTime()); ret_all.pushKV("total_out", total_out); ret_all.pushKV("total_size", total_size); diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 24b63fe83eec..cb316e71ec9a 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -127,9 +127,7 @@ static bool GenerateBlock(ChainstateManager& chainman, CBlock& block, uint64_t& block_hash.SetNull(); block.hashMerkleRoot = BlockMerkleRoot(block); - const CChainParams& chainparams(Params()); - - while (max_tries > 0 && block.nNonce < std::numeric_limits::max() && !CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus()) && !ShutdownRequested()) { + while (max_tries > 0 && block.nNonce < std::numeric_limits::max() && !CheckProofOfWork(block.GetHash(), block.nBits, chainman.GetConsensus()) && !ShutdownRequested()) { ++block.nNonce; --max_tries; } @@ -156,7 +154,7 @@ static UniValue generateBlocks(ChainstateManager& chainman, const NodeContext& n UniValue blockHashes(UniValue::VARR); while (nGenerate > 0 && !ShutdownRequested()) { - std::unique_ptr pblocktemplate(BlockAssembler(chainman.ActiveChainstate(), node, &mempool, Params()).CreateNewBlock(coinbase_script)); + std::unique_ptr pblocktemplate(BlockAssembler(chainman.ActiveChainstate(), node, &mempool).CreateNewBlock(coinbase_script)); if (!pblocktemplate.get()) throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block"); CBlock *pblock = &pblocktemplate->block; @@ -353,8 +351,6 @@ static RPCHelpMan generateblock() } } - const CChainParams& chainparams(Params()); - ChainstateManager& chainman = EnsureChainman(node); CChainState& active_chainstate = chainman.ActiveChainstate(); @@ -362,7 +358,7 @@ static RPCHelpMan generateblock() { LOCK(cs_main); - std::unique_ptr blocktemplate(BlockAssembler(active_chainstate, node, nullptr, chainparams).CreateNewBlock(coinbase_script)); + std::unique_ptr blocktemplate(BlockAssembler(active_chainstate, node, nullptr).CreateNewBlock(coinbase_script)); if (!blocktemplate) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block"); } @@ -379,7 +375,7 @@ static RPCHelpMan generateblock() LOCK(cs_main); BlockValidationState state; - if (!TestBlockValidity(state, *CHECK_NONFATAL(node.chainlocks), *CHECK_NONFATAL(node.evodb), chainparams, active_chainstate, + if (!TestBlockValidity(state, *CHECK_NONFATAL(node.chainlocks), *CHECK_NONFATAL(node.evodb), chainman.GetParams(), active_chainstate, block, chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock), false, false)) { throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.GetRejectReason())); } @@ -467,7 +463,7 @@ static RPCHelpMan getmininginfo() obj.pushKV("difficulty", (double)GetDifficulty(active_chain.Tip())); obj.pushKV("networkhashps", getnetworkhashps().HandleRequest(request)); obj.pushKV("pooledtx", (uint64_t)mempool.size()); - obj.pushKV("chain", Params().NetworkIDString()); + obj.pushKV("chain", chainman.GetParams().NetworkIDString()); obj.pushKV("warnings", GetWarnings(false).original); return obj; }, @@ -700,7 +696,7 @@ static RPCHelpMan getblocktemplate() if (block.hashPrevBlock != pindexPrev->GetBlockHash()) return "inconclusive-not-best-prevblk"; BlockValidationState state; - TestBlockValidity(state, *CHECK_NONFATAL(node.chainlocks), *CHECK_NONFATAL(node.evodb), Params(), active_chainstate, + TestBlockValidity(state, *CHECK_NONFATAL(node.chainlocks), *CHECK_NONFATAL(node.evodb), chainman.GetParams(), active_chainstate, block, pindexPrev, false, true); return BIP22ValidationResult(state); } @@ -719,7 +715,7 @@ static RPCHelpMan getblocktemplate() const CConnman& connman = EnsureConnman(node); - if (!Params().IsTestChain()) { + if (!chainman.GetParams().IsTestChain()) { if (connman.GetNodeCount(ConnectionDirection::Both) == 0) { throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, PACKAGE_NAME " is not connected!"); } @@ -804,7 +800,7 @@ static RPCHelpMan getblocktemplate() // Create new block CScript scriptDummy = CScript() << OP_TRUE; EnsureLLMQContext(node); - pblocktemplate = BlockAssembler(active_chainstate, node, &mempool, Params()).CreateNewBlock(scriptDummy); + pblocktemplate = BlockAssembler(active_chainstate, node, &mempool).CreateNewBlock(scriptDummy); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 5805e74992b8..3efd753d2ac0 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -376,7 +376,7 @@ static RPCHelpMan getrawtransaction() uint256 hash = ParseHashV(request.params[0], "parameter 1"); const CBlockIndex* blockindex = nullptr; - if (hash == Params().GenesisBlock().hashMerkleRoot) { + if (hash == chainman.GetParams().GenesisBlock().hashMerkleRoot) { // Special exception for the genesis block coinbase transaction throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "The genesis block coinbase is not considered an ordinary transaction and cannot be retrieved"); } @@ -404,7 +404,7 @@ static RPCHelpMan getrawtransaction() } uint256 hash_block; - const CTransactionRef tx = GetTransaction(blockindex, node.mempool.get(), hash, Params().GetConsensus(), hash_block); + const CTransactionRef tx = GetTransaction(blockindex, node.mempool.get(), hash, chainman.GetConsensus(), hash_block); if (!tx) { std::string errmsg; if (blockindex) { diff --git a/src/rpc/txoutproof.cpp b/src/rpc/txoutproof.cpp index bf7b8dc2e069..5313d8531cbd 100644 --- a/src/rpc/txoutproof.cpp +++ b/src/rpc/txoutproof.cpp @@ -89,7 +89,7 @@ static RPCHelpMan gettxoutproof() } if (pblockindex == nullptr) { - const CTransactionRef tx = GetTransaction(/*block_index=*/nullptr, /*mempool=*/nullptr, *setTxids.begin(), Params().GetConsensus(), hashBlock); + const CTransactionRef tx = GetTransaction(/*block_index=*/nullptr, /*mempool=*/nullptr, *setTxids.begin(), chainman.GetConsensus(), hashBlock); if (!tx || hashBlock.IsNull()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block"); } @@ -100,7 +100,7 @@ static RPCHelpMan gettxoutproof() } CBlock block; - if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) { + if (!ReadBlockFromDisk(block, pblockindex, chainman.GetConsensus())) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); } diff --git a/src/test/block_reward_reallocation_tests.cpp b/src/test/block_reward_reallocation_tests.cpp index 97c29c62c9d0..8ce98165dcb8 100644 --- a/src/test/block_reward_reallocation_tests.cpp +++ b/src/test/block_reward_reallocation_tests.cpp @@ -184,7 +184,7 @@ BOOST_FIXTURE_TEST_CASE(block_reward_reallocation, TestChainBRRBeforeActivationS BOOST_REQUIRE(dmnman.GetListAtChainTip().HasMN(tx.GetHash())); BOOST_CHECK(tip->nHeight < Params().GetConsensus().BRRHeight); // Creating blocks by different ways - const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get(), Params()).CreateNewBlock(coinbasePubKey); + const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get()).CreateNewBlock(coinbasePubKey); } for ([[maybe_unused]] auto _ : util::irange(499)) { CreateAndProcessBlock({}, coinbasePubKey); @@ -214,7 +214,7 @@ BOOST_FIXTURE_TEST_CASE(block_reward_reallocation, TestChainBRRBeforeActivationS BOOST_REQUIRE(dmnman.GetListAtChainTip().HasMN(tx.GetHash())); const CAmount block_subsidy = GetBlockSubsidyInner(tip->nBits, tip->nHeight, consensus_params, isV20Active); const CAmount masternode_payment = GetMasternodePayment(tip->nHeight, block_subsidy, isV20Active); - const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get(), Params()).CreateNewBlock(coinbasePubKey); + const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get()).CreateNewBlock(coinbasePubKey); BOOST_CHECK_EQUAL(pblocktemplate->voutMasternodePayments[0].nValue, masternode_payment); } @@ -228,7 +228,7 @@ BOOST_FIXTURE_TEST_CASE(block_reward_reallocation, TestChainBRRBeforeActivationS const bool isV20Active{DeploymentActiveAfter(tip, consensus_params, Consensus::DEPLOYMENT_V20)}; const CAmount block_subsidy = GetBlockSubsidyInner(tip->nBits, tip->nHeight, consensus_params, isV20Active); const CAmount masternode_payment = GetMasternodePayment(tip->nHeight, block_subsidy, isV20Active); - const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get(), Params()).CreateNewBlock(coinbasePubKey); + const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get()).CreateNewBlock(coinbasePubKey); BOOST_CHECK_EQUAL(pblocktemplate->block.vtx[0]->GetValueOut(), 28847249686); BOOST_CHECK_EQUAL(pblocktemplate->voutMasternodePayments[0].nValue, masternode_payment); BOOST_CHECK_EQUAL(pblocktemplate->voutMasternodePayments[0].nValue, 14423624841); // 0.4999999999 @@ -245,7 +245,7 @@ BOOST_FIXTURE_TEST_CASE(block_reward_reallocation, TestChainBRRBeforeActivationS const bool isV20Active{DeploymentActiveAfter(tip, consensus_params, Consensus::DEPLOYMENT_V20)}; const CAmount block_subsidy = GetBlockSubsidyInner(tip->nBits, tip->nHeight, consensus_params, isV20Active); const CAmount masternode_payment = GetMasternodePayment(tip->nHeight, block_subsidy, isV20Active); - const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get(), Params()).CreateNewBlock(coinbasePubKey); + const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get()).CreateNewBlock(coinbasePubKey); BOOST_CHECK_EQUAL(pblocktemplate->voutMasternodePayments[0].nValue, masternode_payment); } } @@ -263,7 +263,7 @@ BOOST_FIXTURE_TEST_CASE(block_reward_reallocation, TestChainBRRBeforeActivationS CAmount expected_block_reward = block_subsidy_potential - block_subsidy_potential / 5; const CAmount masternode_payment = GetMasternodePayment(tip->nHeight, block_subsidy, isV20Active); - const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get(), Params()).CreateNewBlock(coinbasePubKey); + const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get()).CreateNewBlock(coinbasePubKey); BOOST_CHECK_EQUAL(pblocktemplate->block.vtx[0]->GetValueOut(), expected_block_reward); BOOST_CHECK_EQUAL(pblocktemplate->block.vtx[0]->GetValueOut(), 141734128); BOOST_CHECK_EQUAL(pblocktemplate->voutMasternodePayments[0].nValue, masternode_payment); @@ -283,7 +283,7 @@ BOOST_FIXTURE_TEST_CASE(block_reward_reallocation, TestChainBRRBeforeActivationS const bool isMNRewardReallocated{DeploymentActiveAfter(tip, consensus_params, Consensus::DEPLOYMENT_MN_RR)}; const CAmount block_subsidy = GetBlockSubsidyInner(tip->nBits, tip->nHeight, consensus_params, isV20Active); CAmount masternode_payment = GetMasternodePayment(tip->nHeight, block_subsidy, isV20Active); - const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get(), Params()).CreateNewBlock(coinbasePubKey); + const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get()).CreateNewBlock(coinbasePubKey); if (isMNRewardReallocated) { const CAmount platform_payment = PlatformShare(masternode_payment); @@ -305,7 +305,7 @@ BOOST_FIXTURE_TEST_CASE(block_reward_reallocation, TestChainBRRBeforeActivationS CAmount masternode_payment = GetMasternodePayment(tip->nHeight, block_subsidy, isV20Active); const CAmount platform_payment = PlatformShare(masternode_payment); masternode_payment -= platform_payment; - const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get(), Params()).CreateNewBlock(coinbasePubKey); + const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get()).CreateNewBlock(coinbasePubKey); CAmount block_subsidy_potential = block_subsidy + block_subsidy_sb; BOOST_CHECK_EQUAL(tip->nHeight, 2358); diff --git a/src/test/blockfilter_index_tests.cpp b/src/test/blockfilter_index_tests.cpp index 4a38ec79d8ad..5e484c88120e 100644 --- a/src/test/blockfilter_index_tests.cpp +++ b/src/test/blockfilter_index_tests.cpp @@ -65,8 +65,7 @@ CBlock BuildChainTestingSetup::CreateBlock(const CBlockIndex* prev, const std::vector& txns, const CScript& scriptPubKey) { - const CChainParams& chainparams = Params(); - std::unique_ptr pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get(), chainparams).CreateNewBlock(scriptPubKey); + std::unique_ptr pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get()).CreateNewBlock(scriptPubKey); CBlock& block = pblocktemplate->block; block.hashPrevBlock = prev->GetBlockHash(); block.nTime = prev->nTime + 1; @@ -83,7 +82,7 @@ CBlock BuildChainTestingSetup::CreateBlock(const CBlockIndex* prev, block.hashMerkleRoot = BlockMerkleRoot(block); } - while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())) ++block.nNonce; + while (!CheckProofOfWork(block.GetHash(), block.nBits, m_node.chainman->GetConsensus())) ++block.nNonce; return block; } diff --git a/src/test/denialofservice_tests.cpp b/src/test/denialofservice_tests.cpp index efdfedc3a207..8172ba5627a6 100644 --- a/src/test/denialofservice_tests.cpp +++ b/src/test/denialofservice_tests.cpp @@ -144,9 +144,8 @@ static void AddRandomOutboundPeer(NodeId& id, std::vector& vNodes, PeerM BOOST_AUTO_TEST_CASE(stale_tip_peer_management) { NodeId id{0}; - const CChainParams& chainparams = Params(); auto connman = std::make_unique(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman); - auto peerLogic = MakePeerManager(*connman, m_node, /*banman=*/nullptr, chainparams, /*ignore_incoming_txs=*/false); + auto peerLogic = MakePeerManager(*connman, m_node, /*banman=*/nullptr, /*ignore_incoming_txs=*/false); constexpr int max_outbound_full_relay = MAX_OUTBOUND_FULL_RELAY_CONNECTIONS; CConnman::Options options; @@ -156,7 +155,7 @@ BOOST_AUTO_TEST_CASE(stale_tip_peer_management) const auto time_init{GetTime()}; SetMockTime(time_init); - const auto time_later{time_init + 3 * std::chrono::seconds{chainparams.GetConsensus().nPowTargetSpacing} + 1s}; + const auto time_later{time_init + 3 * std::chrono::seconds{m_node.chainman->GetConsensus().nPowTargetSpacing} + 1s}; connman->Init(options); std::vector vNodes; @@ -245,9 +244,8 @@ BOOST_AUTO_TEST_CASE(stale_tip_peer_management) BOOST_AUTO_TEST_CASE(block_relay_only_eviction) { NodeId id{0}; - const CChainParams& chainparams = Params(); auto connman = std::make_unique(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman); - auto peerLogic = MakePeerManager(*connman, m_node, /*banman=*/nullptr, chainparams, /*ignore_incoming_txs=*/false); + auto peerLogic = MakePeerManager(*connman, m_node, /*banman=*/nullptr, /*ignore_incoming_txs=*/false); constexpr int max_outbound_block_relay{MAX_BLOCK_RELAY_ONLY_CONNECTIONS}; constexpr int64_t MINIMUM_CONNECT_TIME{30}; @@ -308,10 +306,9 @@ BOOST_AUTO_TEST_CASE(peer_discouragement) { LOCK(NetEventsInterface::g_msgproc_mutex); - const CChainParams& chainparams = Params(); auto banman = std::make_unique(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME); auto connman = std::make_unique(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman); - auto peerLogic = MakePeerManager(*connman, m_node, banman.get(), chainparams, /*ignore_incoming_txs=*/false); + auto peerLogic = MakePeerManager(*connman, m_node, banman.get(), /*ignore_incoming_txs=*/false); CNetAddr tor_netaddr; BOOST_REQUIRE( @@ -410,10 +407,9 @@ BOOST_AUTO_TEST_CASE(DoS_bantime) { LOCK(NetEventsInterface::g_msgproc_mutex); - const CChainParams& chainparams = Params(); auto banman = std::make_unique(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME); auto connman = std::make_unique(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman); - auto peerLogic = MakePeerManager(*connman, m_node, banman.get(), chainparams, /*ignore_incoming_txs=*/false); + auto peerLogic = MakePeerManager(*connman, m_node, banman.get(), /*ignore_incoming_txs=*/false); banman->ClearBanned(); int64_t nStartTime = GetTime(); diff --git a/src/test/dynamic_activation_thresholds_tests.cpp b/src/test/dynamic_activation_thresholds_tests.cpp index 1c5e9c2a492a..f3fea498ee93 100644 --- a/src/test/dynamic_activation_thresholds_tests.cpp +++ b/src/test/dynamic_activation_thresholds_tests.cpp @@ -87,7 +87,7 @@ struct TestChainDATSetup : public TestChainSetup .threshold, threshold(0)); // Next block should be signaling by default - const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get(), Params()).CreateNewBlock(coinbasePubKey); + const auto pblocktemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get()).CreateNewBlock(coinbasePubKey); const uint32_t bitmask = ((uint32_t)1) << consensus_params.vDeployments[deployment_id].bit; BOOST_CHECK_EQUAL(m_node.chainman->ActiveChain().Tip()->nVersion & bitmask, 0); BOOST_CHECK_EQUAL(pblocktemplate->block.nVersion & bitmask, bitmask); diff --git a/src/test/fuzz/tx_pool.cpp b/src/test/fuzz/tx_pool.cpp index 8799b1bad806..e0c46f1ab773 100644 --- a/src/test/fuzz/tx_pool.cpp +++ b/src/test/fuzz/tx_pool.cpp @@ -99,7 +99,7 @@ void Finish(FuzzedDataProvider& fuzzed_data_provider, MockedTxPool& tx_pool, con options.nBlockMaxSize = fuzzed_data_provider.ConsumeIntegralInRange(0U, MaxBlockSize(true)); options.blockMinFeeRate = CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)}; - auto assembler = BlockAssembler{chainstate, node, static_cast(&tx_pool), chainstate.m_params, options}; + auto assembler = BlockAssembler{chainstate, node, static_cast(&tx_pool), options}; auto block_template = assembler.CreateNewBlock(CScript{} << OP_TRUE); Assert(block_template->block.vtx.size() >= 1); } diff --git a/src/test/miner_tests.cpp b/src/test/miner_tests.cpp index 714b84c19182..5968127d67d1 100644 --- a/src/test/miner_tests.cpp +++ b/src/test/miner_tests.cpp @@ -64,7 +64,7 @@ BlockAssembler MinerTestingSetup::AssemblerForTest(const CChainParams& params) options.nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE; options.blockMinFeeRate = blockMinFeeRate; - return BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get(), params, options); + return BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get(), options); } constexpr static struct { diff --git a/src/test/net_peer_connection_tests.cpp b/src/test/net_peer_connection_tests.cpp index 10378237ed67..0243b09041e4 100644 --- a/src/test/net_peer_connection_tests.cpp +++ b/src/test/net_peer_connection_tests.cpp @@ -81,9 +81,8 @@ static void AddPeer(NodeId& id, std::vector& nodes, PeerManager& peerman BOOST_AUTO_TEST_CASE(test_addnode_getaddednodeinfo_and_connection_detection) { - const auto& chainparams = Params(); auto connman = std::make_unique(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman); - auto peerman = MakePeerManager(*connman, m_node, /*banman=*/nullptr, chainparams, /*ignore_incoming_txs=*/false); + auto peerman = MakePeerManager(*connman, m_node, /*banman=*/nullptr, /*ignore_incoming_txs=*/false); NodeId id{0}; std::vector nodes; diff --git a/src/test/util/mining.cpp b/src/test/util/mining.cpp index adeabd74937a..832941de1bcc 100644 --- a/src/test/util/mining.cpp +++ b/src/test/util/mining.cpp @@ -82,7 +82,7 @@ std::shared_ptr PrepareBlock(const NodeContext& node, const CScript& coi { assert(node.mempool); auto block = std::make_shared( - BlockAssembler{node.chainman->ActiveChainstate(), node, Assert(node.mempool.get()), Params()} + BlockAssembler{node.chainman->ActiveChainstate(), node, Assert(node.mempool.get())} .CreateNewBlock(coinbase_scriptPubKey) ->block); diff --git a/src/test/util/setup_common.cpp b/src/test/util/setup_common.cpp index c9edf3448b26..0b8e58faf55a 100644 --- a/src/test/util/setup_common.cpp +++ b/src/test/util/setup_common.cpp @@ -127,10 +127,9 @@ std::ostream& operator<<(std::ostream& os, const uint256& num) std::unique_ptr MakePeerManager(CConnman& connman, NodeContext& node, BanMan* banman, - const CChainParams& chainparams, bool ignore_incoming_txs) { - return PeerManager::make(chainparams, connman, *node.addrman, banman, *node.dstxman, *node.chainman, *node.mempool, *node.mn_metaman, + return PeerManager::make(connman, *node.addrman, banman, *node.dstxman, *node.chainman, *node.mempool, *node.mn_metaman, *node.mn_sync, *node.sporkman, *node.chainlocks, *node.clhandler, node.active_ctx, node.dmnman, node.cj_walletman, node.llmq_ctx, node.observer_ctx, ignore_incoming_txs); } @@ -138,14 +137,12 @@ std::unique_ptr MakePeerManager(CConnman& connman, void DashChainstateSetup(ChainstateManager& chainman, NodeContext& node, bool llmq_dbs_in_memory, - bool llmq_dbs_wipe, - const Consensus::Params& consensus_params) + bool llmq_dbs_wipe) { DashChainstateSetup(chainman, *Assert(node.mn_metaman.get()), *Assert(node.sporkman.get()), *Assert(node.chainlocks), *Assert(node.mn_sync), node.chain_helper, node.dmnman, *node.evodb, node.llmq_ctx, Assert(node.mempool.get()), node.args->GetDataDirNet(), llmq_dbs_in_memory, llmq_dbs_wipe, - llmq::DEFAULT_BLSCHECK_THREADS, llmq::DEFAULT_WORKER_COUNT, llmq::DEFAULT_MAX_RECOVERED_SIGS_AGE, - consensus_params); + llmq::DEFAULT_BLSCHECK_THREADS, llmq::DEFAULT_WORKER_COUNT, llmq::DEFAULT_MAX_RECOVERED_SIGS_AGE); } void DashChainstateSetupClose(NodeContext& node) @@ -309,7 +306,6 @@ ChainTestingSetup::~ChainTestingSetup() void ChainTestingSetup::LoadVerifyActivateChainstate() { - const CChainParams& chainparams = Params(); auto& chainman{*Assert(m_node.chainman)}; auto maybe_load_error = LoadChainstate(fReindex.load(), chainman, @@ -324,7 +320,6 @@ void ChainTestingSetup::LoadVerifyActivateChainstate() Assert(m_node.mempool.get()), Assert(m_node.args)->GetDataDirNet(), fPruneMode, - chainparams.GetConsensus(), m_args.GetBoolArg("-reindex-chainstate", false), m_cache_sizes.block_tree_db, m_cache_sizes.coins_db, @@ -344,10 +339,8 @@ void ChainTestingSetup::LoadVerifyActivateChainstate() *Assert(m_node.evodb.get()), fReindex.load(), m_args.GetBoolArg("-reindex-chainstate", false), - chainparams.GetConsensus(), m_args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS), m_args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL), - /*get_unix_time_seconds=*/static_cast(GetTime), [](bool bls_state) { LogPrintf("%s: bls_legacy_scheme=%d\n", __func__, bls_state); }); @@ -368,7 +361,6 @@ TestingSetup::TestingSetup( { m_coins_db_in_memory = coins_db_in_memory; m_block_tree_db_in_memory = block_tree_db_in_memory; - const CChainParams& chainparams = Params(); // Ideally we'd move all the RPC tests to the functional testing framework // instead of unit tests, but for now we need these here. RegisterAllCoreRPCCommands(tableRPC); @@ -392,7 +384,7 @@ TestingSetup::TestingSetup( #endif // ENABLE_WALLET m_node.banman = std::make_unique(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME); - m_node.peerman = MakePeerManager(*m_node.connman, m_node, m_node.banman.get(), chainparams, + m_node.peerman = MakePeerManager(*m_node.connman, m_node, m_node.banman.get(), /*ignore_incoming_txs=*/false); { CConnman::Options options; @@ -520,9 +512,8 @@ CBlock TestChainSetup::CreateBlock( const CScript& scriptPubKey, CChainState& chainstate) { - const CChainParams& chainparams = Params(); CTxMemPool empty_pool; - CBlock block = BlockAssembler(chainstate, m_node, &empty_pool, chainparams).CreateNewBlock(scriptPubKey)->block; + CBlock block = BlockAssembler(chainstate, m_node, &empty_pool).CreateNewBlock(scriptPubKey)->block; std::vector llmqCommitments; for (const auto& tx : block.vtx) { @@ -572,7 +563,7 @@ CBlock TestChainSetup::CreateBlock( block.hashMerkleRoot = BlockMerkleRoot(block); } - while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())) ++block.nNonce; + while (!CheckProofOfWork(block.GetHash(), block.nBits, m_node.chainman->GetConsensus())) ++block.nNonce; CBlock result = block; return result; diff --git a/src/test/util/setup_common.h b/src/test/util/setup_common.h index 60787206c1f8..632c6039a899 100644 --- a/src/test/util/setup_common.h +++ b/src/test/util/setup_common.h @@ -25,7 +25,6 @@ #include #include -class CChainParams; class CFeeRate; namespace Consensus { struct Params; @@ -84,13 +83,11 @@ static constexpr CAmount CENT{1000000}; std::unique_ptr MakePeerManager(CConnman& connman, node::NodeContext& node, BanMan* banman, - const CChainParams& chainparams, bool ignore_incoming_txs); void DashChainstateSetup(ChainstateManager& chainman, node::NodeContext& node, bool llmq_dbs_in_memory, - bool llmq_dbs_wipe, - const Consensus::Params& consensus_params); + bool llmq_dbs_wipe); void DashChainstateSetupClose(node::NodeContext& node); /** Basic testing setup. diff --git a/src/test/validation_block_tests.cpp b/src/test/validation_block_tests.cpp index 1525d645c196..e08c88b44e02 100644 --- a/src/test/validation_block_tests.cpp +++ b/src/test/validation_block_tests.cpp @@ -67,7 +67,7 @@ std::shared_ptr MinerTestingSetup::Block(const uint256& prev_hash) static int i = 0; static uint64_t time = Params().GenesisBlock().nTime; - auto ptemplate = BlockAssembler(m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get(), Params()).CreateNewBlock(CScript{} << i++ << OP_TRUE); + auto ptemplate = BlockAssembler{m_node.chainman->ActiveChainstate(), m_node, m_node.mempool.get()}.CreateNewBlock(CScript{} << i++ << OP_TRUE); auto pblock = std::make_shared(ptemplate->block); pblock->hashPrevBlock = prev_hash; pblock->nTime = ++time; diff --git a/src/test/validation_chainstatemanager_tests.cpp b/src/test/validation_chainstatemanager_tests.cpp index b68873228dc3..829c79588064 100644 --- a/src/test/validation_chainstatemanager_tests.cpp +++ b/src/test/validation_chainstatemanager_tests.cpp @@ -37,7 +37,6 @@ BOOST_FIXTURE_TEST_SUITE(validation_chainstatemanager_tests, ChainTestingSetup) //! First create a legacy (IBD) chainstate, then create a snapshot chainstate. BOOST_AUTO_TEST_CASE(chainstatemanager) { - const Consensus::Params& consensus_params = Params().GetConsensus(); ChainstateManager& manager = *m_node.chainman; CTxMemPool& mempool = *m_node.mempool; CEvoDB& evodb = *m_node.evodb; @@ -53,7 +52,7 @@ BOOST_AUTO_TEST_CASE(chainstatemanager) /*cache_size_bytes=*/1 << 23, /*in_memory=*/true, /*should_wipe=*/false); WITH_LOCK(::cs_main, c1.InitCoinsCache(1 << 23)); - DashChainstateSetup(manager, m_node, /*llmq_dbs_in_memory=*/true, /*llmq_dbs_wipe=*/false, consensus_params); + DashChainstateSetup(manager, m_node, /*llmq_dbs_in_memory=*/true, /*llmq_dbs_wipe=*/false); BOOST_CHECK(!manager.IsSnapshotActive()); BOOST_CHECK(WITH_LOCK(::cs_main, return !manager.IsSnapshotValidated())); @@ -85,7 +84,7 @@ BOOST_AUTO_TEST_CASE(chainstatemanager) ); chainstates.push_back(&c2); - DashChainstateSetup(manager, m_node, /*llmq_dbs_in_memory=*/true, /*llmq_dbs_wipe=*/false, consensus_params); + DashChainstateSetup(manager, m_node, /*llmq_dbs_in_memory=*/true, /*llmq_dbs_wipe=*/false); BOOST_CHECK_EQUAL(manager.SnapshotBlockhash().value(), snapshot_blockhash); From 505ffbc342ef8626a77d1671466c82e93b20b04b Mon Sep 17 00:00:00 2001 From: Konstantin Akimov Date: Fri, 20 May 2022 19:39:33 +0100 Subject: [PATCH 05/12] partial Merge bitcoin/bitcoin#25064: [kernel 2b/n] Add `ChainstateManager::m_adjusted_time_callback` BACKPORT NOTE: next dependencies are still there: - netaddress.cpp - netbase.cpp - timedata.cpp There's tiny script to find-out who is exactly blocker: find . -name '*kernel*.o' -exec bash -c "nm -C -u '{}' 2>/dev/null | grep -qF 'GetSporkValue(' && echo '{}'" \; GetAdjustedTime is used by governance/vote, governance/object, spork_manager CNetAddress, CService are used by evo/netinfo ---- 53494bc7392591336e09d095f1fc38d63d566abf validation: Have ChainstateManager own m_chainparams (Carl Dong) 04c31c1295eb4ecd42afd54b8e353cbda93d83f0 Add ChainstateManager::m_adjusted_time_callback (Carl Dong) dbe45c34f8b4fd7d615f7e05ef1454798ef0c8ca Add ChainstateManagerOpts, using as ::Options (Carl Dong) Pull request description: ``` This decouples validation.cpp from netaddress.cpp (transitively, timedata.cpp, and asmap.cpp). This is important for libbitcoinkernel as: - There is no reason for the consensus engine to be coupled with netaddress, timedata, and asmap - Users of libbitcoinkernel can now easily supply their own std::function that provides the adjusted time. See the src/Makefile.am changes for some satisfying removals. ``` Top commit has no ACKs. Tree-SHA512: a093ec6ecacdc659d656574f05bd31ade6a6cdb64d5a97684f94ae7e55c0e360b78177553d4d1ef40280192674464d029a0d68e96caf8711d9274011172f1330 Co-authored-by: MacroFake --- src/Makefile.am | 2 +- src/bitcoin-chainstate.cpp | 6 +++++- src/init.cpp | 6 +++++- src/kernel/chainstatemanager_opts.h | 23 +++++++++++++++++++++++ src/node/miner.cpp | 2 +- src/rpc/mining.cpp | 5 +++-- src/test/miner_tests.cpp | 1 + src/test/util/setup_common.cpp | 7 ++++++- src/test/validation_chainstate_tests.cpp | 2 +- src/validation.cpp | 9 ++++----- src/validation.h | 13 +++++++++++-- 11 files changed, 61 insertions(+), 15 deletions(-) create mode 100644 src/kernel/chainstatemanager_opts.h diff --git a/src/Makefile.am b/src/Makefile.am index 3431cbc53509..7b2048a566ed 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -281,6 +281,7 @@ BITCOIN_CORE_H = \ instantsend/net_instantsend.h \ instantsend/signing.h \ kernel/blockmanager_opts.h \ + kernel/chainstatemanager_opts.h \ kernel/coinstats.h \ key.h \ key_io.h \ @@ -1323,7 +1324,6 @@ libdashkernel_la_SOURCES = \ txdb.cpp \ txmempool.cpp \ uint256.cpp \ - util/asmap.cpp \ util/bytevectorhash.cpp \ util/check.cpp \ util/getuniquepath.cpp \ diff --git a/src/bitcoin-chainstate.cpp b/src/bitcoin-chainstate.cpp index 4d5a57f274ad..272b2994e5e3 100644 --- a/src/bitcoin-chainstate.cpp +++ b/src/bitcoin-chainstate.cpp @@ -78,7 +78,11 @@ int main(int argc, char* argv[]) // SETUP: Chainstate - ChainstateManager chainman{chainparams}; + const ChainstateManager::Options chainman_opts{ + chainparams, + static_cast(GetTime), + }; + ChainstateManager chainman{chainman_opts}; CMasternodeMetaMan metaman; std::unique_ptr evodb; diff --git a/src/init.cpp b/src/init.cpp index a160b48f5117..0d1841323a8b 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -1984,7 +1984,11 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) for (bool fLoaded = false; !fLoaded && !ShutdownRequested();) { node.mempool = std::make_unique(node.fee_estimator.get(), mempool_check_ratio); - node.chainman = std::make_unique(chainparams); + const ChainstateManager::Options chainman_opts{ + chainparams, + GetAdjustedTime, + }; + node.chainman = std::make_unique(chainman_opts); ChainstateManager& chainman = *node.chainman; /** diff --git a/src/kernel/chainstatemanager_opts.h b/src/kernel/chainstatemanager_opts.h new file mode 100644 index 000000000000..575d94e2e96a --- /dev/null +++ b/src/kernel/chainstatemanager_opts.h @@ -0,0 +1,23 @@ +// 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. + +#ifndef BITCOIN_KERNEL_CHAINSTATEMANAGER_OPTS_H +#define BITCOIN_KERNEL_CHAINSTATEMANAGER_OPTS_H + +#include +#include + +class CChainParams; + +/** + * An options struct for `ChainstateManager`, more ergonomically referred to as + * `ChainstateManager::Options` due to the using-declaration in + * `ChainstateManager`. + */ +struct ChainstateManagerOpts { + const CChainParams& chainparams; + const std::function adjusted_time_callback{nullptr}; +}; + +#endif // BITCOIN_KERNEL_CHAINSTATEMANAGER_OPTS_H diff --git a/src/node/miner.cpp b/src/node/miner.cpp index 0bbb1ff2fcfd..e475b501b8ad 100644 --- a/src/node/miner.cpp +++ b/src/node/miner.cpp @@ -333,7 +333,7 @@ std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& sc pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(*pblock->vtx[0]); BlockValidationState state; - if (!TestBlockValidity(state, m_chainlocks, m_evoDb, chainparams, m_chainstate, *pblock, pindexPrev, false, false)) { + if (!TestBlockValidity(state, m_chainlocks, m_evoDb, chainparams, m_chainstate, *pblock, pindexPrev, GetAdjustedTime, false, false)) { throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, state.ToString())); } int64_t nTime2 = GetTimeMicros(); diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index cb316e71ec9a..f419d141ba87 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -33,6 +33,7 @@ #include