aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.cirrus.yml39
-rw-r--r--CONTRIBUTING.md4
-rw-r--r--INSTALL.md6
-rw-r--r--build-aux/m4/bitcoin_find_bdb48.m419
-rw-r--r--build_msvc/README.md66
-rw-r--r--build_msvc/bitcoin-qt/bitcoin-qt.vcxproj1
-rw-r--r--build_msvc/bitcoin-util/bitcoin-util.vcxproj2
-rw-r--r--build_msvc/bitcoin.sln100
-rw-r--r--build_msvc/bitcoind/bitcoind.vcxproj6
-rw-r--r--build_msvc/common.init.vcxproj9
-rw-r--r--build_msvc/common.qt.init.vcxproj2
-rw-r--r--build_msvc/libbitcoin_qt/libbitcoin_qt.vcxproj14
-rw-r--r--build_msvc/test_bitcoin-qt/test_bitcoin-qt.vcxproj1
-rwxr-xr-xci/test/00_setup_env_arm.sh4
-rwxr-xr-xci/test/00_setup_env_i686_multiprocess.sh (renamed from ci/test/00_setup_env_native_multiprocess.sh)8
-rwxr-xr-xci/test/00_setup_env_mac.sh2
-rwxr-xr-xci/test/00_setup_env_mac_host.sh2
-rwxr-xr-xci/test/00_setup_env_native_nowallet.sh6
-rwxr-xr-xci/test/00_setup_env_native_qt5.sh8
-rwxr-xr-xci/test/00_setup_env_native_valgrind.sh3
-rwxr-xr-xci/test/00_setup_env_s390x.sh4
-rw-r--r--configure.ac98
-rwxr-xr-xcontrib/devtools/symbol-check.py2
-rwxr-xr-xcontrib/devtools/test-symbol-check.py2
-rw-r--r--contrib/guix/INSTALL.md2
-rw-r--r--contrib/guix/README.md8
-rwxr-xr-xcontrib/guix/guix-build2
-rwxr-xr-xcontrib/guix/guix-codesign2
-rwxr-xr-xcontrib/guix/libexec/build.sh6
-rwxr-xr-xcontrib/signet/getcoins.py94
-rw-r--r--depends/README.md2
-rw-r--r--depends/hosts/darwin.mk2
-rw-r--r--doc/build-unix.md2
-rw-r--r--doc/build-windows.md40
-rw-r--r--doc/dependencies.md5
-rw-r--r--doc/developer-notes.md64
-rw-r--r--doc/fuzzing.md67
-rw-r--r--doc/release-notes-22539.md8
-rw-r--r--doc/release-notes.md42
-rw-r--r--doc/release-notes/release-notes-22.0.md1163
-rw-r--r--doc/release-process.md21
-rw-r--r--doc/tor.md9
-rw-r--r--doc/zmq.md4
-rw-r--r--share/examples/bitcoin.conf2
-rw-r--r--share/qt/Info.plist.in7
-rw-r--r--src/.clang-tidy2
-rw-r--r--src/Makefile.am17
-rw-r--r--src/Makefile.crc32c.include1
-rw-r--r--src/Makefile.qt.include4
-rw-r--r--src/Makefile.qttest.include1
-rw-r--r--src/Makefile.test.include4
-rw-r--r--src/Makefile.test_util.include1
-rw-r--r--src/addrdb.cpp97
-rw-r--r--src/addrdb.h22
-rw-r--r--src/addrman.cpp570
-rw-r--r--src/addrman.h392
-rw-r--r--src/addrman_impl.h271
-rw-r--r--src/bech32.cpp34
-rw-r--r--src/bench/addrman.cpp52
-rw-r--r--src/bench/bech32.cpp1
-rw-r--r--src/bench/bench.cpp17
-rw-r--r--src/bench/bench.h3
-rw-r--r--src/bench/bench_bitcoin.cpp64
-rw-r--r--src/bench/coin_selection.cpp2
-rw-r--r--src/bench/crypto_hash.cpp8
-rw-r--r--src/bench/nanobench.h43
-rw-r--r--src/bench/peer_eviction.cpp10
-rw-r--r--src/bench/rollingbloom.cpp16
-rw-r--r--src/bitcoin-cli.cpp40
-rw-r--r--src/bitcoin-tx.cpp3
-rw-r--r--src/bitcoind.cpp2
-rw-r--r--src/bloom.cpp59
-rw-r--r--src/bloom.h20
-rw-r--r--src/chain.h24
-rw-r--r--src/chainparams.cpp49
-rw-r--r--src/chainparamsbase.cpp2
-rw-r--r--src/checkqueue.h2
-rw-r--r--src/compat/glibc_compat.cpp62
-rw-r--r--src/consensus/amount.h (renamed from src/amount.h)12
-rw-r--r--src/consensus/tx_check.cpp1
-rw-r--r--src/consensus/tx_verify.cpp1
-rw-r--r--src/consensus/tx_verify.h2
-rw-r--r--src/core_io.h8
-rw-r--r--src/core_read.cpp2
-rw-r--r--src/core_write.cpp47
-rw-r--r--src/crc32c/.travis.yml18
-rw-r--r--src/crc32c/.ycm_extra_conf.py4
-rw-r--r--src/crc32c/README.md2
-rw-r--r--src/crc32c/src/crc32c_arm64_check.h10
-rw-r--r--src/dbwrapper.cpp8
-rw-r--r--src/dummywallet.cpp9
-rw-r--r--src/hash.cpp6
-rw-r--r--src/httpserver.cpp15
-rw-r--r--src/index/base.cpp2
-rw-r--r--src/index/base.h3
-rw-r--r--src/index/txindex.cpp163
-rw-r--r--src/index/txindex.h5
-rw-r--r--src/init.cpp118
-rw-r--r--src/init/bitcoin-node.cpp9
-rw-r--r--src/init/bitcoind.cpp11
-rw-r--r--src/interfaces/chain.h2
-rw-r--r--src/interfaces/node.h4
-rw-r--r--src/interfaces/wallet.h6
-rw-r--r--src/key.cpp5
-rw-r--r--src/key.h1
-rw-r--r--src/logging.cpp1
-rw-r--r--src/logging.h1
-rw-r--r--src/logging/timer.h24
-rw-r--r--src/mapport.cpp2
-rw-r--r--src/miner.cpp8
-rw-r--r--src/net.cpp56
-rw-r--r--src/net.h10
-rw-r--r--src/net_processing.cpp37
-rw-r--r--src/net_processing.h4
-rw-r--r--src/netaddress.cpp7
-rw-r--r--src/netaddress.h4
-rw-r--r--src/netbase.cpp2
-rw-r--r--src/node/blockstorage.cpp14
-rw-r--r--src/node/coinstats.h2
-rw-r--r--src/node/context.h4
-rw-r--r--src/node/interfaces.cpp22
-rw-r--r--src/node/psbt.cpp2
-rw-r--r--src/policy/feerate.h2
-rw-r--r--src/policy/fees.h2
-rw-r--r--src/policy/rbf.cpp145
-rw-r--r--src/policy/rbf.h69
-rw-r--r--src/primitives/transaction.cpp1
-rw-r--r--src/primitives/transaction.h2
-rw-r--r--src/pubkey.cpp5
-rw-r--r--src/qt/addressbookpage.cpp10
-rw-r--r--src/qt/bantablemodel.h1
-rw-r--r--src/qt/bitcoin.cpp38
-rw-r--r--src/qt/bitcoin.h13
-rw-r--r--src/qt/bitcoinamountfield.h2
-rw-r--r--src/qt/bitcoingui.cpp29
-rw-r--r--src/qt/bitcoingui.h3
-rw-r--r--src/qt/bitcoinunits.cpp2
-rw-r--r--src/qt/bitcoinunits.h2
-rw-r--r--src/qt/coincontroldialog.cpp18
-rw-r--r--src/qt/coincontroldialog.h6
-rw-r--r--src/qt/forms/optionsdialog.ui26
-rw-r--r--src/qt/guiutil.cpp28
-rw-r--r--src/qt/guiutil.h13
-rw-r--r--src/qt/initexecutor.cpp49
-rw-r--r--src/qt/initexecutor.h1
-rw-r--r--src/qt/intro.cpp4
-rw-r--r--src/qt/optionsdialog.cpp25
-rw-r--r--src/qt/optionsdialog.h1
-rw-r--r--src/qt/optionsmodel.cpp15
-rw-r--r--src/qt/optionsmodel.h2
-rw-r--r--src/qt/psbtoperationsdialog.cpp7
-rw-r--r--src/qt/qrimagewidget.cpp2
-rw-r--r--src/qt/rpcconsole.cpp30
-rw-r--r--src/qt/sendcoinsdialog.cpp15
-rw-r--r--src/qt/sendcoinsrecipient.h2
-rw-r--r--src/qt/test/addressbooktests.cpp4
-rw-r--r--src/qt/test/test_main.cpp8
-rw-r--r--src/qt/test/wallettests.cpp4
-rw-r--r--src/qt/transactionfilterproxy.h2
-rw-r--r--src/qt/transactionrecord.h2
-rw-r--r--src/qt/transactionview.cpp30
-rw-r--r--src/qt/walletcontroller.cpp86
-rw-r--r--src/qt/walletcontroller.h19
-rw-r--r--src/qt/walletframe.cpp6
-rw-r--r--src/qt/walletmodel.cpp7
-rw-r--r--src/qt/walletmodeltransaction.h2
-rw-r--r--src/qt/walletview.cpp24
-rw-r--r--src/qt/walletview.h2
-rw-r--r--src/randomenv.cpp6
-rw-r--r--src/rpc/blockchain.cpp105
-rw-r--r--src/rpc/blockchain.h6
-rw-r--r--src/rpc/client.cpp2
-rw-r--r--src/rpc/external_signer.cpp7
-rw-r--r--src/rpc/mining.cpp20
-rw-r--r--src/rpc/misc.cpp40
-rw-r--r--src/rpc/net.cpp26
-rw-r--r--src/rpc/rawtransaction.cpp101
-rw-r--r--src/rpc/rawtransaction_util.cpp1
-rw-r--r--src/rpc/server.cpp2
-rw-r--r--src/rpc/server.h1
-rw-r--r--src/rpc/util.cpp1
-rw-r--r--src/scheduler.cpp2
-rw-r--r--src/script/sigcache.cpp2
-rw-r--r--src/script/sign.cpp1
-rw-r--r--src/script/standard.cpp41
-rw-r--r--src/script/standard.h18
-rw-r--r--src/signet.cpp2
-rw-r--r--src/sync.cpp25
-rw-r--r--src/sync.h7
-rw-r--r--src/test/README.md26
-rw-r--r--src/test/addrman_tests.cpp232
-rw-r--r--src/test/amount_tests.cpp2
-rw-r--r--src/test/bloom_tests.cpp2
-rw-r--r--src/test/data/README.md2
-rw-r--r--src/test/fuzz/addrman.cpp224
-rw-r--r--src/test/fuzz/asmap.cpp3
-rw-r--r--src/test/fuzz/coins_view.cpp2
-rw-r--r--src/test/fuzz/connman.cpp2
-rw-r--r--src/test/fuzz/data_stream.cpp26
-rw-r--r--src/test/fuzz/deserialize.cpp5
-rw-r--r--src/test/fuzz/fee_rate.cpp2
-rw-r--r--src/test/fuzz/fees.cpp2
-rw-r--r--src/test/fuzz/integer.cpp3
-rw-r--r--src/test/fuzz/locale.cpp6
-rw-r--r--src/test/fuzz/muhash.cpp73
-rw-r--r--src/test/fuzz/net.cpp7
-rw-r--r--src/test/fuzz/parse_numbers.cpp7
-rw-r--r--src/test/fuzz/script.cpp62
-rw-r--r--src/test/fuzz/script_flags.cpp1
-rw-r--r--src/test/fuzz/string.cpp159
-rw-r--r--src/test/fuzz/system.cpp12
-rw-r--r--src/test/fuzz/transaction.cpp4
-rw-r--r--src/test/fuzz/util.cpp1
-rw-r--r--src/test/fuzz/util.h2
-rw-r--r--src/test/fuzz/utxo_snapshot.cpp1
-rw-r--r--src/test/fuzz/versionbits.cpp1
-rw-r--r--src/test/getarg_tests.cpp18
-rw-r--r--src/test/logging_tests.cpp8
-rw-r--r--src/test/policy_fee_tests.cpp2
-rw-r--r--src/test/script_parse_tests.cpp55
-rw-r--r--src/test/script_standard_tests.cpp61
-rw-r--r--src/test/transaction_tests.cpp1
-rw-r--r--src/test/txvalidationcache_tests.cpp9
-rw-r--r--src/test/util/chainstate.h54
-rw-r--r--src/test/util/setup_common.cpp32
-rw-r--r--src/test/util/setup_common.h19
-rw-r--r--src/test/util_tests.cpp214
-rw-r--r--src/test/validation_chainstate_tests.cpp76
-rw-r--r--src/test/validation_chainstatemanager_tests.cpp66
-rw-r--r--src/test/validation_flush_tests.cpp4
-rw-r--r--src/test/validation_tests.cpp1
-rw-r--r--src/timedata.cpp10
-rw-r--r--src/torcontrol.cpp4
-rw-r--r--src/txdb.cpp27
-rw-r--r--src/txdb.h11
-rw-r--r--src/txmempool.cpp40
-rw-r--r--src/txmempool.h31
-rw-r--r--src/util/asmap.cpp38
-rw-r--r--src/util/asmap.h7
-rw-r--r--src/util/moneystr.cpp5
-rw-r--r--src/util/moneystr.h2
-rw-r--r--src/util/rbf.h18
-rw-r--r--src/util/sock.cpp8
-rw-r--r--src/util/strencodings.cpp132
-rw-r--r--src/util/strencodings.h59
-rw-r--r--src/util/syscall_sandbox.cpp909
-rw-r--r--src/util/syscall_sandbox.h57
-rw-r--r--src/util/system.cpp24
-rw-r--r--src/util/system.h2
-rw-r--r--src/util/types.h11
-rw-r--r--src/validation.cpp308
-rw-r--r--src/validation.h54
-rw-r--r--src/wallet/bdb.cpp2
-rw-r--r--src/wallet/coincontrol.h29
-rw-r--r--src/wallet/coinselection.cpp33
-rw-r--r--src/wallet/coinselection.h29
-rw-r--r--src/wallet/fees.h2
-rw-r--r--src/wallet/init.cpp4
-rw-r--r--src/wallet/interfaces.cpp12
-rw-r--r--src/wallet/load.cpp2
-rw-r--r--src/wallet/receive.cpp1
-rw-r--r--src/wallet/receive.h2
-rw-r--r--src/wallet/rpcdump.cpp6
-rw-r--r--src/wallet/rpcwallet.cpp269
-rw-r--r--src/wallet/salvage.cpp2
-rw-r--r--src/wallet/scriptpubkeyman.cpp6
-rw-r--r--src/wallet/spend.cpp93
-rw-r--r--src/wallet/spend.h6
-rw-r--r--src/wallet/sqlite.cpp4
-rw-r--r--src/wallet/test/coinselector_tests.cpp27
-rw-r--r--src/wallet/test/spend_tests.cpp1
-rw-r--r--src/wallet/test/wallet_tests.cpp10
-rw-r--r--src/wallet/transaction.h31
-rw-r--r--src/wallet/wallet.cpp153
-rw-r--r--src/wallet/wallet.h34
-rw-r--r--src/wallet/walletdb.cpp39
-rw-r--r--src/wallet/walletdb.h8
-rw-r--r--src/wallet/wallettool.cpp4
-rw-r--r--src/zmq/zmqnotificationinterface.cpp2
-rw-r--r--src/zmq/zmqpublishnotifier.cpp24
-rw-r--r--test/README.md9
-rw-r--r--test/config.ini.in1
-rw-r--r--test/functional/README.md2
-rwxr-xr-xtest/functional/example_test.py2
-rwxr-xr-xtest/functional/feature_abortnode.py6
-rwxr-xr-xtest/functional/feature_addrman.py98
-rwxr-xr-xtest/functional/feature_asmap.py29
-rwxr-xr-xtest/functional/feature_backwards_compatibility.py6
-rwxr-xr-xtest/functional/feature_bip68_sequence.py26
-rwxr-xr-xtest/functional/feature_block.py5
-rwxr-xr-xtest/functional/feature_blockfilterindex_prune.py6
-rwxr-xr-xtest/functional/feature_blocksdir.py2
-rwxr-xr-xtest/functional/feature_cltv.py9
-rwxr-xr-xtest/functional/feature_coinstatsindex.py28
-rwxr-xr-xtest/functional/feature_config_args.py26
-rwxr-xr-xtest/functional/feature_csv_activation.py18
-rwxr-xr-xtest/functional/feature_dersig.py12
-rwxr-xr-xtest/functional/feature_fee_estimation.py159
-rwxr-xr-xtest/functional/feature_loadblock.py2
-rwxr-xr-xtest/functional/feature_maxuploadtarget.py3
-rwxr-xr-xtest/functional/feature_minchainwork.py4
-rwxr-xr-xtest/functional/feature_notifications.py21
-rwxr-xr-xtest/functional/feature_nulldummy.py6
-rwxr-xr-xtest/functional/feature_presegwit_node_upgrade.py15
-rwxr-xr-xtest/functional/feature_pruning.py12
-rwxr-xr-xtest/functional/feature_rbf.py84
-rwxr-xr-xtest/functional/feature_reindex.py2
-rwxr-xr-xtest/functional/feature_segwit.py93
-rwxr-xr-xtest/functional/feature_signet.py2
-rwxr-xr-xtest/functional/feature_syscall_sandbox.py34
-rwxr-xr-xtest/functional/feature_taproot.py5
-rwxr-xr-xtest/functional/feature_utxo_set_hash.py4
-rwxr-xr-xtest/functional/feature_versionbits_warning.py15
-rwxr-xr-xtest/functional/interface_bitcoin_cli.py17
-rwxr-xr-xtest/functional/interface_rest.py14
-rwxr-xr-xtest/functional/interface_zmq.py47
-rwxr-xr-xtest/functional/mempool_accept.py4
-rwxr-xr-xtest/functional/mempool_accept_wtxid.py4
-rwxr-xr-xtest/functional/mempool_compatibility.py4
-rwxr-xr-xtest/functional/mempool_expiry.py4
-rwxr-xr-xtest/functional/mempool_limit.py83
-rwxr-xr-xtest/functional/mempool_package_limits.py84
-rwxr-xr-xtest/functional/mempool_package_onemore.py2
-rwxr-xr-xtest/functional/mempool_packages.py37
-rwxr-xr-xtest/functional/mempool_persist.py64
-rwxr-xr-xtest/functional/mempool_reorg.py6
-rwxr-xr-xtest/functional/mempool_resurrect.py10
-rwxr-xr-xtest/functional/mempool_spend_coinbase.py10
-rwxr-xr-xtest/functional/mempool_unbroadcast.py2
-rwxr-xr-xtest/functional/mempool_updatefromblock.py2
-rwxr-xr-xtest/functional/mining_basic.py6
-rwxr-xr-xtest/functional/mining_getblocktemplate_longpoll.py4
-rwxr-xr-xtest/functional/mining_prioritisetransaction.py4
-rwxr-xr-xtest/functional/p2p_addr_relay.py14
-rwxr-xr-xtest/functional/p2p_addrfetch.py13
-rwxr-xr-xtest/functional/p2p_addrv2_relay.py9
-rwxr-xr-xtest/functional/p2p_blockfilters.py6
-rwxr-xr-xtest/functional/p2p_blocksonly.py26
-rwxr-xr-xtest/functional/p2p_compactblocks.py16
-rwxr-xr-xtest/functional/p2p_compactblocks_blocksonly.py130
-rwxr-xr-xtest/functional/p2p_compactblocks_hb.py4
-rwxr-xr-xtest/functional/p2p_eviction.py2
-rwxr-xr-xtest/functional/p2p_feefilter.py4
-rwxr-xr-xtest/functional/p2p_filter.py36
-rwxr-xr-xtest/functional/p2p_fingerprint.py4
-rwxr-xr-xtest/functional/p2p_ibd_txrelay.py2
-rwxr-xr-xtest/functional/p2p_invalid_block.py2
-rwxr-xr-xtest/functional/p2p_invalid_locator.py2
-rwxr-xr-xtest/functional/p2p_invalid_tx.py2
-rwxr-xr-xtest/functional/p2p_leak.py2
-rwxr-xr-xtest/functional/p2p_leak_tx.py4
-rwxr-xr-xtest/functional/p2p_node_network_limited.py4
-rwxr-xr-xtest/functional/p2p_permissions.py2
-rwxr-xr-xtest/functional/p2p_segwit.py80
-rwxr-xr-xtest/functional/p2p_sendheaders.py8
-rwxr-xr-xtest/functional/rpc_addresses_deprecation.py56
-rwxr-xr-xtest/functional/rpc_blockchain.py44
-rwxr-xr-xtest/functional/rpc_createmultisig.py8
-rwxr-xr-xtest/functional/rpc_deprecated.py2
-rwxr-xr-xtest/functional/rpc_dumptxoutset.py2
-rwxr-xr-xtest/functional/rpc_fundrawtransaction.py163
-rwxr-xr-xtest/functional/rpc_generateblock.py26
-rwxr-xr-xtest/functional/rpc_getblockfilter.py4
-rwxr-xr-xtest/functional/rpc_getblockstats.py6
-rwxr-xr-xtest/functional/rpc_getchaintips.py4
-rwxr-xr-xtest/functional/rpc_invalidateblock.py10
-rwxr-xr-xtest/functional/rpc_misc.py2
-rwxr-xr-xtest/functional/rpc_net.py53
-rwxr-xr-xtest/functional/rpc_packages.py4
-rwxr-xr-xtest/functional/rpc_preciousblock.py12
-rwxr-xr-xtest/functional/rpc_psbt.py65
-rwxr-xr-xtest/functional/rpc_rawtransaction.py24
-rwxr-xr-xtest/functional/rpc_scantxoutset.py6
-rwxr-xr-xtest/functional/rpc_signer.py11
-rwxr-xr-xtest/functional/rpc_signrawtransaction.py19
-rwxr-xr-xtest/functional/rpc_txoutproof.py8
-rw-r--r--test/functional/test-shell.md2
-rw-r--r--test/functional/test_framework/authproxy.py4
-rw-r--r--test/functional/test_framework/blocktools.py9
-rwxr-xr-xtest/functional/test_framework/p2p.py4
-rwxr-xr-xtest/functional/test_framework/script_util.py62
-rwxr-xr-xtest/functional/test_framework/test_framework.py36
-rw-r--r--test/functional/test_framework/util.py25
-rw-r--r--test/functional/test_framework/wallet.py65
-rwxr-xr-xtest/functional/test_runner.py9
-rwxr-xr-xtest/functional/tool_wallet.py4
-rwxr-xr-xtest/functional/wallet_abandonconflict.py35
-rwxr-xr-xtest/functional/wallet_address_types.py6
-rwxr-xr-xtest/functional/wallet_avoidreuse.py20
-rwxr-xr-xtest/functional/wallet_backup.py12
-rwxr-xr-xtest/functional/wallet_balance.py16
-rwxr-xr-xtest/functional/wallet_basic.py114
-rwxr-xr-xtest/functional/wallet_bumpfee.py18
-rwxr-xr-xtest/functional/wallet_coinbase_category.py6
-rwxr-xr-xtest/functional/wallet_create_tx.py4
-rwxr-xr-xtest/functional/wallet_createwallet.py2
-rwxr-xr-xtest/functional/wallet_disable.py4
-rwxr-xr-xtest/functional/wallet_dump.py2
-rwxr-xr-xtest/functional/wallet_fallbackfee.py2
-rwxr-xr-xtest/functional/wallet_groups.py16
-rwxr-xr-xtest/functional/wallet_hd.py14
-rwxr-xr-xtest/functional/wallet_import_rescan.py6
-rwxr-xr-xtest/functional/wallet_importdescriptors.py10
-rwxr-xr-xtest/functional/wallet_importmulti.py20
-rwxr-xr-xtest/functional/wallet_importprunedfunds.py8
-rwxr-xr-xtest/functional/wallet_keypool.py2
-rwxr-xr-xtest/functional/wallet_keypool_topup.py6
-rwxr-xr-xtest/functional/wallet_labels.py16
-rwxr-xr-xtest/functional/wallet_listreceivedby.py10
-rwxr-xr-xtest/functional/wallet_listsinceblock.py24
-rwxr-xr-xtest/functional/wallet_listtransactions.py6
-rwxr-xr-xtest/functional/wallet_multiwallet.py8
-rwxr-xr-xtest/functional/wallet_orphanedreward.py10
-rwxr-xr-xtest/functional/wallet_reorgsrestore.py14
-rwxr-xr-xtest/functional/wallet_send.py55
-rwxr-xr-xtest/functional/wallet_signer.py5
-rwxr-xr-xtest/functional/wallet_taproot.py14
-rwxr-xr-xtest/functional/wallet_transactiontime_rescan.py161
-rwxr-xr-xtest/functional/wallet_txn_clone.py19
-rwxr-xr-xtest/functional/wallet_txn_doublespend.py19
-rwxr-xr-xtest/functional/wallet_upgradewallet.py4
-rwxr-xr-xtest/functional/wallet_watchonly.py4
-rwxr-xr-xtest/get_previous_releases.py1
-rw-r--r--test/lint/README.md6
-rwxr-xr-xtest/lint/lint-locale-dependence.sh14
-rwxr-xr-xtest/lint/lint-logs.sh2
426 files changed, 8534 insertions, 4248 deletions
diff --git a/.cirrus.yml b/.cirrus.yml
index 5105e0a490..5491f2c04b 100644
--- a/.cirrus.yml
+++ b/.cirrus.yml
@@ -1,6 +1,4 @@
-### Global defaults
-
-env:
+env: # Global defaults
PACKAGE_MANAGER_INSTALL: "apt-get update && apt-get install -y"
MAKEJOBS: "-j4"
TEST_RUNNER_PORT_MIN: "14000" # Must be larger than 12321, which is used for the http cache. See https://cirrus-ci.org/guide/writing-tasks/#http-cache
@@ -77,7 +75,7 @@ task:
<< : *CIRRUS_EPHEMERAL_WORKER_TEMPLATE_ENV
task:
- name: "Win64 native [unit tests, no functional tests] [msvc]"
+ name: "Win64 native [msvc]"
<< : *FILTER_TEMPLATE
windows_container:
cpu: 4
@@ -92,21 +90,18 @@ task:
QT_DOWNLOAD_URL: 'https://download.qt.io/official_releases/qt/5.12/5.12.11/single/qt-everywhere-src-5.12.11.zip'
QT_LOCAL_PATH: 'C:\qt-everywhere-src-5.12.11.zip'
QT_SOURCE_DIR: 'C:\qt-everywhere-src-5.12.11'
- QTBASEDIR: 'C:\Qt5.12.11_x64_static_vs2019_160900'
+ QTBASEDIR: 'C:\Qt_static'
x64_NATIVE_TOOLS: '"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Auxiliary\Build\vcvars64.bat"'
IgnoreWarnIntDirInTempDetected: 'true'
merge_script:
- - ps: git config --global user.email "ci@ci.ci"
- - ps: git config --global user.name "ci"
+ - git config --global user.email "ci@ci.ci"
+ - git config --global user.name "ci"
# Windows filesystem loses the executable bit, and all of the executable
# files are considered "modified" now. It will break the following `git merge`
# command. The next two commands make git ignore this issue.
- - ps: git config core.filemode false
- - ps: git reset --hard
- - ps: if ($env:CIRRUS_PR -eq $null) { exit 0; }
- - ps: git fetch $env:CIRRUS_REPO_CLONE_URL $env:CIRRUS_BASE_BRANCH
- # Merge base to detect silent merge conflicts.
- - ps: git merge FETCH_HEAD
+ - git config core.filemode false
+ - git reset --hard
+ - PowerShell -NoLogo -Command if ($env:CIRRUS_PR -ne $null) { git fetch $env:CIRRUS_REPO_CLONE_URL $env:CIRRUS_BASE_BRANCH; git merge FETCH_HEAD; }
msvc_qt_built_cache:
folder: "%QTBASEDIR%"
reupload_on_changes: false
@@ -130,6 +125,7 @@ task:
folder: 'C:\Users\ContainerAdministrator\AppData\Local\vcpkg\archives'
install_python_script:
- choco install --yes --no-progress python3 --version=3.9.6
+ - pip install zmq
- python -VV
install_vcpkg_script:
- cd ..
@@ -149,12 +145,19 @@ task:
- src\bench_bitcoin.exe > NUL
- python test\util\test_runner.py
- python test\util\rpcauth-test.py
+ functional_tests_script:
+ # Increase the dynamic port range to the maximum allowed value to mitigate "OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted".
+ # See: https://docs.microsoft.com/en-us/biztalk/technical-guides/settings-that-can-be-modified-to-improve-network-performance
+ - netsh int ipv4 set dynamicport tcp start=1025 num=64511
+ - netsh int ipv6 set dynamicport tcp start=1025 num=64511
+ # Exclude feature_dbcrash for now due to timeout
+ - python test\functional\test_runner.py --nocleanup --ci --quiet --combinedlogslen=4000 --jobs=4 --timeout-factor=8 --failfast --extended --exclude feature_dbcrash
task:
- name: 'ARM [unit tests, no functional tests] [buster]'
+ name: 'ARM [unit tests, no functional tests] [bullseye]'
<< : *GLOBAL_TASK_TEMPLATE
arm_container:
- image: debian:buster
+ image: debian:bullseye
cpu: 2
memory: 8G
env:
@@ -235,7 +238,7 @@ task:
FILE_ENV: "./ci/test/00_setup_env_native_fuzz.sh"
task:
- name: '[multiprocess, DEBUG] [focal]'
+ name: '[multiprocess, i686, DEBUG] [focal]'
<< : *GLOBAL_TASK_TEMPLATE
container:
image: ubuntu:focal
@@ -244,7 +247,7 @@ task:
env:
<< : *CIRRUS_EPHEMERAL_WORKER_TEMPLATE_ENV
MAKEJOBS: "-j8"
- FILE_ENV: "./ci/test/00_setup_env_native_multiprocess.sh"
+ FILE_ENV: "./ci/test/00_setup_env_i686_multiprocess.sh"
task:
name: '[no wallet] [bionic]'
@@ -256,7 +259,7 @@ task:
FILE_ENV: "./ci/test/00_setup_env_native_nowallet.sh"
task:
- name: 'macOS 10.14 [gui, no tests] [focal]'
+ name: 'macOS 10.15 [gui, no tests] [focal]'
<< : *DEPENDS_SDK_CACHE_TEMPLATE
<< : *GLOBAL_TASK_TEMPLATE
container:
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e0d3671b07..acf5cc08d1 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -60,8 +60,8 @@ Most communication about Bitcoin Core development happens on IRC, in the
`#bitcoin-core-dev` channel on Libera Chat. The easiest way to participate on IRC is
with the web client, [web.libera.chat](https://web.libera.chat/#bitcoin-core-dev). Chat
history logs can be found
-on [http://www.erisian.com.au/bitcoin-core-dev/](http://www.erisian.com.au/bitcoin-core-dev/)
-and [http://gnusha.org/bitcoin-core-dev/](http://gnusha.org/bitcoin-core-dev/).
+on [https://www.erisian.com.au/bitcoin-core-dev/](https://www.erisian.com.au/bitcoin-core-dev/)
+and [https://gnusha.org/bitcoin-core-dev/](https://gnusha.org/bitcoin-core-dev/).
Discussion about codebase improvements happens in GitHub issues and pull
requests.
diff --git a/INSTALL.md b/INSTALL.md
index 520a47d960..4cead03036 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -1,5 +1 @@
-Building Bitcoin
-================
-
-See doc/build-*.md for instructions on building the various
-elements of the Bitcoin Core reference implementation of Bitcoin.
+See [doc/build-\*.md](/doc) \ No newline at end of file
diff --git a/build-aux/m4/bitcoin_find_bdb48.m4 b/build-aux/m4/bitcoin_find_bdb48.m4
index 5fc5b493d3..3d6c8210ed 100644
--- a/build-aux/m4/bitcoin_find_bdb48.m4
+++ b/build-aux/m4/bitcoin_find_bdb48.m4
@@ -48,15 +48,22 @@ AC_DEFUN([BITCOIN_FIND_BDB48],[
if test "x$bdbpath" = "xX"; then
use_bdb=no
AC_MSG_RESULT([no])
- AC_MSG_ERROR([libdb_cxx headers missing, ]AC_PACKAGE_NAME[ requires this library for BDB wallet support (--without-bdb to disable BDB wallet support)])
+ AC_MSG_WARN([libdb_cxx headers missing])
+ AC_MSG_WARN(AC_PACKAGE_NAME[ requires this library for BDB (legacy) wallet support])
+ AC_MSG_WARN([Passing --without-bdb will suppress this warning])
elif test "x$bdb48path" = "xX"; then
BITCOIN_SUBDIR_TO_INCLUDE(BDB_CPPFLAGS,[${bdbpath}],db_cxx)
AC_ARG_WITH([incompatible-bdb],[AS_HELP_STRING([--with-incompatible-bdb], [allow using a bdb version other than 4.8])],[
- AC_MSG_WARN([Found Berkeley DB other than 4.8; BDB wallets opened by this build will not be portable!])
+ AC_MSG_WARN([Found Berkeley DB other than 4.8])
+ AC_MSG_WARN([BDB (legacy) wallets opened by this build will not be portable!])
+ use_bdb=yes
],[
- AC_MSG_ERROR([Found Berkeley DB other than 4.8, required for portable BDB wallets (--with-incompatible-bdb to ignore or --without-bdb to disable BDB wallet support)])
+ AC_MSG_WARN([Found Berkeley DB other than 4.8])
+ AC_MSG_WARN([BDB (legacy) wallets opened by this build would not be portable!])
+ AC_MSG_WARN([If this is intended, pass --with-incompatible-bdb])
+ AC_MSG_WARN([Passing --without-bdb will suppress this warning])
+ use_bdb=no
])
- use_bdb=yes
else
BITCOIN_SUBDIR_TO_INCLUDE(BDB_CPPFLAGS,[${bdb48path}],db_cxx)
bdbpath="${bdb48path}"
@@ -78,7 +85,9 @@ AC_DEFUN([BITCOIN_FIND_BDB48],[
])
done
if test "x$BDB_LIBS" = "x"; then
- AC_MSG_ERROR([libdb_cxx missing, ]AC_PACKAGE_NAME[ requires this library for BDB wallet support (--without-bdb to disable BDB wallet support)])
+ AC_MSG_WARN([libdb_cxx headers missing])
+ AC_MSG_WARN(AC_PACKAGE_NAME[ requires this library for BDB (legacy) wallet support])
+ AC_MSG_WARN([Passing --without-bdb will suppress this warning])
fi
fi
if test "x$use_bdb" != "xno"; then
diff --git a/build_msvc/README.md b/build_msvc/README.md
index c3705f6b03..36fb942c8e 100644
--- a/build_msvc/README.md
+++ b/build_msvc/README.md
@@ -3,67 +3,65 @@ Building Bitcoin Core with Visual Studio
Introduction
---------------------
-Solution and project files to build the Bitcoin Core applications `msbuild` or Visual Studio can be found in the `build_msvc` directory. The build has been tested with Visual Studio 2019 (building with earlier versions of Visual Studio should not be expected to work).
+Solution and project files to build Bitcoin Core with `msbuild` or Visual Studio can be found in the `build_msvc` directory. The build has been tested with Visual Studio 2019 (building with earlier versions of Visual Studio should not be expected to work).
-Building with Visual Studio is an alternative to the Linux based [cross-compiler build](https://github.com/bitcoin/bitcoin/blob/master/doc/build-windows.md).
+To build Bitcoin Core from the command-line, it is sufficient to only install the Visual Studio Build Tools component.
-Quick Start
----------------------
-The minimal steps required to build Bitcoin Core with the msbuild toolchain are below. More detailed instructions are contained in the following sections.
+Building with Visual Studio is an alternative to the Linux based [cross-compiler build](../doc/build-windows.md).
-```
-cd build_msvc
-py -3 msvc-autogen.py
-msbuild /m bitcoin.sln /p:Platform=x64 /p:Configuration=Release /t:build
-```
-Dependencies
+Prerequisites
---------------------
-A number of [open source libraries](https://github.com/bitcoin/bitcoin/blob/master/doc/dependencies.md) are required in order to be able to build Bitcoin Core.
+To build [dependencies](../doc/dependencies.md) (except for [Qt](#qt)),
+the default approach is to use the [vcpkg](https://docs.microsoft.com/en-us/cpp/vcpkg) package manager from Microsoft:
-Options for installing the dependencies in a Visual Studio compatible manner are:
+1. [Install](https://vcpkg.io/en/getting-started.html) vcpkg.
-- Use Microsoft's [vcpkg](https://docs.microsoft.com/en-us/cpp/vcpkg) to download the source packages and build locally. This is the recommended approach.
-- Download the source code, build each dependency, add the required include paths, link libraries and binary tools to the Visual Studio project files.
-- Use [nuget](https://www.nuget.org/) packages with the understanding that any binary files have been compiled by an untrusted third party.
+2. By default, vcpkg makes both `release` and `debug` builds for each package.
+To save build time and disk space, one could skip `debug` builds (example uses PowerShell):
+```powershell
-The [external dependencies](https://github.com/bitcoin/bitcoin/blob/master/doc/dependencies.md) required for building are listed in the `build_msvc/vcpkg.json` file. To ensure `msbuild` project files automatically install the `vcpkg` dependencies use:
-
-```
-vcpkg integrate install
+Add-Content -Path "vcpkg\triplets\x64-windows-static.cmake" -Value "set(VCPKG_BUILD_TYPE release)"
```
Qt
---------------------
-In order to build Bitcoin Core a static build of Qt is required. The runtime library version (e.g. v142) and platform type (x86 or x64) must also match.
+To build Bitcoin Core with the GUI, a static build of Qt is required.
+
+1. Download a single ZIP archive of Qt source code from https://download.qt.io/official_releases/qt/ (e.g., [`qt-everywhere-src-5.12.11.zip`](https://download.qt.io/official_releases/qt/5.12/5.12.11/single/qt-everywhere-src-5.12.11.zip)), and expand it into a dedicated folder. The following instructions assume that this folder is `C:\dev\qt-source`.
+
+2. Open "x64 Native Tools Command Prompt for VS 2019", and input the following commands:
+```cmd
+cd C:\dev\qt-source
+mkdir build
+cd build
+..\configure -release -silent -opensource -confirm-license -opengl desktop -no-shared -static -static-runtime -mp -qt-zlib -qt-pcre -qt-libpng -no-libjpeg -nomake examples -nomake tests -nomake tools -no-dbus -no-libudev -no-icu -no-gtk -no-opengles3 -no-angle -no-sql-sqlite -no-sql-odbc -no-sqlite -no-libudev -no-vulkan -skip qt3d -skip qtactiveqt -skip qtandroidextras -skip qtcanvas3d -skip qtcharts -skip qtconnectivity -skip qtdatavis3d -skip qtdeclarative -skip qtdoc -skip qtgamepad -skip qtgraphicaleffects -skip qtimageformats -skip qtlocation -skip qtmacextras -skip qtmultimedia -skip qtnetworkauth -skip qtpurchasing -skip qtquickcontrols -skip qtquickcontrols2 -skip qtscript -skip qtscxml -skip qtsensors -skip qtserialbus -skip qtserialport -skip qtspeech -skip qtvirtualkeyboard -skip qtwayland -skip qtwebchannel -skip qtwebengine -skip qtwebsockets -skip qtwebview -skip qtx11extras -skip qtxmlpatterns -no-openssl -no-feature-sql -no-feature-sqlmodel -prefix C:\Qt_static
+nmake
+nmake install
+```
-Some prebuilt x64 versions of Qt can be downloaded from [here](https://github.com/sipsorcery/qt_win_binary/releases). Please be aware these downloads are NOT officially sanctioned by Bitcoin Core and are provided for developer convenience only. They should NOT be used for builds that will be used in a production environment or with real funds.
+One could speed up building with [`jom`](https://wiki.qt.io/Jom), a replacement for `nmake` which makes use of all CPU cores.
-To determine which Qt prebuilt version to download open the `.cirrus.yml` file and note the `QT_DOWNLOAD_URL`. When extracting the zip file the destination path must be set to `C:\`. This is due to the way that Qt includes, libraries and tools use internal paths.
+To build Bitcoin Core without Qt, unload or disable the `bitcoin-qt`, `libbitcoin_qt` and `test_bitcoin-qt` projects.
-To build Bitcoin Core without Qt unload or disable the `bitcoin-qt`, `libbitcoin_qt` and `test_bitcoin-qt` projects.
Building
---------------------
-The instructions below use `vcpkg` to install the dependencies.
-
-- Install [`vcpkg`](https://github.com/Microsoft/vcpkg).
-
-- Use Python to generate `*.vcxproj` from Makefile
+1. Use Python to generate `*.vcxproj` from Makefile:
```
PS >py -3 msvc-autogen.py
```
-- An optional step is to adjust the settings in the `build_msvc` directory and the `common.init.vcxproj` file. This project file contains settings that are common to all projects such as the runtime library version and target Windows SDK version. The Qt directories can also be set.
+2. An optional step is to adjust the settings in the `build_msvc` directory and the `common.init.vcxproj` file. This project file contains settings that are common to all projects such as the runtime library version and target Windows SDK version. The Qt directories can also be set. To specify a non-default path to a static Qt package directory, use the `QTBASEDIR` environment variable.
-- To build from the command line with the Visual Studio 2019 toolchain use:
+3. To build from the command-line with the Visual Studio 2019 toolchain use:
-```
-msbuild /m bitcoin.sln /p:Platform=x64 /p:Configuration=Release /t:build
+```cmd
+msbuild -property:Configuration=Release -maxCpuCount -verbosity:minimal bitcoin.sln
```
-- Alternatively, open the `build_msvc/bitcoin.sln` file in Visual Studio 2019.
+Alternatively, open the `build_msvc/bitcoin.sln` file in Visual Studio 2019.
Security
---------------------
diff --git a/build_msvc/bitcoin-qt/bitcoin-qt.vcxproj b/build_msvc/bitcoin-qt/bitcoin-qt.vcxproj
index a697c1dfb6..724dae1969 100644
--- a/build_msvc/bitcoin-qt/bitcoin-qt.vcxproj
+++ b/build_msvc/bitcoin-qt/bitcoin-qt.vcxproj
@@ -9,6 +9,7 @@
</PropertyGroup>
<ItemGroup>
<ClCompile Include="..\..\src\qt\main.cpp" />
+ <ClCompile Include="..\..\src\init\bitcoind.cpp" />
<ResourceCompile Include="..\..\src\qt\res\bitcoin-qt-res.rc" />
</ItemGroup>
<ItemGroup>
diff --git a/build_msvc/bitcoin-util/bitcoin-util.vcxproj b/build_msvc/bitcoin-util/bitcoin-util.vcxproj
index 3a6aa4a837..8a0964824b 100644
--- a/build_msvc/bitcoin-util/bitcoin-util.vcxproj
+++ b/build_msvc/bitcoin-util/bitcoin-util.vcxproj
@@ -2,7 +2,7 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\common.init.vcxproj" />
<PropertyGroup Label="Globals">
- <ProjectGuid>{D3022AF6-AD33-4CE3-B358-87CB6A1B29CF}</ProjectGuid>
+ <ProjectGuid>{57A04EC9-542A-4E40-83D0-AC3BE1F36805}</ProjectGuid>
</PropertyGroup>
<PropertyGroup Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
diff --git a/build_msvc/bitcoin.sln b/build_msvc/bitcoin.sln
index 7d8591c10b..1b1f27a8a9 100644
--- a/build_msvc/bitcoin.sln
+++ b/build_msvc/bitcoin.sln
@@ -32,7 +32,7 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bench_bitcoin", "bench_bitc
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bitcoin-tx", "bitcoin-tx\bitcoin-tx.vcxproj", "{D3022AF6-AD33-4CE3-B358-87CB6A1B29CF}"
EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bitcoin-util", "bitcoin-util\bitcoin-util.vcxproj", "{D3022AF6-AD33-4CE3-B358-87CB6A1B29CF}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bitcoin-util", "bitcoin-util\bitcoin-util.vcxproj", "{57A04EC9-542A-4E40-83D0-AC3BE1F36805}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bitcoin-wallet", "bitcoin-wallet\bitcoin-wallet.vcxproj", "{84DE8790-EDE3-4483-81AC-C32F15E861F4}"
EndProject
@@ -53,195 +53,105 @@ EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
- Debug|x86 = Debug|x86
Release|x64 = Release|x64
- Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2B384FA8-9EE1-4544-93CB-0D733C25E8CE}.Debug|x64.ActiveCfg = Debug|x64
{2B384FA8-9EE1-4544-93CB-0D733C25E8CE}.Debug|x64.Build.0 = Debug|x64
- {2B384FA8-9EE1-4544-93CB-0D733C25E8CE}.Debug|x86.ActiveCfg = Debug|Win32
- {2B384FA8-9EE1-4544-93CB-0D733C25E8CE}.Debug|x86.Build.0 = Debug|Win32
{2B384FA8-9EE1-4544-93CB-0D733C25E8CE}.Release|x64.ActiveCfg = Release|x64
{2B384FA8-9EE1-4544-93CB-0D733C25E8CE}.Release|x64.Build.0 = Release|x64
- {2B384FA8-9EE1-4544-93CB-0D733C25E8CE}.Release|x86.ActiveCfg = Release|Win32
- {2B384FA8-9EE1-4544-93CB-0D733C25E8CE}.Release|x86.Build.0 = Release|Win32
{E78473E9-B850-456C-9120-276301E04C06}.Debug|x64.ActiveCfg = Debug|x64
{E78473E9-B850-456C-9120-276301E04C06}.Debug|x64.Build.0 = Debug|x64
- {E78473E9-B850-456C-9120-276301E04C06}.Debug|x86.ActiveCfg = Debug|Win32
- {E78473E9-B850-456C-9120-276301E04C06}.Debug|x86.Build.0 = Debug|Win32
{E78473E9-B850-456C-9120-276301E04C06}.Release|x64.ActiveCfg = Release|x64
{E78473E9-B850-456C-9120-276301E04C06}.Release|x64.Build.0 = Release|x64
- {E78473E9-B850-456C-9120-276301E04C06}.Release|x86.ActiveCfg = Release|Win32
- {E78473E9-B850-456C-9120-276301E04C06}.Release|x86.Build.0 = Release|Win32
{D4513DDF-6013-44DC-ADCC-12EAF6D1F038}.Debug|x64.ActiveCfg = Debug|x64
{D4513DDF-6013-44DC-ADCC-12EAF6D1F038}.Debug|x64.Build.0 = Debug|x64
- {D4513DDF-6013-44DC-ADCC-12EAF6D1F038}.Debug|x86.ActiveCfg = Debug|Win32
- {D4513DDF-6013-44DC-ADCC-12EAF6D1F038}.Debug|x86.Build.0 = Debug|Win32
{D4513DDF-6013-44DC-ADCC-12EAF6D1F038}.Release|x64.ActiveCfg = Release|x64
{D4513DDF-6013-44DC-ADCC-12EAF6D1F038}.Release|x64.Build.0 = Release|x64
- {D4513DDF-6013-44DC-ADCC-12EAF6D1F038}.Release|x86.ActiveCfg = Release|Win32
- {D4513DDF-6013-44DC-ADCC-12EAF6D1F038}.Release|x86.Build.0 = Release|Win32
{B53A5535-EE9D-4C6F-9A26-F79EE3BC3754}.Debug|x64.ActiveCfg = Debug|x64
{B53A5535-EE9D-4C6F-9A26-F79EE3BC3754}.Debug|x64.Build.0 = Debug|x64
- {B53A5535-EE9D-4C6F-9A26-F79EE3BC3754}.Debug|x86.ActiveCfg = Debug|Win32
- {B53A5535-EE9D-4C6F-9A26-F79EE3BC3754}.Debug|x86.Build.0 = Debug|Win32
{B53A5535-EE9D-4C6F-9A26-F79EE3BC3754}.Release|x64.ActiveCfg = Release|x64
{B53A5535-EE9D-4C6F-9A26-F79EE3BC3754}.Release|x64.Build.0 = Release|x64
- {B53A5535-EE9D-4C6F-9A26-F79EE3BC3754}.Release|x86.ActiveCfg = Release|Win32
- {B53A5535-EE9D-4C6F-9A26-F79EE3BC3754}.Release|x86.Build.0 = Release|Win32
{7C87E378-DF58-482E-AA2F-1BC129BC19CE}.Debug|x64.ActiveCfg = Debug|x64
{7C87E378-DF58-482E-AA2F-1BC129BC19CE}.Debug|x64.Build.0 = Debug|x64
- {7C87E378-DF58-482E-AA2F-1BC129BC19CE}.Debug|x86.ActiveCfg = Debug|Win32
- {7C87E378-DF58-482E-AA2F-1BC129BC19CE}.Debug|x86.Build.0 = Debug|Win32
{7C87E378-DF58-482E-AA2F-1BC129BC19CE}.Release|x64.ActiveCfg = Release|x64
{7C87E378-DF58-482E-AA2F-1BC129BC19CE}.Release|x64.Build.0 = Release|x64
- {7C87E378-DF58-482E-AA2F-1BC129BC19CE}.Release|x86.ActiveCfg = Release|Win32
- {7C87E378-DF58-482E-AA2F-1BC129BC19CE}.Release|x86.Build.0 = Release|Win32
{6190199C-6CF4-4DAD-BFBD-93FA72A760C1}.Debug|x64.ActiveCfg = Debug|x64
{6190199C-6CF4-4DAD-BFBD-93FA72A760C1}.Debug|x64.Build.0 = Debug|x64
- {6190199C-6CF4-4DAD-BFBD-93FA72A760C1}.Debug|x86.ActiveCfg = Debug|Win32
- {6190199C-6CF4-4DAD-BFBD-93FA72A760C1}.Debug|x86.Build.0 = Debug|Win32
{6190199C-6CF4-4DAD-BFBD-93FA72A760C1}.Release|x64.ActiveCfg = Release|x64
{6190199C-6CF4-4DAD-BFBD-93FA72A760C1}.Release|x64.Build.0 = Release|x64
- {6190199C-6CF4-4DAD-BFBD-93FA72A760C1}.Release|x86.ActiveCfg = Release|Win32
- {6190199C-6CF4-4DAD-BFBD-93FA72A760C1}.Release|x86.Build.0 = Release|Win32
{460FEE33-1FE1-483F-B3BF-931FF8E969A5}.Debug|x64.ActiveCfg = Debug|x64
{460FEE33-1FE1-483F-B3BF-931FF8E969A5}.Debug|x64.Build.0 = Debug|x64
- {460FEE33-1FE1-483F-B3BF-931FF8E969A5}.Debug|x86.ActiveCfg = Debug|Win32
- {460FEE33-1FE1-483F-B3BF-931FF8E969A5}.Debug|x86.Build.0 = Debug|Win32
{460FEE33-1FE1-483F-B3BF-931FF8E969A5}.Release|x64.ActiveCfg = Release|x64
{460FEE33-1FE1-483F-B3BF-931FF8E969A5}.Release|x64.Build.0 = Release|x64
- {460FEE33-1FE1-483F-B3BF-931FF8E969A5}.Release|x86.ActiveCfg = Release|Win32
- {460FEE33-1FE1-483F-B3BF-931FF8E969A5}.Release|x86.Build.0 = Release|Win32
{5724BA7D-A09A-4BA8-800B-C4C1561B3D69}.Debug|x64.ActiveCfg = Debug|x64
{5724BA7D-A09A-4BA8-800B-C4C1561B3D69}.Debug|x64.Build.0 = Debug|x64
- {5724BA7D-A09A-4BA8-800B-C4C1561B3D69}.Debug|x86.ActiveCfg = Debug|Win32
- {5724BA7D-A09A-4BA8-800B-C4C1561B3D69}.Debug|x86.Build.0 = Debug|Win32
{5724BA7D-A09A-4BA8-800B-C4C1561B3D69}.Release|x64.ActiveCfg = Release|x64
{5724BA7D-A09A-4BA8-800B-C4C1561B3D69}.Release|x64.Build.0 = Release|x64
- {5724BA7D-A09A-4BA8-800B-C4C1561B3D69}.Release|x86.ActiveCfg = Release|Win32
- {5724BA7D-A09A-4BA8-800B-C4C1561B3D69}.Release|x86.Build.0 = Release|Win32
{93B86837-B543-48A5-A89B-7C87ABB77DF2}.Debug|x64.ActiveCfg = Debug|x64
{93B86837-B543-48A5-A89B-7C87ABB77DF2}.Debug|x64.Build.0 = Debug|x64
- {93B86837-B543-48A5-A89B-7C87ABB77DF2}.Debug|x86.ActiveCfg = Debug|Win32
- {93B86837-B543-48A5-A89B-7C87ABB77DF2}.Debug|x86.Build.0 = Debug|Win32
{93B86837-B543-48A5-A89B-7C87ABB77DF2}.Release|x64.ActiveCfg = Release|x64
{93B86837-B543-48A5-A89B-7C87ABB77DF2}.Release|x64.Build.0 = Release|x64
- {93B86837-B543-48A5-A89B-7C87ABB77DF2}.Release|x86.ActiveCfg = Release|Win32
- {93B86837-B543-48A5-A89B-7C87ABB77DF2}.Release|x86.Build.0 = Release|Win32
{792D487F-F14C-49FC-A9DE-3FC150F31C3F}.Debug|x64.ActiveCfg = Debug|x64
{792D487F-F14C-49FC-A9DE-3FC150F31C3F}.Debug|x64.Build.0 = Debug|x64
- {792D487F-F14C-49FC-A9DE-3FC150F31C3F}.Debug|x86.ActiveCfg = Debug|Win32
- {792D487F-F14C-49FC-A9DE-3FC150F31C3F}.Debug|x86.Build.0 = Debug|Win32
{792D487F-F14C-49FC-A9DE-3FC150F31C3F}.Release|x64.ActiveCfg = Release|x64
{792D487F-F14C-49FC-A9DE-3FC150F31C3F}.Release|x64.Build.0 = Release|x64
- {792D487F-F14C-49FC-A9DE-3FC150F31C3F}.Release|x86.ActiveCfg = Release|Win32
- {792D487F-F14C-49FC-A9DE-3FC150F31C3F}.Release|x86.Build.0 = Release|Win32
{A56B73DB-D46D-4882-8374-1FE3FFA08F07}.Debug|x64.ActiveCfg = Debug|x64
{A56B73DB-D46D-4882-8374-1FE3FFA08F07}.Debug|x64.Build.0 = Debug|x64
- {A56B73DB-D46D-4882-8374-1FE3FFA08F07}.Debug|x86.ActiveCfg = Debug|Win32
- {A56B73DB-D46D-4882-8374-1FE3FFA08F07}.Debug|x86.Build.0 = Debug|Win32
{A56B73DB-D46D-4882-8374-1FE3FFA08F07}.Release|x64.ActiveCfg = Release|x64
{A56B73DB-D46D-4882-8374-1FE3FFA08F07}.Release|x64.Build.0 = Release|x64
- {A56B73DB-D46D-4882-8374-1FE3FFA08F07}.Release|x86.ActiveCfg = Release|Win32
- {A56B73DB-D46D-4882-8374-1FE3FFA08F07}.Release|x86.Build.0 = Release|Win32
{0667528C-D734-4009-ADF9-C0D6C4A5A5A6}.Debug|x64.ActiveCfg = Debug|x64
{0667528C-D734-4009-ADF9-C0D6C4A5A5A6}.Debug|x64.Build.0 = Debug|x64
- {0667528C-D734-4009-ADF9-C0D6C4A5A5A6}.Debug|x86.ActiveCfg = Debug|Win32
- {0667528C-D734-4009-ADF9-C0D6C4A5A5A6}.Debug|x86.Build.0 = Debug|Win32
{0667528C-D734-4009-ADF9-C0D6C4A5A5A6}.Release|x64.ActiveCfg = Release|x64
{0667528C-D734-4009-ADF9-C0D6C4A5A5A6}.Release|x64.Build.0 = Release|x64
- {0667528C-D734-4009-ADF9-C0D6C4A5A5A6}.Release|x86.ActiveCfg = Release|Win32
- {0667528C-D734-4009-ADF9-C0D6C4A5A5A6}.Release|x86.Build.0 = Release|Win32
{0B2D7431-F876-4A58-87BF-F748338CD3BF}.Debug|x64.ActiveCfg = Debug|x64
{0B2D7431-F876-4A58-87BF-F748338CD3BF}.Debug|x64.Build.0 = Debug|x64
- {0B2D7431-F876-4A58-87BF-F748338CD3BF}.Debug|x86.ActiveCfg = Debug|Win32
- {0B2D7431-F876-4A58-87BF-F748338CD3BF}.Debug|x86.Build.0 = Debug|Win32
{0B2D7431-F876-4A58-87BF-F748338CD3BF}.Release|x64.ActiveCfg = Release|x64
{0B2D7431-F876-4A58-87BF-F748338CD3BF}.Release|x64.Build.0 = Release|x64
- {0B2D7431-F876-4A58-87BF-F748338CD3BF}.Release|x86.ActiveCfg = Release|Win32
- {0B2D7431-F876-4A58-87BF-F748338CD3BF}.Release|x86.Build.0 = Release|Win32
{1125654E-E1B2-4431-8B5C-62EA9A2FEECB}.Debug|x64.ActiveCfg = Debug|x64
{1125654E-E1B2-4431-8B5C-62EA9A2FEECB}.Debug|x64.Build.0 = Debug|x64
- {1125654E-E1B2-4431-8B5C-62EA9A2FEECB}.Debug|x86.ActiveCfg = Debug|Win32
- {1125654E-E1B2-4431-8B5C-62EA9A2FEECB}.Debug|x86.Build.0 = Debug|Win32
{1125654E-E1B2-4431-8B5C-62EA9A2FEECB}.Release|x64.ActiveCfg = Release|x64
{1125654E-E1B2-4431-8B5C-62EA9A2FEECB}.Release|x64.Build.0 = Release|x64
- {1125654E-E1B2-4431-8B5C-62EA9A2FEECB}.Release|x86.ActiveCfg = Release|Win32
- {1125654E-E1B2-4431-8B5C-62EA9A2FEECB}.Release|x86.Build.0 = Release|Win32
{D3022AF6-AD33-4CE3-B358-87CB6A1B29CF}.Debug|x64.ActiveCfg = Debug|x64
{D3022AF6-AD33-4CE3-B358-87CB6A1B29CF}.Debug|x64.Build.0 = Debug|x64
- {D3022AF6-AD33-4CE3-B358-87CB6A1B29CF}.Debug|x86.ActiveCfg = Debug|Win32
- {D3022AF6-AD33-4CE3-B358-87CB6A1B29CF}.Debug|x86.Build.0 = Debug|Win32
{D3022AF6-AD33-4CE3-B358-87CB6A1B29CF}.Release|x64.ActiveCfg = Release|x64
{D3022AF6-AD33-4CE3-B358-87CB6A1B29CF}.Release|x64.Build.0 = Release|x64
- {D3022AF6-AD33-4CE3-B358-87CB6A1B29CF}.Release|x86.ActiveCfg = Release|Win32
- {D3022AF6-AD33-4CE3-B358-87CB6A1B29CF}.Release|x86.Build.0 = Release|Win32
+ {57A04EC9-542A-4E40-83D0-AC3BE1F36805}.Debug|x64.ActiveCfg = Debug|x64
+ {57A04EC9-542A-4E40-83D0-AC3BE1F36805}.Debug|x64.Build.0 = Debug|x64
+ {57A04EC9-542A-4E40-83D0-AC3BE1F36805}.Release|x64.ActiveCfg = Release|x64
+ {57A04EC9-542A-4E40-83D0-AC3BE1F36805}.Release|x64.Build.0 = Release|x64
{84DE8790-EDE3-4483-81AC-C32F15E861F4}.Debug|x64.ActiveCfg = Debug|x64
{84DE8790-EDE3-4483-81AC-C32F15E861F4}.Debug|x64.Build.0 = Debug|x64
- {84DE8790-EDE3-4483-81AC-C32F15E861F4}.Debug|x86.ActiveCfg = Debug|Win32
- {84DE8790-EDE3-4483-81AC-C32F15E861F4}.Debug|x86.Build.0 = Debug|Win32
{84DE8790-EDE3-4483-81AC-C32F15E861F4}.Release|x64.ActiveCfg = Release|x64
{84DE8790-EDE3-4483-81AC-C32F15E861F4}.Release|x64.Build.0 = Release|x64
- {84DE8790-EDE3-4483-81AC-C32F15E861F4}.Release|x86.ActiveCfg = Release|Win32
- {84DE8790-EDE3-4483-81AC-C32F15E861F4}.Release|x86.Build.0 = Release|Win32
{F91AC55E-6F5E-4C58-9AC5-B40DB7DEEF93}.Debug|x64.ActiveCfg = Debug|x64
{F91AC55E-6F5E-4C58-9AC5-B40DB7DEEF93}.Debug|x64.Build.0 = Debug|x64
- {F91AC55E-6F5E-4C58-9AC5-B40DB7DEEF93}.Debug|x86.ActiveCfg = Debug|Win32
- {F91AC55E-6F5E-4C58-9AC5-B40DB7DEEF93}.Debug|x86.Build.0 = Debug|Win32
{F91AC55E-6F5E-4C58-9AC5-B40DB7DEEF93}.Release|x64.ActiveCfg = Release|x64
{F91AC55E-6F5E-4C58-9AC5-B40DB7DEEF93}.Release|x64.Build.0 = Release|x64
- {F91AC55E-6F5E-4C58-9AC5-B40DB7DEEF93}.Release|x86.ActiveCfg = Release|Win32
- {F91AC55E-6F5E-4C58-9AC5-B40DB7DEEF93}.Release|x86.Build.0 = Release|Win32
{BB493552-3B8C-4A8C-BF69-A6E7A51D2EA6}.Debug|x64.ActiveCfg = Debug|x64
{BB493552-3B8C-4A8C-BF69-A6E7A51D2EA6}.Debug|x64.Build.0 = Debug|x64
- {BB493552-3B8C-4A8C-BF69-A6E7A51D2EA6}.Debug|x86.ActiveCfg = Debug|Win32
- {BB493552-3B8C-4A8C-BF69-A6E7A51D2EA6}.Debug|x86.Build.0 = Debug|Win32
{BB493552-3B8C-4A8C-BF69-A6E7A51D2EA6}.Release|x64.ActiveCfg = Release|x64
{BB493552-3B8C-4A8C-BF69-A6E7A51D2EA6}.Release|x64.Build.0 = Release|x64
- {BB493552-3B8C-4A8C-BF69-A6E7A51D2EA6}.Release|x86.ActiveCfg = Release|Win32
- {BB493552-3B8C-4A8C-BF69-A6E7A51D2EA6}.Release|x86.Build.0 = Release|Win32
{18430FEF-6B61-4C53-B396-718E02850F1B}.Debug|x64.ActiveCfg = Debug|x64
{18430FEF-6B61-4C53-B396-718E02850F1B}.Debug|x64.Build.0 = Debug|x64
- {18430FEF-6B61-4C53-B396-718E02850F1B}.Debug|x86.ActiveCfg = Debug|Win32
- {18430FEF-6B61-4C53-B396-718E02850F1B}.Debug|x86.Build.0 = Debug|Win32
{18430FEF-6B61-4C53-B396-718E02850F1B}.Release|x64.ActiveCfg = Release|x64
{18430FEF-6B61-4C53-B396-718E02850F1B}.Release|x64.Build.0 = Release|x64
- {18430FEF-6B61-4C53-B396-718E02850F1B}.Release|x86.ActiveCfg = Release|Win32
- {18430FEF-6B61-4C53-B396-718E02850F1B}.Release|x86.Build.0 = Release|Win32
{2B4ABFF8-D1FD-4845-88C9-1F3C0A6512BF}.Debug|x64.ActiveCfg = Debug|x64
{2B4ABFF8-D1FD-4845-88C9-1F3C0A6512BF}.Debug|x64.Build.0 = Debug|x64
- {2B4ABFF8-D1FD-4845-88C9-1F3C0A6512BF}.Debug|x86.ActiveCfg = Debug|Win32
- {2B4ABFF8-D1FD-4845-88C9-1F3C0A6512BF}.Debug|x86.Build.0 = Debug|Win32
{2B4ABFF8-D1FD-4845-88C9-1F3C0A6512BF}.Release|x64.ActiveCfg = Release|x64
{2B4ABFF8-D1FD-4845-88C9-1F3C0A6512BF}.Release|x64.Build.0 = Release|x64
- {2B4ABFF8-D1FD-4845-88C9-1F3C0A6512BF}.Release|x86.ActiveCfg = Release|Win32
- {2B4ABFF8-D1FD-4845-88C9-1F3C0A6512BF}.Release|x86.Build.0 = Release|Win32
{7E99172D-7FF2-4CB6-B736-AC9B76ED412A}.Debug|x64.ActiveCfg = Debug|x64
{7E99172D-7FF2-4CB6-B736-AC9B76ED412A}.Debug|x64.Build.0 = Debug|x64
- {7E99172D-7FF2-4CB6-B736-AC9B76ED412A}.Debug|x86.ActiveCfg = Debug|Win32
- {7E99172D-7FF2-4CB6-B736-AC9B76ED412A}.Debug|x86.Build.0 = Debug|Win32
{7E99172D-7FF2-4CB6-B736-AC9B76ED412A}.Release|x64.ActiveCfg = Release|x64
{7E99172D-7FF2-4CB6-B736-AC9B76ED412A}.Release|x64.Build.0 = Release|x64
- {7E99172D-7FF2-4CB6-B736-AC9B76ED412A}.Release|x86.ActiveCfg = Release|Win32
- {7E99172D-7FF2-4CB6-B736-AC9B76ED412A}.Release|x86.Build.0 = Release|Win32
{868474FD-35F6-4400-8EED-30A33E7521D4}.Debug|x64.ActiveCfg = Debug|x64
{868474FD-35F6-4400-8EED-30A33E7521D4}.Debug|x64.Build.0 = Debug|x64
- {868474FD-35F6-4400-8EED-30A33E7521D4}.Debug|x86.ActiveCfg = Debug|Win32
- {868474FD-35F6-4400-8EED-30A33E7521D4}.Debug|x86.Build.0 = Debug|Win32
{868474FD-35F6-4400-8EED-30A33E7521D4}.Release|x64.ActiveCfg = Release|x64
{868474FD-35F6-4400-8EED-30A33E7521D4}.Release|x64.Build.0 = Release|x64
- {868474FD-35F6-4400-8EED-30A33E7521D4}.Release|x86.ActiveCfg = Release|Win32
- {868474FD-35F6-4400-8EED-30A33E7521D4}.Release|x86.Build.0 = Release|Win32
{51201D5E-D939-4854-AE9D-008F03FF518E}.Debug|x64.ActiveCfg = Debug|x64
{51201D5E-D939-4854-AE9D-008F03FF518E}.Debug|x64.Build.0 = Debug|x64
- {51201D5E-D939-4854-AE9D-008F03FF518E}.Debug|x86.ActiveCfg = Debug|Win32
- {51201D5E-D939-4854-AE9D-008F03FF518E}.Debug|x86.Build.0 = Debug|Win32
{51201D5E-D939-4854-AE9D-008F03FF518E}.Release|x64.ActiveCfg = Release|x64
{51201D5E-D939-4854-AE9D-008F03FF518E}.Release|x64.Build.0 = Release|x64
- {51201D5E-D939-4854-AE9D-008F03FF518E}.Release|x86.ActiveCfg = Release|Win32
- {51201D5E-D939-4854-AE9D-008F03FF518E}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/build_msvc/bitcoind/bitcoind.vcxproj b/build_msvc/bitcoind/bitcoind.vcxproj
index c2c32af838..d56c359fe0 100644
--- a/build_msvc/bitcoind/bitcoind.vcxproj
+++ b/build_msvc/bitcoind/bitcoind.vcxproj
@@ -58,6 +58,8 @@
<ReplaceInFile FilePath="$(ConfigIniOut)"
Replace="@PACKAGE_NAME@" By="Bitcoin Core"></ReplaceInFile>
<ReplaceInFile FilePath="$(ConfigIniOut)"
+ Replace="@PACKAGE_BUGREPORT@" By="https://github.com/bitcoin/bitcoin/issues"></ReplaceInFile>
+ <ReplaceInFile FilePath="$(ConfigIniOut)"
Replace="@abs_top_srcdir@" By="..\.." ToFullPath="true"></ReplaceInFile>
<ReplaceInFile FilePath="$(ConfigIniOut)"
Replace="@abs_top_builddir@" By="..\.." ToFullPath="true"></ReplaceInFile>
@@ -72,11 +74,15 @@
<ReplaceInFile FilePath="$(ConfigIniOut)"
Replace="@BUILD_BITCOIN_CLI_TRUE@" By=""></ReplaceInFile>
<ReplaceInFile FilePath="$(ConfigIniOut)"
+ Replace="@BUILD_BITCOIN_WALLET_TRUE@" By=""></ReplaceInFile>
+ <ReplaceInFile FilePath="$(ConfigIniOut)"
Replace="@BUILD_BITCOIND_TRUE@" By=""></ReplaceInFile>
<ReplaceInFile FilePath="$(ConfigIniOut)"
Replace="@ENABLE_FUZZ_TRUE@" By=""></ReplaceInFile>
<ReplaceInFile FilePath="$(ConfigIniOut)"
Replace="@ENABLE_ZMQ_TRUE@" By=""></ReplaceInFile>
+ <ReplaceInFile FilePath="$(ConfigIniOut)"
+ Replace="@ENABLE_EXTERNAL_SIGNER_TRUE@" By=""></ReplaceInFile>
</Target>
<Import Project="..\common.vcxproj" />
</Project>
diff --git a/build_msvc/common.init.vcxproj b/build_msvc/common.init.vcxproj
index 6ea018d846..fb4d70cc78 100644
--- a/build_msvc/common.init.vcxproj
+++ b/build_msvc/common.init.vcxproj
@@ -14,7 +14,6 @@
<VcpkgUseStatic>true</VcpkgUseStatic>
<VcpkgAutoLink>true</VcpkgAutoLink>
<VcpkgConfiguration>$(Configuration)</VcpkgConfiguration>
- <VcpkgTriplet Condition="'$(Platform)'=='Win32'">x86-windows-static</VcpkgTriplet>
<VcpkgTriplet Condition="'$(Platform)'=='x64'">x64-windows-static</VcpkgTriplet>
</PropertyGroup>
@@ -35,14 +34,6 @@
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
- <ProjectConfiguration Include="Release|Win32">
- <Configuration>Release</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Debug|Win32">
- <Configuration>Debug</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
</ItemGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
diff --git a/build_msvc/common.qt.init.vcxproj b/build_msvc/common.qt.init.vcxproj
index df2fd2fb49..cc8063e545 100644
--- a/build_msvc/common.qt.init.vcxproj
+++ b/build_msvc/common.qt.init.vcxproj
@@ -2,7 +2,7 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="QtGlobals">
- <QtBaseDir>C:\Qt5.12.11_x64_static_vs2019_160900</QtBaseDir>
+ <QtBaseDir Condition="'$(QTBASEDIR)' == ''">C:\Qt_static</QtBaseDir>
<QtPluginsLibraryDir>$(QtBaseDir)\plugins</QtPluginsLibraryDir>
<QtLibraryDir>$(QtBaseDir)\lib</QtLibraryDir>
<QtIncludeDir>$(QtBaseDir)\include</QtIncludeDir>
diff --git a/build_msvc/libbitcoin_qt/libbitcoin_qt.vcxproj b/build_msvc/libbitcoin_qt/libbitcoin_qt.vcxproj
index 6c45d4dbd8..a64ae881f2 100644
--- a/build_msvc/libbitcoin_qt/libbitcoin_qt.vcxproj
+++ b/build_msvc/libbitcoin_qt/libbitcoin_qt.vcxproj
@@ -140,20 +140,6 @@
</ClCompile>
</ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <ClCompile>
- <PreprocessorDefinitions>_X86_;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>$(QtIncludes);$(GeneratedFilesOutDir)\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- </ClCompile>
- </ItemDefinitionGroup>
-
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <ClCompile>
- <PreprocessorDefinitions>_X86_;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>$(QtIncludes);$(GeneratedFilesOutDir)\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- </ClCompile>
- </ItemDefinitionGroup>
-
<ItemGroup>
<QT_MOC Include="..\..\src\qt\bitcoinamountfield.cpp" />
<QT_MOC Include="..\..\src\qt\intro.cpp" />
diff --git a/build_msvc/test_bitcoin-qt/test_bitcoin-qt.vcxproj b/build_msvc/test_bitcoin-qt/test_bitcoin-qt.vcxproj
index 1d2c86b7ac..08b12bdd85 100644
--- a/build_msvc/test_bitcoin-qt/test_bitcoin-qt.vcxproj
+++ b/build_msvc/test_bitcoin-qt/test_bitcoin-qt.vcxproj
@@ -8,6 +8,7 @@
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
</PropertyGroup>
<ItemGroup>
+ <ClCompile Include="..\..\src\init\bitcoind.cpp" />
<ClCompile Include="..\..\src\test\util\setup_common.cpp" />
<ClCompile Include="..\..\src\qt\test\addressbooktests.cpp" />
<ClCompile Include="..\..\src\qt\test\apptests.cpp" />
diff --git a/ci/test/00_setup_env_arm.sh b/ci/test/00_setup_env_arm.sh
index 8d2b70e549..f18052fe37 100755
--- a/ci/test/00_setup_env_arm.sh
+++ b/ci/test/00_setup_env_arm.sh
@@ -18,11 +18,11 @@ if [ -n "$QEMU_USER_CMD" ]; then
fi
export CONTAINER_NAME=ci_arm_linux
# Use debian to avoid 404 apt errors when cross compiling
-export DOCKER_NAME_TAG="debian:buster"
+export DOCKER_NAME_TAG="debian:bullseye"
export USE_BUSY_BOX=true
export RUN_UNIT_TESTS=true
export RUN_FUNCTIONAL_TESTS=false
export GOAL="install"
# -Wno-psabi is to disable ABI warnings: "note: parameter passing for argument of type ... changed in GCC 7.1"
# This could be removed once the ABI change warning does not show up by default
-export BITCOIN_CONFIG="--enable-glibc-back-compat --enable-reduce-exports CXXFLAGS=-Wno-psabi"
+export BITCOIN_CONFIG="--enable-reduce-exports CXXFLAGS=-Wno-psabi"
diff --git a/ci/test/00_setup_env_native_multiprocess.sh b/ci/test/00_setup_env_i686_multiprocess.sh
index 8869b2a083..a25c98a004 100755
--- a/ci/test/00_setup_env_native_multiprocess.sh
+++ b/ci/test/00_setup_env_i686_multiprocess.sh
@@ -6,11 +6,13 @@
export LC_ALL=C.UTF-8
-export CONTAINER_NAME=ci_native_multiprocess
+export HOST=i686-pc-linux-gnu
+export CONTAINER_NAME=ci_i686_multiprocess
export DOCKER_NAME_TAG=ubuntu:20.04
-export PACKAGES="cmake python3 python3-pip llvm clang"
+export PACKAGES="cmake python3 python3-pip llvm clang g++-multilib"
export DEP_OPTS="DEBUG=1 MULTIPROCESS=1"
export GOAL="install"
-export BITCOIN_CONFIG="--enable-debug CC=clang CXX=clang++" # Use clang to avoid OOM
+export BITCOIN_CONFIG="--enable-debug CC='clang -m32' CXX='clang++ -m32' LDFLAGS='--rtlib=compiler-rt -lgcc_s'"
export TEST_RUNNER_ENV="BITCOIND=bitcoin-node"
+export TEST_RUNNER_EXTRA="--nosandbox"
export PIP_PACKAGES="lief"
diff --git a/ci/test/00_setup_env_mac.sh b/ci/test/00_setup_env_mac.sh
index 310e964973..8bccf4fc67 100755
--- a/ci/test/00_setup_env_mac.sh
+++ b/ci/test/00_setup_env_mac.sh
@@ -8,7 +8,7 @@ export LC_ALL=C.UTF-8
export CONTAINER_NAME=ci_macos_cross
export DOCKER_NAME_TAG=ubuntu:20.04 # Check that Focal can cross-compile to macos
-export HOST=x86_64-apple-darwin18
+export HOST=x86_64-apple-darwin19
export PACKAGES="cmake imagemagick librsvg2-bin libz-dev libtiff-tools libtinfo5 python3-setuptools xorriso"
export XCODE_VERSION=12.1
export XCODE_BUILD_ID=12A7403
diff --git a/ci/test/00_setup_env_mac_host.sh b/ci/test/00_setup_env_mac_host.sh
index c0d951a041..02889ec936 100755
--- a/ci/test/00_setup_env_mac_host.sh
+++ b/ci/test/00_setup_env_mac_host.sh
@@ -6,7 +6,7 @@
export LC_ALL=C.UTF-8
-export HOST=x86_64-apple-darwin18
+export HOST=x86_64-apple-darwin19
export PIP_PACKAGES="zmq lief"
export GOAL="install"
export BITCOIN_CONFIG="--with-gui --enable-reduce-exports"
diff --git a/ci/test/00_setup_env_native_nowallet.sh b/ci/test/00_setup_env_native_nowallet.sh
index d167c9198a..e9a20fca7d 100755
--- a/ci/test/00_setup_env_native_nowallet.sh
+++ b/ci/test/00_setup_env_native_nowallet.sh
@@ -8,7 +8,7 @@ export LC_ALL=C.UTF-8
export CONTAINER_NAME=ci_native_nowallet
export DOCKER_NAME_TAG=ubuntu:18.04 # Use bionic to have one config run the tests in python3.6, see doc/dependencies.md
-export PACKAGES="python3-zmq clang-5.0 llvm-5.0" # Use clang-5 to test C++17 compatibility, see doc/dependencies.md
-export DEP_OPTS="NO_WALLET=1"
+export PACKAGES="python3-zmq clang-7 llvm-7 libc++abi-7-dev libc++-7-dev" # Use clang-7 to test C++17 compatibility, see doc/dependencies.md
+export DEP_OPTS="NO_WALLET=1 CC=clang-7 CXX='clang++-7 -stdlib=libc++'"
export GOAL="install"
-export BITCOIN_CONFIG="--enable-glibc-back-compat --enable-reduce-exports CC=clang-5.0 CXX=clang++-5.0"
+export BITCOIN_CONFIG="--enable-reduce-exports CC=clang-7 CXX='clang++-7 -stdlib=libc++'"
diff --git a/ci/test/00_setup_env_native_qt5.sh b/ci/test/00_setup_env_native_qt5.sh
index b3e967c898..8176179f0b 100755
--- a/ci/test/00_setup_env_native_qt5.sh
+++ b/ci/test/00_setup_env_native_qt5.sh
@@ -7,13 +7,13 @@
export LC_ALL=C.UTF-8
export CONTAINER_NAME=ci_native_qt5
-export DOCKER_NAME_TAG=ubuntu:18.04 # Check that bionic gcc-7 can compile our c++17 and run our functional tests in python3, see doc/dependencies.md
-export PACKAGES="python3-zmq qtbase5-dev qttools5-dev-tools libdbus-1-dev libharfbuzz-dev"
+export DOCKER_NAME_TAG=ubuntu:18.04 # Check that bionic gcc-8 can compile our C++17 and run our functional tests in python3, see doc/dependencies.md
+export PACKAGES="gcc-8 g++-8 python3-zmq qtbase5-dev qttools5-dev-tools libdbus-1-dev libharfbuzz-dev"
export DEP_OPTS="NO_QT=1 NO_UPNP=1 NO_NATPMP=1 DEBUG=1 ALLOW_HOST_PACKAGES=1"
export TEST_RUNNER_EXTRA="--previous-releases --coverage --extended --exclude feature_dbcrash" # Run extended tests so that coverage does not fail, but exclude the very slow dbcrash
export RUN_UNIT_TESTS_SEQUENTIAL="true"
export RUN_UNIT_TESTS="false"
export GOAL="install"
export PREVIOUS_RELEASES_TO_DOWNLOAD="v0.15.2 v0.16.3 v0.17.2 v0.18.1 v0.19.1 v0.20.1"
-export BITCOIN_CONFIG="--enable-zmq --with-libs=no --with-gui=qt5 --enable-glibc-back-compat --enable-reduce-exports
---enable-debug --disable-fuzz-binary CFLAGS=\"-g0 -O2 -funsigned-char\" CXXFLAGS=\"-g0 -O2 -funsigned-char\""
+export BITCOIN_CONFIG="--enable-zmq --with-libs=no --with-gui=qt5 --enable-reduce-exports
+--enable-debug --disable-fuzz-binary CFLAGS=\"-g0 -O2 -funsigned-char\" CXXFLAGS=\"-g0 -O2 -funsigned-char\" CC=gcc-8 CXX=g++-8"
diff --git a/ci/test/00_setup_env_native_valgrind.sh b/ci/test/00_setup_env_native_valgrind.sh
index e079a7057c..78af869e70 100755
--- a/ci/test/00_setup_env_native_valgrind.sh
+++ b/ci/test/00_setup_env_native_valgrind.sh
@@ -6,10 +6,11 @@
export LC_ALL=C.UTF-8
+export DOCKER_NAME_TAG="ubuntu:20.04"
export CONTAINER_NAME=ci_native_valgrind
export PACKAGES="valgrind clang llvm python3-zmq libevent-dev bsdmainutils libboost-dev libboost-system-dev libboost-filesystem-dev libboost-test-dev libdb5.3++-dev libminiupnpc-dev libnatpmp-dev libzmq3-dev libsqlite3-dev"
export USE_VALGRIND=1
export NO_DEPENDS=1
-export TEST_RUNNER_EXTRA="--exclude rpc_bind" # Excluded for now, see https://github.com/bitcoin/bitcoin/issues/17765#issuecomment-602068547
+export TEST_RUNNER_EXTRA="--exclude rpc_bind,feature_bind_extra" # Excluded for now, see https://github.com/bitcoin/bitcoin/issues/17765#issuecomment-602068547
export GOAL="install"
export BITCOIN_CONFIG="--enable-zmq --with-incompatible-bdb --with-gui=no CC=clang CXX=clang++" # TODO enable GUI
diff --git a/ci/test/00_setup_env_s390x.sh b/ci/test/00_setup_env_s390x.sh
index 51a0fd9117..fd253123e6 100755
--- a/ci/test/00_setup_env_s390x.sh
+++ b/ci/test/00_setup_env_s390x.sh
@@ -18,9 +18,9 @@ if [ -n "$QEMU_USER_CMD" ]; then
fi
# Use debian to avoid 404 apt errors
export CONTAINER_NAME=ci_s390x
-export DOCKER_NAME_TAG="debian:buster"
-export RUN_UNIT_TESTS=true
+export DOCKER_NAME_TAG="debian:bookworm"
export TEST_RUNNER_ENV="LC_ALL=C"
+export TEST_RUNNER_EXTRA="--exclude rpc_bind,feature_bind_extra" # Excluded for now, see https://github.com/bitcoin/bitcoin/issues/17765#issuecomment-602068547
export RUN_FUNCTIONAL_TESTS=true
export GOAL="install"
export BITCOIN_CONFIG="--enable-reduce-exports --with-incompatible-bdb"
diff --git a/configure.ac b/configure.ac
index e50d53f6dd..5a6f21fe42 100644
--- a/configure.ac
+++ b/configure.ac
@@ -71,6 +71,12 @@ case $host in
;;
esac
+AC_ARG_WITH([seccomp],
+ [AS_HELP_STRING([--with-seccomp],
+ [enable experimental syscall sandbox feature (-sandbox), default is yes if seccomp-bpf is detected under Linux x86_64])],
+ [seccomp_found=$withval],
+ [seccomp_found=auto])
+
dnl Require C++17 compiler (no GNU extensions)
AX_CXX_COMPILE_STDCXX([17], [noext], [mandatory])
@@ -101,7 +107,7 @@ AC_PATH_TOOL(GCOV, gcov)
AC_PATH_TOOL(LLVM_COV, llvm-cov)
AC_PATH_PROG(LCOV, lcov)
dnl Python 3.6 is specified in .python-version and should be used if available, see doc/dependencies.md
-AC_PATH_PROGS([PYTHON], [python3.6 python3.7 python3.8 python3.9 python3 python])
+AC_PATH_PROGS([PYTHON], [python3.6 python3.7 python3.8 python3.9, python3.10, python3 python])
AC_PATH_PROG(GENHTML, genhtml)
AC_PATH_PROG([GIT], [git])
AC_PATH_PROG(CCACHE,ccache)
@@ -240,15 +246,9 @@ AC_ARG_ENABLE([lcov-branch-coverage],
[use_lcov_branch=yes],
[use_lcov_branch=no])
-AC_ARG_ENABLE([glibc-back-compat],
- [AS_HELP_STRING([--enable-glibc-back-compat],
- [enable backwards compatibility with glibc])],
- [use_glibc_compat=$enableval],
- [use_glibc_compat=no])
-
AC_ARG_ENABLE([threadlocal],
[AS_HELP_STRING([--enable-threadlocal],
- [enable features that depend on the c++ thread_local keyword (currently just thread names in debug logs). (default is to enabled if there is platform support and glibc-back-compat is not enabled)])],
+ [enable features that depend on the c++ thread_local keyword (currently just thread names in debug logs). (default is to enable if there is platform support)])],
[use_thread_local=$enableval],
[use_thread_local=auto])
@@ -574,13 +574,17 @@ AX_CHECK_COMPILE_FLAG([-march=armv8-a+crc+crypto],[[ARM_CRC_CXXFLAGS="-march=arm
TEMP_CXXFLAGS="$CXXFLAGS"
CXXFLAGS="$CXXFLAGS $ARM_CRC_CXXFLAGS"
-AC_MSG_CHECKING(for ARM CRC32 intrinsics)
+AC_MSG_CHECKING(for AArch64 CRC32 intrinsics)
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
#include <arm_acle.h>
#include <arm_neon.h>
]],[[
+#ifdef __aarch64__
__crc32cb(0, 0); __crc32ch(0, 0); __crc32cw(0, 0); __crc32cd(0, 0);
vmull_p64(0, 0);
+#else
+#error "crc32c library does not support hardware acceleration on 32-bit ARM"
+#endif
]])],
[ AC_MSG_RESULT(yes); enable_arm_crc=yes; ],
[ AC_MSG_RESULT(no)]
@@ -863,17 +867,7 @@ if test x$ac_cv_sys_large_files != x &&
CPPFLAGS="$CPPFLAGS -D_LARGE_FILES=$ac_cv_sys_large_files"
fi
-if test x$use_glibc_compat != xno; then
- AX_CHECK_LINK_FLAG([[-Wl,--wrap=__divmoddi4]], [COMPAT_LDFLAGS="$COMPAT_LDFLAGS -Wl,--wrap=__divmoddi4"])
- AX_CHECK_LINK_FLAG([[-Wl,--wrap=log2f]], [COMPAT_LDFLAGS="$COMPAT_LDFLAGS -Wl,--wrap=log2f"])
- case $host in
- powerpc64* | ppc64*)
- AX_CHECK_LINK_FLAG([[-Wl,--no-tls-get-addr-optimize]], [COMPAT_LDFLAGS="$COMPAT_LDFLAGS -Wl,--no-tls-get-addr-optimize"])
- ;;
- esac
-else
- AC_SEARCH_LIBS([clock_gettime],[rt])
-fi
+AC_SEARCH_LIBS([clock_gettime],[rt])
if test "x$enable_gprof" = xyes; then
dnl -pg is incompatible with -pie. Since hardening and profiling together doesn't make sense,
@@ -1065,7 +1059,7 @@ AC_COMPILE_IFELSE([AC_LANG_SOURCE([
dnl thread_local is currently disabled when building with glibc back compat.
dnl Our minimum supported glibc is 2.17, however support for thread_local
dnl did not arrive in glibc until 2.18.
-if test "x$use_thread_local" = xyes || { test "x$use_thread_local" = xauto && test "x$use_glibc_compat" = xno; }; then
+if test "x$use_thread_local" = xyes || test "x$use_thread_local" = xauto; then
TEMP_LDFLAGS="$LDFLAGS"
LDFLAGS="$TEMP_LDFLAGS $PTHREAD_CFLAGS"
AC_MSG_CHECKING([for thread_local support])
@@ -1222,8 +1216,6 @@ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <xmmintrin.h>]], [[
AC_MSG_CHECKING(for strong getauxval support in the system headers)
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
- #include <arm_acle.h>
- #include <arm_neon.h>
#include <sys/auxv.h>
]], [[
getauxval(AT_HWCAP);
@@ -1232,26 +1224,14 @@ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
[ AC_MSG_RESULT(no); HAVE_STRONG_GETAUXVAL=0 ]
)
-AC_MSG_CHECKING(for weak getauxval support in the compiler)
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
- #ifdef __linux__
- unsigned long getauxval(unsigned long type) __attribute__((weak));
- #define AT_HWCAP 16
- #endif
- ]], [[
- getauxval(AT_HWCAP);
- ]])],
- [ AC_MSG_RESULT(yes); HAVE_WEAK_GETAUXVAL=1; AC_DEFINE(HAVE_WEAK_GETAUXVAL, 1, [Define this symbol to build code that uses getauxval (weak linking)]) ],
- [ AC_MSG_RESULT(no); HAVE_WEAK_GETAUXVAL=0 ]
-)
-
+have_any_system=no
AC_MSG_CHECKING([for std::system])
AC_LINK_IFELSE(
[ AC_LANG_PROGRAM(
[[ #include <cstdlib> ]],
[[ int nErr = std::system(""); ]]
)],
- [ AC_MSG_RESULT(yes); AC_DEFINE(HAVE_STD__SYSTEM, 1, Define to 1 if std::system is available.)],
+ [ AC_MSG_RESULT(yes); have_any_system=yes],
[ AC_MSG_RESULT(no) ]
)
@@ -1261,11 +1241,13 @@ AC_LINK_IFELSE(
[[ ]],
[[ int nErr = ::_wsystem(""); ]]
)],
- [ AC_MSG_RESULT(yes); AC_DEFINE(HAVE_WSYSTEM, 1, Define to 1 if ::wsystem is available.)],
+ [ AC_MSG_RESULT(yes); have_any_system=yes],
[ AC_MSG_RESULT(no) ]
)
-AC_DEFINE([HAVE_SYSTEM], [HAVE_STD__SYSTEM || HAVE_WSYSTEM], [std::system or ::wsystem])
+if test "x$have_any_system" != "xno"; then
+ AC_DEFINE(HAVE_SYSTEM, 1, Define to 1 if std::system or ::wsystem is available.)
+fi
LEVELDB_CPPFLAGS=
LIBLEVELDB=
@@ -1456,6 +1438,36 @@ if test "x$use_external_signer" != xno; then
fi
AM_CONDITIONAL([ENABLE_EXTERNAL_SIGNER], [test "x$use_external_signer" = "xyes"])
+dnl Do not compile with syscall sandbox support when compiling under the sanitizers.
+dnl The sanitizers introduce use of syscalls that are not typically used in bitcoind
+dnl (such as execve when the sanitizers execute llvm-symbolizer).
+if test x$use_sanitizers != x; then
+ AC_MSG_WARN(Specifying --with-sanitizers forces --without-seccomp since the sanitizers introduce use of syscalls not allowed by the bitcoind syscall sandbox (-sandbox=<mode>).)
+ seccomp_found=no
+fi
+if test "x$seccomp_found" != "xno"; then
+ AC_MSG_CHECKING([for seccomp-bpf (Linux x86-64)])
+ AC_PREPROC_IFELSE([AC_LANG_PROGRAM([[
+ @%:@include <linux/seccomp.h>
+ ]], [[
+ #if !defined(__x86_64__)
+ # error Syscall sandbox is an experimental feature currently available only under Linux x86-64.
+ #endif
+ ]])],[
+ AC_MSG_RESULT(yes)
+ seccomp_found="yes"
+ AC_DEFINE(USE_SYSCALL_SANDBOX, 1, [Define this symbol to build with syscall sandbox support.])
+ ],[
+ AC_MSG_RESULT(no)
+ seccomp_found="no"
+ ])
+fi
+dnl Currently only enable -sandbox=<mode> feature if seccomp is found.
+dnl In the future, sandboxing could be also be supported with other
+dnl sandboxing mechanisms besides seccomp.
+use_syscall_sandbox=$seccomp_found
+AM_CONDITIONAL([ENABLE_SYSCALL_SANDBOX], [test "x$use_syscall_sandbox" != "xno"])
+
dnl Check for reduced exports
if test x$use_reduce_exports = xyes; then
AX_CHECK_COMPILE_FLAG([-fvisibility=hidden],[CXXFLAGS="$CXXFLAGS -fvisibility=hidden"],
@@ -1649,8 +1661,8 @@ if test "x$use_ccache" != "xno"; then
fi
AC_MSG_RESULT($use_ccache)
if test "x$use_ccache" = "xyes"; then
- AX_CHECK_COMPILE_FLAG([-fdebug-prefix-map=A=B],[DEBUG_CXXFLAGS="$DEBUG_CXXFLAGS -fdebug-prefix-map=\$(abs_srcdir)=."],,[[$CXXFLAG_WERROR]])
- AX_CHECK_PREPROC_FLAG([-fmacro-prefix-map=A=B],[DEBUG_CPPFLAGS="$DEBUG_CPPFLAGS -fmacro-prefix-map=\$(abs_srcdir)=."],,[[$CXXFLAG_WERROR]])
+ AX_CHECK_COMPILE_FLAG([-fdebug-prefix-map=A=B],[DEBUG_CXXFLAGS="$DEBUG_CXXFLAGS -fdebug-prefix-map=\$(abs_top_srcdir)=."],,[[$CXXFLAG_WERROR]])
+ AX_CHECK_PREPROC_FLAG([-fmacro-prefix-map=A=B],[DEBUG_CPPFLAGS="$DEBUG_CPPFLAGS -fmacro-prefix-map=\$(abs_top_srcdir)=."],,[[$CXXFLAG_WERROR]])
fi
fi
@@ -1806,7 +1818,6 @@ AM_CONDITIONAL([ENABLE_BENCH],[test x$use_bench = xyes])
AM_CONDITIONAL([USE_QRCODE], [test x$use_qr = xyes])
AM_CONDITIONAL([USE_LCOV],[test x$use_lcov = xyes])
AM_CONDITIONAL([USE_LIBEVENT],[test x$use_libevent = xyes])
-AM_CONDITIONAL([GLIBC_BACK_COMPAT],[test x$use_glibc_compat = xyes])
AM_CONDITIONAL([HARDEN],[test x$use_hardening = xyes])
AM_CONDITIONAL([ENABLE_SSE42],[test x$enable_sse42 = xyes])
AM_CONDITIONAL([ENABLE_SSE41],[test x$enable_sse41 = xyes])
@@ -1849,7 +1860,6 @@ AC_SUBST(DEBUG_CPPFLAGS)
AC_SUBST(WARN_CXXFLAGS)
AC_SUBST(NOWARN_CXXFLAGS)
AC_SUBST(DEBUG_CXXFLAGS)
-AC_SUBST(COMPAT_LDFLAGS)
AC_SUBST(ERROR_CXXFLAGS)
AC_SUBST(GPROF_CXXFLAGS)
AC_SUBST(GPROF_LDFLAGS)
@@ -1889,7 +1899,6 @@ AC_SUBST(HAVE_O_CLOEXEC)
AC_SUBST(HAVE_BUILTIN_PREFETCH)
AC_SUBST(HAVE_MM_PREFETCH)
AC_SUBST(HAVE_STRONG_GETAUXVAL)
-AC_SUBST(HAVE_WEAK_GETAUXVAL)
AC_SUBST(ANDROID_ARCH)
AC_CONFIG_FILES([Makefile src/Makefile doc/man/Makefile share/setup.nsi share/qt/Info.plist test/config.ini])
AC_CONFIG_FILES([contrib/devtools/split-debug.sh],[chmod +x contrib/devtools/split-debug.sh])
@@ -1948,6 +1957,7 @@ echo
echo "Options used to compile and link:"
echo " external signer = $use_external_signer"
echo " multiprocess = $build_multiprocess"
+echo " with experimental syscall sandbox support = $use_syscall_sandbox"
echo " with libs = $build_bitcoin_libs"
echo " with wallet = $enable_wallet"
if test "x$enable_wallet" != "xno"; then
diff --git a/contrib/devtools/symbol-check.py b/contrib/devtools/symbol-check.py
index 61f727fa63..98cab1b7fc 100755
--- a/contrib/devtools/symbol-check.py
+++ b/contrib/devtools/symbol-check.py
@@ -217,7 +217,7 @@ def check_MACHO_libraries(filename) -> bool:
def check_MACHO_min_os(filename) -> bool:
binary = lief.parse(filename)
- if binary.build_version.minos == [10,14,0]:
+ if binary.build_version.minos == [10,15,0]:
return True
return False
diff --git a/contrib/devtools/test-symbol-check.py b/contrib/devtools/test-symbol-check.py
index 2da7ae793d..651589c11b 100755
--- a/contrib/devtools/test-symbol-check.py
+++ b/contrib/devtools/test-symbol-check.py
@@ -137,7 +137,7 @@ class TestSymbolChecks(unittest.TestCase):
}
''')
- self.assertEqual(call_symbol_check(cc, source, executable, ['-Wl,-platform_version','-Wl,macos', '-Wl,10.14', '-Wl,11.4']),
+ self.assertEqual(call_symbol_check(cc, source, executable, ['-Wl,-platform_version','-Wl,macos', '-Wl,10.15', '-Wl,11.4']),
(1, f'{executable}: failed SDK'))
def test_PE(self):
diff --git a/contrib/guix/INSTALL.md b/contrib/guix/INSTALL.md
index 63aa3e02b2..68aae18731 100644
--- a/contrib/guix/INSTALL.md
+++ b/contrib/guix/INSTALL.md
@@ -358,7 +358,7 @@ This is especially notable because Ubuntu Focal packages `libgit2 v0.28.4`, and
Should you be in this situation, you need to build both `libgit2 v1.1.x` and
`guile-git` from source.
-Source: http://logs.guix.gnu.org/guix/2020-11-12.log#232527
+Source: https://logs.guix.gnu.org/guix/2020-11-12.log#232527
##### `{scheme,guile}-bytestructures` v1.0.8 and v1.0.9 are broken for Guile v2.2
diff --git a/contrib/guix/README.md b/contrib/guix/README.md
index 2bb464a40d..51a034c26e 100644
--- a/contrib/guix/README.md
+++ b/contrib/guix/README.md
@@ -75,7 +75,7 @@ crucial differences:
1. Since only Windows and macOS build outputs require codesigning, the `HOSTS`
environment variable will have a sane default value of `x86_64-w64-mingw32
- x86_64-apple-darwin18` instead of all the platforms.
+ x86_64-apple-darwin19` instead of all the platforms.
2. The `guix-codesign` command ***requires*** a `DETACHED_SIGS_REPO` flag.
* _**DETACHED_SIGS_REPO**_
@@ -159,7 +159,7 @@ which case you can override the default list by setting the space-separated
`HOSTS` environment variable:
```sh
-env HOSTS='x86_64-w64-mingw32 x86_64-apple-darwin18' ./contrib/guix/guix-build
+env HOSTS='x86_64-w64-mingw32 x86_64-apple-darwin19' ./contrib/guix/guix-build
```
See the [recognized environment variables][env-vars-list] section for more
@@ -224,7 +224,7 @@ details.
_(defaults to "x86\_64-linux-gnu arm-linux-gnueabihf aarch64-linux-gnu
riscv64-linux-gnu powerpc64-linux-gnu powerpc64le-linux-gnu
- x86\_64-w64-mingw32 x86\_64-apple-darwin18")_
+ x86\_64-w64-mingw32 x86\_64-apple-darwin19")_
* _**SOURCES_PATH**_
@@ -467,7 +467,7 @@ start over.
- `/root/.cache/guix/`
- `/root/.guix-profile/`
-[b17e]: http://bootstrappable.org/
+[b17e]: https://bootstrappable.org/
[r12e/source-date-epoch]: https://reproducible-builds.org/docs/source-date-epoch/
[guix/install.sh]: https://git.savannah.gnu.org/cgit/guix.git/plain/etc/guix-install.sh
diff --git a/contrib/guix/guix-build b/contrib/guix/guix-build
index dd7229b6fa..9317fa7fde 100755
--- a/contrib/guix/guix-build
+++ b/contrib/guix/guix-build
@@ -76,7 +76,7 @@ mkdir -p "$VERSION_BASE"
# Default to building for all supported HOSTs (overridable by environment)
export HOSTS="${HOSTS:-x86_64-linux-gnu arm-linux-gnueabihf aarch64-linux-gnu riscv64-linux-gnu powerpc64-linux-gnu powerpc64le-linux-gnu
x86_64-w64-mingw32
- x86_64-apple-darwin18}"
+ x86_64-apple-darwin19}"
# Usage: distsrc_for_host HOST
#
diff --git a/contrib/guix/guix-codesign b/contrib/guix/guix-codesign
index 3f464f89e6..aff897037d 100755
--- a/contrib/guix/guix-codesign
+++ b/contrib/guix/guix-codesign
@@ -91,7 +91,7 @@ fi
################
# Default to building for all supported HOSTs (overridable by environment)
-export HOSTS="${HOSTS:-x86_64-w64-mingw32 x86_64-apple-darwin18}"
+export HOSTS="${HOSTS:-x86_64-w64-mingw32 x86_64-apple-darwin19}"
# Usage: distsrc_for_host HOST
#
diff --git a/contrib/guix/libexec/build.sh b/contrib/guix/libexec/build.sh
index 356bd70070..93526f8c45 100755
--- a/contrib/guix/libexec/build.sh
+++ b/contrib/guix/libexec/build.sh
@@ -147,7 +147,7 @@ case "$HOST" in
#
# After the native packages in depends are built, the ld wrapper should
# no longer affect our build, as clang would instead reach for
- # x86_64-apple-darwin18-ld from cctools
+ # x86_64-apple-darwin19-ld from cctools
;;
*) export GUIX_LD_WRAPPER_DISABLE_RPATH=yes ;;
esac
@@ -423,8 +423,8 @@ mkdir -p "$DISTSRC"
find "${DISTNAME}" -print0 \
| sort --zero-terminated \
| tar --create --no-recursion --mode='u+rw,go+r-w,a+X' --null --files-from=- \
- | gzip -9n > "${OUTDIR}/${DISTNAME}-${HOST//x86_64-apple-darwin18/osx64}.tar.gz" \
- || ( rm -f "${OUTDIR}/${DISTNAME}-${HOST//x86_64-apple-darwin18/osx64}.tar.gz" && exit 1 )
+ | gzip -9n > "${OUTDIR}/${DISTNAME}-${HOST//x86_64-apple-darwin19/osx64}.tar.gz" \
+ || ( rm -f "${OUTDIR}/${DISTNAME}-${HOST//x86_64-apple-darwin19/osx64}.tar.gz" && exit 1 )
;;
esac
) # $DISTSRC/installed
diff --git a/contrib/signet/getcoins.py b/contrib/signet/getcoins.py
index dc203f1254..3d0aa5d132 100755
--- a/contrib/signet/getcoins.py
+++ b/contrib/signet/getcoins.py
@@ -4,18 +4,77 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import argparse
+import io
+import requests
import subprocess
import sys
-import requests
DEFAULT_GLOBAL_FAUCET = 'https://signetfaucet.com/claim'
+DEFAULT_GLOBAL_CAPTCHA = 'https://signetfaucet.com/captcha'
GLOBAL_FIRST_BLOCK_HASH = '00000086d6b2636cb2a392d45edc4ec544a10024d30141c9adf4bfd9de533b53'
+# braille unicode block
+BASE = 0x2800
+BIT_PER_PIXEL = [
+ [0x01, 0x08],
+ [0x02, 0x10],
+ [0x04, 0x20],
+ [0x40, 0x80],
+]
+BW = 2
+BH = 4
+
+# imagemagick or compatible fork (used for converting SVG)
+CONVERT = 'convert'
+
+class PPMImage:
+ '''
+ Load a PPM image (Pillow-ish API).
+ '''
+ def __init__(self, f):
+ if f.readline() != b'P6\n':
+ raise ValueError('Invalid ppm format: header')
+ line = f.readline()
+ (width, height) = (int(x) for x in line.rstrip().split(b' '))
+ if f.readline() != b'255\n':
+ raise ValueError('Invalid ppm format: color depth')
+ data = f.read(width * height * 3)
+ stride = width * 3
+ self.size = (width, height)
+ self._grid = [[tuple(data[stride * y + 3 * x:stride * y + 3 * (x + 1)]) for x in range(width)] for y in range(height)]
+
+ def getpixel(self, pos):
+ return self._grid[pos[1]][pos[0]]
+
+def print_image(img, threshold=128):
+ '''Print black-and-white image to terminal in braille unicode characters.'''
+ x_blocks = (img.size[0] + BW - 1) // BW
+ y_blocks = (img.size[1] + BH - 1) // BH
+
+ for yb in range(y_blocks):
+ line = []
+ for xb in range(x_blocks):
+ ch = BASE
+ for y in range(BH):
+ for x in range(BW):
+ try:
+ val = img.getpixel((xb * BW + x, yb * BH + y))
+ except IndexError:
+ pass
+ else:
+ if val[0] < threshold:
+ ch |= BIT_PER_PIXEL[y][x]
+ line.append(chr(ch))
+ print(''.join(line))
+
parser = argparse.ArgumentParser(description='Script to get coins from a faucet.', epilog='You may need to start with double-dash (--) when providing bitcoin-cli arguments.')
parser.add_argument('-c', '--cmd', dest='cmd', default='bitcoin-cli', help='bitcoin-cli command to use')
parser.add_argument('-f', '--faucet', dest='faucet', default=DEFAULT_GLOBAL_FAUCET, help='URL of the faucet')
+parser.add_argument('-g', '--captcha', dest='captcha', default=DEFAULT_GLOBAL_CAPTCHA, help='URL of the faucet captcha, or empty if no captcha is needed')
parser.add_argument('-a', '--addr', dest='addr', default='', help='Bitcoin address to which the faucet should send')
parser.add_argument('-p', '--password', dest='password', default='', help='Faucet password, if any')
+parser.add_argument('-n', '--amount', dest='amount', default='0.001', help='Amount to request (0.001-0.1, default is 0.001)')
+parser.add_argument('-i', '--imagemagick', dest='imagemagick', default=CONVERT, help='Path to imagemagick convert utility')
parser.add_argument('bitcoin_cli_args', nargs='*', help='Arguments to pass on to bitcoin-cli (default: -signet)')
args = parser.parse_args()
@@ -43,14 +102,43 @@ if args.faucet.lower() == DEFAULT_GLOBAL_FAUCET:
if curr_signet_hash != GLOBAL_FIRST_BLOCK_HASH:
print('The global faucet cannot be used with a custom Signet network. Please use the global signet or setup your custom faucet to use this functionality.\n')
exit(1)
+else:
+ # For custom faucets, don't request captcha by default.
+ if args.captcha == DEFAULT_GLOBAL_CAPTCHA:
+ args.captcha = ''
if args.addr == '':
# get address for receiving coins
args.addr = bitcoin_cli(['getnewaddress', 'faucet', 'bech32'])
-data = {'address': args.addr, 'password': args.password}
+data = {'address': args.addr, 'password': args.password, 'amount': args.amount}
+
+# Store cookies
+# for debugging: print(session.cookies.get_dict())
+session = requests.Session()
+
+if args.captcha != '': # Retrieve a captcha
+ try:
+ res = session.get(args.captcha)
+ except:
+ print('Unexpected error when contacting faucet:', sys.exc_info()[0])
+ exit(1)
+
+ # Convert SVG image to PPM, and load it
+ try:
+ rv = subprocess.run([args.imagemagick, '-', '-depth', '8', 'ppm:-'], input=res.content, check=True, capture_output=True)
+ except FileNotFoundError:
+ print('The binary', args.imagemagick, 'could not be found. Please make sure ImageMagick (or a compatible fork) is installed and that the correct path is specified.')
+ exit(1)
+ img = PPMImage(io.BytesIO(rv.stdout))
+
+ # Terminal interaction
+ print_image(img)
+ print('Enter captcha: ', end='')
+ data['captcha'] = input()
+
try:
- res = requests.post(args.faucet, data=data)
+ res = session.post(args.faucet, data=data)
except:
print('Unexpected error when contacting faucet:', sys.exc_info()[0])
exit(1)
diff --git a/depends/README.md b/depends/README.md
index 4f3b6df487..15c82cddf2 100644
--- a/depends/README.md
+++ b/depends/README.md
@@ -28,7 +28,7 @@ Common `host-platform-triplet`s for cross compilation are:
- `i686-pc-linux-gnu` for Linux 32 bit
- `x86_64-pc-linux-gnu` for x86 Linux
- `x86_64-w64-mingw32` for Win64
-- `x86_64-apple-darwin18` for macOS
+- `x86_64-apple-darwin19` for macOS
- `arm-linux-gnueabihf` for Linux ARM 32 bit
- `aarch64-linux-gnu` for Linux ARM 64 bit
- `powerpc64-linux-gnu` for Linux POWER 64-bit (big endian)
diff --git a/depends/hosts/darwin.mk b/depends/hosts/darwin.mk
index 5a7ae2df9a..ea92bb7793 100644
--- a/depends/hosts/darwin.mk
+++ b/depends/hosts/darwin.mk
@@ -1,4 +1,4 @@
-OSX_MIN_VERSION=10.14
+OSX_MIN_VERSION=10.15
OSX_SDK_VERSION=10.15.6
XCODE_VERSION=12.1
XCODE_BUILD_ID=12A7403
diff --git a/doc/build-unix.md b/doc/build-unix.md
index 44b6ad5968..02c36eea7c 100644
--- a/doc/build-unix.md
+++ b/doc/build-unix.md
@@ -348,7 +348,7 @@ To build executables for ARM:
make HOST=arm-linux-gnueabihf NO_QT=1
cd ..
./autogen.sh
- CONFIG_SITE=$PWD/depends/arm-linux-gnueabihf/share/config.site ./configure --enable-glibc-back-compat --enable-reduce-exports LDFLAGS=-static-libstdc++
+ CONFIG_SITE=$PWD/depends/arm-linux-gnueabihf/share/config.site ./configure --enable-reduce-exports LDFLAGS=-static-libstdc++
make
diff --git a/doc/build-windows.md b/doc/build-windows.md
index f88b9739de..0b895eadfb 100644
--- a/doc/build-windows.md
+++ b/doc/build-windows.md
@@ -5,11 +5,9 @@ Below are some notes on how to build Bitcoin Core for Windows.
The options known to work for building Bitcoin Core on Windows are:
-* On Linux, using the [Mingw-w64](https://mingw-w64.org/doku.php) cross compiler tool chain. Ubuntu Bionic 18.04 is required
-and is the platform used to build the Bitcoin Core Windows release binaries.
-* On Windows, using [Windows
-Subsystem for Linux (WSL)](https://docs.microsoft.com/windows/wsl/about) and the Mingw-w64 cross compiler tool chain.
-* On Windows, using a native compiler tool chain such as [Visual Studio](https://www.visualstudio.com). See [README.md](/build_msvc/README.md).
+* On Linux, using the [Mingw-w64](https://www.mingw-w64.org/) cross compiler tool chain.
+* On Windows, using [Windows Subsystem for Linux (WSL)](https://docs.microsoft.com/windows/wsl/about) and Mingw-w64.
+* On Windows, using [Microsoft Visual Studio](https://www.visualstudio.com). See [README.md](/build_msvc/README.md).
Other options which may work, but which have not been extensively tested are (please contribute instructions):
@@ -18,40 +16,12 @@ Other options which may work, but which have not been extensively tested are (pl
Installing Windows Subsystem for Linux
---------------------------------------
-With Windows 10, Microsoft has released a new feature named the [Windows
-Subsystem for Linux (WSL)](https://docs.microsoft.com/windows/wsl/about). This
-feature allows you to run a bash shell directly on Windows in an Ubuntu-based
-environment. Within this environment you can cross compile for Windows without
-the need for a separate Linux VM or server. Note that while WSL can be installed with
-other Linux variants, such as OpenSUSE, the following instructions have only been
-tested with Ubuntu.
-
-This feature is not supported in versions of Windows prior to Windows 10 or on
-Windows Server SKUs. In addition, it is available [only for 64-bit versions of
-Windows](https://docs.microsoft.com/windows/wsl/install-win10).
-
-Full instructions to install WSL are available on the above link.
-To install WSL on Windows 10 with Fall Creators Update installed (version >= 16215.0) do the following:
-
-1. Enable the Windows Subsystem for Linux feature
- * Open the Windows Features dialog (`OptionalFeatures.exe`)
- * Enable 'Windows Subsystem for Linux'
- * Click 'OK' and restart if necessary
-2. Install Ubuntu
- * Open Microsoft Store and search for "Ubuntu 18.04" or use [this link](https://www.microsoft.com/store/productId/9N9TNGVNDL3Q)
- * Click Install
-3. Complete Installation
- * Open a cmd prompt and type "Ubuntu1804"
- * Create a new UNIX user account (this is a separate account from your Windows account)
-
-After the bash shell is active, you can follow the instructions below, starting
-with the "Cross-compilation" section. Compiling the 64-bit version is
-recommended, but it is possible to compile the 32-bit version.
+Follow the upstream installation instructions, available [here](https://docs.microsoft.com/windows/wsl/install-win10).
Cross-compilation for Ubuntu and Windows Subsystem for Linux
------------------------------------------------------------
-The steps below can be performed on Ubuntu (including in a VM) or WSL. The depends system
+The steps below can be performed on Ubuntu or WSL. The depends system
will also work on other Linux distributions, however the commands for
installing the toolchain will be different.
diff --git a/doc/dependencies.md b/doc/dependencies.md
index b7634718e8..0c1fd6ba98 100644
--- a/doc/dependencies.md
+++ b/doc/dependencies.md
@@ -7,11 +7,12 @@ These are the dependencies currently used by Bitcoin Core. You can find instruct
| --- | --- | --- | --- | --- | --- |
| Berkeley DB | [4.8.30](https://www.oracle.com/technetwork/database/database-technologies/berkeleydb/downloads/index.html) | 4.8.x | No | | |
| Boost | [1.71.0](https://www.boost.org/users/download/) | [1.64.0](https://github.com/bitcoin/bitcoin/pull/22320) | No | | |
-| Clang<sup>[ \* ](#note1)</sup> | | [5.0+](https://releases.llvm.org/download.html) (C++17 support) | | | |
+| Clang<sup>[ \* ](#note1)</sup> | | [7.0](https://releases.llvm.org/download.html) (C++17 & std::filesystem support) | | | |
| Expat | [2.2.7](https://libexpat.github.io/) | | No | Yes | |
| fontconfig | [2.12.1](https://www.freedesktop.org/software/fontconfig/release/) | | No | Yes | |
| FreeType | [2.7.1](https://download.savannah.gnu.org/releases/freetype) | | No | | [Yes](https://github.com/bitcoin/bitcoin/blob/master/depends/packages/qt.mk) (Android only) |
-| GCC | | [7+](https://gcc.gnu.org/) (C++17 support) | | | |
+| GCC | | [8.1](https://gcc.gnu.org/) (C++17 & std::filesystem support) | | | |
+| glibc | | [2.17](https://www.gnu.org/software/libc/) | | | | |
| HarfBuzz-NG | | | | | [Yes](https://github.com/bitcoin/bitcoin/blob/master/depends/packages/qt.mk) |
| libevent | [2.1.12-stable](https://github.com/libevent/libevent/releases) | [2.0.21](https://github.com/bitcoin/bitcoin/pull/18676) | No | | |
| libnatpmp | git commit [4536032...](https://github.com/miniupnp/libnatpmp/tree/4536032ae32268a45c073a4d5e91bbab4534773a) | | No | | |
diff --git a/doc/developer-notes.md b/doc/developer-notes.md
index 3e13adeec0..a05ea93a46 100644
--- a/doc/developer-notes.md
+++ b/doc/developer-notes.md
@@ -12,6 +12,7 @@ Developer Notes
- [Generating Documentation](#generating-documentation)
- [Development tips and tricks](#development-tips-and-tricks)
- [Compiling for debugging](#compiling-for-debugging)
+ - [Show sources in debugging](#show-sources-in-debugging)
- [Compiling for gprof profiling](#compiling-for-gprof-profiling)
- [`debug.log`](#debuglog)
- [Signet, testnet, and regtest modes](#signet-testnet-and-regtest-modes)
@@ -253,6 +254,35 @@ Development tips and tricks
Run configure with `--enable-debug` to add additional compiler flags that
produce better debugging builds.
+### Show sources in debugging
+
+If you have ccache enabled, absolute paths are stripped from debug information
+with the -fdebug-prefix-map and -fmacro-prefix-map options (if supported by the
+compiler). This might break source file detection in case you move binaries
+after compilation, debug from the directory other than the project root or use
+an IDE that only supports absolute paths for debugging.
+
+There are a few possible fixes:
+
+1. Configure source file mapping.
+
+For `gdb` create or append to `.gdbinit` file:
+```
+set substitute-path ./src /path/to/project/root/src
+```
+
+For `lldb` create or append to `.lldbinit` file:
+```
+settings set target.source-map ./src /path/to/project/root/src
+```
+
+2. Add a symlink to the `./src` directory:
+```
+ln -s /path/to/project/root/src src
+```
+
+3. Use `debugedit` to modify debug information in the binary.
+
### Compiling for gprof profiling
Run configure with the `--enable-gprof` option, then make.
@@ -349,7 +379,7 @@ make cov
Profiling is a good way to get a precise idea of where time is being spent in
code. One tool for doing profiling on Linux platforms is called
-[`perf`](http://www.brendangregg.com/perf.html), and has been integrated into
+[`perf`](https://www.brendangregg.com/perf.html), and has been integrated into
the functional test framework. Perf can observe a running process and sample
(at some frequency) where its execution is.
@@ -963,37 +993,41 @@ Subtrees
Several parts of the repository are subtrees of software maintained elsewhere.
-Some of these are maintained by active developers of Bitcoin Core, in which case changes should probably go
-directly upstream without being PRed directly against the project. They will be merged back in the next
-subtree merge.
+Some of these are maintained by active developers of Bitcoin Core, in which case
+changes should go directly upstream without being PRed directly against the project.
+They will be merged back in the next subtree merge.
-Others are external projects without a tight relationship with our project. Changes to these should also
-be sent upstream, but bugfixes may also be prudent to PR against Bitcoin Core so that they can be integrated
-quickly. Cosmetic changes should be purely taken upstream.
+Others are external projects without a tight relationship with our project. Changes
+to these should also be sent upstream, but bugfixes may also be prudent to PR against
+a Bitcoin Core subtree, so that they can be integrated quickly. Cosmetic changes
+should be taken upstream.
-There is a tool in `test/lint/git-subtree-check.sh` ([instructions](../test/lint#git-subtree-checksh)) to check a subtree directory for consistency with
-its upstream repository.
+There is a tool in `test/lint/git-subtree-check.sh` ([instructions](../test/lint#git-subtree-checksh))
+to check a subtree directory for consistency with its upstream repository.
Current subtrees include:
- src/leveldb
- - Upstream at https://github.com/google/leveldb ; Maintained by Google, but
- open important PRs to Core to avoid delay.
+ - Subtree at https://github.com/bitcoin-core/leveldb-subtree ; maintained by Core contributors.
+ - Upstream at https://github.com/google/leveldb ; maintained by Google. Open
+ important PRs to the subtree to avoid delay.
- **Note**: Follow the instructions in [Upgrading LevelDB](#upgrading-leveldb) when
merging upstream changes to the LevelDB subtree.
- src/crc32c
- Used by leveldb for hardware acceleration of CRC32C checksums for data integrity.
- - Upstream at https://github.com/google/crc32c ; Maintained by Google.
+ - Subtree at https://github.com/bitcoin-core/crc32c-subtree ; maintained by Core contributors.
+ - Upstream at https://github.com/google/crc32c ; maintained by Google.
- src/secp256k1
- - Upstream at https://github.com/bitcoin-core/secp256k1/ ; actively maintained by Core contributors.
+ - Upstream at https://github.com/bitcoin-core/secp256k1/ ; maintained by Core contributors.
- src/crypto/ctaes
- - Upstream at https://github.com/bitcoin-core/ctaes ; actively maintained by Core contributors.
+ - Upstream at https://github.com/bitcoin-core/ctaes ; maintained by Core contributors.
- src/univalue
- - Upstream at https://github.com/bitcoin-core/univalue ; actively maintained by Core contributors, deviates from upstream https://github.com/jgarzik/univalue
+ - Subtree at https://github.com/bitcoin-core/univalue-subtree ; maintained by Core contributors.
+ - Deviates from upstream https://github.com/jgarzik/univalue.
Upgrading LevelDB
---------------------
diff --git a/doc/fuzzing.md b/doc/fuzzing.md
index ee9c65d4d4..0880f9f581 100644
--- a/doc/fuzzing.md
+++ b/doc/fuzzing.md
@@ -254,6 +254,73 @@ $ honggfuzz/honggfuzz --exit_upon_crash --quiet --timeout 4 -n 1 -Q \
-debug
```
+# Fuzzing Bitcoin Core using Eclipser (v1.x)
+
+## Quickstart guide
+
+To quickly get started fuzzing Bitcoin Core using [Eclipser v1.x](https://github.com/SoftSec-KAIST/Eclipser/tree/v1.x):
+
+```sh
+$ git clone https://github.com/bitcoin/bitcoin
+$ cd bitcoin/
+$ sudo vim /etc/apt/sources.list # Uncomment the lines starting with 'deb-src'.
+$ sudo apt-get update
+$ sudo apt-get build-dep qemu
+$ sudo apt-get install libtool libtool-bin wget automake autoconf bison gdb
+```
+
+At this point, you must install the .NET core. The process differs, depending on your Linux distribution.
+See [this link](https://docs.microsoft.com/en-us/dotnet/core/install/linux) for details.
+On ubuntu 20.04, the following should work:
+
+```sh
+$ wget -q https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb
+$ sudo dpkg -i packages-microsoft-prod.deb
+$ rm packages-microsoft-prod.deb
+$ sudo apt-get update
+$ sudo apt-get install -y dotnet-sdk-2.1
+```
+
+You will also want to make sure Python is installed as `python` for the Eclipser install to succeed.
+
+```sh
+$ git clone https://github.com/SoftSec-KAIST/Eclipser.git
+$ cd Eclipser
+$ git checkout v1.x
+$ make
+$ cd ..
+$ ./autogen.sh
+$ ./configure --enable-fuzz
+$ make
+$ mkdir -p outputs/
+$ FUZZ=bech32 dotnet Eclipser/build/Eclipser.dll fuzz -p src/test/fuzz/fuzz -t 36000 -o outputs --src stdin
+```
+
+This will perform 10 hours of fuzzing.
+
+To make further use of the inputs generated by Eclipser, you
+must first decode them:
+
+```sh
+$ dotnet Eclipser/build/Eclipser.dll decode -i outputs/testcase -o decoded_outputs
+```
+This will place raw inputs in the directory `decoded_outputs/decoded_stdins`. Crashes are in the `outputs/crashes` directory, and must
+be decoded in the same way.
+
+Fuzzing with Eclipser will likely be much more effective if using an existing corpus:
+
+```sh
+$ git clone https://github.com/bitcoin-core/qa-assets
+$ FUZZ=bech32 dotnet Eclipser/build/Eclipser.dll fuzz -p src/test/fuzz/fuzz -t 36000 -i qa-assets/fuzz_seed_corpus/bech32 outputs --src stdin
+```
+
+Note that fuzzing with Eclipser on certain targets (those that create 'full nodes', e.g. `process_message*`) will,
+for now, slowly fill `/tmp/` with improperly cleaned-up files, which will cause spurious crashes.
+See [this proposed patch](https://github.com/bitcoin/bitcoin/pull/22472) for more information.
+
+Read the [Eclipser documentation for v1.x](https://github.com/SoftSec-KAIST/Eclipser/tree/v1.x) for more details on using Eclipser.
+
+
# OSS-Fuzz
Bitcoin Core participates in Google's [OSS-Fuzz](https://github.com/google/oss-fuzz/tree/master/projects/bitcoin-core)
diff --git a/doc/release-notes-22539.md b/doc/release-notes-22539.md
new file mode 100644
index 0000000000..9f56071451
--- /dev/null
+++ b/doc/release-notes-22539.md
@@ -0,0 +1,8 @@
+Notable changes
+===============
+
+P2P and network changes
+-----------------------
+
+- Fee estimation now takes the feerate of replacement (RBF) transactions into
+ account.
diff --git a/doc/release-notes.md b/doc/release-notes.md
index 6815408ca7..81e79dd3a9 100644
--- a/doc/release-notes.md
+++ b/doc/release-notes.md
@@ -46,7 +46,7 @@ Compatibility
==============
Bitcoin Core is supported and extensively tested on operating systems
-using the Linux kernel, macOS 10.14+, and Windows 7 and newer. Bitcoin
+using the Linux kernel, macOS 10.15+, and Windows 7 and newer. Bitcoin
Core should also work on most other Unix-like systems but is not as
frequently tested on them. It is not recommended to use Bitcoin Core on
unsupported systems.
@@ -61,9 +61,30 @@ P2P and network changes
They will become eligible for address gossip after sending an ADDR, ADDRV2,
or GETADDR message. (#21528)
+Rescan startup parameter removed
+--------------------------------
+
+The `-rescan` startup parameter has been removed. Wallets which require
+rescanning due to corruption will still be rescanned on startup.
+Otherwise, please use the `rescanblockchain` RPC to trigger a rescan. (#23123)
+
Updated RPCs
------------
+- The `-deprecatedrpc=addresses` configuration option has been removed. RPCs
+ `gettxout`, `getrawtransaction`, `decoderawtransaction`, `decodescript`,
+ `gettransaction verbose=true` and REST endpoints `/rest/tx`, `/rest/getutxos`,
+ `/rest/block` no longer return the `addresses` and `reqSigs` fields, which
+ were previously deprecated in 22.0. (#22650)
+
+- `listunspent` now includes `ancestorcount`, `ancestorsize`, and
+ `ancestorfees` for each transaction output that is still in the mempool.
+ (#12677)
+
+- `lockunspent` now optionally takes a third parameter, `persistent`, which
+ causes the lock to be written persistently to the wallet database. This
+ allows UTXOs to remain locked even after node restarts or crashes. (#23065)
+
New RPCs
--------
@@ -86,17 +107,30 @@ New settings
Updated settings
----------------
+- In previous releases, the meaning of the command line option
+ `-persistmempool` (without a value provided) incorrectly disabled mempool
+ persistence. `-persistmempool` is now treated like other boolean options to
+ mean `-persistmempool=1`. Passing `-persistmempool=0`, `-persistmempool=1`
+ and `-nopersistmempool` is unaffected. (#23061)
+
Tools and Utilities
-------------------
- Update `-getinfo` to return data in a user-friendly format that also reduces vertical space. (#21832)
+- CLI `-addrinfo` now returns a single field for the number of `onion` addresses
+ known to the node instead of separate `torv2` and `torv3` fields, as support
+ for Tor V2 addresses was removed from Bitcoin Core in 22.0. (#22544)
+
Wallet
------
GUI changes
-----------
+- UTXOs which are locked via the GUI are now stored persistently in the
+ wallet database, so are not lost on node shutdown or crash. (#23065)
+
Low-level changes
=================
@@ -109,10 +143,8 @@ Tests
-----
- For the `regtest` network the activation heights of several softforks were
- changed.
- * BIP 34 (blockheight in coinbase) from 500 to 2 (#16333)
- * BIP 66 (DERSIG) from 1251 to 102 (#22632)
- * BIP 65 (CLTV) from 1351 to 111 (#21862)
+ set to block height 1. They can be changed by the runtime setting
+ `-testactivationheight=name@height`. (#22818)
Credits
=======
diff --git a/doc/release-notes/release-notes-22.0.md b/doc/release-notes/release-notes-22.0.md
new file mode 100644
index 0000000000..972c91aa6f
--- /dev/null
+++ b/doc/release-notes/release-notes-22.0.md
@@ -0,0 +1,1163 @@
+22.0 Release Notes
+==================
+
+Bitcoin Core version 22.0 is now available from:
+
+ <https://bitcoincore.org/bin/bitcoin-core-22.0/>
+
+This release includes new features, various bug fixes and performance
+improvements, as well as updated translations.
+
+Please report bugs using the issue tracker at GitHub:
+
+ <https://github.com/bitcoin/bitcoin/issues>
+
+To receive security and update notifications, please subscribe to:
+
+ <https://bitcoincore.org/en/list/announcements/join/>
+
+How to Upgrade
+==============
+
+If you are running an older version, shut it down. Wait until it has completely
+shut down (which might take a few minutes in some cases), then run the
+installer (on Windows) or just copy over `/Applications/Bitcoin-Qt` (on Mac)
+or `bitcoind`/`bitcoin-qt` (on Linux).
+
+Upgrading directly from a version of Bitcoin Core that has reached its EOL is
+possible, but it might take some time if the data directory needs to be migrated. Old
+wallet versions of Bitcoin Core are generally supported.
+
+Compatibility
+==============
+
+Bitcoin Core is supported and extensively tested on operating systems
+using the Linux kernel, macOS 10.14+, and Windows 7 and newer. Bitcoin
+Core should also work on most other Unix-like systems but is not as
+frequently tested on them. It is not recommended to use Bitcoin Core on
+unsupported systems.
+
+From Bitcoin Core 22.0 onwards, macOS versions earlier than 10.14 are no longer supported.
+
+Notable changes
+===============
+
+P2P and network changes
+-----------------------
+- Added support for running Bitcoin Core as an
+ [I2P (Invisible Internet Project)](https://en.wikipedia.org/wiki/I2P) service
+ and connect to such services. See [i2p.md](https://github.com/bitcoin/bitcoin/blob/22.x/doc/i2p.md) for details. (#20685)
+- This release removes support for Tor version 2 hidden services in favor of Tor
+ v3 only, as the Tor network [dropped support for Tor
+ v2](https://blog.torproject.org/v2-deprecation-timeline) with the release of
+ Tor version 0.4.6. Henceforth, Bitcoin Core ignores Tor v2 addresses; it
+ neither rumors them over the network to other peers, nor stores them in memory
+ or to `peers.dat`. (#22050)
+
+- Added NAT-PMP port mapping support via
+ [`libnatpmp`](https://miniupnp.tuxfamily.org/libnatpmp.html). (#18077)
+
+New and Updated RPCs
+--------------------
+
+- Due to [BIP 350](https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki)
+ being implemented, behavior for all RPCs that accept addresses is changed when
+ a native witness version 1 (or higher) is passed. These now require a Bech32m
+ encoding instead of a Bech32 one, and Bech32m encoding will be used for such
+ addresses in RPC output as well. No version 1 addresses should be created
+ for mainnet until consensus rules are adopted that give them meaning
+ (as will happen through [BIP 341](https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki)).
+ Once that happens, Bech32m is expected to be used for them, so this shouldn't
+ affect any production systems, but may be observed on other networks where such
+ addresses already have meaning (like signet). (#20861)
+
+- The `getpeerinfo` RPC returns two new boolean fields, `bip152_hb_to` and
+ `bip152_hb_from`, that respectively indicate whether we selected a peer to be
+ in compact blocks high-bandwidth mode or whether a peer selected us as a
+ compact blocks high-bandwidth peer. High-bandwidth peers send new block
+ announcements via a `cmpctblock` message rather than the usual inv/headers
+ announcements. See BIP 152 for more details. (#19776)
+
+- `getpeerinfo` no longer returns the following fields: `addnode`, `banscore`,
+ and `whitelisted`, which were previously deprecated in 0.21. Instead of
+ `addnode`, the `connection_type` field returns manual. Instead of
+ `whitelisted`, the `permissions` field indicates if the peer has special
+ privileges. The `banscore` field has simply been removed. (#20755)
+
+- The following RPCs: `gettxout`, `getrawtransaction`, `decoderawtransaction`,
+ `decodescript`, `gettransaction`, and REST endpoints: `/rest/tx`,
+ `/rest/getutxos`, `/rest/block` deprecated the following fields (which are no
+ longer returned in the responses by default): `addresses`, `reqSigs`.
+ The `-deprecatedrpc=addresses` flag must be passed for these fields to be
+ included in the RPC response. This flag/option will be available only for this major release, after which
+ the deprecation will be removed entirely. Note that these fields are attributes of
+ the `scriptPubKey` object returned in the RPC response. However, in the response
+ of `decodescript` these fields are top-level attributes, and included again as attributes
+ of the `scriptPubKey` object. (#20286)
+
+- When creating a hex-encoded bitcoin transaction using the `bitcoin-tx` utility
+ with the `-json` option set, the following fields: `addresses`, `reqSigs` are no longer
+ returned in the tx output of the response. (#20286)
+
+- The `listbanned` RPC now returns two new numeric fields: `ban_duration` and `time_remaining`.
+ Respectively, these new fields indicate the duration of a ban and the time remaining until a ban expires,
+ both in seconds. Additionally, the `ban_created` field is repositioned to come before `banned_until`. (#21602)
+
+- The `setban` RPC can ban onion addresses again. This fixes a regression introduced in version 0.21.0. (#20852)
+
+- The `getnodeaddresses` RPC now returns a "network" field indicating the
+ network type (ipv4, ipv6, onion, or i2p) for each address. (#21594)
+
+- `getnodeaddresses` now also accepts a "network" argument (ipv4, ipv6, onion,
+ or i2p) to return only addresses of the specified network. (#21843)
+
+- The `testmempoolaccept` RPC now accepts multiple transactions (still experimental at the moment,
+ API may be unstable). This is intended for testing transaction packages with dependency
+ relationships; it is not recommended for batch-validating independent transactions. In addition to
+ mempool policy, package policies apply: the list cannot contain more than 25 transactions or have a
+ total size exceeding 101K virtual bytes, and cannot conflict with (spend the same inputs as) each other or
+ the mempool, even if it would be a valid BIP125 replace-by-fee. There are some known limitations to
+ the accuracy of the test accept: it's possible for `testmempoolaccept` to return "allowed"=True for a
+ group of transactions, but "too-long-mempool-chain" if they are actually submitted. (#20833)
+
+- `addmultisigaddress` and `createmultisig` now support up to 20 keys for
+ Segwit addresses. (#20867)
+
+Changes to Wallet or GUI related RPCs can be found in the GUI or Wallet section below.
+
+Build System
+------------
+
+- Release binaries are now produced using the new `guix`-based build system.
+ The [/doc/release-process.md](/doc/release-process.md) document has been updated accordingly.
+
+Files
+-----
+
+- The list of banned hosts and networks (via `setban` RPC) is now saved on disk
+ in JSON format in `banlist.json` instead of `banlist.dat`. `banlist.dat` is
+ only read on startup if `banlist.json` is not present. Changes are only written to the new
+ `banlist.json`. A future version of Bitcoin Core may completely ignore
+ `banlist.dat`. (#20966)
+
+New settings
+------------
+
+- The `-natpmp` option has been added to use NAT-PMP to map the listening port.
+ If both UPnP and NAT-PMP are enabled, a successful allocation from UPnP
+ prevails over one from NAT-PMP. (#18077)
+
+Updated settings
+----------------
+
+Changes to Wallet or GUI related settings can be found in the GUI or Wallet section below.
+
+- Passing an invalid `-rpcauth` argument now cause bitcoind to fail to start. (#20461)
+
+Tools and Utilities
+-------------------
+
+- A new CLI `-addrinfo` command returns the number of addresses known to the
+ node per network type (including Tor v2 versus v3) and total. This can be
+ useful to see if the node knows enough addresses in a network to use options
+ like `-onlynet=<network>` or to upgrade to this release of Bitcoin Core 22.0
+ that supports Tor v3 only. (#21595)
+
+- A new `-rpcwaittimeout` argument to `bitcoin-cli` sets the timeout
+ in seconds to use with `-rpcwait`. If the timeout expires,
+ `bitcoin-cli` will report a failure. (#21056)
+
+Wallet
+------
+
+- External signers such as hardware wallets can now be used through the new RPC methods `enumeratesigners` and `displayaddress`. Support is also added to the `send` RPC call. This feature is experimental. See [external-signer.md](https://github.com/bitcoin/bitcoin/blob/22.x/doc/external-signer.md) for details. (#16546)
+
+- A new `listdescriptors` RPC is available to inspect the contents of descriptor-enabled wallets.
+ The RPC returns public versions of all imported descriptors, including their timestamp and flags.
+ For ranged descriptors, it also returns the range boundaries and the next index to generate addresses from. (#20226)
+
+- The `bumpfee` RPC is not available with wallets that have private keys
+ disabled. `psbtbumpfee` can be used instead. (#20891)
+
+- The `fundrawtransaction`, `send` and `walletcreatefundedpsbt` RPCs now support an `include_unsafe` option
+ that when `true` allows using unsafe inputs to fund the transaction.
+ Note that the resulting transaction may become invalid if one of the unsafe inputs disappears.
+ If that happens, the transaction must be funded with different inputs and republished. (#21359)
+
+- We now support up to 20 keys in `multi()` and `sortedmulti()` descriptors
+ under `wsh()`. (#20867)
+
+- Taproot descriptors can be imported into the wallet only after activation has occurred on the network (e.g. mainnet, testnet, signet) in use. See [descriptors.md](https://github.com/bitcoin/bitcoin/blob/22.x/doc/descriptors.md) for supported descriptors.
+
+GUI changes
+-----------
+
+- External signers such as hardware wallets can now be used. These require an external tool such as [HWI](https://github.com/bitcoin-core/HWI) to be installed and configured under Options -> Wallet. When creating a new wallet a new option "External signer" will appear in the dialog. If the device is detected, its name is suggested as the wallet name. The watch-only keys are then automatically imported. Receive addresses can be verified on the device. The send dialog will automatically use the connected device. This feature is experimental and the UI may freeze for a few seconds when performing these actions.
+
+Low-level changes
+=================
+
+RPC
+---
+
+- The RPC server can process a limited number of simultaneous RPC requests.
+ Previously, if this limit was exceeded, the RPC server would respond with
+ [status code 500 (`HTTP_INTERNAL_SERVER_ERROR`)](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_server_errors).
+ Now it returns status code 503 (`HTTP_SERVICE_UNAVAILABLE`). (#18335)
+
+- Error codes have been updated to be more accurate for the following error cases (#18466):
+ - `signmessage` now returns RPC_INVALID_ADDRESS_OR_KEY (-5) if the
+ passed address is invalid. Previously returned RPC_TYPE_ERROR (-3).
+ - `verifymessage` now returns RPC_INVALID_ADDRESS_OR_KEY (-5) if the
+ passed address is invalid. Previously returned RPC_TYPE_ERROR (-3).
+ - `verifymessage` now returns RPC_TYPE_ERROR (-3) if the passed signature
+ is malformed. Previously returned RPC_INVALID_ADDRESS_OR_KEY (-5).
+
+Tests
+-----
+
+22.0 change log
+===============
+
+A detailed list of changes in this version follows. To keep the list to a manageable length, small refactors and typo fixes are not included, and similar changes are sometimes condensed into one line.
+
+### Consensus
+- bitcoin/bitcoin#19438 Introduce deploymentstatus (ajtowns)
+- bitcoin/bitcoin#20207 Follow-up extra comments on taproot code and tests (sipa)
+- bitcoin/bitcoin#21330 Deal with missing data in signature hashes more consistently (sipa)
+
+### Policy
+- bitcoin/bitcoin#18766 Disable fee estimation in blocksonly mode (by removing the fee estimates global) (darosior)
+- bitcoin/bitcoin#20497 Add `MAX_STANDARD_SCRIPTSIG_SIZE` to policy (sanket1729)
+- bitcoin/bitcoin#20611 Move `TX_MAX_STANDARD_VERSION` to policy (MarcoFalke)
+
+### Mining
+- bitcoin/bitcoin#19937, bitcoin/bitcoin#20923 Signet mining utility (ajtowns)
+
+### Block and transaction handling
+- bitcoin/bitcoin#14501 Fix possible data race when committing block files (luke-jr)
+- bitcoin/bitcoin#15946 Allow maintaining the blockfilterindex when using prune (jonasschnelli)
+- bitcoin/bitcoin#18710 Add local thread pool to CCheckQueue (hebasto)
+- bitcoin/bitcoin#19521 Coinstats Index (fjahr)
+- bitcoin/bitcoin#19806 UTXO snapshot activation (jamesob)
+- bitcoin/bitcoin#19905 Remove dead CheckForkWarningConditionsOnNewFork (MarcoFalke)
+- bitcoin/bitcoin#19935 Move SaltedHashers to separate file and add some new ones (achow101)
+- bitcoin/bitcoin#20054 Remove confusing and useless "unexpected version" warning (MarcoFalke)
+- bitcoin/bitcoin#20519 Handle rename failure in `DumpMempool(…)` by using the `RenameOver(…)` return value (practicalswift)
+- bitcoin/bitcoin#20749, bitcoin/bitcoin#20750, bitcoin/bitcoin#21055, bitcoin/bitcoin#21270, bitcoin/bitcoin#21525, bitcoin/bitcoin#21391, bitcoin/bitcoin#21767, bitcoin/bitcoin#21866 Prune `g_chainman` usage (dongcarl)
+- bitcoin/bitcoin#20833 rpc/validation: enable packages through testmempoolaccept (glozow)
+- bitcoin/bitcoin#20834 Locks and docs in ATMP and CheckInputsFromMempoolAndCache (glozow)
+- bitcoin/bitcoin#20854 Remove unnecessary try-block (amitiuttarwar)
+- bitcoin/bitcoin#20868 Remove redundant check on pindex (jarolrod)
+- bitcoin/bitcoin#20921 Don't try to invalidate genesis block in CChainState::InvalidateBlock (theStack)
+- bitcoin/bitcoin#20972 Locks: Annotate CTxMemPool::check to require `cs_main` (dongcarl)
+- bitcoin/bitcoin#21009 Remove RewindBlockIndex logic (dhruv)
+- bitcoin/bitcoin#21025 Guard chainman chainstates with `cs_main` (dongcarl)
+- bitcoin/bitcoin#21202 Two small clang lock annotation improvements (amitiuttarwar)
+- bitcoin/bitcoin#21523 Run VerifyDB on all chainstates (jamesob)
+- bitcoin/bitcoin#21573 Update libsecp256k1 subtree to latest master (sipa)
+- bitcoin/bitcoin#21582, bitcoin/bitcoin#21584, bitcoin/bitcoin#21585 Fix assumeutxo crashes (MarcoFalke)
+- bitcoin/bitcoin#21681 Fix ActivateSnapshot to use hardcoded nChainTx (jamesob)
+- bitcoin/bitcoin#21796 index: Avoid async shutdown on init error (MarcoFalke)
+- bitcoin/bitcoin#21946 Document and test lack of inherited signaling in RBF policy (ariard)
+- bitcoin/bitcoin#22084 Package testmempoolaccept followups (glozow)
+- bitcoin/bitcoin#22102 Remove `Warning:` from warning message printed for unknown new rules (prayank23)
+- bitcoin/bitcoin#22112 Force port 0 in I2P (vasild)
+- bitcoin/bitcoin#22135 CRegTestParams: Use `args` instead of `gArgs` (kiminuo)
+- bitcoin/bitcoin#22146 Reject invalid coin height and output index when loading assumeutxo (MarcoFalke)
+- bitcoin/bitcoin#22253 Distinguish between same tx and same-nonwitness-data tx in mempool (glozow)
+- bitcoin/bitcoin#22261 Two small fixes to node broadcast logic (jnewbery)
+- bitcoin/bitcoin#22415 Make `m_mempool` optional in CChainState (jamesob)
+- bitcoin/bitcoin#22499 Update assumed chain params (sriramdvt)
+- bitcoin/bitcoin#22589 net, doc: update I2P hardcoded seeds and docs for 22.0 (jonatack)
+
+### P2P protocol and network code
+- bitcoin/bitcoin#18077 Add NAT-PMP port forwarding support (hebasto)
+- bitcoin/bitcoin#18722 addrman: improve performance by using more suitable containers (vasild)
+- bitcoin/bitcoin#18819 Replace `cs_feeFilter` with simple std::atomic (MarcoFalke)
+- bitcoin/bitcoin#19203 Add regression fuzz harness for CVE-2017-18350. Add FuzzedSocket (practicalswift)
+- bitcoin/bitcoin#19288 fuzz: Add fuzzing harness for TorController (practicalswift)
+- bitcoin/bitcoin#19415 Make DNS lookup mockable, add fuzzing harness (practicalswift)
+- bitcoin/bitcoin#19509 Per-Peer Message Capture (troygiorshev)
+- bitcoin/bitcoin#19763 Don't try to relay to the address' originator (vasild)
+- bitcoin/bitcoin#19771 Replace enum CConnMan::NumConnections with enum class ConnectionDirection (luke-jr)
+- bitcoin/bitcoin#19776 net, rpc: expose high bandwidth mode state via getpeerinfo (theStack)
+- bitcoin/bitcoin#19832 Put disconnecting logs into BCLog::NET category (hebasto)
+- bitcoin/bitcoin#19858 Periodically make block-relay connections and sync headers (sdaftuar)
+- bitcoin/bitcoin#19884 No delay in adding fixed seeds if -dnsseed=0 and peers.dat is empty (dhruv)
+- bitcoin/bitcoin#20079 Treat handshake misbehavior like unknown message (MarcoFalke)
+- bitcoin/bitcoin#20138 Assume that SetCommonVersion is called at most once per peer (MarcoFalke)
+- bitcoin/bitcoin#20162 p2p: declare Announcement::m_state as uint8_t, add getter/setter (jonatack)
+- bitcoin/bitcoin#20197 Protect onions in AttemptToEvictConnection(), add eviction protection test coverage (jonatack)
+- bitcoin/bitcoin#20210 assert `CNode::m_inbound_onion` is inbound in ctor, add getter, unit tests (jonatack)
+- bitcoin/bitcoin#20228 addrman: Make addrman a top-level component (jnewbery)
+- bitcoin/bitcoin#20234 Don't bind on 0.0.0.0 if binds are restricted to Tor (vasild)
+- bitcoin/bitcoin#20477 Add unit testing of node eviction logic (practicalswift)
+- bitcoin/bitcoin#20516 Well-defined CAddress disk serialization, and addrv2 anchors.dat (sipa)
+- bitcoin/bitcoin#20557 addrman: Fix new table bucketing during unserialization (jnewbery)
+- bitcoin/bitcoin#20561 Periodically clear `m_addr_known` (sdaftuar)
+- bitcoin/bitcoin#20599 net processing: Tolerate sendheaders and sendcmpct messages before verack (jnewbery)
+- bitcoin/bitcoin#20616 Check CJDNS address is valid (lontivero)
+- bitcoin/bitcoin#20617 Remove `m_is_manual_connection` from CNodeState (ariard)
+- bitcoin/bitcoin#20624 net processing: Remove nStartingHeight check from block relay (jnewbery)
+- bitcoin/bitcoin#20651 Make p2p recv buffer timeout 20 minutes for all peers (jnewbery)
+- bitcoin/bitcoin#20661 Only select from addrv2-capable peers for torv3 address relay (sipa)
+- bitcoin/bitcoin#20685 Add I2P support using I2P SAM (vasild)
+- bitcoin/bitcoin#20690 Clean up logging of outbound connection type (sdaftuar)
+- bitcoin/bitcoin#20721 Move ping data to `net_processing` (jnewbery)
+- bitcoin/bitcoin#20724 Cleanup of -debug=net log messages (ajtowns)
+- bitcoin/bitcoin#20747 net processing: Remove dropmessagestest (jnewbery)
+- bitcoin/bitcoin#20764 cli -netinfo peer connections dashboard updates 🎄 ✨ (jonatack)
+- bitcoin/bitcoin#20788 add RAII socket and use it instead of bare SOCKET (vasild)
+- bitcoin/bitcoin#20791 remove unused legacyWhitelisted in AcceptConnection() (jonatack)
+- bitcoin/bitcoin#20816 Move RecordBytesSent() call out of `cs_vSend` lock (jnewbery)
+- bitcoin/bitcoin#20845 Log to net debug in MaybeDiscourageAndDisconnect except for noban and manual peers (MarcoFalke)
+- bitcoin/bitcoin#20864 Move SocketSendData lock annotation to header (MarcoFalke)
+- bitcoin/bitcoin#20965 net, rpc: return `NET_UNROUTABLE` as `not_publicly_routable`, automate helps (jonatack)
+- bitcoin/bitcoin#20966 banman: save the banlist in a JSON format on disk (vasild)
+- bitcoin/bitcoin#21015 Make all of `net_processing` (and some of net) use std::chrono types (dhruv)
+- bitcoin/bitcoin#21029 bitcoin-cli: Correct docs (no "generatenewaddress" exists) (luke-jr)
+- bitcoin/bitcoin#21148 Split orphan handling from `net_processing` into txorphanage (ajtowns)
+- bitcoin/bitcoin#21162 Net Processing: Move RelayTransaction() into PeerManager (jnewbery)
+- bitcoin/bitcoin#21167 make `CNode::m_inbound_onion` public, initialize explicitly (jonatack)
+- bitcoin/bitcoin#21186 net/net processing: Move addr data into `net_processing` (jnewbery)
+- bitcoin/bitcoin#21187 Net processing: Only call PushAddress() from `net_processing` (jnewbery)
+- bitcoin/bitcoin#21198 Address outstanding review comments from PR20721 (jnewbery)
+- bitcoin/bitcoin#21222 log: Clarify log message when file does not exist (MarcoFalke)
+- bitcoin/bitcoin#21235 Clarify disconnect log message in ProcessGetBlockData, remove send bool (MarcoFalke)
+- bitcoin/bitcoin#21236 Net processing: Extract `addr` send functionality into MaybeSendAddr() (jnewbery)
+- bitcoin/bitcoin#21261 update inbound eviction protection for multiple networks, add I2P peers (jonatack)
+- bitcoin/bitcoin#21328 net, refactor: pass uint16 CService::port as uint16 (jonatack)
+- bitcoin/bitcoin#21387 Refactor sock to add I2P fuzz and unit tests (vasild)
+- bitcoin/bitcoin#21395 Net processing: Remove unused CNodeState.address member (jnewbery)
+- bitcoin/bitcoin#21407 i2p: limit the size of incoming messages (vasild)
+- bitcoin/bitcoin#21506 p2p, refactor: make NetPermissionFlags an enum class (jonatack)
+- bitcoin/bitcoin#21509 Don't send FEEFILTER in blocksonly mode (mzumsande)
+- bitcoin/bitcoin#21560 Add Tor v3 hardcoded seeds (laanwj)
+- bitcoin/bitcoin#21563 Restrict period when `cs_vNodes` mutex is locked (hebasto)
+- bitcoin/bitcoin#21564 Avoid calling getnameinfo when formatting IPv4 addresses in CNetAddr::ToStringIP (practicalswift)
+- bitcoin/bitcoin#21631 i2p: always check the return value of Sock::Wait() (vasild)
+- bitcoin/bitcoin#21644 p2p, bugfix: use NetPermissions::HasFlag() in CConnman::Bind() (jonatack)
+- bitcoin/bitcoin#21659 flag relevant Sock methods with [[nodiscard]] (vasild)
+- bitcoin/bitcoin#21750 remove unnecessary check of `CNode::cs_vSend` (vasild)
+- bitcoin/bitcoin#21756 Avoid calling `getnameinfo` when formatting IPv6 addresses in `CNetAddr::ToStringIP` (practicalswift)
+- bitcoin/bitcoin#21775 Limit `m_block_inv_mutex` (MarcoFalke)
+- bitcoin/bitcoin#21825 Add I2P hardcoded seeds (jonatack)
+- bitcoin/bitcoin#21843 p2p, rpc: enable GetAddr, GetAddresses, and getnodeaddresses by network (jonatack)
+- bitcoin/bitcoin#21845 net processing: Don't require locking `cs_main` before calling RelayTransactions() (jnewbery)
+- bitcoin/bitcoin#21872 Sanitize message type for logging (laanwj)
+- bitcoin/bitcoin#21914 Use stronger AddLocal() for our I2P address (vasild)
+- bitcoin/bitcoin#21985 Return IPv6 scope id in `CNetAddr::ToStringIP()` (laanwj)
+- bitcoin/bitcoin#21992 Remove -feefilter option (amadeuszpawlik)
+- bitcoin/bitcoin#21996 Pass strings to NetPermissions::TryParse functions by const ref (jonatack)
+- bitcoin/bitcoin#22013 ignore block-relay-only peers when skipping DNS seed (ajtowns)
+- bitcoin/bitcoin#22050 Remove tor v2 support (jonatack)
+- bitcoin/bitcoin#22096 AddrFetch - don't disconnect on self-announcements (mzumsande)
+- bitcoin/bitcoin#22141 net processing: Remove hash and fValidatedHeaders from QueuedBlock (jnewbery)
+- bitcoin/bitcoin#22144 Randomize message processing peer order (sipa)
+- bitcoin/bitcoin#22147 Protect last outbound HB compact block peer (sdaftuar)
+- bitcoin/bitcoin#22179 Torv2 removal followups (vasild)
+- bitcoin/bitcoin#22211 Relay I2P addresses even if not reachable (by us) (vasild)
+- bitcoin/bitcoin#22284 Performance improvements to ProtectEvictionCandidatesByRatio() (jonatack)
+- bitcoin/bitcoin#22387 Rate limit the processing of rumoured addresses (sipa)
+- bitcoin/bitcoin#22455 addrman: detect on-disk corrupted nNew and nTried during unserialization (vasild)
+
+### Wallet
+- bitcoin/bitcoin#15710 Catch `ios_base::failure` specifically (Bushstar)
+- bitcoin/bitcoin#16546 External signer support - Wallet Box edition (Sjors)
+- bitcoin/bitcoin#17331 Use effective values throughout coin selection (achow101)
+- bitcoin/bitcoin#18418 Increase `OUTPUT_GROUP_MAX_ENTRIES` to 100 (fjahr)
+- bitcoin/bitcoin#18842 Mark replaced tx to not be in the mempool anymore (MarcoFalke)
+- bitcoin/bitcoin#19136 Add `parent_desc` to `getaddressinfo` (achow101)
+- bitcoin/bitcoin#19137 wallettool: Add dump and createfromdump commands (achow101)
+- bitcoin/bitcoin#19651 `importdescriptor`s update existing (S3RK)
+- bitcoin/bitcoin#20040 Refactor OutputGroups to handle fees and spending eligibility on grouping (achow101)
+- bitcoin/bitcoin#20202 Make BDB support optional (achow101)
+- bitcoin/bitcoin#20226, bitcoin/bitcoin#21277, - bitcoin/bitcoin#21063 Add `listdescriptors` command (S3RK)
+- bitcoin/bitcoin#20267 Disable and fix tests for when BDB is not compiled (achow101)
+- bitcoin/bitcoin#20275 List all wallets in non-SQLite and non-BDB builds (ryanofsky)
+- bitcoin/bitcoin#20365 wallettool: Add parameter to create descriptors wallet (S3RK)
+- bitcoin/bitcoin#20403 `upgradewallet` fixes, improvements, test coverage (jonatack)
+- bitcoin/bitcoin#20448 `unloadwallet`: Allow specifying `wallet_name` param matching RPC endpoint wallet (luke-jr)
+- bitcoin/bitcoin#20536 Error with "Transaction too large" if the funded tx will end up being too large after signing (achow101)
+- bitcoin/bitcoin#20687 Add missing check for -descriptors wallet tool option (MarcoFalke)
+- bitcoin/bitcoin#20952 Add BerkeleyDB version sanity check at init time (laanwj)
+- bitcoin/bitcoin#21127 Load flags before everything else (Sjors)
+- bitcoin/bitcoin#21141 Add new format string placeholders for walletnotify (maayank)
+- bitcoin/bitcoin#21238 A few descriptor improvements to prepare for Taproot support (sipa)
+- bitcoin/bitcoin#21302 `createwallet` examples for descriptor wallets (S3RK)
+- bitcoin/bitcoin#21329 descriptor wallet: Cache last hardened xpub and use in normalized descriptors (achow101)
+- bitcoin/bitcoin#21365 Basic Taproot signing support for descriptor wallets (sipa)
+- bitcoin/bitcoin#21417 Misc external signer improvement and HWI 2 support (Sjors)
+- bitcoin/bitcoin#21467 Move external signer out of wallet module (Sjors)
+- bitcoin/bitcoin#21572 Fix wrong wallet RPC context set after #21366 (ryanofsky)
+- bitcoin/bitcoin#21574 Drop JSONRPCRequest constructors after #21366 (ryanofsky)
+- bitcoin/bitcoin#21666 Miscellaneous external signer changes (fanquake)
+- bitcoin/bitcoin#21759 Document coin selection code (glozow)
+- bitcoin/bitcoin#21786 Ensure sat/vB feerates are in range (mantissa of 3) (jonatack)
+- bitcoin/bitcoin#21944 Fix issues when `walletdir` is root directory (prayank23)
+- bitcoin/bitcoin#22042 Replace size/weight estimate tuple with struct for named fields (instagibbs)
+- bitcoin/bitcoin#22051 Basic Taproot derivation support for descriptors (sipa)
+- bitcoin/bitcoin#22154 Add OutputType::BECH32M and related wallet support for fetching bech32m addresses (achow101)
+- bitcoin/bitcoin#22156 Allow tr() import only when Taproot is active (achow101)
+- bitcoin/bitcoin#22166 Add support for inferring tr() descriptors (sipa)
+- bitcoin/bitcoin#22173 Do not load external signers wallets when unsupported (achow101)
+- bitcoin/bitcoin#22308 Add missing BlockUntilSyncedToCurrentChain (MarcoFalke)
+- bitcoin/bitcoin#22334 Do not spam about non-existent spk managers (S3RK)
+- bitcoin/bitcoin#22379 Erase spkmans rather than setting to nullptr (achow101)
+- bitcoin/bitcoin#22421 Make IsSegWitOutput return true for taproot outputs (sipa)
+- bitcoin/bitcoin#22461 Change ScriptPubKeyMan::Upgrade default to True (achow101)
+- bitcoin/bitcoin#22492 Reorder locks in dumpwallet to avoid lock order assertion (achow101)
+- bitcoin/bitcoin#22686 Use GetSelectionAmount in ApproximateBestSubset (achow101)
+
+### RPC and other APIs
+- bitcoin/bitcoin#18335, bitcoin/bitcoin#21484 cli: Print useful error if bitcoind rpc work queue exceeded (LarryRuane)
+- bitcoin/bitcoin#18466 Fix invalid parameter error codes for `{sign,verify}message` RPCs (theStack)
+- bitcoin/bitcoin#18772 Calculate fees in `getblock` using BlockUndo data (robot-visions)
+- bitcoin/bitcoin#19033 http: Release work queue after event base finish (promag)
+- bitcoin/bitcoin#19055 Add MuHash3072 implementation (fjahr)
+- bitcoin/bitcoin#19145 Add `hash_type` MUHASH for gettxoutsetinfo (fjahr)
+- bitcoin/bitcoin#19847 Avoid duplicate set lookup in `gettxoutproof` (promag)
+- bitcoin/bitcoin#20286 Deprecate `addresses` and `reqSigs` from RPC outputs (mjdietzx)
+- bitcoin/bitcoin#20459 Fail to return undocumented return values (MarcoFalke)
+- bitcoin/bitcoin#20461 Validate `-rpcauth` arguments (promag)
+- bitcoin/bitcoin#20556 Properly document return values (`submitblock`, `gettxout`, `getblocktemplate`, `scantxoutset`) (MarcoFalke)
+- bitcoin/bitcoin#20755 Remove deprecated fields from `getpeerinfo` (amitiuttarwar)
+- bitcoin/bitcoin#20832 Better error messages for invalid addresses (eilx2)
+- bitcoin/bitcoin#20867 Support up to 20 keys for multisig under Segwit context (darosior)
+- bitcoin/bitcoin#20877 cli: `-netinfo` user help and argument parsing improvements (jonatack)
+- bitcoin/bitcoin#20891 Remove deprecated bumpfee behavior (achow101)
+- bitcoin/bitcoin#20916 Return wtxid from `testmempoolaccept` (MarcoFalke)
+- bitcoin/bitcoin#20917 Add missing signet mentions in network name lists (theStack)
+- bitcoin/bitcoin#20941 Document `RPC_TRANSACTION_ALREADY_IN_CHAIN` exception (jarolrod)
+- bitcoin/bitcoin#20944 Return total fee in `getmempoolinfo` (MarcoFalke)
+- bitcoin/bitcoin#20964 Add specific error code for "wallet already loaded" (laanwj)
+- bitcoin/bitcoin#21053 Document {previous,next}blockhash as optional (theStack)
+- bitcoin/bitcoin#21056 Add a `-rpcwaittimeout` parameter to limit time spent waiting (cdecker)
+- bitcoin/bitcoin#21192 cli: Treat high detail levels as maximum in `-netinfo` (laanwj)
+- bitcoin/bitcoin#21311 Document optional fields for `getchaintxstats` result (theStack)
+- bitcoin/bitcoin#21359 `include_unsafe` option for fundrawtransaction (t-bast)
+- bitcoin/bitcoin#21426 Remove `scantxoutset` EXPERIMENTAL warning (jonatack)
+- bitcoin/bitcoin#21544 Missing doc updates for bumpfee psbt update (MarcoFalke)
+- bitcoin/bitcoin#21594 Add `network` field to `getnodeaddresses` (jonatack)
+- bitcoin/bitcoin#21595, bitcoin/bitcoin#21753 cli: Create `-addrinfo` (jonatack)
+- bitcoin/bitcoin#21602 Add additional ban time fields to `listbanned` (jarolrod)
+- bitcoin/bitcoin#21679 Keep default argument value in correct type (promag)
+- bitcoin/bitcoin#21718 Improve error message for `getblock` invalid datatype (klementtan)
+- bitcoin/bitcoin#21913 RPCHelpMan fixes (kallewoof)
+- bitcoin/bitcoin#22021 `bumpfee`/`psbtbumpfee` fixes and updates (jonatack)
+- bitcoin/bitcoin#22043 `addpeeraddress` test coverage, code simplify/constness (jonatack)
+- bitcoin/bitcoin#22327 cli: Avoid truncating `-rpcwaittimeout` (MarcoFalke)
+
+### GUI
+- bitcoin/bitcoin#18948 Call setParent() in the parent's context (hebasto)
+- bitcoin/bitcoin#20482 Add depends qt fix for ARM macs (jonasschnelli)
+- bitcoin/bitcoin#21836 scripted-diff: Replace three dots with ellipsis in the ui strings (hebasto)
+- bitcoin/bitcoin#21935 Enable external signer support for GUI builds (Sjors)
+- bitcoin/bitcoin#22133 Make QWindowsVistaStylePlugin available again (regression) (hebasto)
+- bitcoin-core/gui#4 UI external signer support (e.g. hardware wallet) (Sjors)
+- bitcoin-core/gui#13 Hide peer detail view if multiple are selected (promag)
+- bitcoin-core/gui#18 Add peertablesortproxy module (hebasto)
+- bitcoin-core/gui#21 Improve pruning tooltip (fluffypony, BitcoinErrorLog)
+- bitcoin-core/gui#72 Log static plugins meta data and used style (hebasto)
+- bitcoin-core/gui#79 Embed monospaced font (hebasto)
+- bitcoin-core/gui#85 Remove unused "What's This" button in dialogs on Windows OS (hebasto)
+- bitcoin-core/gui#115 Replace "Hide tray icon" option with positive "Show tray icon" one (hebasto)
+- bitcoin-core/gui#118 Remove BDB version from the Information tab (hebasto)
+- bitcoin-core/gui#121 Early subscribe core signals in transaction table model (promag)
+- bitcoin-core/gui#123 Do not accept command while executing another one (hebasto)
+- bitcoin-core/gui#125 Enable changing the autoprune block space size in intro dialog (luke-jr)
+- bitcoin-core/gui#138 Unlock encrypted wallet "OK" button bugfix (mjdietzx)
+- bitcoin-core/gui#139 doc: Improve gui/src/qt README.md (jarolrod)
+- bitcoin-core/gui#154 Support macOS Dark mode (goums, Uplab)
+- bitcoin-core/gui#162 Add network to peers window and peer details (jonatack)
+- bitcoin-core/gui#163, bitcoin-core/gui#180 Peer details: replace Direction with Connection Type (jonatack)
+- bitcoin-core/gui#164 Handle peer addition/removal in a right way (hebasto)
+- bitcoin-core/gui#165 Save QSplitter state in QSettings (hebasto)
+- bitcoin-core/gui#173 Follow Qt docs when implementing rowCount and columnCount (hebasto)
+- bitcoin-core/gui#179 Add Type column to peers window, update peer details name/tooltip (jonatack)
+- bitcoin-core/gui#186 Add information to "Confirm fee bump" window (prayank23)
+- bitcoin-core/gui#189 Drop workaround for QTBUG-42503 which was fixed in Qt 5.5.0 (prusnak)
+- bitcoin-core/gui#194 Save/restore RPCConsole geometry only for window (hebasto)
+- bitcoin-core/gui#202 Fix right panel toggle in peers tab (RandyMcMillan)
+- bitcoin-core/gui#203 Display plain "Inbound" in peer details (jonatack)
+- bitcoin-core/gui#204 Drop buggy TableViewLastColumnResizingFixer class (hebasto)
+- bitcoin-core/gui#205, bitcoin-core/gui#229 Save/restore TransactionView and recentRequestsView tables column sizes (hebasto)
+- bitcoin-core/gui#206 Display fRelayTxes and `bip152_highbandwidth_{to, from}` in peer details (jonatack)
+- bitcoin-core/gui#213 Add Copy Address Action to Payment Requests (jarolrod)
+- bitcoin-core/gui#214 Disable requests context menu actions when appropriate (jarolrod)
+- bitcoin-core/gui#217 Make warning label look clickable (jarolrod)
+- bitcoin-core/gui#219 Prevent the main window popup menu (hebasto)
+- bitcoin-core/gui#220 Do not translate file extensions (hebasto)
+- bitcoin-core/gui#221 RPCConsole translatable string fixes and improvements (jonatack)
+- bitcoin-core/gui#226 Add "Last Block" and "Last Tx" rows to peer details area (jonatack)
+- bitcoin-core/gui#233 qt test: Don't bind to regtest port (achow101)
+- bitcoin-core/gui#243 Fix issue when disabling the auto-enabled blank wallet checkbox (jarolrod)
+- bitcoin-core/gui#246 Revert "qt: Use "fusion" style on macOS Big Sur with old Qt" (hebasto)
+- bitcoin-core/gui#248 For values of "Bytes transferred" and "Bytes/s" with 1000-based prefix names use 1000-based divisor instead of 1024-based (wodry)
+- bitcoin-core/gui#251 Improve URI/file handling message (hebasto)
+- bitcoin-core/gui#256 Save/restore column sizes of the tables in the Peers tab (hebasto)
+- bitcoin-core/gui#260 Handle exceptions isntead of crash (hebasto)
+- bitcoin-core/gui#263 Revamp context menus (hebasto)
+- bitcoin-core/gui#271 Don't clear console prompt when font resizing (jarolrod)
+- bitcoin-core/gui#275 Support runtime appearance adjustment on macOS (hebasto)
+- bitcoin-core/gui#276 Elide long strings in their middle in the Peers tab (hebasto)
+- bitcoin-core/gui#281 Set shortcuts for console's resize buttons (jarolrod)
+- bitcoin-core/gui#293 Enable wordWrap for Services (RandyMcMillan)
+- bitcoin-core/gui#296 Do not use QObject::tr plural syntax for numbers with a unit symbol (hebasto)
+- bitcoin-core/gui#297 Avoid unnecessary translations (hebasto)
+- bitcoin-core/gui#298 Peertableview alternating row colors (RandyMcMillan)
+- bitcoin-core/gui#300 Remove progress bar on modal overlay (brunoerg)
+- bitcoin-core/gui#309 Add access to the Peers tab from the network icon (hebasto)
+- bitcoin-core/gui#311 Peers Window rename 'Peer id' to 'Peer' (jarolrod)
+- bitcoin-core/gui#313 Optimize string concatenation by default (hebasto)
+- bitcoin-core/gui#325 Align numbers in the "Peer Id" column to the right (hebasto)
+- bitcoin-core/gui#329 Make console buttons look clickable (jarolrod)
+- bitcoin-core/gui#330 Allow prompt icon to be colorized (jarolrod)
+- bitcoin-core/gui#331 Make RPC console welcome message translation-friendly (hebasto)
+- bitcoin-core/gui#332 Replace disambiguation strings with translator comments (hebasto)
+- bitcoin-core/gui#335 test: Use QSignalSpy instead of QEventLoop (jarolrod)
+- bitcoin-core/gui#343 Improve the GUI responsiveness when progress dialogs are used (hebasto)
+- bitcoin-core/gui#361 Fix GUI segfault caused by bitcoin/bitcoin#22216 (ryanofsky)
+- bitcoin-core/gui#362 Add keyboard shortcuts to context menus (luke-jr)
+- bitcoin-core/gui#366 Dark Mode fixes/portability (luke-jr)
+- bitcoin-core/gui#375 Emit dataChanged signal to dynamically re-sort Peers table (hebasto)
+- bitcoin-core/gui#393 Fix regression in "Encrypt Wallet" menu item (hebasto)
+- bitcoin-core/gui#396 Ensure external signer option remains disabled without signers (achow101)
+- bitcoin-core/gui#406 Handle new added plurals in `bitcoin_en.ts` (hebasto)
+
+### Build system
+- bitcoin/bitcoin#17227 Add Android packaging support (icota)
+- bitcoin/bitcoin#17920 guix: Build support for macOS (dongcarl)
+- bitcoin/bitcoin#18298 Fix Qt processing of configure script for depends with DEBUG=1 (hebasto)
+- bitcoin/bitcoin#19160 multiprocess: Add basic spawn and IPC support (ryanofsky)
+- bitcoin/bitcoin#19504 Bump minimum python version to 3.6 (ajtowns)
+- bitcoin/bitcoin#19522 fix building libconsensus with reduced exports for Darwin targets (fanquake)
+- bitcoin/bitcoin#19683 Pin clang search paths for darwin host (dongcarl)
+- bitcoin/bitcoin#19764 Split boost into build/host packages + bump + cleanup (dongcarl)
+- bitcoin/bitcoin#19817 libtapi 1100.0.11 (fanquake)
+- bitcoin/bitcoin#19846 enable unused member function diagnostic (Zero-1729)
+- bitcoin/bitcoin#19867 Document and cleanup Qt hacks (fanquake)
+- bitcoin/bitcoin#20046 Set `CMAKE_INSTALL_RPATH` for native packages (ryanofsky)
+- bitcoin/bitcoin#20223 Drop the leading 0 from the version number (achow101)
+- bitcoin/bitcoin#20333 Remove `native_biplist` dependency (fanquake)
+- bitcoin/bitcoin#20353 configure: Support -fdebug-prefix-map and -fmacro-prefix-map (ajtowns)
+- bitcoin/bitcoin#20359 Various config.site.in improvements and linting (dongcarl)
+- bitcoin/bitcoin#20413 Require C++17 compiler (MarcoFalke)
+- bitcoin/bitcoin#20419 Set minimum supported macOS to 10.14 (fanquake)
+- bitcoin/bitcoin#20421 miniupnpc 2.2.2 (fanquake)
+- bitcoin/bitcoin#20422 Mac deployment unification (fanquake)
+- bitcoin/bitcoin#20424 Update univalue subtree (MarcoFalke)
+- bitcoin/bitcoin#20449 Fix Windows installer build (achow101)
+- bitcoin/bitcoin#20468 Warn when generating man pages for binaries built from a dirty branch (tylerchambers)
+- bitcoin/bitcoin#20469 Avoid secp256k1.h include from system (dergoegge)
+- bitcoin/bitcoin#20470 Replace genisoimage with xorriso (dongcarl)
+- bitcoin/bitcoin#20471 Use C++17 in depends (fanquake)
+- bitcoin/bitcoin#20496 Drop unneeded macOS framework dependencies (hebasto)
+- bitcoin/bitcoin#20520 Do not force Precompiled Headers (PCH) for building Qt on Linux (hebasto)
+- bitcoin/bitcoin#20549 Support make src/bitcoin-node and src/bitcoin-gui (promag)
+- bitcoin/bitcoin#20565 Ensure PIC build for bdb on Android (BlockMechanic)
+- bitcoin/bitcoin#20594 Fix getauxval calls in randomenv.cpp (jonasschnelli)
+- bitcoin/bitcoin#20603 Update crc32c subtree (MarcoFalke)
+- bitcoin/bitcoin#20609 configure: output notice that test binary is disabled by fuzzing (apoelstra)
+- bitcoin/bitcoin#20619 guix: Quality of life improvements (dongcarl)
+- bitcoin/bitcoin#20629 Improve id string robustness (dongcarl)
+- bitcoin/bitcoin#20641 Use Qt top-level build facilities (hebasto)
+- bitcoin/bitcoin#20650 Drop workaround for a fixed bug in Qt build system (hebasto)
+- bitcoin/bitcoin#20673 Use more legible qmake commands in qt package (hebasto)
+- bitcoin/bitcoin#20684 Define .INTERMEDIATE target once only (hebasto)
+- bitcoin/bitcoin#20720 more robustly check for fcf-protection support (fanquake)
+- bitcoin/bitcoin#20734 Make platform-specific targets available for proper platform builds only (hebasto)
+- bitcoin/bitcoin#20936 build fuzz tests by default (danben)
+- bitcoin/bitcoin#20937 guix: Make nsis reproducible by respecting SOURCE-DATE-EPOCH (dongcarl)
+- bitcoin/bitcoin#20938 fix linking against -latomic when building for riscv (fanquake)
+- bitcoin/bitcoin#20939 fix `RELOC_SECTION` security check for bitcoin-util (fanquake)
+- bitcoin/bitcoin#20963 gitian-linux: Build binaries for 64-bit POWER (continued) (laanwj)
+- bitcoin/bitcoin#21036 gitian: Bump descriptors to focal for 22.0 (fanquake)
+- bitcoin/bitcoin#21045 Adds switch to enable/disable randomized base address in MSVC builds (EthanHeilman)
+- bitcoin/bitcoin#21065 make macOS HOST in download-osx generic (fanquake)
+- bitcoin/bitcoin#21078 guix: only download sources for hosts being built (fanquake)
+- bitcoin/bitcoin#21116 Disable --disable-fuzz-binary for gitian/guix builds (hebasto)
+- bitcoin/bitcoin#21182 remove mostly pointless `BOOST_PROCESS` macro (fanquake)
+- bitcoin/bitcoin#21205 actually fail when Boost is missing (fanquake)
+- bitcoin/bitcoin#21209 use newer source for libnatpmp (fanquake)
+- bitcoin/bitcoin#21226 Fix fuzz binary compilation under windows (danben)
+- bitcoin/bitcoin#21231 Add /opt/homebrew to path to look for boost libraries (fyquah)
+- bitcoin/bitcoin#21239 guix: Add codesignature attachment support for osx+win (dongcarl)
+- bitcoin/bitcoin#21250 Make `HAVE_O_CLOEXEC` available outside LevelDB (bugfix) (theStack)
+- bitcoin/bitcoin#21272 guix: Passthrough `SDK_PATH` into container (dongcarl)
+- bitcoin/bitcoin#21274 assumptions: Assume C++17 (fanquake)
+- bitcoin/bitcoin#21286 Bump minimum Qt version to 5.9.5 (hebasto)
+- bitcoin/bitcoin#21298 guix: Bump time-machine, glibc, and linux-headers (dongcarl)
+- bitcoin/bitcoin#21304 guix: Add guix-clean script + establish gc-root for container profiles (dongcarl)
+- bitcoin/bitcoin#21320 fix libnatpmp macos cross compile (fanquake)
+- bitcoin/bitcoin#21321 guix: Add curl to required tool list (hebasto)
+- bitcoin/bitcoin#21333 set Unicode true for NSIS installer (fanquake)
+- bitcoin/bitcoin#21339 Make `AM_CONDITIONAL([ENABLE_EXTERNAL_SIGNER])` unconditional (hebasto)
+- bitcoin/bitcoin#21349 Fix fuzz-cuckoocache cross-compiling with DEBUG=1 (hebasto)
+- bitcoin/bitcoin#21354 build, doc: Drop no longer required packages from macOS cross-compiling dependencies (hebasto)
+- bitcoin/bitcoin#21363 build, qt: Improve Qt static plugins/libs check code (hebasto)
+- bitcoin/bitcoin#21375 guix: Misc feedback-based fixes + hier restructuring (dongcarl)
+- bitcoin/bitcoin#21376 Qt 5.12.10 (fanquake)
+- bitcoin/bitcoin#21382 Clean remnants of QTBUG-34748 fix (hebasto)
+- bitcoin/bitcoin#21400 Fix regression introduced in #21363 (hebasto)
+- bitcoin/bitcoin#21403 set --build when configuring packages in depends (fanquake)
+- bitcoin/bitcoin#21421 don't try and use -fstack-clash-protection on Windows (fanquake)
+- bitcoin/bitcoin#21423 Cleanups and follow ups after bumping Qt to 5.12.10 (hebasto)
+- bitcoin/bitcoin#21427 Fix `id_string` invocations (dongcarl)
+- bitcoin/bitcoin#21430 Add -Werror=implicit-fallthrough compile flag (hebasto)
+- bitcoin/bitcoin#21457 Split libtapi and clang out of `native_cctools` (fanquake)
+- bitcoin/bitcoin#21462 guix: Add guix-{attest,verify} scripts (dongcarl)
+- bitcoin/bitcoin#21495 build, qt: Fix static builds on macOS Big Sur (hebasto)
+- bitcoin/bitcoin#21497 Do not opt-in unused CoreWLAN stuff in depends for macOS (hebasto)
+- bitcoin/bitcoin#21543 Enable safe warnings for msvc builds (hebasto)
+- bitcoin/bitcoin#21565 Make `bitcoin_qt.m4` more generic (fanquake)
+- bitcoin/bitcoin#21610 remove -Wdeprecated-register from NOWARN flags (fanquake)
+- bitcoin/bitcoin#21613 enable -Wdocumentation (fanquake)
+- bitcoin/bitcoin#21629 Fix configuring when building depends with `NO_BDB=1` (fanquake)
+- bitcoin/bitcoin#21654 build, qt: Make Qt rcc output always deterministic (hebasto)
+- bitcoin/bitcoin#21655 build, qt: No longer need to set `QT_RCC_TEST=1` for determinism (hebasto)
+- bitcoin/bitcoin#21658 fix make deploy for arm64-darwin (sgulls)
+- bitcoin/bitcoin#21694 Use XLIFF file to provide more context to Transifex translators (hebasto)
+- bitcoin/bitcoin#21708, bitcoin/bitcoin#21593 Drop pointless sed commands (hebasto)
+- bitcoin/bitcoin#21731 Update msvc build to use Qt5.12.10 binaries (sipsorcery)
+- bitcoin/bitcoin#21733 Re-add command to install vcpkg (dplusplus1024)
+- bitcoin/bitcoin#21793 Use `-isysroot` over `--sysroot` on macOS (fanquake)
+- bitcoin/bitcoin#21869 Add missing `-D_LIBCPP_DEBUG=1` to debug flags (MarcoFalke)
+- bitcoin/bitcoin#21889 macho: check for control flow instrumentation (fanquake)
+- bitcoin/bitcoin#21920 Improve macro for testing -latomic requirement (MarcoFalke)
+- bitcoin/bitcoin#21991 libevent 2.1.12-stable (fanquake)
+- bitcoin/bitcoin#22054 Bump Qt version to 5.12.11 (hebasto)
+- bitcoin/bitcoin#22063 Use Qt archive of the same version as the compiled binaries (hebasto)
+- bitcoin/bitcoin#22070 Don't use cf-protection when targeting arm-apple-darwin (fanquake)
+- bitcoin/bitcoin#22071 Latest config.guess and config.sub (fanquake)
+- bitcoin/bitcoin#22075 guix: Misc leftover usability improvements (dongcarl)
+- bitcoin/bitcoin#22123 Fix qt.mk for mac arm64 (promag)
+- bitcoin/bitcoin#22174 build, qt: Fix libraries linking order for Linux hosts (hebasto)
+- bitcoin/bitcoin#22182 guix: Overhaul how guix-{attest,verify} works and hierarchy (dongcarl)
+- bitcoin/bitcoin#22186 build, qt: Fix compiling qt package in depends with GCC 11 (hebasto)
+- bitcoin/bitcoin#22199 macdeploy: minor fixups and simplifications (fanquake)
+- bitcoin/bitcoin#22230 Fix MSVC linker /SubSystem option for bitcoin-qt.exe (hebasto)
+- bitcoin/bitcoin#22234 Mark print-% target as phony (dgoncharov)
+- bitcoin/bitcoin#22238 improve detection of eBPF support (fanquake)
+- bitcoin/bitcoin#22258 Disable deprecated-copy warning only when external warnings are enabled (MarcoFalke)
+- bitcoin/bitcoin#22320 set minimum required Boost to 1.64.0 (fanquake)
+- bitcoin/bitcoin#22348 Fix cross build for Windows with Boost Process (hebasto)
+- bitcoin/bitcoin#22365 guix: Avoid relying on newer symbols by rebasing our cross toolchains on older glibcs (dongcarl)
+- bitcoin/bitcoin#22381 guix: Test security-check sanity before performing them (with macOS) (fanquake)
+- bitcoin/bitcoin#22405 Remove --enable-glibc-back-compat from Guix build (fanquake)
+- bitcoin/bitcoin#22406 Remove --enable-determinism configure option (fanquake)
+- bitcoin/bitcoin#22410 Avoid GCC 7.1 ABI change warning in guix build (sipa)
+- bitcoin/bitcoin#22436 use aarch64 Clang if cross-compiling for darwin on aarch64 (fanquake)
+- bitcoin/bitcoin#22465 guix: Pin kernel-header version, time-machine to upstream 1.3.0 commit (dongcarl)
+- bitcoin/bitcoin#22511 guix: Silence `getent(1)` invocation, doc fixups (dongcarl)
+- bitcoin/bitcoin#22531 guix: Fixes to guix-{attest,verify} (achow101)
+- bitcoin/bitcoin#22642 release: Release with separate sha256sums and sig files (dongcarl)
+- bitcoin/bitcoin#22685 clientversion: No suffix `#if CLIENT_VERSION_IS_RELEASE` (dongcarl)
+- bitcoin/bitcoin#22713 Fix build with Boost 1.77.0 (sizeofvoid)
+
+### Tests and QA
+- bitcoin/bitcoin#14604 Add test and refactor `feature_block.py` (sanket1729)
+- bitcoin/bitcoin#17556 Change `feature_config_args.py` not to rely on strange regtest=0 behavior (ryanofsky)
+- bitcoin/bitcoin#18795 wallet issue with orphaned rewards (domob1812)
+- bitcoin/bitcoin#18847 compressor: Use a prevector in CompressScript serialization (jb55)
+- bitcoin/bitcoin#19259 fuzz: Add fuzzing harness for LoadMempool(…) and DumpMempool(…) (practicalswift)
+- bitcoin/bitcoin#19315 Allow outbound & block-relay-only connections in functional tests. (amitiuttarwar)
+- bitcoin/bitcoin#19698 Apply strict verification flags for transaction tests and assert backwards compatibility (glozow)
+- bitcoin/bitcoin#19801 Check for all possible `OP_CLTV` fail reasons in `feature_cltv.py` (BIP 65) (theStack)
+- bitcoin/bitcoin#19893 Remove or explain syncwithvalidationinterfacequeue (MarcoFalke)
+- bitcoin/bitcoin#19972 fuzz: Add fuzzing harness for node eviction logic (practicalswift)
+- bitcoin/bitcoin#19982 Fix inconsistent lock order in `wallet_tests/CreateWallet` (hebasto)
+- bitcoin/bitcoin#20000 Fix creation of "std::string"s with \0s (vasild)
+- bitcoin/bitcoin#20047 Use `wait_for_{block,header}` helpers in `p2p_fingerprint.py` (theStack)
+- bitcoin/bitcoin#20171 Add functional test `test_txid_inv_delay` (ariard)
+- bitcoin/bitcoin#20189 Switch to BIP341's suggested scheme for outputs without script (sipa)
+- bitcoin/bitcoin#20248 Fix length of R check in `key_signature_tests` (dgpv)
+- bitcoin/bitcoin#20276, bitcoin/bitcoin#20385, bitcoin/bitcoin#20688, bitcoin/bitcoin#20692 Run various mempool tests even with wallet disabled (mjdietzx)
+- bitcoin/bitcoin#20323 Create or use existing properly initialized NodeContexts (dongcarl)
+- bitcoin/bitcoin#20354 Add `feature_taproot.py --previous_release` (MarcoFalke)
+- bitcoin/bitcoin#20370 fuzz: Version handshake (MarcoFalke)
+- bitcoin/bitcoin#20377 fuzz: Fill various small fuzzing gaps (practicalswift)
+- bitcoin/bitcoin#20425 fuzz: Make CAddrMan fuzzing harness deterministic (practicalswift)
+- bitcoin/bitcoin#20430 Sanitizers: Add suppression for unsigned-integer-overflow in libstdc++ (jonasschnelli)
+- bitcoin/bitcoin#20437 fuzz: Avoid time-based "non-determinism" in fuzzing harnesses by using mocked GetTime() (practicalswift)
+- bitcoin/bitcoin#20458 Add `is_bdb_compiled` helper (Sjors)
+- bitcoin/bitcoin#20466 Fix intermittent `p2p_fingerprint` issue (MarcoFalke)
+- bitcoin/bitcoin#20472 Add testing of ParseInt/ParseUInt edge cases with leading +/-/0:s (practicalswift)
+- bitcoin/bitcoin#20507 sync: print proper lock order location when double lock is detected (vasild)
+- bitcoin/bitcoin#20522 Fix sync issue in `disconnect_p2ps` (amitiuttarwar)
+- bitcoin/bitcoin#20524 Move `MIN_VERSION_SUPPORTED` to p2p.py (jnewbery)
+- bitcoin/bitcoin#20540 Fix `wallet_multiwallet` issue on windows (MarcoFalke)
+- bitcoin/bitcoin#20560 fuzz: Link all targets once (MarcoFalke)
+- bitcoin/bitcoin#20567 Add option to git-subtree-check to do full check, add help (laanwj)
+- bitcoin/bitcoin#20569 Fix intermittent `wallet_multiwallet` issue with `got_loading_error` (MarcoFalke)
+- bitcoin/bitcoin#20613 Use Popen.wait instead of RPC in `assert_start_raises_init_error` (MarcoFalke)
+- bitcoin/bitcoin#20663 fuzz: Hide `script_assets_test_minimizer` (MarcoFalke)
+- bitcoin/bitcoin#20674 fuzz: Call SendMessages after ProcessMessage to increase coverage (MarcoFalke)
+- bitcoin/bitcoin#20683 Fix restart node race (MarcoFalke)
+- bitcoin/bitcoin#20686 fuzz: replace CNode code with fuzz/util.h::ConsumeNode() (jonatack)
+- bitcoin/bitcoin#20733 Inline non-member functions with body in fuzzing headers (pstratem)
+- bitcoin/bitcoin#20737 Add missing assignment in `mempool_resurrect.py` (MarcoFalke)
+- bitcoin/bitcoin#20745 Correct `epoll_ctl` data race suppression (hebasto)
+- bitcoin/bitcoin#20748 Add race:SendZmqMessage tsan suppression (MarcoFalke)
+- bitcoin/bitcoin#20760 Set correct nValue for multi-op-return policy check (MarcoFalke)
+- bitcoin/bitcoin#20761 fuzz: Check that `NULL_DATA` is unspendable (MarcoFalke)
+- bitcoin/bitcoin#20765 fuzz: Check that certain script TxoutType are nonstandard (mjdietzx)
+- bitcoin/bitcoin#20772 fuzz: Bolster ExtractDestination(s) checks (mjdietzx)
+- bitcoin/bitcoin#20789 fuzz: Rework strong and weak net enum fuzzing (MarcoFalke)
+- bitcoin/bitcoin#20828 fuzz: Introduce CallOneOf helper to replace switch-case (MarcoFalke)
+- bitcoin/bitcoin#20839 fuzz: Avoid extraneous copy of input data, using Span<> (MarcoFalke)
+- bitcoin/bitcoin#20844 Add sanitizer suppressions for AMD EPYC CPUs (MarcoFalke)
+- bitcoin/bitcoin#20857 Update documentation in `feature_csv_activation.py` (PiRK)
+- bitcoin/bitcoin#20876 Replace getmempoolentry with testmempoolaccept in MiniWallet (MarcoFalke)
+- bitcoin/bitcoin#20881 fuzz: net permission flags in net processing (MarcoFalke)
+- bitcoin/bitcoin#20882 fuzz: Add missing muhash registration (MarcoFalke)
+- bitcoin/bitcoin#20908 fuzz: Use mocktime in `process_message*` fuzz targets (MarcoFalke)
+- bitcoin/bitcoin#20915 fuzz: Fail if message type is not fuzzed (MarcoFalke)
+- bitcoin/bitcoin#20946 fuzz: Consolidate fuzzing TestingSetup initialization (dongcarl)
+- bitcoin/bitcoin#20954 Declare `nodes` type `in test_framework.py` (kiminuo)
+- bitcoin/bitcoin#20955 Fix `get_previous_releases.py` for aarch64 (MarcoFalke)
+- bitcoin/bitcoin#20969 check that getblockfilter RPC fails without block filter index (theStack)
+- bitcoin/bitcoin#20971 Work around libFuzzer deadlock (MarcoFalke)
+- bitcoin/bitcoin#20993 Store subversion (user agent) as string in `msg_version` (theStack)
+- bitcoin/bitcoin#20995 fuzz: Avoid initializing version to less than `MIN_PEER_PROTO_VERSION` (MarcoFalke)
+- bitcoin/bitcoin#20998 Fix BlockToJsonVerbose benchmark (martinus)
+- bitcoin/bitcoin#21003 Move MakeNoLogFileContext to `libtest_util`, and use it in bench (MarcoFalke)
+- bitcoin/bitcoin#21008 Fix zmq test flakiness, improve speed (theStack)
+- bitcoin/bitcoin#21023 fuzz: Disable shuffle when merge=1 (MarcoFalke)
+- bitcoin/bitcoin#21037 fuzz: Avoid designated initialization (C++20) in fuzz tests (practicalswift)
+- bitcoin/bitcoin#21042 doc, test: Improve `setup_clean_chain` documentation (fjahr)
+- bitcoin/bitcoin#21080 fuzz: Configure check for main function (take 2) (MarcoFalke)
+- bitcoin/bitcoin#21084 Fix timeout decrease in `feature_assumevalid` (brunoerg)
+- bitcoin/bitcoin#21096 Re-add dead code detection (flack)
+- bitcoin/bitcoin#21100 Remove unused function `xor_bytes` (theStack)
+- bitcoin/bitcoin#21115 Fix Windows cross build (hebasto)
+- bitcoin/bitcoin#21117 Remove `assert_blockchain_height` (MarcoFalke)
+- bitcoin/bitcoin#21121 Small unit test improvements, including helper to make mempool transaction (amitiuttarwar)
+- bitcoin/bitcoin#21124 Remove unnecessary assignment in bdb (brunoerg)
+- bitcoin/bitcoin#21125 Change `BOOST_CHECK` to `BOOST_CHECK_EQUAL` for paths (kiminuo)
+- bitcoin/bitcoin#21142, bitcoin/bitcoin#21512 fuzz: Add `tx_pool` fuzz target (MarcoFalke)
+- bitcoin/bitcoin#21165 Use mocktime in `test_seed_peers` (dhruv)
+- bitcoin/bitcoin#21169 fuzz: Add RPC interface fuzzing. Increase fuzzing coverage from 65% to 70% (practicalswift)
+- bitcoin/bitcoin#21170 bench: Add benchmark to write json into a string (martinus)
+- bitcoin/bitcoin#21178 Run `mempool_reorg.py` even with wallet disabled (DariusParvin)
+- bitcoin/bitcoin#21185 fuzz: Remove expensive and redundant muhash from crypto fuzz target (MarcoFalke)
+- bitcoin/bitcoin#21200 Speed up `rpc_blockchain.py` by removing miniwallet.generate() (MarcoFalke)
+- bitcoin/bitcoin#21211 Move `P2WSH_OP_TRUE` to shared test library (MarcoFalke)
+- bitcoin/bitcoin#21228 Avoid comparision of integers with different signs (jonasschnelli)
+- bitcoin/bitcoin#21230 Fix `NODE_NETWORK_LIMITED_MIN_BLOCKS` disconnection (MarcoFalke)
+- bitcoin/bitcoin#21252 Add missing wait for sync to `feature_blockfilterindex_prune` (MarcoFalke)
+- bitcoin/bitcoin#21254 Avoid connecting to real network when running tests (MarcoFalke)
+- bitcoin/bitcoin#21264 fuzz: Two scripted diff renames (MarcoFalke)
+- bitcoin/bitcoin#21280 Bug fix in `transaction_tests` (glozow)
+- bitcoin/bitcoin#21293 Replace accidentally placed bit-OR with logical-OR (hebasto)
+- bitcoin/bitcoin#21297 `feature_blockfilterindex_prune.py` improvements (jonatack)
+- bitcoin/bitcoin#21310 zmq test: fix sync-up by matching notification to generated block (theStack)
+- bitcoin/bitcoin#21334 Additional BIP9 tests (Sjors)
+- bitcoin/bitcoin#21338 Add functional test for anchors.dat (brunoerg)
+- bitcoin/bitcoin#21345 Bring `p2p_leak.py` up to date (mzumsande)
+- bitcoin/bitcoin#21357 Unconditionally check for fRelay field in test framework (jarolrod)
+- bitcoin/bitcoin#21358 fuzz: Add missing include (`test/util/setup_common.h`) (MarcoFalke)
+- bitcoin/bitcoin#21371 fuzz: fix gcc Woverloaded-virtual build warnings (jonatack)
+- bitcoin/bitcoin#21373 Generate fewer blocks in `feature_nulldummy` to fix timeouts, speed up (jonatack)
+- bitcoin/bitcoin#21390 Test improvements for UTXO set hash tests (fjahr)
+- bitcoin/bitcoin#21410 increase `rpc_timeout` for fundrawtx `test_transaction_too_large` (jonatack)
+- bitcoin/bitcoin#21411 add logging, reduce blocks, move `sync_all` in `wallet_` groups (jonatack)
+- bitcoin/bitcoin#21438 Add ParseUInt8() test coverage (jonatack)
+- bitcoin/bitcoin#21443 fuzz: Implement `fuzzed_dns_lookup_function` as a lambda (practicalswift)
+- bitcoin/bitcoin#21445 cirrus: Use SSD cluster for speedup (MarcoFalke)
+- bitcoin/bitcoin#21477 Add test for CNetAddr::ToString IPv6 address formatting (RFC 5952) (practicalswift)
+- bitcoin/bitcoin#21487 fuzz: Use ConsumeWeakEnum in addrman for service flags (MarcoFalke)
+- bitcoin/bitcoin#21488 Add ParseUInt16() unit test and fuzz coverage (jonatack)
+- bitcoin/bitcoin#21491 test: remove duplicate assertions in util_tests (jonatack)
+- bitcoin/bitcoin#21522 fuzz: Use PickValue where possible (MarcoFalke)
+- bitcoin/bitcoin#21531 remove qt byteswap compattests (fanquake)
+- bitcoin/bitcoin#21557 small cleanup in RPCNestedTests tests (fanquake)
+- bitcoin/bitcoin#21586 Add missing suppression for signed-integer-overflow:txmempool.cpp (MarcoFalke)
+- bitcoin/bitcoin#21592 Remove option to make TestChain100Setup non-deterministic (MarcoFalke)
+- bitcoin/bitcoin#21597 Document `race:validation_chainstatemanager_tests` suppression (MarcoFalke)
+- bitcoin/bitcoin#21599 Replace file level integer overflow suppression with function level suppression (practicalswift)
+- bitcoin/bitcoin#21604 Document why no symbol names can be used for suppressions (MarcoFalke)
+- bitcoin/bitcoin#21606 fuzz: Extend psbt fuzz target a bit (MarcoFalke)
+- bitcoin/bitcoin#21617 fuzz: Fix uninitialized read in i2p test (MarcoFalke)
+- bitcoin/bitcoin#21630 fuzz: split FuzzedSock interface and implementation (vasild)
+- bitcoin/bitcoin#21634 Skip SQLite fsyncs while testing (achow101)
+- bitcoin/bitcoin#21669 Remove spurious double lock tsan suppressions by bumping to clang-12 (MarcoFalke)
+- bitcoin/bitcoin#21676 Use mocktime to avoid intermittent failure in `rpc_tests` (MarcoFalke)
+- bitcoin/bitcoin#21677 fuzz: Avoid use of low file descriptor ids (which may be in use) in FuzzedSock (practicalswift)
+- bitcoin/bitcoin#21678 Fix TestPotentialDeadLockDetected suppression (hebasto)
+- bitcoin/bitcoin#21689 Remove intermittently failing and not very meaningful `BOOST_CHECK` in `cnetaddr_basic` (practicalswift)
+- bitcoin/bitcoin#21691 Check that no versionbits are re-used (MarcoFalke)
+- bitcoin/bitcoin#21707 Extend functional tests for addr relay (mzumsande)
+- bitcoin/bitcoin#21712 Test default `include_mempool` value of gettxout (promag)
+- bitcoin/bitcoin#21738 Use clang-12 for ASAN, Add missing suppression (MarcoFalke)
+- bitcoin/bitcoin#21740 add new python linter to check file names and permissions (windsok)
+- bitcoin/bitcoin#21749 Bump shellcheck version (hebasto)
+- bitcoin/bitcoin#21754 Run `feature_cltv` with MiniWallet (MarcoFalke)
+- bitcoin/bitcoin#21762 Speed up `mempool_spend_coinbase.py` (MarcoFalke)
+- bitcoin/bitcoin#21773 fuzz: Ensure prevout is consensus-valid (MarcoFalke)
+- bitcoin/bitcoin#21777 Fix `feature_notifications.py` intermittent issue (MarcoFalke)
+- bitcoin/bitcoin#21785 Fix intermittent issue in `p2p_addr_relay.py` (MarcoFalke)
+- bitcoin/bitcoin#21787 Fix off-by-ones in `rpc_fundrawtransaction` assertions (jonatack)
+- bitcoin/bitcoin#21792 Fix intermittent issue in `p2p_segwit.py` (MarcoFalke)
+- bitcoin/bitcoin#21795 fuzz: Terminate immediately if a fuzzing harness tries to perform a DNS lookup (belt and suspenders) (practicalswift)
+- bitcoin/bitcoin#21798 fuzz: Create a block template in `tx_pool` targets (MarcoFalke)
+- bitcoin/bitcoin#21804 Speed up `p2p_segwit.py` (jnewbery)
+- bitcoin/bitcoin#21810 fuzz: Various RPC fuzzer follow-ups (practicalswift)
+- bitcoin/bitcoin#21814 Fix `feature_config_args.py` intermittent issue (MarcoFalke)
+- bitcoin/bitcoin#21821 Add missing test for empty P2WSH redeem (MarcoFalke)
+- bitcoin/bitcoin#21822 Resolve bug in `interface_bitcoin_cli.py` (klementtan)
+- bitcoin/bitcoin#21846 fuzz: Add `-fsanitize=integer` suppression needed for RPC fuzzer (`generateblock`) (practicalswift)
+- bitcoin/bitcoin#21849 fuzz: Limit toxic test globals to their respective scope (MarcoFalke)
+- bitcoin/bitcoin#21867 use MiniWallet for `p2p_blocksonly.py` (theStack)
+- bitcoin/bitcoin#21873 minor fixes & improvements for files linter test (windsok)
+- bitcoin/bitcoin#21874 fuzz: Add `WRITE_ALL_FUZZ_TARGETS_AND_ABORT` (MarcoFalke)
+- bitcoin/bitcoin#21884 fuzz: Remove unused --enable-danger-fuzz-link-all option (MarcoFalke)
+- bitcoin/bitcoin#21890 fuzz: Limit ParseISO8601DateTime fuzzing to 32-bit (MarcoFalke)
+- bitcoin/bitcoin#21891 fuzz: Remove strprintf test cases that are known to fail (MarcoFalke)
+- bitcoin/bitcoin#21892 fuzz: Avoid excessively large min fee rate in `tx_pool` (MarcoFalke)
+- bitcoin/bitcoin#21895 Add TSA annotations to the WorkQueue class members (hebasto)
+- bitcoin/bitcoin#21900 use MiniWallet for `feature_csv_activation.py` (theStack)
+- bitcoin/bitcoin#21909 fuzz: Limit max insertions in timedata fuzz test (MarcoFalke)
+- bitcoin/bitcoin#21922 fuzz: Avoid timeout in EncodeBase58 (MarcoFalke)
+- bitcoin/bitcoin#21927 fuzz: Run const CScript member functions only once (MarcoFalke)
+- bitcoin/bitcoin#21929 fuzz: Remove incorrect float round-trip serialization test (MarcoFalke)
+- bitcoin/bitcoin#21936 fuzz: Terminate immediately if a fuzzing harness tries to create a TCP socket (belt and suspenders) (practicalswift)
+- bitcoin/bitcoin#21941 fuzz: Call const member functions in addrman fuzz test only once (MarcoFalke)
+- bitcoin/bitcoin#21945 add P2PK support to MiniWallet (theStack)
+- bitcoin/bitcoin#21948 Fix off-by-one in mockscheduler test RPC (MarcoFalke)
+- bitcoin/bitcoin#21953 fuzz: Add `utxo_snapshot` target (MarcoFalke)
+- bitcoin/bitcoin#21970 fuzz: Add missing CheckTransaction before CheckTxInputs (MarcoFalke)
+- bitcoin/bitcoin#21989 Use `COINBASE_MATURITY` in functional tests (kiminuo)
+- bitcoin/bitcoin#22003 Add thread safety annotations (ajtowns)
+- bitcoin/bitcoin#22004 fuzz: Speed up transaction fuzz target (MarcoFalke)
+- bitcoin/bitcoin#22005 fuzz: Speed up banman fuzz target (MarcoFalke)
+- bitcoin/bitcoin#22029 [fuzz] Improve transport deserialization fuzz test coverage (dhruv)
+- bitcoin/bitcoin#22048 MiniWallet: introduce enum type for output mode (theStack)
+- bitcoin/bitcoin#22057 use MiniWallet (P2PK mode) for `feature_dersig.py` (theStack)
+- bitcoin/bitcoin#22065 Mark `CheckTxInputs` `[[nodiscard]]`. Avoid UUM in fuzzing harness `coins_view` (practicalswift)
+- bitcoin/bitcoin#22069 fuzz: don't try and use fopencookie() when building for Android (fanquake)
+- bitcoin/bitcoin#22082 update nanobench from release 4.0.0 to 4.3.4 (martinus)
+- bitcoin/bitcoin#22086 remove BasicTestingSetup from unit tests that don't need it (fanquake)
+- bitcoin/bitcoin#22089 MiniWallet: fix fee calculation for P2PK and check tx vsize (theStack)
+- bitcoin/bitcoin#21107, bitcoin/bitcoin#22092 Convert documentation into type annotations (fanquake)
+- bitcoin/bitcoin#22095 Additional BIP32 test vector for hardened derivation with leading zeros (kristapsk)
+- bitcoin/bitcoin#22103 Fix IPv6 check on BSD systems (n-thumann)
+- bitcoin/bitcoin#22118 check anchors.dat when node starts for the first time (brunoerg)
+- bitcoin/bitcoin#22120 `p2p_invalid_block`: Check that a block rejected due to too-new tim… (willcl-ark)
+- bitcoin/bitcoin#22153 Fix `p2p_leak.py` intermittent failure (mzumsande)
+- bitcoin/bitcoin#22169 p2p, rpc, fuzz: various tiny follow-ups (jonatack)
+- bitcoin/bitcoin#22176 Correct outstanding -Werror=sign-compare errors (Empact)
+- bitcoin/bitcoin#22180 fuzz: Increase branch coverage of the float fuzz target (MarcoFalke)
+- bitcoin/bitcoin#22187 Add `sync_blocks` in `wallet_orphanedreward.py` (domob1812)
+- bitcoin/bitcoin#22201 Fix TestShell to allow running in Jupyter Notebook (josibake)
+- bitcoin/bitcoin#22202 Add temporary coinstats suppressions (MarcoFalke)
+- bitcoin/bitcoin#22203 Use ConnmanTestMsg from test lib in `denialofservice_tests` (MarcoFalke)
+- bitcoin/bitcoin#22210 Use MiniWallet in `test_no_inherited_signaling` RBF test (MarcoFalke)
+- bitcoin/bitcoin#22224 Update msvc and appveyor builds to use Qt5.12.11 binaries (sipsorcery)
+- bitcoin/bitcoin#22249 Kill process group to avoid dangling processes when using `--failfast` (S3RK)
+- bitcoin/bitcoin#22267 fuzz: Speed up crypto fuzz target (MarcoFalke)
+- bitcoin/bitcoin#22270 Add bitcoin-util tests (+refactors) (MarcoFalke)
+- bitcoin/bitcoin#22271 fuzz: Assert roundtrip equality for `CPubKey` (theStack)
+- bitcoin/bitcoin#22279 fuzz: add missing ECCVerifyHandle to `base_encode_decode` (apoelstra)
+- bitcoin/bitcoin#22292 bench, doc: benchmarking updates and fixups (jonatack)
+- bitcoin/bitcoin#22306 Improvements to `p2p_addr_relay.py` (amitiuttarwar)
+- bitcoin/bitcoin#22310 Add functional test for replacement relay fee check (ariard)
+- bitcoin/bitcoin#22311 Add missing syncwithvalidationinterfacequeue in `p2p_blockfilters` (MarcoFalke)
+- bitcoin/bitcoin#22313 Add missing `sync_all` to `feature_coinstatsindex` (MarcoFalke)
+- bitcoin/bitcoin#22322 fuzz: Check banman roundtrip (MarcoFalke)
+- bitcoin/bitcoin#22363 Use `script_util` helpers for creating P2{PKH,SH,WPKH,WSH} scripts (theStack)
+- bitcoin/bitcoin#22399 fuzz: Rework CTxDestination fuzzing (MarcoFalke)
+- bitcoin/bitcoin#22408 add tests for `bad-txns-prevout-null` reject reason (theStack)
+- bitcoin/bitcoin#22445 fuzz: Move implementations of non-template fuzz helpers from util.h to util.cpp (sriramdvt)
+- bitcoin/bitcoin#22446 Fix `wallet_listdescriptors.py` if bdb is not compiled (hebasto)
+- bitcoin/bitcoin#22447 Whitelist `rpc_rawtransaction` peers to speed up tests (jonatack)
+- bitcoin/bitcoin#22742 Use proper target in `do_fund_send` (S3RK)
+
+### Miscellaneous
+- bitcoin/bitcoin#19337 sync: Detect double lock from the same thread (vasild)
+- bitcoin/bitcoin#19809 log: Prefix log messages with function name and source code location if -logsourcelocations is set (practicalswift)
+- bitcoin/bitcoin#19866 eBPF Linux tracepoints (jb55)
+- bitcoin/bitcoin#20024 init: Fix incorrect warning "Reducing -maxconnections from N to N-1, because of system limitations" (practicalswift)
+- bitcoin/bitcoin#20145 contrib: Add getcoins.py script to get coins from (signet) faucet (kallewoof)
+- bitcoin/bitcoin#20255 util: Add assume() identity function (MarcoFalke)
+- bitcoin/bitcoin#20288 script, doc: Contrib/seeds updates (jonatack)
+- bitcoin/bitcoin#20358 src/randomenv.cpp: Fix build on uclibc (ffontaine)
+- bitcoin/bitcoin#20406 util: Avoid invalid integer negation in formatmoney and valuefromamount (practicalswift)
+- bitcoin/bitcoin#20434 contrib: Parse elf directly for symbol and security checks (laanwj)
+- bitcoin/bitcoin#20451 lint: Run mypy over contrib/devtools (fanquake)
+- bitcoin/bitcoin#20476 contrib: Add test for elf symbol-check (laanwj)
+- bitcoin/bitcoin#20530 lint: Update cppcheck linter to c++17 and improve explicit usage (fjahr)
+- bitcoin/bitcoin#20589 log: Clarify that failure to read/write `fee_estimates.dat` is non-fatal (MarcoFalke)
+- bitcoin/bitcoin#20602 util: Allow use of c++14 chrono literals (MarcoFalke)
+- bitcoin/bitcoin#20605 init: Signal-safe instant shutdown (laanwj)
+- bitcoin/bitcoin#20608 contrib: Add symbol check test for PE binaries (fanquake)
+- bitcoin/bitcoin#20689 contrib: Replace binary verification script verify.sh with python rewrite (theStack)
+- bitcoin/bitcoin#20715 util: Add argsmanager::getcommand() and use it in bitcoin-wallet (MarcoFalke)
+- bitcoin/bitcoin#20735 script: Remove outdated extract-osx-sdk.sh (hebasto)
+- bitcoin/bitcoin#20817 lint: Update list of spelling linter false positives, bump to codespell 2.0.0 (theStack)
+- bitcoin/bitcoin#20884 script: Improve robustness of bitcoind.service on startup (hebasto)
+- bitcoin/bitcoin#20906 contrib: Embed c++11 patch in `install_db4.sh` (gruve-p)
+- bitcoin/bitcoin#21004 contrib: Fix docker args conditional in gitian-build (setpill)
+- bitcoin/bitcoin#21007 bitcoind: Add -daemonwait option to wait for initialization (laanwj)
+- bitcoin/bitcoin#21041 log: Move "Pre-allocating up to position 0x[…] in […].dat" log message to debug category (practicalswift)
+- bitcoin/bitcoin#21059 Drop boost/preprocessor dependencies (hebasto)
+- bitcoin/bitcoin#21087 guix: Passthrough `BASE_CACHE` into container (dongcarl)
+- bitcoin/bitcoin#21088 guix: Jump forwards in time-machine and adapt (dongcarl)
+- bitcoin/bitcoin#21089 guix: Add support for powerpc64{,le} (dongcarl)
+- bitcoin/bitcoin#21110 util: Remove boost `posix_time` usage from `gettime*` (fanquake)
+- bitcoin/bitcoin#21111 Improve OpenRC initscript (parazyd)
+- bitcoin/bitcoin#21123 code style: Add EditorConfig file (kiminuo)
+- bitcoin/bitcoin#21173 util: Faster hexstr => 13% faster blocktojson (martinus)
+- bitcoin/bitcoin#21221 tools: Allow argument/parameter bin packing in clang-format (jnewbery)
+- bitcoin/bitcoin#21244 Move GetDataDir to ArgsManager (kiminuo)
+- bitcoin/bitcoin#21255 contrib: Run test-symbol-check for risc-v (fanquake)
+- bitcoin/bitcoin#21271 guix: Explicitly set umask in build container (dongcarl)
+- bitcoin/bitcoin#21300 script: Add explanatory comment to tc.sh (dscotese)
+- bitcoin/bitcoin#21317 util: Make assume() usable as unary expression (MarcoFalke)
+- bitcoin/bitcoin#21336 Make .gitignore ignore src/test/fuzz/fuzz.exe (hebasto)
+- bitcoin/bitcoin#21337 guix: Update darwin native packages dependencies (hebasto)
+- bitcoin/bitcoin#21405 compat: remove memcpy -> memmove backwards compatibility alias (fanquake)
+- bitcoin/bitcoin#21418 contrib: Make systemd invoke dependencies only when ready (laanwj)
+- bitcoin/bitcoin#21447 Always add -daemonwait to known command line arguments (hebasto)
+- bitcoin/bitcoin#21471 bugfix: Fix `bech32_encode` calls in `gen_key_io_test_vectors.py` (sipa)
+- bitcoin/bitcoin#21615 script: Add trusted key for hebasto (hebasto)
+- bitcoin/bitcoin#21664 contrib: Use lief for macos and windows symbol & security checks (fanquake)
+- bitcoin/bitcoin#21695 contrib: Remove no longer used contrib/bitcoin-qt.pro (hebasto)
+- bitcoin/bitcoin#21711 guix: Add full installation and usage documentation (dongcarl)
+- bitcoin/bitcoin#21799 guix: Use `gcc-8` across the board (dongcarl)
+- bitcoin/bitcoin#21802 Avoid UB in util/asmap (advance a dereferenceable iterator outside its valid range) (MarcoFalke)
+- bitcoin/bitcoin#21823 script: Update reviewers (jonatack)
+- bitcoin/bitcoin#21850 Remove `GetDataDir(net_specific)` function (kiminuo)
+- bitcoin/bitcoin#21871 scripts: Add checks for minimum required os versions (fanquake)
+- bitcoin/bitcoin#21966 Remove double serialization; use software encoder for fee estimation (sipa)
+- bitcoin/bitcoin#22060 contrib: Add torv3 seed nodes for testnet, drop v2 ones (laanwj)
+- bitcoin/bitcoin#22244 devtools: Correctly extract symbol versions in symbol-check (laanwj)
+- bitcoin/bitcoin#22533 guix/build: Remove vestigial SKIPATTEST.TAG (dongcarl)
+- bitcoin/bitcoin#22643 guix-verify: Non-zero exit code when anything fails (dongcarl)
+- bitcoin/bitcoin#22654 guix: Don't include directory name in SHA256SUMS (achow101)
+
+### Documentation
+- bitcoin/bitcoin#15451 clarify getdata limit after #14897 (HashUnlimited)
+- bitcoin/bitcoin#15545 Explain why CheckBlock() is called before AcceptBlock (Sjors)
+- bitcoin/bitcoin#17350 Add developer documentation to isminetype (HAOYUatHZ)
+- bitcoin/bitcoin#17934 Use `CONFIG_SITE` variable instead of --prefix option (hebasto)
+- bitcoin/bitcoin#18030 Coin::IsSpent() can also mean never existed (Sjors)
+- bitcoin/bitcoin#18096 IsFinalTx comment about nSequence & `OP_CLTV` (nothingmuch)
+- bitcoin/bitcoin#18568 Clarify developer notes about constant naming (ryanofsky)
+- bitcoin/bitcoin#19961 doc: tor.md updates (jonatack)
+- bitcoin/bitcoin#19968 Clarify CRollingBloomFilter size estimate (robot-dreams)
+- bitcoin/bitcoin#20200 Rename CODEOWNERS to REVIEWERS (adamjonas)
+- bitcoin/bitcoin#20329 docs/descriptors.md: Remove hardened marker in the path after xpub (dgpv)
+- bitcoin/bitcoin#20380 Add instructions on how to fuzz the P2P layer using Honggfuzz NetDriver (practicalswift)
+- bitcoin/bitcoin#20414 Remove generated manual pages from master branch (laanwj)
+- bitcoin/bitcoin#20473 Document current boost dependency as 1.71.0 (laanwj)
+- bitcoin/bitcoin#20512 Add bash as an OpenBSD dependency (emilengler)
+- bitcoin/bitcoin#20568 Use FeeModes doc helper in estimatesmartfee (MarcoFalke)
+- bitcoin/bitcoin#20577 libconsensus: add missing error code description, fix NBitcoin link (theStack)
+- bitcoin/bitcoin#20587 Tidy up Tor doc (more stringent) (wodry)
+- bitcoin/bitcoin#20592 Update wtxidrelay documentation per BIP339 (jonatack)
+- bitcoin/bitcoin#20601 Update for FreeBSD 12.2, add GUI Build Instructions (jarolrod)
+- bitcoin/bitcoin#20635 fix misleading comment about call to non-existing function (pox)
+- bitcoin/bitcoin#20646 Refer to BIPs 339/155 in feature negotiation (jonatack)
+- bitcoin/bitcoin#20653 Move addr relay comment in net to correct place (MarcoFalke)
+- bitcoin/bitcoin#20677 Remove shouty enums in `net_processing` comments (sdaftuar)
+- bitcoin/bitcoin#20741 Update 'Secure string handling' (prayank23)
+- bitcoin/bitcoin#20757 tor.md and -onlynet help updates (jonatack)
+- bitcoin/bitcoin#20829 Add -netinfo help (jonatack)
+- bitcoin/bitcoin#20830 Update developer notes with signet (jonatack)
+- bitcoin/bitcoin#20890 Add explicit macdeployqtplus dependencies install step (hebasto)
+- bitcoin/bitcoin#20913 Add manual page generation for bitcoin-util (laanwj)
+- bitcoin/bitcoin#20985 Add xorriso to macOS depends packages (fanquake)
+- bitcoin/bitcoin#20986 Update developer notes to discourage very long lines (jnewbery)
+- bitcoin/bitcoin#20987 Add instructions for generating RPC docs (ben-kaufman)
+- bitcoin/bitcoin#21026 Document use of make-tag script to make tags (laanwj)
+- bitcoin/bitcoin#21028 doc/bips: Add BIPs 43, 44, 49, and 84 (luke-jr)
+- bitcoin/bitcoin#21049 Add release notes for listdescriptors RPC (S3RK)
+- bitcoin/bitcoin#21060 More precise -debug and -debugexclude doc (wodry)
+- bitcoin/bitcoin#21077 Clarify -timeout and -peertimeout config options (glozow)
+- bitcoin/bitcoin#21105 Correctly identify script type (niftynei)
+- bitcoin/bitcoin#21163 Guix is shipped in Debian and Ubuntu (MarcoFalke)
+- bitcoin/bitcoin#21210 Rework internal and external links (MarcoFalke)
+- bitcoin/bitcoin#21246 Correction for VerifyTaprootCommitment comments (roconnor-blockstream)
+- bitcoin/bitcoin#21263 Clarify that squashing should happen before review (MarcoFalke)
+- bitcoin/bitcoin#21323 guix, doc: Update default HOSTS value (hebasto)
+- bitcoin/bitcoin#21324 Update build instructions for Fedora (hebasto)
+- bitcoin/bitcoin#21343 Revamp macOS build doc (jarolrod)
+- bitcoin/bitcoin#21346 install qt5 when building on macOS (fanquake)
+- bitcoin/bitcoin#21384 doc: add signet to bitcoin.conf documentation (jonatack)
+- bitcoin/bitcoin#21394 Improve comment about protected peers (amitiuttarwar)
+- bitcoin/bitcoin#21398 Update fuzzing docs for afl-clang-lto (MarcoFalke)
+- bitcoin/bitcoin#21444 net, doc: Doxygen updates and fixes in netbase.{h,cpp} (jonatack)
+- bitcoin/bitcoin#21481 Tell howto install clang-format on Debian/Ubuntu (wodry)
+- bitcoin/bitcoin#21567 Fix various misleading comments (glozow)
+- bitcoin/bitcoin#21661 Fix name of script guix-build (Emzy)
+- bitcoin/bitcoin#21672 Remove boostrap info from `GUIX_COMMON_FLAGS` doc (fanquake)
+- bitcoin/bitcoin#21688 Note on SDK for macOS depends cross-compile (jarolrod)
+- bitcoin/bitcoin#21709 Update reduce-memory.md and bitcoin.conf -maxconnections info (jonatack)
+- bitcoin/bitcoin#21710 update helps for addnode rpc and -addnode/-maxconnections config options (jonatack)
+- bitcoin/bitcoin#21752 Clarify that feerates are per virtual size (MarcoFalke)
+- bitcoin/bitcoin#21811 Remove Visual Studio 2017 reference from readme (sipsorcery)
+- bitcoin/bitcoin#21818 Fixup -coinstatsindex help, update bitcoin.conf and files.md (jonatack)
+- bitcoin/bitcoin#21856 add OSS-Fuzz section to fuzzing.md doc (adamjonas)
+- bitcoin/bitcoin#21912 Remove mention of priority estimation (MarcoFalke)
+- bitcoin/bitcoin#21925 Update bips.md for 0.21.1 (MarcoFalke)
+- bitcoin/bitcoin#21942 improve make with parallel jobs description (klementtan)
+- bitcoin/bitcoin#21947 Fix OSS-Fuzz links (MarcoFalke)
+- bitcoin/bitcoin#21988 note that brew installed qt is not supported (jarolrod)
+- bitcoin/bitcoin#22056 describe in fuzzing.md how to reproduce a CI crash (jonatack)
+- bitcoin/bitcoin#22080 add maxuploadtarget to bitcoin.conf example (jarolrod)
+- bitcoin/bitcoin#22088 Improve note on choosing posix mingw32 (jarolrod)
+- bitcoin/bitcoin#22109 Fix external links (IRC, …) (MarcoFalke)
+- bitcoin/bitcoin#22121 Various validation doc fixups (MarcoFalke)
+- bitcoin/bitcoin#22172 Update tor.md, release notes with removal of tor v2 support (jonatack)
+- bitcoin/bitcoin#22204 Remove obsolete `okSafeMode` RPC guideline from developer notes (theStack)
+- bitcoin/bitcoin#22208 Update `REVIEWERS` (practicalswift)
+- bitcoin/bitcoin#22250 add basic I2P documentation (vasild)
+- bitcoin/bitcoin#22296 Final merge of release notes snippets, mv to wiki (MarcoFalke)
+- bitcoin/bitcoin#22335 recommend `--disable-external-signer` in OpenBSD build guide (theStack)
+- bitcoin/bitcoin#22339 Document minimum required libc++ version (hebasto)
+- bitcoin/bitcoin#22349 Repository IRC updates (jonatack)
+- bitcoin/bitcoin#22360 Remove unused section from release process (MarcoFalke)
+- bitcoin/bitcoin#22369 Add steps for Transifex to release process (jonatack)
+- bitcoin/bitcoin#22393 Added info to bitcoin.conf doc (bliotti)
+- bitcoin/bitcoin#22402 Install Rosetta on M1-macOS for qt in depends (hebasto)
+- bitcoin/bitcoin#22432 Fix incorrect `testmempoolaccept` doc (glozow)
+- bitcoin/bitcoin#22648 doc, test: improve i2p/tor docs and i2p reachable unit tests (jonatack)
+
+Credits
+=======
+
+Thanks to everyone who directly contributed to this release:
+
+- Aaron Clauson
+- Adam Jonas
+- amadeuszpawlik
+- Amiti Uttarwar
+- Andrew Chow
+- Andrew Poelstra
+- Anthony Towns
+- Antoine Poinsot
+- Antoine Riard
+- apawlik
+- apitko
+- Ben Carman
+- Ben Woosley
+- benk10
+- Bezdrighin
+- Block Mechanic
+- Brian Liotti
+- Bruno Garcia
+- Carl Dong
+- Christian Decker
+- coinforensics
+- Cory Fields
+- Dan Benjamin
+- Daniel Kraft
+- Darius Parvin
+- Dhruv Mehta
+- Dmitry Goncharov
+- Dmitry Petukhov
+- dplusplus1024
+- dscotese
+- Duncan Dean
+- Elle Mouton
+- Elliott Jin
+- Emil Engler
+- Ethan Heilman
+- eugene
+- Evan Klitzke
+- Fabian Jahr
+- Fabrice Fontaine
+- fanquake
+- fdov
+- flack
+- Fotis Koutoupas
+- Fu Yong Quah
+- fyquah
+- glozow
+- Gregory Sanders
+- Guido Vranken
+- Gunar C. Gessner
+- h
+- HAOYUatHZ
+- Hennadii Stepanov
+- Igor Cota
+- Ikko Ashimine
+- Ivan Metlushko
+- jackielove4u
+- James O'Beirne
+- Jarol Rodriguez
+- Joel Klabo
+- John Newbery
+- Jon Atack
+- Jonas Schnelli
+- João Barbosa
+- Josiah Baker
+- Karl-Johan Alm
+- Kiminuo
+- Klement Tan
+- Kristaps Kaupe
+- Larry Ruane
+- lisa neigut
+- Lucas Ontivero
+- Luke Dashjr
+- Maayan Keshet
+- MarcoFalke
+- Martin Ankerl
+- Martin Zumsande
+- Michael Dietz
+- Michael Polzer
+- Michael Tidwell
+- Niklas Gögge
+- nthumann
+- Oliver Gugger
+- parazyd
+- Patrick Strateman
+- Pavol Rusnak
+- Peter Bushnell
+- Pierre K
+- Pieter Wuille
+- PiRK
+- pox
+- practicalswift
+- Prayank
+- R E Broadley
+- Rafael Sadowski
+- randymcmillan
+- Raul Siles
+- Riccardo Spagni
+- Russell O'Connor
+- Russell Yanofsky
+- S3RK
+- saibato
+- Samuel Dobson
+- sanket1729
+- Sawyer Billings
+- Sebastian Falbesoner
+- setpill
+- sgulls
+- sinetek
+- Sjors Provoost
+- Sriram
+- Stephan Oeste
+- Suhas Daftuar
+- Sylvain Goumy
+- t-bast
+- Troy Giorshev
+- Tushar Singla
+- Tyler Chambers
+- Uplab
+- Vasil Dimov
+- W. J. van der Laan
+- willcl-ark
+- William Bright
+- William Casarin
+- windsok
+- wodry
+- Yerzhan Mazhkenov
+- Yuval Kogman
+- Zero
+
+As well as to everyone that helped with translations on
+[Transifex](https://www.transifex.com/bitcoin/bitcoin/).
diff --git a/doc/release-process.md b/doc/release-process.md
index 3e4748b742..6a5202d0f9 100644
--- a/doc/release-process.md
+++ b/doc/release-process.md
@@ -271,26 +271,7 @@ cat "$VERSION"/*/all.SHA256SUMS.asc > SHA256SUMS.asc
- Push the flatpak to flathub, e.g. https://github.com/flathub/org.bitcoincore.bitcoin-qt/pull/2
- - Push the latest version to master (if applicable), e.g. https://github.com/bitcoin-core/packaging/pull/32
-
- - Create a new branch for the major release "0.xx" from master (used to build the snap package) and request the
- track (if applicable), e.g. https://forum.snapcraft.io/t/track-request-for-bitcoin-core-snap/10112/7
-
- - Notify MarcoFalke so that he can start building the snap package
-
- - https://code.launchpad.net/~bitcoin-core/bitcoin-core-snap/+git/packaging (Click "Import Now" to fetch the branch)
- - https://code.launchpad.net/~bitcoin-core/bitcoin-core-snap/+git/packaging/+ref/0.xx (Click "Create snap package")
- - Name it "bitcoin-core-snap-0.xx"
- - Leave owner and series as-is
- - Select architectures that are compiled via guix
- - Leave "automatically build when branch changes" unticked
- - Tick "automatically upload to store"
- - Put "bitcoin-core" in the registered store package name field
- - Tick the "edge" box
- - Put "0.xx" in the track field
- - Click "create snap package"
- - Click "Request builds" for every new release on this branch (after updating the snapcraft.yml in the branch to reflect the latest guix results)
- - Promote release on https://snapcraft.io/bitcoin-core/releases if it passes sanity checks
+ - Push the snap, see https://github.com/bitcoin-core/packaging/blob/master/snap/build.md
- This repo
diff --git a/doc/tor.md b/doc/tor.md
index a3ec1987aa..8dc82ca91e 100644
--- a/doc/tor.md
+++ b/doc/tor.md
@@ -23,10 +23,9 @@ There are several ways to see your local onion address in Bitcoin Core:
You may set the `-debug=tor` config logging option to have additional
information in the debug log about your Tor configuration.
-CLI `-addrinfo` returns the number of addresses known to your node per network
-type, including Tor v2 and v3. This is useful to see how many onion addresses
-are known to your node for `-onlynet=onion` and how many Tor v3 addresses it
-knows when upgrading to Bitcoin Core v22.0 and up that supports Tor v3 only.
+CLI `-addrinfo` returns the number of addresses known to your node per
+network. This can be useful to see how many onion peers your node knows,
+e.g. for `-onlynet=onion`.
## 1. Run Bitcoin Core behind a Tor proxy
@@ -134,7 +133,7 @@ You can also check the group of the cookie file. On most Linux systems, the Tor
auth cookie will usually be `/run/tor/control.authcookie`:
```
-stat -c '%G' /run/tor/control.authcookie
+TORGROUP=$(stat -c '%G' /run/tor/control.authcookie)
```
Once you have determined the `${TORGROUP}` and selected the `${USER}` that will
diff --git a/doc/zmq.md b/doc/zmq.md
index 85f3370130..0521fe08d8 100644
--- a/doc/zmq.md
+++ b/doc/zmq.md
@@ -84,6 +84,7 @@ For instance:
$ bitcoind -zmqpubhashtx=tcp://127.0.0.1:28332 \
-zmqpubhashtx=tcp://192.168.1.2:28332 \
+ -zmqpubhashblock="tcp://[::1]:28333" \
-zmqpubrawtx=ipc:///tmp/bitcoind.tx.raw \
-zmqpubhashtxhwm=10000
@@ -125,6 +126,9 @@ Setting the keepalive values appropriately for your operating environment may
improve connectivity in situations where long-lived connections are silently
dropped by network middle boxes.
+Also, the socket's ZMQ_IPV6 option is enabled to accept connections from IPv6
+hosts as well. If needed, this option has to be set on the client side too.
+
## Remarks
From the perspective of bitcoind, the ZeroMQ socket is write-only; PUB
diff --git a/share/examples/bitcoin.conf b/share/examples/bitcoin.conf
index 4a947001fa..c5b79709c7 100644
--- a/share/examples/bitcoin.conf
+++ b/share/examples/bitcoin.conf
@@ -157,7 +157,7 @@
#coinstatsindex=1
# Enable pruning to reduce storage requirements by deleting old blocks.
-# This mode is incompatible with -txindex, -coinstatsindex and -rescan.
+# This mode is incompatible with -txindex and -coinstatsindex.
# 0 = default (no pruning).
# 1 = allows manual pruning via RPC.
# >=550 = target to stay under in MiB.
diff --git a/share/qt/Info.plist.in b/share/qt/Info.plist.in
index da10dbb3be..053359e0a8 100644
--- a/share/qt/Info.plist.in
+++ b/share/qt/Info.plist.in
@@ -3,7 +3,7 @@
<plist version="0.9">
<dict>
<key>LSMinimumSystemVersion</key>
- <string>10.14.0</string>
+ <string>10.15.0</string>
<key>LSArchitecturePriority</key>
<array>
@@ -16,6 +16,11 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
+ <key>CFBundleSupportedPlatforms</key>
+ <array>
+ <string>MacOSX</string>
+ </array>
+
<key>NSHumanReadableCopyright</key>
<string>@CLIENT_VERSION_MAJOR@.@CLIENT_VERSION_MINOR@.@CLIENT_VERSION_BUILD@, Copyright © 2009-@COPYRIGHT_YEAR@ @COPYRIGHT_HOLDERS_FINAL@</string>
diff --git a/src/.clang-tidy b/src/.clang-tidy
new file mode 100644
index 0000000000..27616ad072
--- /dev/null
+++ b/src/.clang-tidy
@@ -0,0 +1,2 @@
+Checks: '-*,bugprone-argument-comment'
+WarningsAsErrors: bugprone-argument-comment
diff --git a/src/Makefile.am b/src/Makefile.am
index 6f8245de8a..12fdc9ad75 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -117,6 +117,7 @@ endif
BITCOIN_CORE_H = \
addrdb.h \
addrman.h \
+ addrman_impl.h \
attributes.h \
banman.h \
base58.h \
@@ -261,6 +262,7 @@ BITCOIN_CORE_H = \
util/sock.h \
util/spanparsing.h \
util/string.h \
+ util/syscall_sandbox.h \
util/system.h \
util/thread.h \
util/threadnames.h \
@@ -268,6 +270,7 @@ BITCOIN_CORE_H = \
util/tokenpipe.h \
util/trace.h \
util/translation.h \
+ util/types.h \
util/ui_change_type.h \
util/url.h \
util/vector.h \
@@ -497,9 +500,9 @@ crypto_libbitcoin_crypto_shani_a_SOURCES = crypto/sha256_shani.cpp
libbitcoin_consensus_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES)
libbitcoin_consensus_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
libbitcoin_consensus_a_SOURCES = \
- amount.h \
arith_uint256.cpp \
arith_uint256.h \
+ consensus/amount.h \
consensus/merkle.cpp \
consensus/merkle.h \
consensus/params.h \
@@ -570,7 +573,7 @@ libbitcoin_common_a_SOURCES = \
# util: shared between all executables.
# This library *must* be included to make sure that the glibc
-# backward-compatibility objects and their sanity checks are linked.
+# sanity checks are linked.
libbitcoin_util_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES)
libbitcoin_util_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
libbitcoin_util_a_SOURCES = \
@@ -610,6 +613,7 @@ libbitcoin_util_a_SOURCES = \
util/spanparsing.cpp \
util/strencodings.cpp \
util/string.cpp \
+ util/syscall_sandbox.cpp \
util/time.cpp \
util/tokenpipe.cpp \
$(BITCOIN_CORE_H)
@@ -618,11 +622,6 @@ if USE_LIBEVENT
libbitcoin_util_a_SOURCES += util/url.cpp
endif
-if GLIBC_BACK_COMPAT
-libbitcoin_util_a_SOURCES += compat/glibc_compat.cpp
-AM_LDFLAGS += $(COMPAT_LDFLAGS)
-endif
-
# cli: shared between bitcoin-cli and bitcoin-qt
libbitcoin_cli_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES)
libbitcoin_cli_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
@@ -750,10 +749,6 @@ if BUILD_BITCOIN_LIBS
include_HEADERS = script/bitcoinconsensus.h
libbitcoinconsensus_la_SOURCES = support/cleanse.cpp $(crypto_libbitcoin_crypto_base_a_SOURCES) $(libbitcoin_consensus_a_SOURCES)
-if GLIBC_BACK_COMPAT
- libbitcoinconsensus_la_SOURCES += compat/glibc_compat.cpp
-endif
-
libbitcoinconsensus_la_LDFLAGS = $(AM_LDFLAGS) -no-undefined $(RELDFLAGS)
libbitcoinconsensus_la_LIBADD = $(LIBSECP256K1)
libbitcoinconsensus_la_CPPFLAGS = $(AM_CPPFLAGS) -I$(builddir)/obj -I$(srcdir)/secp256k1/include -DBUILD_BITCOIN_INTERNAL
diff --git a/src/Makefile.crc32c.include b/src/Makefile.crc32c.include
index 113272e65e..3cbe71792c 100644
--- a/src/Makefile.crc32c.include
+++ b/src/Makefile.crc32c.include
@@ -14,7 +14,6 @@ CRC32C_CPPFLAGS_INT += -I$(srcdir)/crc32c/include
CRC32C_CPPFLAGS_INT += -DHAVE_BUILTIN_PREFETCH=@HAVE_BUILTIN_PREFETCH@
CRC32C_CPPFLAGS_INT += -DHAVE_MM_PREFETCH=@HAVE_MM_PREFETCH@
CRC32C_CPPFLAGS_INT += -DHAVE_STRONG_GETAUXVAL=@HAVE_STRONG_GETAUXVAL@
-CRC32C_CPPFLAGS_INT += -DHAVE_WEAK_GETAUXVAL=@HAVE_WEAK_GETAUXVAL@
CRC32C_CPPFLAGS_INT += -DCRC32C_TESTS_BUILT_WITH_GLOG=0
if ENABLE_SSE42
diff --git a/src/Makefile.qt.include b/src/Makefile.qt.include
index 6f450bbc74..f4b0b3adbe 100644
--- a/src/Makefile.qt.include
+++ b/src/Makefile.qt.include
@@ -338,14 +338,14 @@ bitcoin_qt_libtoolflags = $(AM_LIBTOOLFLAGS) --tag CXX
qt_bitcoin_qt_CPPFLAGS = $(bitcoin_qt_cppflags)
qt_bitcoin_qt_CXXFLAGS = $(bitcoin_qt_cxxflags)
-qt_bitcoin_qt_SOURCES = $(bitcoin_qt_sources)
+qt_bitcoin_qt_SOURCES = $(bitcoin_qt_sources) init/bitcoind.cpp
qt_bitcoin_qt_LDADD = $(bitcoin_qt_ldadd)
qt_bitcoin_qt_LDFLAGS = $(bitcoin_qt_ldflags)
qt_bitcoin_qt_LIBTOOLFLAGS = $(bitcoin_qt_libtoolflags)
bitcoin_gui_CPPFLAGS = $(bitcoin_qt_cppflags)
bitcoin_gui_CXXFLAGS = $(bitcoin_qt_cxxflags)
-bitcoin_gui_SOURCES = $(bitcoin_qt_sources)
+bitcoin_gui_SOURCES = $(bitcoin_qt_sources) init/bitcoind.cpp
bitcoin_gui_LDADD = $(bitcoin_qt_ldadd)
bitcoin_gui_LDFLAGS = $(bitcoin_qt_ldflags)
bitcoin_gui_LIBTOOLFLAGS = $(bitcoin_qt_libtoolflags)
diff --git a/src/Makefile.qttest.include b/src/Makefile.qttest.include
index 91a5e9fd9b..8a5521eeb5 100644
--- a/src/Makefile.qttest.include
+++ b/src/Makefile.qttest.include
@@ -28,6 +28,7 @@ qt_test_test_bitcoin_qt_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BITCOIN_
$(QT_INCLUDES) $(QT_TEST_INCLUDES)
qt_test_test_bitcoin_qt_SOURCES = \
+ init/bitcoind.cpp \
qt/test/apptests.cpp \
qt/test/rpcnestedtests.cpp \
qt/test/test_main.cpp \
diff --git a/src/Makefile.test.include b/src/Makefile.test.include
index a85a359960..d70793ffa9 100644
--- a/src/Makefile.test.include
+++ b/src/Makefile.test.include
@@ -119,8 +119,9 @@ BITCOIN_TESTS =\
test/sanity_tests.cpp \
test/scheduler_tests.cpp \
test/script_p2sh_tests.cpp \
- test/script_tests.cpp \
+ test/script_parse_tests.cpp \
test/script_standard_tests.cpp \
+ test/script_tests.cpp \
test/scriptnum_tests.cpp \
test/serfloat_tests.cpp \
test/serialize_tests.cpp \
@@ -232,7 +233,6 @@ test_fuzz_fuzz_SOURCES = \
test/fuzz/crypto_hkdf_hmac_sha256_l32.cpp \
test/fuzz/crypto_poly1305.cpp \
test/fuzz/cuckoocache.cpp \
- test/fuzz/data_stream.cpp \
test/fuzz/decode_tx.cpp \
test/fuzz/descriptor_parse.cpp \
test/fuzz/deserialize.cpp \
diff --git a/src/Makefile.test_util.include b/src/Makefile.test_util.include
index 85e50ebf70..0a3b99e7d2 100644
--- a/src/Makefile.test_util.include
+++ b/src/Makefile.test_util.include
@@ -9,6 +9,7 @@ EXTRA_LIBRARIES += \
TEST_UTIL_H = \
test/util/blockfilter.h \
+ test/util/chainstate.h \
test/util/logging.h \
test/util/mining.h \
test/util/net.h \
diff --git a/src/addrdb.cpp b/src/addrdb.cpp
index 345dbdfb16..50fd09101e 100644
--- a/src/addrdb.cpp
+++ b/src/addrdb.cpp
@@ -18,8 +18,15 @@
#include <univalue.h>
#include <util/settings.h>
#include <util/system.h>
+#include <util/translation.h>
namespace {
+
+class DbNotFoundError : public std::exception
+{
+ using std::exception::exception;
+};
+
template <typename Stream, typename Data>
bool SerializeDB(Stream& stream, const Data& data)
{
@@ -77,47 +84,40 @@ bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data
}
template <typename Stream, typename Data>
-bool DeserializeDB(Stream& stream, Data& data, bool fCheckSum = true)
+void DeserializeDB(Stream& stream, Data& data, bool fCheckSum = true)
{
- try {
- CHashVerifier<Stream> verifier(&stream);
- // de-serialize file header (network specific magic number) and ..
- unsigned char pchMsgTmp[4];
- verifier >> pchMsgTmp;
- // ... verify the network matches ours
- if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
- return error("%s: Invalid network magic number", __func__);
-
- // de-serialize data
- verifier >> data;
-
- // verify checksum
- if (fCheckSum) {
- uint256 hashTmp;
- stream >> hashTmp;
- if (hashTmp != verifier.GetHash()) {
- return error("%s: Checksum mismatch, data corrupted", __func__);
- }
- }
- }
- catch (const std::exception& e) {
- return error("%s: Deserialize or I/O error - %s", __func__, e.what());
+ CHashVerifier<Stream> verifier(&stream);
+ // de-serialize file header (network specific magic number) and ..
+ unsigned char pchMsgTmp[4];
+ verifier >> pchMsgTmp;
+ // ... verify the network matches ours
+ if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) {
+ throw std::runtime_error{"Invalid network magic number"};
}
- return true;
+ // de-serialize data
+ verifier >> data;
+
+ // verify checksum
+ if (fCheckSum) {
+ uint256 hashTmp;
+ stream >> hashTmp;
+ if (hashTmp != verifier.GetHash()) {
+ throw std::runtime_error{"Checksum mismatch, data corrupted"};
+ }
+ }
}
template <typename Data>
-bool DeserializeFileDB(const fs::path& path, Data& data, int version)
+void DeserializeFileDB(const fs::path& path, Data& data, int version)
{
// open input file, and associate with CAutoFile
FILE* file = fsbridge::fopen(path, "rb");
CAutoFile filein(file, SER_DISK, version);
if (filein.IsNull()) {
- LogPrintf("Missing or invalid file %s\n", path.string());
- return false;
+ throw DbNotFoundError{};
}
- return DeserializeDB(filein, data);
+ DeserializeDB(filein, data);
}
} // namespace
@@ -170,24 +170,38 @@ bool CBanDB::Read(banmap_t& banSet)
return true;
}
-CAddrDB::CAddrDB()
-{
- pathAddr = gArgs.GetDataDirNet() / "peers.dat";
-}
-
-bool CAddrDB::Write(const CAddrMan& addr)
+bool DumpPeerAddresses(const ArgsManager& args, const AddrMan& addr)
{
+ const auto pathAddr = args.GetDataDirNet() / "peers.dat";
return SerializeFileDB("peers", pathAddr, addr, CLIENT_VERSION);
}
-bool CAddrDB::Read(CAddrMan& addr)
+void ReadFromStream(AddrMan& addr, CDataStream& ssPeers)
{
- return DeserializeFileDB(pathAddr, addr, CLIENT_VERSION);
+ DeserializeDB(ssPeers, addr, false);
}
-bool CAddrDB::Read(CAddrMan& addr, CDataStream& ssPeers)
+std::optional<bilingual_str> LoadAddrman(const std::vector<bool>& asmap, const ArgsManager& args, std::unique_ptr<AddrMan>& addrman)
{
- return DeserializeDB(ssPeers, addr, false);
+ auto check_addrman = std::clamp<int32_t>(args.GetIntArg("-checkaddrman", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), 0, 1000000);
+ addrman = std::make_unique<AddrMan>(asmap, /* deterministic */ false, /* consistency_check_ratio */ check_addrman);
+
+ int64_t nStart = GetTimeMillis();
+ const auto path_addr{args.GetDataDirNet() / "peers.dat"};
+ try {
+ DeserializeFileDB(path_addr, *addrman, CLIENT_VERSION);
+ LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman->size(), GetTimeMillis() - nStart);
+ } catch (const DbNotFoundError&) {
+ // Addrman can be in an inconsistent state after failure, reset it
+ addrman = std::make_unique<AddrMan>(asmap, /* deterministic */ false, /* consistency_check_ratio */ check_addrman);
+ LogPrintf("Creating peers.dat because the file was not found (%s)\n", path_addr);
+ DumpPeerAddresses(args, *addrman);
+ } catch (const std::exception& e) {
+ addrman = nullptr;
+ return strprintf(_("Invalid or corrupt peers.dat (%s). If you believe this is a bug, please report it to %s. As a workaround, you can move the file (%s) out of the way (rename, move, or delete) to have a new one created on the next start."),
+ e.what(), PACKAGE_BUGREPORT, path_addr);
+ }
+ return std::nullopt;
}
void DumpAnchors(const fs::path& anchors_db_path, const std::vector<CAddress>& anchors)
@@ -199,9 +213,10 @@ void DumpAnchors(const fs::path& anchors_db_path, const std::vector<CAddress>& a
std::vector<CAddress> ReadAnchors(const fs::path& anchors_db_path)
{
std::vector<CAddress> anchors;
- if (DeserializeFileDB(anchors_db_path, anchors, CLIENT_VERSION | ADDRV2_FORMAT)) {
+ try {
+ DeserializeFileDB(anchors_db_path, anchors, CLIENT_VERSION | ADDRV2_FORMAT);
LogPrintf("Loaded %i addresses from %s\n", anchors.size(), anchors_db_path.filename());
- } else {
+ } catch (const std::exception&) {
anchors.clear();
}
diff --git a/src/addrdb.h b/src/addrdb.h
index 26b1c5880f..19be4b5bb4 100644
--- a/src/addrdb.h
+++ b/src/addrdb.h
@@ -10,23 +10,18 @@
#include <net_types.h> // For banmap_t
#include <univalue.h>
+#include <optional>
#include <vector>
+class ArgsManager;
+class AddrMan;
class CAddress;
-class CAddrMan;
class CDataStream;
+struct bilingual_str;
-/** Access to the (IP) address database (peers.dat) */
-class CAddrDB
-{
-private:
- fs::path pathAddr;
-public:
- CAddrDB();
- bool Write(const CAddrMan& addr);
- bool Read(CAddrMan& addr);
- static bool Read(CAddrMan& addr, CDataStream& ssPeers);
-};
+bool DumpPeerAddresses(const ArgsManager& args, const AddrMan& addr);
+/** Only used by tests. */
+void ReadFromStream(AddrMan& addr, CDataStream& ssPeers);
/** Access to the banlist database (banlist.json) */
class CBanDB
@@ -52,6 +47,9 @@ public:
bool Read(banmap_t& banSet);
};
+/** Returns an error string on failure */
+std::optional<bilingual_str> LoadAddrman(const std::vector<bool>& asmap, const ArgsManager& args, std::unique_ptr<AddrMan>& addrman);
+
/**
* Dump the anchor IP address database (anchors.dat)
*
diff --git a/src/addrman.cpp b/src/addrman.cpp
index 717cadaedf..c364a7710b 100644
--- a/src/addrman.cpp
+++ b/src/addrman.cpp
@@ -4,22 +4,27 @@
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <addrman.h>
+#include <addrman_impl.h>
#include <hash.h>
-#include <logging.h>
#include <netaddress.h>
+#include <protocol.h>
+#include <random.h>
#include <serialize.h>
+#include <streams.h>
+#include <timedata.h>
+#include <tinyformat.h>
+#include <uint256.h>
+#include <util/check.h>
#include <cmath>
#include <optional>
-#include <unordered_map>
-#include <unordered_set>
/** Over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread */
static constexpr uint32_t ADDRMAN_TRIED_BUCKETS_PER_GROUP{8};
/** Over how many buckets entries with new addresses originating from a single group are spread */
static constexpr uint32_t ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP{64};
-/** Maximum number of times an address can be added to the new table */
+/** Maximum number of times an address can occur in the new table */
static constexpr int32_t ADDRMAN_NEW_BUCKETS_PER_ADDRESS{8};
/** How old addresses can maximally be */
static constexpr int64_t ADDRMAN_HORIZON_DAYS{30};
@@ -36,7 +41,7 @@ static constexpr size_t ADDRMAN_SET_TRIED_COLLISION_SIZE{10};
/** The maximum time we'll spend trying to resolve a tried table collision, in seconds */
static constexpr int64_t ADDRMAN_TEST_WINDOW{40*60}; // 40 minutes
-int CAddrInfo::GetTriedBucket(const uint256& nKey, const std::vector<bool> &asmap) const
+int AddrInfo::GetTriedBucket(const uint256& nKey, const std::vector<bool>& asmap) const
{
uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetKey()).GetCheapHash();
uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup(asmap) << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetCheapHash();
@@ -46,7 +51,7 @@ int CAddrInfo::GetTriedBucket(const uint256& nKey, const std::vector<bool> &asma
return tried_bucket;
}
-int CAddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src, const std::vector<bool> &asmap) const
+int AddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src, const std::vector<bool>& asmap) const
{
std::vector<unsigned char> vchSourceGroupKey = src.GetGroup(asmap);
uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup(asmap) << vchSourceGroupKey).GetCheapHash();
@@ -57,13 +62,13 @@ int CAddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src, const std:
return new_bucket;
}
-int CAddrInfo::GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const
+int AddrInfo::GetBucketPosition(const uint256& nKey, bool fNew, int nBucket) const
{
uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << (fNew ? uint8_t{'N'} : uint8_t{'K'}) << nBucket << GetKey()).GetCheapHash();
return hash1 % ADDRMAN_BUCKET_SIZE;
}
-bool CAddrInfo::IsTerrible(int64_t nNow) const
+bool AddrInfo::IsTerrible(int64_t nNow) const
{
if (nLastTry && nLastTry >= nNow - 60) // never remove things tried in the last minute
return false;
@@ -83,7 +88,7 @@ bool CAddrInfo::IsTerrible(int64_t nNow) const
return false;
}
-double CAddrInfo::GetChance(int64_t nNow) const
+double AddrInfo::GetChance(int64_t nNow) const
{
double fChance = 1.0;
int64_t nSinceLastTry = std::max<int64_t>(nNow - nLastTry, 0);
@@ -98,7 +103,7 @@ double CAddrInfo::GetChance(int64_t nNow) const
return fChance;
}
-CAddrMan::CAddrMan(std::vector<bool> asmap, bool deterministic, int32_t consistency_check_ratio)
+AddrManImpl::AddrManImpl(std::vector<bool>&& asmap, bool deterministic, int32_t consistency_check_ratio)
: insecure_rand{deterministic}
, nKey{deterministic ? uint256{1} : insecure_rand.rand256()}
, m_consistency_check_ratio{consistency_check_ratio}
@@ -116,8 +121,13 @@ CAddrMan::CAddrMan(std::vector<bool> asmap, bool deterministic, int32_t consiste
}
}
+AddrManImpl::~AddrManImpl()
+{
+ nKey.SetNull();
+}
+
template <typename Stream>
-void CAddrMan::Serialize(Stream& s_) const
+void AddrManImpl::Serialize(Stream& s_) const
{
LOCK(cs);
@@ -180,7 +190,7 @@ void CAddrMan::Serialize(Stream& s_) const
int nIds = 0;
for (const auto& entry : mapInfo) {
mapUnkIds[entry.first] = nIds;
- const CAddrInfo &info = entry.second;
+ const AddrInfo& info = entry.second;
if (info.nRefCount) {
assert(nIds != nNew); // this means nNew was wrong, oh ow
s << info;
@@ -189,7 +199,7 @@ void CAddrMan::Serialize(Stream& s_) const
}
nIds = 0;
for (const auto& entry : mapInfo) {
- const CAddrInfo &info = entry.second;
+ const AddrInfo& info = entry.second;
if (info.fInTried) {
assert(nIds != nTried); // this means nTried was wrong, oh ow
s << info;
@@ -220,7 +230,7 @@ void CAddrMan::Serialize(Stream& s_) const
}
template <typename Stream>
-void CAddrMan::Unserialize(Stream& s_)
+void AddrManImpl::Unserialize(Stream& s_)
{
LOCK(cs);
@@ -259,21 +269,21 @@ void CAddrMan::Unserialize(Stream& s_)
if (nNew > ADDRMAN_NEW_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE || nNew < 0) {
throw std::ios_base::failure(
- strprintf("Corrupt CAddrMan serialization: nNew=%d, should be in [0, %d]",
+ strprintf("Corrupt AddrMan serialization: nNew=%d, should be in [0, %d]",
nNew,
ADDRMAN_NEW_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE));
}
if (nTried > ADDRMAN_TRIED_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE || nTried < 0) {
throw std::ios_base::failure(
- strprintf("Corrupt CAddrMan serialization: nTried=%d, should be in [0, %d]",
+ strprintf("Corrupt AddrMan serialization: nTried=%d, should be in [0, %d]",
nTried,
ADDRMAN_TRIED_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE));
}
// Deserialize entries from the new table.
for (int n = 0; n < nNew; n++) {
- CAddrInfo &info = mapInfo[n];
+ AddrInfo& info = mapInfo[n];
s >> info;
mapAddr[info] = n;
info.nRandomPos = vRandom.size();
@@ -284,7 +294,7 @@ void CAddrMan::Unserialize(Stream& s_)
// Deserialize entries from the tried table.
int nLost = 0;
for (int n = 0; n < nTried; n++) {
- CAddrInfo info;
+ AddrInfo info;
s >> info;
int nKBucket = info.GetTriedBucket(nKey, m_asmap);
int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket);
@@ -341,7 +351,7 @@ void CAddrMan::Unserialize(Stream& s_)
for (auto bucket_entry : bucket_entries) {
int bucket{bucket_entry.first};
const int entry_index{bucket_entry.second};
- CAddrInfo& info = mapInfo[entry_index];
+ AddrInfo& info = mapInfo[entry_index];
// Don't store the entry in the new bucket if it's not a valid address for our addrman
if (!info.IsValid()) continue;
@@ -383,19 +393,15 @@ void CAddrMan::Unserialize(Stream& s_)
LogPrint(BCLog::ADDRMAN, "addrman lost %i new and %i tried addresses due to collisions or invalid addresses\n", nLostUnk, nLost);
}
- Check();
+ const int check_code{ForceCheckAddrman()};
+ if (check_code != 0) {
+ throw std::ios_base::failure(strprintf(
+ "Corrupt data. Consistency check failed with code %s",
+ check_code));
+ }
}
-// explicit instantiation
-template void CAddrMan::Serialize(CHashWriter& s) const;
-template void CAddrMan::Serialize(CAutoFile& s) const;
-template void CAddrMan::Serialize(CDataStream& s) const;
-template void CAddrMan::Unserialize(CAutoFile& s);
-template void CAddrMan::Unserialize(CHashVerifier<CAutoFile>& s);
-template void CAddrMan::Unserialize(CDataStream& s);
-template void CAddrMan::Unserialize(CHashVerifier<CDataStream>& s);
-
-CAddrInfo* CAddrMan::Find(const CNetAddr& addr, int* pnId)
+AddrInfo* AddrManImpl::Find(const CNetAddr& addr, int* pnId)
{
AssertLockHeld(cs);
@@ -410,12 +416,12 @@ CAddrInfo* CAddrMan::Find(const CNetAddr& addr, int* pnId)
return nullptr;
}
-CAddrInfo* CAddrMan::Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId)
+AddrInfo* AddrManImpl::Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId)
{
AssertLockHeld(cs);
int nId = nIdCount++;
- mapInfo[nId] = CAddrInfo(addr, addrSource);
+ mapInfo[nId] = AddrInfo(addr, addrSource);
mapAddr[addr] = nId;
mapInfo[nId].nRandomPos = vRandom.size();
vRandom.push_back(nId);
@@ -424,7 +430,7 @@ CAddrInfo* CAddrMan::Create(const CAddress& addr, const CNetAddr& addrSource, in
return &mapInfo[nId];
}
-void CAddrMan::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2) const
+void AddrManImpl::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2) const
{
AssertLockHeld(cs);
@@ -448,12 +454,12 @@ void CAddrMan::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2) const
vRandom[nRndPos2] = nId1;
}
-void CAddrMan::Delete(int nId)
+void AddrManImpl::Delete(int nId)
{
AssertLockHeld(cs);
assert(mapInfo.count(nId) != 0);
- CAddrInfo& info = mapInfo[nId];
+ AddrInfo& info = mapInfo[nId];
assert(!info.fInTried);
assert(info.nRefCount == 0);
@@ -464,14 +470,14 @@ void CAddrMan::Delete(int nId)
nNew--;
}
-void CAddrMan::ClearNew(int nUBucket, int nUBucketPos)
+void AddrManImpl::ClearNew(int nUBucket, int nUBucketPos)
{
AssertLockHeld(cs);
// if there is an entry in the specified bucket, delete it.
if (vvNew[nUBucket][nUBucketPos] != -1) {
int nIdDelete = vvNew[nUBucket][nUBucketPos];
- CAddrInfo& infoDelete = mapInfo[nIdDelete];
+ AddrInfo& infoDelete = mapInfo[nIdDelete];
assert(infoDelete.nRefCount > 0);
infoDelete.nRefCount--;
vvNew[nUBucket][nUBucketPos] = -1;
@@ -481,16 +487,19 @@ void CAddrMan::ClearNew(int nUBucket, int nUBucketPos)
}
}
-void CAddrMan::MakeTried(CAddrInfo& info, int nId)
+void AddrManImpl::MakeTried(AddrInfo& info, int nId)
{
AssertLockHeld(cs);
// remove the entry from all new buckets
- for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) {
- int pos = info.GetBucketPosition(nKey, true, bucket);
+ const int start_bucket{info.GetNewBucket(nKey, m_asmap)};
+ for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; ++n) {
+ const int bucket{(start_bucket + n) % ADDRMAN_NEW_BUCKET_COUNT};
+ const int pos{info.GetBucketPosition(nKey, true, bucket)};
if (vvNew[bucket][pos] == nId) {
vvNew[bucket][pos] = -1;
info.nRefCount--;
+ if (info.nRefCount == 0) break;
}
}
nNew--;
@@ -506,7 +515,7 @@ void CAddrMan::MakeTried(CAddrInfo& info, int nId)
// find an item to evict
int nIdEvict = vvTried[nKBucket][nKBucketPos];
assert(mapInfo.count(nIdEvict) == 1);
- CAddrInfo& infoOld = mapInfo[nIdEvict];
+ AddrInfo& infoOld = mapInfo[nIdEvict];
// Remove the to-be-evicted item from the tried set.
infoOld.fInTried = false;
@@ -531,7 +540,7 @@ void CAddrMan::MakeTried(CAddrInfo& info, int nId)
info.fInTried = true;
}
-void CAddrMan::Good_(const CService& addr, bool test_before_evict, int64_t nTime)
+void AddrManImpl::Good_(const CService& addr, bool test_before_evict, int64_t nTime)
{
AssertLockHeld(cs);
@@ -539,13 +548,13 @@ void CAddrMan::Good_(const CService& addr, bool test_before_evict, int64_t nTime
nLastGood = nTime;
- CAddrInfo* pinfo = Find(addr, &nId);
+ AddrInfo* pinfo = Find(addr, &nId);
// if not found, bail out
if (!pinfo)
return;
- CAddrInfo& info = *pinfo;
+ AddrInfo& info = *pinfo;
// check whether we are talking about the exact same CService (including same port)
if (info != addr)
@@ -562,22 +571,10 @@ void CAddrMan::Good_(const CService& addr, bool test_before_evict, int64_t nTime
if (info.fInTried)
return;
- // find a bucket it is in now
- int nRnd = insecure_rand.randrange(ADDRMAN_NEW_BUCKET_COUNT);
- int nUBucket = -1;
- for (unsigned int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
- int nB = (n + nRnd) % ADDRMAN_NEW_BUCKET_COUNT;
- int nBpos = info.GetBucketPosition(nKey, true, nB);
- if (vvNew[nB][nBpos] == nId) {
- nUBucket = nB;
- break;
- }
- }
-
- // if no bucket is found, something bad happened;
- // TODO: maybe re-add the node, but for now, just bail out
- if (nUBucket == -1)
+ // if it is not in new, something bad happened
+ if (!Assume(info.nRefCount > 0)) {
return;
+ }
// which tried bucket to move the entry to
int tried_bucket = info.GetTriedBucket(nKey, m_asmap);
@@ -599,7 +596,7 @@ void CAddrMan::Good_(const CService& addr, bool test_before_evict, int64_t nTime
}
}
-bool CAddrMan::Add_(const CAddress& addr, const CNetAddr& source, int64_t nTimePenalty)
+bool AddrManImpl::Add_(const CAddress& addr, const CNetAddr& source, int64_t nTimePenalty)
{
AssertLockHeld(cs);
@@ -608,7 +605,7 @@ bool CAddrMan::Add_(const CAddress& addr, const CNetAddr& source, int64_t nTimeP
bool fNew = false;
int nId;
- CAddrInfo* pinfo = Find(addr, &nId);
+ AddrInfo* pinfo = Find(addr, &nId);
// Do not set a penalty for a source's self-announcement
if (addr == source) {
@@ -655,7 +652,7 @@ bool CAddrMan::Add_(const CAddress& addr, const CNetAddr& source, int64_t nTimeP
if (vvNew[nUBucket][nUBucketPos] != nId) {
bool fInsert = vvNew[nUBucket][nUBucketPos] == -1;
if (!fInsert) {
- CAddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]];
+ AddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]];
if (infoExisting.IsTerrible() || (infoExisting.nRefCount > 1 && pinfo->nRefCount == 0)) {
// Overwrite the existing new table entry.
fInsert = true;
@@ -674,17 +671,17 @@ bool CAddrMan::Add_(const CAddress& addr, const CNetAddr& source, int64_t nTimeP
return fNew;
}
-void CAddrMan::Attempt_(const CService& addr, bool fCountFailure, int64_t nTime)
+void AddrManImpl::Attempt_(const CService& addr, bool fCountFailure, int64_t nTime)
{
AssertLockHeld(cs);
- CAddrInfo* pinfo = Find(addr);
+ AddrInfo* pinfo = Find(addr);
// if not found, bail out
if (!pinfo)
return;
- CAddrInfo& info = *pinfo;
+ AddrInfo& info = *pinfo;
// check whether we are talking about the exact same CService (including same port)
if (info != addr)
@@ -698,15 +695,13 @@ void CAddrMan::Attempt_(const CService& addr, bool fCountFailure, int64_t nTime)
}
}
-CAddrInfo CAddrMan::Select_(bool newOnly) const
+std::pair<CAddress, int64_t> AddrManImpl::Select_(bool newOnly) const
{
AssertLockHeld(cs);
- if (vRandom.empty())
- return CAddrInfo();
+ if (vRandom.empty()) return {};
- if (newOnly && nNew == 0)
- return CAddrInfo();
+ if (newOnly && nNew == 0) return {};
// Use a 50% chance for choosing between tried and new table entries.
if (!newOnly &&
@@ -723,9 +718,10 @@ CAddrInfo CAddrMan::Select_(bool newOnly) const
int nId = vvTried[nKBucket][nKBucketPos];
const auto it_found{mapInfo.find(nId)};
assert(it_found != mapInfo.end());
- const CAddrInfo& info{it_found->second};
- if (insecure_rand.randbits(30) < fChanceFactor * info.GetChance() * (1 << 30))
- return info;
+ const AddrInfo& info{it_found->second};
+ if (insecure_rand.randbits(30) < fChanceFactor * info.GetChance() * (1 << 30)) {
+ return {info, info.nLastTry};
+ }
fChanceFactor *= 1.2;
}
} else {
@@ -741,107 +737,16 @@ CAddrInfo CAddrMan::Select_(bool newOnly) const
int nId = vvNew[nUBucket][nUBucketPos];
const auto it_found{mapInfo.find(nId)};
assert(it_found != mapInfo.end());
- const CAddrInfo& info{it_found->second};
- if (insecure_rand.randbits(30) < fChanceFactor * info.GetChance() * (1 << 30))
- return info;
- fChanceFactor *= 1.2;
- }
- }
-}
-
-int CAddrMan::Check_() const
-{
- AssertLockHeld(cs);
-
- // Run consistency checks 1 in m_consistency_check_ratio times if enabled
- if (m_consistency_check_ratio == 0) return 0;
- if (insecure_rand.randrange(m_consistency_check_ratio) >= 1) return 0;
-
- LogPrint(BCLog::ADDRMAN, "Addrman checks started: new %i, tried %i, total %u\n", nNew, nTried, vRandom.size());
-
- std::unordered_set<int> setTried;
- std::unordered_map<int, int> mapNew;
-
- if (vRandom.size() != (size_t)(nTried + nNew))
- return -7;
-
- for (const auto& entry : mapInfo) {
- int n = entry.first;
- const CAddrInfo& info = entry.second;
- if (info.fInTried) {
- if (!info.nLastSuccess)
- return -1;
- if (info.nRefCount)
- return -2;
- setTried.insert(n);
- } else {
- if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
- return -3;
- if (!info.nRefCount)
- return -4;
- mapNew[n] = info.nRefCount;
- }
- const auto it{mapAddr.find(info)};
- if (it == mapAddr.end() || it->second != n) {
- return -5;
- }
- if (info.nRandomPos < 0 || (size_t)info.nRandomPos >= vRandom.size() || vRandom[info.nRandomPos] != n)
- return -14;
- if (info.nLastTry < 0)
- return -6;
- if (info.nLastSuccess < 0)
- return -8;
- }
-
- if (setTried.size() != (size_t)nTried)
- return -9;
- if (mapNew.size() != (size_t)nNew)
- return -10;
-
- for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) {
- for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
- if (vvTried[n][i] != -1) {
- if (!setTried.count(vvTried[n][i]))
- return -11;
- const auto it{mapInfo.find(vvTried[n][i])};
- if (it == mapInfo.end() || it->second.GetTriedBucket(nKey, m_asmap) != n) {
- return -17;
- }
- if (it->second.GetBucketPosition(nKey, false, n) != i) {
- return -18;
- }
- setTried.erase(vvTried[n][i]);
- }
- }
- }
-
- for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
- for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
- if (vvNew[n][i] != -1) {
- if (!mapNew.count(vvNew[n][i]))
- return -12;
- const auto it{mapInfo.find(vvNew[n][i])};
- if (it == mapInfo.end() || it->second.GetBucketPosition(nKey, true, n) != i) {
- return -19;
- }
- if (--mapNew[vvNew[n][i]] == 0)
- mapNew.erase(vvNew[n][i]);
+ const AddrInfo& info{it_found->second};
+ if (insecure_rand.randbits(30) < fChanceFactor * info.GetChance() * (1 << 30)) {
+ return {info, info.nLastTry};
}
+ fChanceFactor *= 1.2;
}
}
-
- if (setTried.size())
- return -13;
- if (mapNew.size())
- return -15;
- if (nKey.IsNull())
- return -16;
-
- LogPrint(BCLog::ADDRMAN, "Addrman checks completed successfully\n");
- return 0;
}
-void CAddrMan::GetAddr_(std::vector<CAddress>& vAddr, size_t max_addresses, size_t max_pct, std::optional<Network> network) const
+std::vector<CAddress> AddrManImpl::GetAddr_(size_t max_addresses, size_t max_pct, std::optional<Network> network) const
{
AssertLockHeld(cs);
@@ -855,8 +760,9 @@ void CAddrMan::GetAddr_(std::vector<CAddress>& vAddr, size_t max_addresses, size
// gather a list of random nodes, skipping those of low quality
const int64_t now{GetAdjustedTime()};
+ std::vector<CAddress> addresses;
for (unsigned int n = 0; n < vRandom.size(); n++) {
- if (vAddr.size() >= nNodes)
+ if (addresses.size() >= nNodes)
break;
int nRndPos = insecure_rand.randrange(vRandom.size() - n) + n;
@@ -864,7 +770,7 @@ void CAddrMan::GetAddr_(std::vector<CAddress>& vAddr, size_t max_addresses, size
const auto it{mapInfo.find(vRandom[n])};
assert(it != mapInfo.end());
- const CAddrInfo& ai{it->second};
+ const AddrInfo& ai{it->second};
// Filter by network (optional)
if (network != std::nullopt && ai.GetNetClass() != network) continue;
@@ -872,21 +778,23 @@ void CAddrMan::GetAddr_(std::vector<CAddress>& vAddr, size_t max_addresses, size
// Filter for quality
if (ai.IsTerrible(now)) continue;
- vAddr.push_back(ai);
+ addresses.push_back(ai);
}
+
+ return addresses;
}
-void CAddrMan::Connected_(const CService& addr, int64_t nTime)
+void AddrManImpl::Connected_(const CService& addr, int64_t nTime)
{
AssertLockHeld(cs);
- CAddrInfo* pinfo = Find(addr);
+ AddrInfo* pinfo = Find(addr);
// if not found, bail out
if (!pinfo)
return;
- CAddrInfo& info = *pinfo;
+ AddrInfo& info = *pinfo;
// check whether we are talking about the exact same CService (including same port)
if (info != addr)
@@ -898,17 +806,17 @@ void CAddrMan::Connected_(const CService& addr, int64_t nTime)
info.nTime = nTime;
}
-void CAddrMan::SetServices_(const CService& addr, ServiceFlags nServices)
+void AddrManImpl::SetServices_(const CService& addr, ServiceFlags nServices)
{
AssertLockHeld(cs);
- CAddrInfo* pinfo = Find(addr);
+ AddrInfo* pinfo = Find(addr);
// if not found, bail out
if (!pinfo)
return;
- CAddrInfo& info = *pinfo;
+ AddrInfo& info = *pinfo;
// check whether we are talking about the exact same CService (including same port)
if (info != addr)
@@ -918,7 +826,7 @@ void CAddrMan::SetServices_(const CService& addr, ServiceFlags nServices)
info.nServices = nServices;
}
-void CAddrMan::ResolveCollisions_()
+void AddrManImpl::ResolveCollisions_()
{
AssertLockHeld(cs);
@@ -931,7 +839,7 @@ void CAddrMan::ResolveCollisions_()
if (mapInfo.count(id_new) != 1) {
erase_collision = true;
} else {
- CAddrInfo& info_new = mapInfo[id_new];
+ AddrInfo& info_new = mapInfo[id_new];
// Which tried bucket to move the entry to.
int tried_bucket = info_new.GetTriedBucket(nKey, m_asmap);
@@ -942,7 +850,7 @@ void CAddrMan::ResolveCollisions_()
// Get the to-be-evicted address that is being tested
int id_old = vvTried[tried_bucket][tried_bucket_pos];
- CAddrInfo& info_old = mapInfo[id_old];
+ AddrInfo& info_old = mapInfo[id_old];
// Has successfully connected in last X hours
if (GetAdjustedTime() - info_old.nLastSuccess < ADDRMAN_REPLACEMENT_HOURS*(60*60)) {
@@ -979,11 +887,11 @@ void CAddrMan::ResolveCollisions_()
}
}
-CAddrInfo CAddrMan::SelectTriedCollision_()
+std::pair<CAddress, int64_t> AddrManImpl::SelectTriedCollision_()
{
AssertLockHeld(cs);
- if (m_tried_collisions.size() == 0) return CAddrInfo();
+ if (m_tried_collisions.size() == 0) return {};
std::set<int>::iterator it = m_tried_collisions.begin();
@@ -994,43 +902,291 @@ CAddrInfo CAddrMan::SelectTriedCollision_()
// If id_new not found in mapInfo remove it from m_tried_collisions
if (mapInfo.count(id_new) != 1) {
m_tried_collisions.erase(it);
- return CAddrInfo();
+ return {};
}
- const CAddrInfo& newInfo = mapInfo[id_new];
+ const AddrInfo& newInfo = mapInfo[id_new];
// which tried bucket to move the entry to
int tried_bucket = newInfo.GetTriedBucket(nKey, m_asmap);
int tried_bucket_pos = newInfo.GetBucketPosition(nKey, false, tried_bucket);
- int id_old = vvTried[tried_bucket][tried_bucket_pos];
+ const AddrInfo& info_old = mapInfo[vvTried[tried_bucket][tried_bucket_pos]];
+ return {info_old, info_old.nLastTry};
+}
- return mapInfo[id_old];
+void AddrManImpl::Check() const
+{
+ AssertLockHeld(cs);
+
+ // Run consistency checks 1 in m_consistency_check_ratio times if enabled
+ if (m_consistency_check_ratio == 0) return;
+ if (insecure_rand.randrange(m_consistency_check_ratio) >= 1) return;
+
+ const int err{ForceCheckAddrman()};
+ if (err) {
+ LogPrintf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
+ assert(false);
+ }
}
-std::vector<bool> CAddrMan::DecodeAsmap(fs::path path)
+int AddrManImpl::ForceCheckAddrman() const
{
- std::vector<bool> bits;
- FILE *filestr = fsbridge::fopen(path, "rb");
- CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
- if (file.IsNull()) {
- LogPrintf("Failed to open asmap file from disk\n");
- return bits;
+ AssertLockHeld(cs);
+
+ LogPrint(BCLog::ADDRMAN, "Addrman checks started: new %i, tried %i, total %u\n", nNew, nTried, vRandom.size());
+
+ std::unordered_set<int> setTried;
+ std::unordered_map<int, int> mapNew;
+
+ if (vRandom.size() != (size_t)(nTried + nNew))
+ return -7;
+
+ for (const auto& entry : mapInfo) {
+ int n = entry.first;
+ const AddrInfo& info = entry.second;
+ if (info.fInTried) {
+ if (!info.nLastSuccess)
+ return -1;
+ if (info.nRefCount)
+ return -2;
+ setTried.insert(n);
+ } else {
+ if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
+ return -3;
+ if (!info.nRefCount)
+ return -4;
+ mapNew[n] = info.nRefCount;
+ }
+ const auto it{mapAddr.find(info)};
+ if (it == mapAddr.end() || it->second != n) {
+ return -5;
+ }
+ if (info.nRandomPos < 0 || (size_t)info.nRandomPos >= vRandom.size() || vRandom[info.nRandomPos] != n)
+ return -14;
+ if (info.nLastTry < 0)
+ return -6;
+ if (info.nLastSuccess < 0)
+ return -8;
}
- fseek(filestr, 0, SEEK_END);
- int length = ftell(filestr);
- LogPrintf("Opened asmap file %s (%d bytes) from disk\n", path, length);
- fseek(filestr, 0, SEEK_SET);
- uint8_t cur_byte;
- for (int i = 0; i < length; ++i) {
- file >> cur_byte;
- for (int bit = 0; bit < 8; ++bit) {
- bits.push_back((cur_byte >> bit) & 1);
+
+ if (setTried.size() != (size_t)nTried)
+ return -9;
+ if (mapNew.size() != (size_t)nNew)
+ return -10;
+
+ for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) {
+ for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
+ if (vvTried[n][i] != -1) {
+ if (!setTried.count(vvTried[n][i]))
+ return -11;
+ const auto it{mapInfo.find(vvTried[n][i])};
+ if (it == mapInfo.end() || it->second.GetTriedBucket(nKey, m_asmap) != n) {
+ return -17;
+ }
+ if (it->second.GetBucketPosition(nKey, false, n) != i) {
+ return -18;
+ }
+ setTried.erase(vvTried[n][i]);
+ }
}
}
- if (!SanityCheckASMap(bits)) {
- LogPrintf("Sanity check of asmap file %s failed\n", path);
- return {};
+
+ for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
+ for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
+ if (vvNew[n][i] != -1) {
+ if (!mapNew.count(vvNew[n][i]))
+ return -12;
+ const auto it{mapInfo.find(vvNew[n][i])};
+ if (it == mapInfo.end() || it->second.GetBucketPosition(nKey, true, n) != i) {
+ return -19;
+ }
+ if (--mapNew[vvNew[n][i]] == 0)
+ mapNew.erase(vvNew[n][i]);
+ }
+ }
+ }
+
+ if (setTried.size())
+ return -13;
+ if (mapNew.size())
+ return -15;
+ if (nKey.IsNull())
+ return -16;
+
+ LogPrint(BCLog::ADDRMAN, "Addrman checks completed successfully\n");
+ return 0;
+}
+
+size_t AddrManImpl::size() const
+{
+ LOCK(cs); // TODO: Cache this in an atomic to avoid this overhead
+ return vRandom.size();
+}
+
+bool AddrManImpl::Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, int64_t nTimePenalty)
+{
+ LOCK(cs);
+ int nAdd = 0;
+ Check();
+ for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++)
+ nAdd += Add_(*it, source, nTimePenalty) ? 1 : 0;
+ Check();
+ if (nAdd) {
+ LogPrint(BCLog::ADDRMAN, "Added %i addresses from %s: %i tried, %i new\n", nAdd, source.ToString(), nTried, nNew);
}
- return bits;
+ return nAdd > 0;
+}
+
+void AddrManImpl::Good(const CService& addr, int64_t nTime)
+{
+ LOCK(cs);
+ Check();
+ Good_(addr, /* test_before_evict */ true, nTime);
+ Check();
+}
+
+void AddrManImpl::Attempt(const CService& addr, bool fCountFailure, int64_t nTime)
+{
+ LOCK(cs);
+ Check();
+ Attempt_(addr, fCountFailure, nTime);
+ Check();
+}
+
+void AddrManImpl::ResolveCollisions()
+{
+ LOCK(cs);
+ Check();
+ ResolveCollisions_();
+ Check();
+}
+
+std::pair<CAddress, int64_t> AddrManImpl::SelectTriedCollision()
+{
+ LOCK(cs);
+ Check();
+ const auto ret = SelectTriedCollision_();
+ Check();
+ return ret;
+}
+
+std::pair<CAddress, int64_t> AddrManImpl::Select(bool newOnly) const
+{
+ LOCK(cs);
+ Check();
+ const auto addrRet = Select_(newOnly);
+ Check();
+ return addrRet;
+}
+
+std::vector<CAddress> AddrManImpl::GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network) const
+{
+ LOCK(cs);
+ Check();
+ const auto addresses = GetAddr_(max_addresses, max_pct, network);
+ Check();
+ return addresses;
+}
+
+void AddrManImpl::Connected(const CService& addr, int64_t nTime)
+{
+ LOCK(cs);
+ Check();
+ Connected_(addr, nTime);
+ Check();
+}
+
+void AddrManImpl::SetServices(const CService& addr, ServiceFlags nServices)
+{
+ LOCK(cs);
+ Check();
+ SetServices_(addr, nServices);
+ Check();
+}
+
+const std::vector<bool>& AddrManImpl::GetAsmap() const
+{
+ return m_asmap;
+}
+
+AddrMan::AddrMan(std::vector<bool> asmap, bool deterministic, int32_t consistency_check_ratio)
+ : m_impl(std::make_unique<AddrManImpl>(std::move(asmap), deterministic, consistency_check_ratio)) {}
+
+AddrMan::~AddrMan() = default;
+
+template <typename Stream>
+void AddrMan::Serialize(Stream& s_) const
+{
+ m_impl->Serialize<Stream>(s_);
+}
+
+template <typename Stream>
+void AddrMan::Unserialize(Stream& s_)
+{
+ m_impl->Unserialize<Stream>(s_);
+}
+
+// explicit instantiation
+template void AddrMan::Serialize(CHashWriter& s) const;
+template void AddrMan::Serialize(CAutoFile& s) const;
+template void AddrMan::Serialize(CDataStream& s) const;
+template void AddrMan::Unserialize(CAutoFile& s);
+template void AddrMan::Unserialize(CHashVerifier<CAutoFile>& s);
+template void AddrMan::Unserialize(CDataStream& s);
+template void AddrMan::Unserialize(CHashVerifier<CDataStream>& s);
+
+size_t AddrMan::size() const
+{
+ return m_impl->size();
+}
+
+bool AddrMan::Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, int64_t nTimePenalty)
+{
+ return m_impl->Add(vAddr, source, nTimePenalty);
+}
+
+void AddrMan::Good(const CService& addr, int64_t nTime)
+{
+ m_impl->Good(addr, nTime);
+}
+
+void AddrMan::Attempt(const CService& addr, bool fCountFailure, int64_t nTime)
+{
+ m_impl->Attempt(addr, fCountFailure, nTime);
+}
+
+void AddrMan::ResolveCollisions()
+{
+ m_impl->ResolveCollisions();
+}
+
+std::pair<CAddress, int64_t> AddrMan::SelectTriedCollision()
+{
+ return m_impl->SelectTriedCollision();
+}
+
+std::pair<CAddress, int64_t> AddrMan::Select(bool newOnly) const
+{
+ return m_impl->Select(newOnly);
+}
+
+std::vector<CAddress> AddrMan::GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network) const
+{
+ return m_impl->GetAddr(max_addresses, max_pct, network);
+}
+
+void AddrMan::Connected(const CService& addr, int64_t nTime)
+{
+ m_impl->Connected(addr, nTime);
+}
+
+void AddrMan::SetServices(const CService& addr, ServiceFlags nServices)
+{
+ m_impl->SetServices(addr, nServices);
+}
+
+const std::vector<bool>& AddrMan::GetAsmap() const
+{
+ return m_impl->GetAsmap();
}
diff --git a/src/addrman.h b/src/addrman.h
index 74bfe9748b..174ab4f811 100644
--- a/src/addrman.h
+++ b/src/addrman.h
@@ -6,101 +6,22 @@
#ifndef BITCOIN_ADDRMAN_H
#define BITCOIN_ADDRMAN_H
-#include <clientversion.h>
-#include <config/bitcoin-config.h>
-#include <fs.h>
-#include <hash.h>
#include <netaddress.h>
#include <protocol.h>
-#include <random.h>
#include <streams.h>
-#include <sync.h>
#include <timedata.h>
-#include <tinyformat.h>
-#include <util/system.h>
-#include <iostream>
+#include <cstdint>
+#include <memory>
#include <optional>
-#include <set>
-#include <stdint.h>
-#include <unordered_map>
+#include <utility>
#include <vector>
+class AddrManImpl;
+
/** Default for -checkaddrman */
static constexpr int32_t DEFAULT_ADDRMAN_CONSISTENCY_CHECKS{0};
-/**
- * Extended statistics about a CAddress
- */
-class CAddrInfo : public CAddress
-{
-public:
- //! last try whatsoever by us (memory only)
- int64_t nLastTry{0};
-
- //! last counted attempt (memory only)
- int64_t nLastCountAttempt{0};
-
-private:
- //! where knowledge about this address first came from
- CNetAddr source;
-
- //! last successful connection by us
- int64_t nLastSuccess{0};
-
- //! connection attempts since last successful attempt
- int nAttempts{0};
-
- //! reference count in new sets (memory only)
- int nRefCount{0};
-
- //! in tried set? (memory only)
- bool fInTried{false};
-
- //! position in vRandom
- mutable int nRandomPos{-1};
-
- friend class CAddrMan;
- friend class CAddrManDeterministic;
-
-public:
-
- SERIALIZE_METHODS(CAddrInfo, obj)
- {
- READWRITEAS(CAddress, obj);
- READWRITE(obj.source, obj.nLastSuccess, obj.nAttempts);
- }
-
- CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn), source(addrSource)
- {
- }
-
- CAddrInfo() : CAddress(), source()
- {
- }
-
- //! Calculate in which "tried" bucket this entry belongs
- int GetTriedBucket(const uint256 &nKey, const std::vector<bool> &asmap) const;
-
- //! Calculate in which "new" bucket this entry belongs, given a certain source
- int GetNewBucket(const uint256 &nKey, const CNetAddr& src, const std::vector<bool> &asmap) const;
-
- //! Calculate in which "new" bucket this entry belongs, using its default source
- int GetNewBucket(const uint256 &nKey, const std::vector<bool> &asmap) const
- {
- return GetNewBucket(nKey, source, asmap);
- }
-
- //! Calculate in which position of a bucket to store this entry.
- int GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const;
-
- //! Determine whether the statistics about this entry are bad enough so that it can just be deleted
- bool IsTerrible(int64_t nNow = GetAdjustedTime()) const;
-
- //! Calculate the relative chance this entry should be given when selecting nodes to connect to
- double GetChance(int64_t nNow = GetAdjustedTime()) const;
-};
-
/** Stochastic address manager
*
* Design goals:
@@ -130,301 +51,64 @@ public:
* * Several indexes are kept for high performance. Setting m_consistency_check_ratio with the -checkaddrman
* configuration option will introduce (expensive) consistency checks for the entire data structure.
*/
-
-/** Total number of buckets for tried addresses */
-static constexpr int32_t ADDRMAN_TRIED_BUCKET_COUNT_LOG2{8};
-static constexpr int ADDRMAN_TRIED_BUCKET_COUNT{1 << ADDRMAN_TRIED_BUCKET_COUNT_LOG2};
-
-/** Total number of buckets for new addresses */
-static constexpr int32_t ADDRMAN_NEW_BUCKET_COUNT_LOG2{10};
-static constexpr int ADDRMAN_NEW_BUCKET_COUNT{1 << ADDRMAN_NEW_BUCKET_COUNT_LOG2};
-
-/** Maximum allowed number of entries in buckets for new and tried addresses */
-static constexpr int32_t ADDRMAN_BUCKET_SIZE_LOG2{6};
-static constexpr int ADDRMAN_BUCKET_SIZE{1 << ADDRMAN_BUCKET_SIZE_LOG2};
-
-/**
- * Stochastical (IP) address manager
- */
-class CAddrMan
+class AddrMan
{
+ const std::unique_ptr<AddrManImpl> m_impl;
+
public:
- // Read asmap from provided binary file
- static std::vector<bool> DecodeAsmap(fs::path path);
+ explicit AddrMan(std::vector<bool> asmap, bool deterministic, int32_t consistency_check_ratio);
- template <typename Stream>
- void Serialize(Stream& s_) const EXCLUSIVE_LOCKS_REQUIRED(!cs);
+ ~AddrMan();
template <typename Stream>
- void Unserialize(Stream& s_) EXCLUSIVE_LOCKS_REQUIRED(!cs);
-
- explicit CAddrMan(std::vector<bool> asmap, bool deterministic, int32_t consistency_check_ratio);
+ void Serialize(Stream& s_) const;
- ~CAddrMan()
- {
- nKey.SetNull();
- }
+ template <typename Stream>
+ void Unserialize(Stream& s_);
//! Return the number of (unique) addresses in all tables.
- size_t size() const
- EXCLUSIVE_LOCKS_REQUIRED(!cs)
- {
- LOCK(cs); // TODO: Cache this in an atomic to avoid this overhead
- return vRandom.size();
- }
+ size_t size() const;
//! Add addresses to addrman's new table.
- bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64_t nTimePenalty = 0)
- EXCLUSIVE_LOCKS_REQUIRED(!cs)
- {
- LOCK(cs);
- int nAdd = 0;
- Check();
- for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++)
- nAdd += Add_(*it, source, nTimePenalty) ? 1 : 0;
- Check();
- if (nAdd) {
- LogPrint(BCLog::ADDRMAN, "Added %i addresses from %s: %i tried, %i new\n", nAdd, source.ToString(), nTried, nNew);
- }
- return nAdd > 0;
- }
+ bool Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, int64_t nTimePenalty = 0);
- //! Mark an entry as accessible.
- void Good(const CService &addr, int64_t nTime = GetAdjustedTime())
- EXCLUSIVE_LOCKS_REQUIRED(!cs)
- {
- LOCK(cs);
- Check();
- Good_(addr, /* test_before_evict */ true, nTime);
- Check();
- }
+ //! Mark an entry as accessible, possibly moving it from "new" to "tried".
+ void Good(const CService& addr, int64_t nTime = GetAdjustedTime());
//! Mark an entry as connection attempted to.
- void Attempt(const CService &addr, bool fCountFailure, int64_t nTime = GetAdjustedTime())
- EXCLUSIVE_LOCKS_REQUIRED(!cs)
- {
- LOCK(cs);
- Check();
- Attempt_(addr, fCountFailure, nTime);
- Check();
- }
+ void Attempt(const CService& addr, bool fCountFailure, int64_t nTime = GetAdjustedTime());
//! See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
- void ResolveCollisions()
- EXCLUSIVE_LOCKS_REQUIRED(!cs)
- {
- LOCK(cs);
- Check();
- ResolveCollisions_();
- Check();
- }
-
- //! Randomly select an address in tried that another address is attempting to evict.
- CAddrInfo SelectTriedCollision()
- EXCLUSIVE_LOCKS_REQUIRED(!cs)
- {
- LOCK(cs);
- Check();
- const CAddrInfo ret = SelectTriedCollision_();
- Check();
- return ret;
- }
+ void ResolveCollisions();
/**
- * Choose an address to connect to.
+ * Randomly select an address in the tried table that another address is
+ * attempting to evict.
+ *
+ * @return CAddress The record for the selected tried peer.
+ * int64_t The last time we attempted to connect to that peer.
*/
- CAddrInfo Select(bool newOnly = false) const
- EXCLUSIVE_LOCKS_REQUIRED(!cs)
- {
- LOCK(cs);
- Check();
- const CAddrInfo addrRet = Select_(newOnly);
- Check();
- return addrRet;
- }
+ std::pair<CAddress, int64_t> SelectTriedCollision();
/**
- * Return all or many randomly selected addresses, optionally by network.
+ * Choose an address to connect to.
*
- * @param[in] max_addresses Maximum number of addresses to return (0 = all).
- * @param[in] max_pct Maximum percentage of addresses to return (0 = all).
- * @param[in] network Select only addresses of this network (nullopt = all).
+ * @param[in] newOnly Whether to only select addresses from the new table.
+ * @return CAddress The record for the selected peer.
+ * int64_t The last time we attempted to connect to that peer.
*/
- std::vector<CAddress> GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network) const
- EXCLUSIVE_LOCKS_REQUIRED(!cs)
- {
- LOCK(cs);
- Check();
- std::vector<CAddress> vAddr;
- GetAddr_(vAddr, max_addresses, max_pct, network);
- Check();
- return vAddr;
- }
-
- //! Outer function for Connected_()
- void Connected(const CService &addr, int64_t nTime = GetAdjustedTime())
- EXCLUSIVE_LOCKS_REQUIRED(!cs)
- {
- LOCK(cs);
- Check();
- Connected_(addr, nTime);
- Check();
- }
-
- void SetServices(const CService &addr, ServiceFlags nServices)
- EXCLUSIVE_LOCKS_REQUIRED(!cs)
- {
- LOCK(cs);
- Check();
- SetServices_(addr, nServices);
- Check();
- }
-
- const std::vector<bool>& GetAsmap() const { return m_asmap; }
-
-private:
- //! A mutex to protect the inner data structures.
- mutable Mutex cs;
-
- //! Source of random numbers for randomization in inner loops
- mutable FastRandomContext insecure_rand GUARDED_BY(cs);
-
- //! secret key to randomize bucket select with
- uint256 nKey;
-
- //! Serialization versions.
- enum Format : uint8_t {
- V0_HISTORICAL = 0, //!< historic format, before commit e6b343d88
- V1_DETERMINISTIC = 1, //!< for pre-asmap files
- V2_ASMAP = 2, //!< for files including asmap version
- V3_BIP155 = 3, //!< same as V2_ASMAP plus addresses are in BIP155 format
- };
-
- //! The maximum format this software knows it can unserialize. Also, we always serialize
- //! in this format.
- //! The format (first byte in the serialized stream) can be higher than this and
- //! still this software may be able to unserialize the file - if the second byte
- //! (see `lowest_compatible` in `Unserialize()`) is less or equal to this.
- static constexpr Format FILE_FORMAT = Format::V3_BIP155;
-
- //! The initial value of a field that is incremented every time an incompatible format
- //! change is made (such that old software versions would not be able to parse and
- //! understand the new file format). This is 32 because we overtook the "key size"
- //! field which was 32 historically.
- //! @note Don't increment this. Increment `lowest_compatible` in `Serialize()` instead.
- static constexpr uint8_t INCOMPATIBILITY_BASE = 32;
-
- //! last used nId
- int nIdCount GUARDED_BY(cs){0};
-
- //! table with information about all nIds
- std::unordered_map<int, CAddrInfo> mapInfo GUARDED_BY(cs);
-
- //! find an nId based on its network address
- std::unordered_map<CNetAddr, int, CNetAddrHash> mapAddr GUARDED_BY(cs);
-
- //! randomly-ordered vector of all nIds
- //! This is mutable because it is unobservable outside the class, so any
- //! changes to it (even in const methods) are also unobservable.
- mutable std::vector<int> vRandom GUARDED_BY(cs);
-
- // number of "tried" entries
- int nTried GUARDED_BY(cs){0};
-
- //! list of "tried" buckets
- int vvTried[ADDRMAN_TRIED_BUCKET_COUNT][ADDRMAN_BUCKET_SIZE] GUARDED_BY(cs);
-
- //! number of (unique) "new" entries
- int nNew GUARDED_BY(cs){0};
-
- //! list of "new" buckets
- int vvNew[ADDRMAN_NEW_BUCKET_COUNT][ADDRMAN_BUCKET_SIZE] GUARDED_BY(cs);
-
- //! last time Good was called (memory only). Initially set to 1 so that "never" is strictly worse.
- int64_t nLastGood GUARDED_BY(cs){1};
-
- //! Holds addrs inserted into tried table that collide with existing entries. Test-before-evict discipline used to resolve these collisions.
- std::set<int> m_tried_collisions;
-
- /** Perform consistency checks every m_consistency_check_ratio operations (if non-zero). */
- const int32_t m_consistency_check_ratio;
-
- // Compressed IP->ASN mapping, loaded from a file when a node starts.
- // Should be always empty if no file was provided.
- // This mapping is then used for bucketing nodes in Addrman.
- //
- // If asmap is provided, nodes will be bucketed by
- // AS they belong to, in order to make impossible for a node
- // to connect to several nodes hosted in a single AS.
- // This is done in response to Erebus attack, but also to generally
- // diversify the connections every node creates,
- // especially useful when a large fraction of nodes
- // operate under a couple of cloud providers.
- //
- // If a new asmap was provided, the existing records
- // would be re-bucketed accordingly.
- const std::vector<bool> m_asmap;
-
- //! Find an entry.
- CAddrInfo* Find(const CNetAddr& addr, int *pnId = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
-
- //! Create a new entry and add it to the internal data structures mapInfo, mapAddr and vRandom.
- CAddrInfo* Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
-
- //! Swap two elements in vRandom.
- void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2) const EXCLUSIVE_LOCKS_REQUIRED(cs);
-
- //! Move an entry from the "new" table(s) to the "tried" table
- void MakeTried(CAddrInfo& info, int nId) EXCLUSIVE_LOCKS_REQUIRED(cs);
-
- //! Delete an entry. It must not be in tried, and have refcount 0.
- void Delete(int nId) EXCLUSIVE_LOCKS_REQUIRED(cs);
-
- //! Clear a position in a "new" table. This is the only place where entries are actually deleted.
- void ClearNew(int nUBucket, int nUBucketPos) EXCLUSIVE_LOCKS_REQUIRED(cs);
-
- //! Mark an entry "good", possibly moving it from "new" to "tried".
- void Good_(const CService &addr, bool test_before_evict, int64_t time) EXCLUSIVE_LOCKS_REQUIRED(cs);
-
- //! Add an entry to the "new" table.
- bool Add_(const CAddress &addr, const CNetAddr& source, int64_t nTimePenalty) EXCLUSIVE_LOCKS_REQUIRED(cs);
-
- //! Mark an entry as attempted to connect.
- void Attempt_(const CService &addr, bool fCountFailure, int64_t nTime) EXCLUSIVE_LOCKS_REQUIRED(cs);
-
- //! Select an address to connect to, if newOnly is set to true, only the new table is selected from.
- CAddrInfo Select_(bool newOnly) const EXCLUSIVE_LOCKS_REQUIRED(cs);
-
- //! See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
- void ResolveCollisions_() EXCLUSIVE_LOCKS_REQUIRED(cs);
-
- //! Return a random to-be-evicted tried table address.
- CAddrInfo SelectTriedCollision_() EXCLUSIVE_LOCKS_REQUIRED(cs);
-
- //! Consistency check
- void Check() const EXCLUSIVE_LOCKS_REQUIRED(cs)
- {
- AssertLockHeld(cs);
-
- const int err = Check_();
- if (err) {
- LogPrintf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
- assert(false);
- }
- }
-
- //! Perform consistency check. Returns an error code or zero.
- int Check_() const EXCLUSIVE_LOCKS_REQUIRED(cs);
+ std::pair<CAddress, int64_t> Select(bool newOnly = false) const;
/**
* Return all or many randomly selected addresses, optionally by network.
*
- * @param[out] vAddr Vector of randomly selected addresses from vRandom.
* @param[in] max_addresses Maximum number of addresses to return (0 = all).
* @param[in] max_pct Maximum percentage of addresses to return (0 = all).
* @param[in] network Select only addresses of this network (nullopt = all).
+ *
+ * @return A vector of randomly selected addresses from vRandom.
*/
- void GetAddr_(std::vector<CAddress>& vAddr, size_t max_addresses, size_t max_pct, std::optional<Network> network) const EXCLUSIVE_LOCKS_REQUIRED(cs);
+ std::vector<CAddress> GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network) const;
/** We have successfully connected to this peer. Calling this function
* updates the CAddress's nTime, which is used in our IsTerrible()
@@ -437,13 +121,15 @@ private:
* @param[in] addr The address of the peer we were connected to
* @param[in] nTime The time that we were last connected to this peer
*/
- void Connected_(const CService& addr, int64_t nTime) EXCLUSIVE_LOCKS_REQUIRED(cs);
+ void Connected(const CService& addr, int64_t nTime = GetAdjustedTime());
//! Update an entry's service bits.
- void SetServices_(const CService &addr, ServiceFlags nServices) EXCLUSIVE_LOCKS_REQUIRED(cs);
+ void SetServices(const CService& addr, ServiceFlags nServices);
+
+ const std::vector<bool>& GetAsmap() const;
- friend class CAddrManTest;
- friend class CAddrManDeterministic;
+ friend class AddrManTest;
+ friend class AddrManDeterministic;
};
#endif // BITCOIN_ADDRMAN_H
diff --git a/src/addrman_impl.h b/src/addrman_impl.h
new file mode 100644
index 0000000000..1dc7f25f9c
--- /dev/null
+++ b/src/addrman_impl.h
@@ -0,0 +1,271 @@
+// Copyright (c) 2021 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_ADDRMAN_IMPL_H
+#define BITCOIN_ADDRMAN_IMPL_H
+
+#include <logging.h>
+#include <netaddress.h>
+#include <protocol.h>
+#include <serialize.h>
+#include <sync.h>
+#include <uint256.h>
+
+#include <cstdint>
+#include <optional>
+#include <set>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+/** Total number of buckets for tried addresses */
+static constexpr int32_t ADDRMAN_TRIED_BUCKET_COUNT_LOG2{8};
+static constexpr int ADDRMAN_TRIED_BUCKET_COUNT{1 << ADDRMAN_TRIED_BUCKET_COUNT_LOG2};
+/** Total number of buckets for new addresses */
+static constexpr int32_t ADDRMAN_NEW_BUCKET_COUNT_LOG2{10};
+static constexpr int ADDRMAN_NEW_BUCKET_COUNT{1 << ADDRMAN_NEW_BUCKET_COUNT_LOG2};
+/** Maximum allowed number of entries in buckets for new and tried addresses */
+static constexpr int32_t ADDRMAN_BUCKET_SIZE_LOG2{6};
+static constexpr int ADDRMAN_BUCKET_SIZE{1 << ADDRMAN_BUCKET_SIZE_LOG2};
+
+/**
+ * Extended statistics about a CAddress
+ */
+class AddrInfo : public CAddress
+{
+public:
+ //! last try whatsoever by us (memory only)
+ int64_t nLastTry{0};
+
+ //! last counted attempt (memory only)
+ int64_t nLastCountAttempt{0};
+
+ //! where knowledge about this address first came from
+ CNetAddr source;
+
+ //! last successful connection by us
+ int64_t nLastSuccess{0};
+
+ //! connection attempts since last successful attempt
+ int nAttempts{0};
+
+ //! reference count in new sets (memory only)
+ int nRefCount{0};
+
+ //! in tried set? (memory only)
+ bool fInTried{false};
+
+ //! position in vRandom
+ mutable int nRandomPos{-1};
+
+ SERIALIZE_METHODS(AddrInfo, obj)
+ {
+ READWRITEAS(CAddress, obj);
+ READWRITE(obj.source, obj.nLastSuccess, obj.nAttempts);
+ }
+
+ AddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn), source(addrSource)
+ {
+ }
+
+ AddrInfo() : CAddress(), source()
+ {
+ }
+
+ //! Calculate in which "tried" bucket this entry belongs
+ int GetTriedBucket(const uint256 &nKey, const std::vector<bool> &asmap) const;
+
+ //! Calculate in which "new" bucket this entry belongs, given a certain source
+ int GetNewBucket(const uint256 &nKey, const CNetAddr& src, const std::vector<bool> &asmap) const;
+
+ //! Calculate in which "new" bucket this entry belongs, using its default source
+ int GetNewBucket(const uint256 &nKey, const std::vector<bool> &asmap) const
+ {
+ return GetNewBucket(nKey, source, asmap);
+ }
+
+ //! Calculate in which position of a bucket to store this entry.
+ int GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const;
+
+ //! Determine whether the statistics about this entry are bad enough so that it can just be deleted
+ bool IsTerrible(int64_t nNow = GetAdjustedTime()) const;
+
+ //! Calculate the relative chance this entry should be given when selecting nodes to connect to
+ double GetChance(int64_t nNow = GetAdjustedTime()) const;
+};
+
+class AddrManImpl
+{
+public:
+ AddrManImpl(std::vector<bool>&& asmap, bool deterministic, int32_t consistency_check_ratio);
+
+ ~AddrManImpl();
+
+ template <typename Stream>
+ void Serialize(Stream& s_) const EXCLUSIVE_LOCKS_REQUIRED(!cs);
+
+ template <typename Stream>
+ void Unserialize(Stream& s_) EXCLUSIVE_LOCKS_REQUIRED(!cs);
+
+ size_t size() const EXCLUSIVE_LOCKS_REQUIRED(!cs);
+
+ bool Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, int64_t nTimePenalty)
+ EXCLUSIVE_LOCKS_REQUIRED(!cs);
+
+ void Good(const CService& addr, int64_t nTime)
+ EXCLUSIVE_LOCKS_REQUIRED(!cs);
+
+ void Attempt(const CService& addr, bool fCountFailure, int64_t nTime)
+ EXCLUSIVE_LOCKS_REQUIRED(!cs);
+
+ void ResolveCollisions() EXCLUSIVE_LOCKS_REQUIRED(!cs);
+
+ std::pair<CAddress, int64_t> SelectTriedCollision() EXCLUSIVE_LOCKS_REQUIRED(!cs);
+
+ std::pair<CAddress, int64_t> Select(bool newOnly) const
+ EXCLUSIVE_LOCKS_REQUIRED(!cs);
+
+ std::vector<CAddress> GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network) const
+ EXCLUSIVE_LOCKS_REQUIRED(!cs);
+
+ void Connected(const CService& addr, int64_t nTime)
+ EXCLUSIVE_LOCKS_REQUIRED(!cs);
+
+ void SetServices(const CService& addr, ServiceFlags nServices)
+ EXCLUSIVE_LOCKS_REQUIRED(!cs);
+
+ const std::vector<bool>& GetAsmap() const;
+
+ friend class AddrManTest;
+ friend class AddrManDeterministic;
+
+private:
+ //! A mutex to protect the inner data structures.
+ mutable Mutex cs;
+
+ //! Source of random numbers for randomization in inner loops
+ mutable FastRandomContext insecure_rand GUARDED_BY(cs);
+
+ //! secret key to randomize bucket select with
+ uint256 nKey;
+
+ //! Serialization versions.
+ enum Format : uint8_t {
+ V0_HISTORICAL = 0, //!< historic format, before commit e6b343d88
+ V1_DETERMINISTIC = 1, //!< for pre-asmap files
+ V2_ASMAP = 2, //!< for files including asmap version
+ V3_BIP155 = 3, //!< same as V2_ASMAP plus addresses are in BIP155 format
+ };
+
+ //! The maximum format this software knows it can unserialize. Also, we always serialize
+ //! in this format.
+ //! The format (first byte in the serialized stream) can be higher than this and
+ //! still this software may be able to unserialize the file - if the second byte
+ //! (see `lowest_compatible` in `Unserialize()`) is less or equal to this.
+ static constexpr Format FILE_FORMAT = Format::V3_BIP155;
+
+ //! The initial value of a field that is incremented every time an incompatible format
+ //! change is made (such that old software versions would not be able to parse and
+ //! understand the new file format). This is 32 because we overtook the "key size"
+ //! field which was 32 historically.
+ //! @note Don't increment this. Increment `lowest_compatible` in `Serialize()` instead.
+ static constexpr uint8_t INCOMPATIBILITY_BASE = 32;
+
+ //! last used nId
+ int nIdCount GUARDED_BY(cs){0};
+
+ //! table with information about all nIds
+ std::unordered_map<int, AddrInfo> mapInfo GUARDED_BY(cs);
+
+ //! find an nId based on its network address
+ std::unordered_map<CNetAddr, int, CNetAddrHash> mapAddr GUARDED_BY(cs);
+
+ //! randomly-ordered vector of all nIds
+ //! This is mutable because it is unobservable outside the class, so any
+ //! changes to it (even in const methods) are also unobservable.
+ mutable std::vector<int> vRandom GUARDED_BY(cs);
+
+ // number of "tried" entries
+ int nTried GUARDED_BY(cs){0};
+
+ //! list of "tried" buckets
+ int vvTried[ADDRMAN_TRIED_BUCKET_COUNT][ADDRMAN_BUCKET_SIZE] GUARDED_BY(cs);
+
+ //! number of (unique) "new" entries
+ int nNew GUARDED_BY(cs){0};
+
+ //! list of "new" buckets
+ int vvNew[ADDRMAN_NEW_BUCKET_COUNT][ADDRMAN_BUCKET_SIZE] GUARDED_BY(cs);
+
+ //! last time Good was called (memory only). Initially set to 1 so that "never" is strictly worse.
+ int64_t nLastGood GUARDED_BY(cs){1};
+
+ //! Holds addrs inserted into tried table that collide with existing entries. Test-before-evict discipline used to resolve these collisions.
+ std::set<int> m_tried_collisions;
+
+ /** Perform consistency checks every m_consistency_check_ratio operations (if non-zero). */
+ const int32_t m_consistency_check_ratio;
+
+ // Compressed IP->ASN mapping, loaded from a file when a node starts.
+ // Should be always empty if no file was provided.
+ // This mapping is then used for bucketing nodes in Addrman.
+ //
+ // If asmap is provided, nodes will be bucketed by
+ // AS they belong to, in order to make impossible for a node
+ // to connect to several nodes hosted in a single AS.
+ // This is done in response to Erebus attack, but also to generally
+ // diversify the connections every node creates,
+ // especially useful when a large fraction of nodes
+ // operate under a couple of cloud providers.
+ //
+ // If a new asmap was provided, the existing records
+ // would be re-bucketed accordingly.
+ const std::vector<bool> m_asmap;
+
+ //! Find an entry.
+ AddrInfo* Find(const CNetAddr& addr, int* pnId = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ //! Create a new entry and add it to the internal data structures mapInfo, mapAddr and vRandom.
+ AddrInfo* Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ //! Swap two elements in vRandom.
+ void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2) const EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ //! Delete an entry. It must not be in tried, and have refcount 0.
+ void Delete(int nId) EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ //! Clear a position in a "new" table. This is the only place where entries are actually deleted.
+ void ClearNew(int nUBucket, int nUBucketPos) EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ //! Move an entry from the "new" table(s) to the "tried" table
+ void MakeTried(AddrInfo& info, int nId) EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ void Good_(const CService& addr, bool test_before_evict, int64_t time) EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ bool Add_(const CAddress& addr, const CNetAddr& source, int64_t nTimePenalty) EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ void Attempt_(const CService& addr, bool fCountFailure, int64_t nTime) EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ std::pair<CAddress, int64_t> Select_(bool newOnly) const EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ std::vector<CAddress> GetAddr_(size_t max_addresses, size_t max_pct, std::optional<Network> network) const EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ void Connected_(const CService& addr, int64_t nTime) EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ void SetServices_(const CService& addr, ServiceFlags nServices) EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ void ResolveCollisions_() EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ std::pair<CAddress, int64_t> SelectTriedCollision_() EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ //! Consistency check, taking into account m_consistency_check_ratio. Will std::abort if an inconsistency is detected.
+ void Check() const EXCLUSIVE_LOCKS_REQUIRED(cs);
+
+ //! Perform consistency check, regardless of m_consistency_check_ratio.
+ //! @returns an error code or zero.
+ int ForceCheckAddrman() const EXCLUSIVE_LOCKS_REQUIRED(cs);
+};
+
+#endif // BITCOIN_ADDRMAN_IMPL_H
diff --git a/src/bech32.cpp b/src/bech32.cpp
index 288b14e023..9da2488ef2 100644
--- a/src/bech32.cpp
+++ b/src/bech32.cpp
@@ -66,6 +66,26 @@ uint32_t PolyMod(const data& v)
// the above example, `c` initially corresponds to 1 mod g(x), and after processing 2 inputs of
// v, it corresponds to x^2 + v0*x + v1 mod g(x). As 1 mod g(x) = 1, that is the starting value
// for `c`.
+
+ // The following Sage code constructs the generator used:
+ //
+ // B = GF(2) # Binary field
+ // BP.<b> = B[] # Polynomials over the binary field
+ // F_mod = b**5 + b**3 + 1
+ // F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition
+ // FP.<x> = F[] # Polynomials over GF(32)
+ // E_mod = x**2 + F.fetch_int(9)*x + F.fetch_int(23)
+ // E.<e> = F.extension(E_mod) # GF(1024) extension field definition
+ // for p in divisors(E.order() - 1): # Verify e has order 1023.
+ // assert((e**p == 1) == (p % 1023 == 0))
+ // G = lcm([(e**i).minpoly() for i in range(997,1000)])
+ // print(G) # Print out the generator
+ //
+ // It demonstrates that g(x) is the least common multiple of the minimal polynomials
+ // of 3 consecutive powers (997,998,999) of a primitive element (e) of GF(1024).
+ // That guarantees it is, in fact, the generator of a primitive BCH code with cycle
+ // length 1023 and distance 4. See https://en.wikipedia.org/wiki/BCH_code for more details.
+
uint32_t c = 1;
for (const auto v_i : v) {
// We want to update `c` to correspond to a polynomial with one extra term. If the initial
@@ -88,12 +108,21 @@ uint32_t PolyMod(const data& v)
// Then compute c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i:
c = ((c & 0x1ffffff) << 5) ^ v_i;
- // Finally, for each set bit n in c0, conditionally add {2^n}k(x):
+ // Finally, for each set bit n in c0, conditionally add {2^n}k(x). These constants can be
+ // computed using the following Sage code (continuing the code above):
+ //
+ // for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(g(x) mod x^6), packed in hex integers.
+ // v = 0
+ // for coef in reversed((F.fetch_int(i)*(G % x**6)).coefficients(sparse=True)):
+ // v = v*32 + coef.integer_representation()
+ // print("0x%x" % v)
+ //
if (c0 & 1) c ^= 0x3b6a57b2; // k(x) = {29}x^5 + {22}x^4 + {20}x^3 + {21}x^2 + {29}x + {18}
if (c0 & 2) c ^= 0x26508e6d; // {2}k(x) = {19}x^5 + {5}x^4 + x^3 + {3}x^2 + {19}x + {13}
if (c0 & 4) c ^= 0x1ea119fa; // {4}k(x) = {15}x^5 + {10}x^4 + {2}x^3 + {6}x^2 + {15}x + {26}
if (c0 & 8) c ^= 0x3d4233dd; // {8}k(x) = {30}x^5 + {20}x^4 + {4}x^3 + {12}x^2 + {30}x + {29}
if (c0 & 16) c ^= 0x2a1462b3; // {16}k(x) = {21}x^5 + x^4 + {8}x^3 + {24}x^2 + {21}x + {19}
+
}
return c;
}
@@ -125,7 +154,8 @@ Encoding VerifyChecksum(const std::string& hrp, const data& values)
// PolyMod computes what value to xor into the final values to make the checksum 0. However,
// if we required that the checksum was 0, it would be the case that appending a 0 to a valid
// list of values would result in a new valid list. For that reason, Bech32 requires the
- // resulting checksum to be 1 instead. In Bech32m, this constant was amended.
+ // resulting checksum to be 1 instead. In Bech32m, this constant was amended. See
+ // https://gist.github.com/sipa/14c248c288c3880a3b191f978a34508e for details.
const uint32_t check = PolyMod(Cat(ExpandHRP(hrp), values));
if (check == EncodingConstant(Encoding::BECH32)) return Encoding::BECH32;
if (check == EncodingConstant(Encoding::BECH32M)) return Encoding::BECH32M;
diff --git a/src/bench/addrman.cpp b/src/bench/addrman.cpp
index 8fbb68c04c..d6834a239b 100644
--- a/src/bench/addrman.cpp
+++ b/src/bench/addrman.cpp
@@ -5,6 +5,7 @@
#include <addrman.h>
#include <bench/bench.h>
#include <random.h>
+#include <util/check.h>
#include <util/time.h>
#include <optional>
@@ -52,14 +53,14 @@ static void CreateAddresses()
}
}
-static void AddAddressesToAddrMan(CAddrMan& addrman)
+static void AddAddressesToAddrMan(AddrMan& addrman)
{
for (size_t source_i = 0; source_i < NUM_SOURCES; ++source_i) {
addrman.Add(g_addresses[source_i], g_sources[source_i]);
}
}
-static void FillAddrMan(CAddrMan& addrman)
+static void FillAddrMan(AddrMan& addrman)
{
CreateAddresses();
@@ -73,26 +74,26 @@ static void AddrManAdd(benchmark::Bench& bench)
CreateAddresses();
bench.run([&] {
- CAddrMan addrman{/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0};
+ AddrMan addrman{/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0};
AddAddressesToAddrMan(addrman);
});
}
static void AddrManSelect(benchmark::Bench& bench)
{
- CAddrMan addrman(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
+ AddrMan addrman(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
FillAddrMan(addrman);
bench.run([&] {
const auto& address = addrman.Select();
- assert(address.GetPort() > 0);
+ assert(address.first.GetPort() > 0);
});
}
static void AddrManGetAddr(benchmark::Bench& bench)
{
- CAddrMan addrman(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
+ AddrMan addrman(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
FillAddrMan(addrman);
@@ -102,40 +103,33 @@ static void AddrManGetAddr(benchmark::Bench& bench)
});
}
-static void AddrManGood(benchmark::Bench& bench)
+static void AddrManAddThenGood(benchmark::Bench& bench)
{
- /* Create many CAddrMan objects - one to be modified at each loop iteration.
- * This is necessary because the CAddrMan::Good() method modifies the
- * object, affecting the timing of subsequent calls to the same method and
- * we want to do the same amount of work in every loop iteration. */
-
- bench.epochs(5).epochIterations(1);
- const size_t addrman_count{bench.epochs() * bench.epochIterations()};
-
- std::vector<std::unique_ptr<CAddrMan>> addrmans(addrman_count);
- for (size_t i{0}; i < addrman_count; ++i) {
- addrmans[i] = std::make_unique<CAddrMan>(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
- FillAddrMan(*addrmans[i]);
- }
-
- auto markSomeAsGood = [](CAddrMan& addrman) {
+ auto markSomeAsGood = [](AddrMan& addrman) {
for (size_t source_i = 0; source_i < NUM_SOURCES; ++source_i) {
for (size_t addr_i = 0; addr_i < NUM_ADDRESSES_PER_SOURCE; ++addr_i) {
- if (addr_i % 32 == 0) {
- addrman.Good(g_addresses[source_i][addr_i]);
- }
+ addrman.Good(g_addresses[source_i][addr_i]);
}
}
};
- uint64_t i = 0;
+ CreateAddresses();
+
bench.run([&] {
- markSomeAsGood(*addrmans.at(i));
- ++i;
+ // To make the benchmark independent of the number of evaluations, we always prepare a new addrman.
+ // This is necessary because AddrMan::Good() method modifies the object, affecting the timing of subsequent calls
+ // to the same method and we want to do the same amount of work in every loop iteration.
+ //
+ // This has some overhead (exactly the result of AddrManAdd benchmark), but that overhead is constant so improvements in
+ // AddrMan::Good() will still be noticeable.
+ AddrMan addrman(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
+ AddAddressesToAddrMan(addrman);
+
+ markSomeAsGood(addrman);
});
}
BENCHMARK(AddrManAdd);
BENCHMARK(AddrManSelect);
BENCHMARK(AddrManGetAddr);
-BENCHMARK(AddrManGood);
+BENCHMARK(AddrManAddThenGood);
diff --git a/src/bench/bech32.cpp b/src/bench/bech32.cpp
index 8e10862a37..bc3685818e 100644
--- a/src/bench/bech32.cpp
+++ b/src/bench/bech32.cpp
@@ -3,7 +3,6 @@
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
-#include <bench/nanobench.h>
#include <bech32.h>
#include <util/strencodings.h>
diff --git a/src/bench/bench.cpp b/src/bench/bench.cpp
index 012057e792..030bc43396 100644
--- a/src/bench/bench.cpp
+++ b/src/bench/bench.cpp
@@ -4,11 +4,18 @@
#include <bench/bench.h>
-#include <chainparams.h>
#include <test/util/setup_common.h>
-#include <validation.h>
+#include <chrono>
+#include <fstream>
+#include <functional>
+#include <iostream>
+#include <map>
#include <regex>
+#include <string>
+#include <vector>
+
+using namespace std::chrono_literals;
const std::function<void(const std::string&)> G_TEST_LOG_FUN{};
@@ -61,6 +68,12 @@ void benchmark::BenchRunner::RunAll(const Args& args)
Bench bench;
bench.name(p.first);
+ if (args.min_time > 0ms) {
+ // convert to nanos before dividing to reduce rounding errors
+ std::chrono::nanoseconds min_time_ns = args.min_time;
+ bench.minEpochTime(min_time_ns / bench.epochs());
+ }
+
if (args.asymptote.empty()) {
p.second(bench);
} else {
diff --git a/src/bench/bench.h b/src/bench/bench.h
index c4fcd80e33..b0e4006ee3 100644
--- a/src/bench/bench.h
+++ b/src/bench/bench.h
@@ -41,11 +41,12 @@ using ankerl::nanobench::Bench;
typedef std::function<void(Bench&)> BenchFunction;
struct Args {
- std::string regex_filter;
bool is_list_only;
+ std::chrono::milliseconds min_time;
std::vector<double> asymptote;
std::string output_csv;
std::string output_json;
+ std::string regex_filter;
};
class BenchRunner
diff --git a/src/bench/bench_bitcoin.cpp b/src/bench/bench_bitcoin.cpp
index aab777cac1..0b43ea1fd5 100644
--- a/src/bench/bench_bitcoin.cpp
+++ b/src/bench/bench_bitcoin.cpp
@@ -4,21 +4,28 @@
#include <bench/bench.h>
+#include <clientversion.h>
#include <crypto/sha256.h>
#include <util/strencodings.h>
#include <util/system.h>
-#include <memory>
+#include <chrono>
+#include <cstdint>
+#include <iostream>
+#include <sstream>
+#include <vector>
static const char* DEFAULT_BENCH_FILTER = ".*";
+static constexpr int64_t DEFAULT_MIN_TIME_MS{10};
static void SetupBenchArgs(ArgsManager& argsman)
{
SetupHelpOptions(argsman);
- argsman.AddArg("-asymptote=n1,n2,n3,...", "Test asymptotic growth of the runtime of an algorithm, if supported by the benchmark", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
+ argsman.AddArg("-asymptote=<n1,n2,n3,...>", "Test asymptotic growth of the runtime of an algorithm, if supported by the benchmark", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-filter=<regex>", strprintf("Regular expression filter to select benchmark by name (default: %s)", DEFAULT_BENCH_FILTER), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
- argsman.AddArg("-list", "List benchmarks without executing them", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
+ argsman.AddArg("-list", "List benchmarks without executing them", ArgsManager::ALLOW_BOOL, OptionsCategory::OPTIONS);
+ argsman.AddArg("-min_time=<milliseconds>", strprintf("Minimum runtime per benchmark, in milliseconds (default: %d)", DEFAULT_MIN_TIME_MS), ArgsManager::ALLOW_INT, OptionsCategory::OPTIONS);
argsman.AddArg("-output_csv=<output.csv>", "Generate CSV file with the most important benchmark results", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-output_json=<output.json>", "Generate JSON file with all benchmark results", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
}
@@ -48,17 +55,62 @@ int main(int argc, char** argv)
}
if (HelpRequested(argsman)) {
- std::cout << argsman.GetHelpMessage();
+ std::cout << "Usage: bench_bitcoin [options]\n"
+ "\n"
+ << argsman.GetHelpMessage()
+ << "Description:\n"
+ "\n"
+ " bench_bitcoin executes microbenchmarks. The quality of the benchmark results\n"
+ " highly depend on the stability of the machine. It can sometimes be difficult\n"
+ " to get stable, repeatable results, so here are a few tips:\n"
+ "\n"
+ " * Use pyperf [1] to disable frequency scaling, turbo boost etc. For best\n"
+ " results, use CPU pinning and CPU isolation (see [2]).\n"
+ "\n"
+ " * Each call of run() should do exactly the same work. E.g. inserting into\n"
+ " a std::vector doesn't do that as it will reallocate on certain calls. Make\n"
+ " sure each run has exactly the same preconditions.\n"
+ "\n"
+ " * If results are still not reliable, increase runtime with e.g.\n"
+ " -min_time=5000 to let a benchmark run for at least 5 seconds.\n"
+ "\n"
+ " * bench_bitcoin uses nanobench [3] for which there is extensive\n"
+ " documentation available online.\n"
+ "\n"
+ "Environment Variables:\n"
+ "\n"
+ " To attach a profiler you can run a benchmark in endless mode. This can be\n"
+ " done with the environment variable NANOBENCH_ENDLESS. E.g. like so:\n"
+ "\n"
+ " NANOBENCH_ENDLESS=MuHash ./bench_bitcoin -filter=MuHash\n"
+ "\n"
+ " In rare cases it can be useful to suppress stability warnings. This can be\n"
+ " done with the environment variable NANOBENCH_SUPPRESS_WARNINGS, e.g:\n"
+ "\n"
+ " NANOBENCH_SUPPRESS_WARNINGS=1 ./bench_bitcoin\n"
+ "\n"
+ "Notes:\n"
+ "\n"
+ " 1. pyperf\n"
+ " https://github.com/psf/pyperf\n"
+ "\n"
+ " 2. CPU pinning & isolation\n"
+ " https://pyperf.readthedocs.io/en/latest/system.html\n"
+ "\n"
+ " 3. nanobench\n"
+ " https://github.com/martinus/nanobench\n"
+ "\n";
return EXIT_SUCCESS;
}
benchmark::Args args;
- args.regex_filter = argsman.GetArg("-filter", DEFAULT_BENCH_FILTER);
- args.is_list_only = argsman.GetBoolArg("-list", false);
args.asymptote = parseAsymptote(argsman.GetArg("-asymptote", ""));
+ args.is_list_only = argsman.GetBoolArg("-list", false);
+ args.min_time = std::chrono::milliseconds(argsman.GetIntArg("-min_time", DEFAULT_MIN_TIME_MS));
args.output_csv = argsman.GetArg("-output_csv", "");
args.output_json = argsman.GetArg("-output_json", "");
+ args.regex_filter = argsman.GetArg("-filter", DEFAULT_BENCH_FILTER);
benchmark::BenchRunner::RunAll(args);
diff --git a/src/bench/coin_selection.cpp b/src/bench/coin_selection.cpp
index aa79aab755..934b574f8b 100644
--- a/src/bench/coin_selection.cpp
+++ b/src/bench/coin_selection.cpp
@@ -53,7 +53,7 @@ static void CoinSelection(benchmark::Bench& bench)
const CoinSelectionParams coin_selection_params(/* change_output_size= */ 34,
/* change_spend_size= */ 148, /* effective_feerate= */ CFeeRate(0),
/* long_term_feerate= */ CFeeRate(0), /* discard_feerate= */ CFeeRate(0),
- /* tx_no_inputs_size= */ 0, /* avoid_partial= */ false);
+ /* tx_noinputs_size= */ 0, /* avoid_partial= */ false);
bench.run([&] {
std::set<CInputCoin> setCoinsRet;
CAmount nValueRet;
diff --git a/src/bench/crypto_hash.cpp b/src/bench/crypto_hash.cpp
index 30fe11be6b..d36e504bfc 100644
--- a/src/bench/crypto_hash.cpp
+++ b/src/bench/crypto_hash.cpp
@@ -110,9 +110,9 @@ static void MuHash(benchmark::Bench& bench)
{
MuHash3072 acc;
unsigned char key[32] = {0};
- int i = 0;
+ uint32_t i = 0;
bench.run([&] {
- key[0] = ++i;
+ key[0] = ++i & 0xFF;
acc *= MuHash3072(key);
});
}
@@ -134,10 +134,6 @@ static void MuHashDiv(benchmark::Bench& bench)
FastRandomContext rng(true);
MuHash3072 muhash{rng.randbytes(32)};
- for (size_t i = 0; i < bench.epochIterations(); ++i) {
- acc *= muhash;
- }
-
bench.run([&] {
acc /= muhash;
});
diff --git a/src/bench/nanobench.h b/src/bench/nanobench.h
index 030d6ebf6a..27df08fb69 100644
--- a/src/bench/nanobench.h
+++ b/src/bench/nanobench.h
@@ -33,7 +33,7 @@
// see https://semver.org/
#define ANKERL_NANOBENCH_VERSION_MAJOR 4 // incompatible API changes
#define ANKERL_NANOBENCH_VERSION_MINOR 3 // backwards-compatible changes
-#define ANKERL_NANOBENCH_VERSION_PATCH 4 // backwards-compatible bug fixes
+#define ANKERL_NANOBENCH_VERSION_PATCH 6 // backwards-compatible bug fixes
///////////////////////////////////////////////////////////////////////////////////////////////////
// public facing api - as minimal as possible
@@ -88,13 +88,15 @@
} while (0)
#endif
-#if defined(__linux__) && defined(PERF_EVENT_IOC_ID) && defined(PERF_COUNT_HW_REF_CPU_CYCLES) && defined(PERF_FLAG_FD_CLOEXEC) && \
- !defined(ANKERL_NANOBENCH_DISABLE_PERF_COUNTERS)
-// only enable perf counters on kernel 3.14 which seems to have all the necessary defines. The three PERF_... defines are not in
-// kernel 2.6.32 (all others are).
-# define ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS() 1
-#else
-# define ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS() 0
+#define ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS() 0
+#if defined(__linux__) && !defined(ANKERL_NANOBENCH_DISABLE_PERF_COUNTERS)
+# include <linux/version.h>
+# if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 14, 0)
+// PERF_COUNT_HW_REF_CPU_CYCLES only available since kernel 3.3
+// PERF_FLAG_FD_CLOEXEC since kernel 3.14
+# undef ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS
+# define ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS() 1
+# endif
#endif
#if defined(__clang__)
@@ -2210,20 +2212,20 @@ struct IterationLogic::Impl {
columns.emplace_back(10, 1, "err%", "%", rErrorMedian * 100.0);
double rInsMedian = -1.0;
- if (mResult.has(Result::Measure::instructions)) {
+ if (mBench.performanceCounters() && mResult.has(Result::Measure::instructions)) {
rInsMedian = mResult.median(Result::Measure::instructions);
columns.emplace_back(18, 2, "ins/" + mBench.unit(), "", rInsMedian / mBench.batch());
}
double rCycMedian = -1.0;
- if (mResult.has(Result::Measure::cpucycles)) {
+ if (mBench.performanceCounters() && mResult.has(Result::Measure::cpucycles)) {
rCycMedian = mResult.median(Result::Measure::cpucycles);
columns.emplace_back(18, 2, "cyc/" + mBench.unit(), "", rCycMedian / mBench.batch());
}
if (rInsMedian > 0.0 && rCycMedian > 0.0) {
columns.emplace_back(9, 3, "IPC", "", rCycMedian <= 0.0 ? 0.0 : rInsMedian / rCycMedian);
}
- if (mResult.has(Result::Measure::branchinstructions)) {
+ if (mBench.performanceCounters() && mResult.has(Result::Measure::branchinstructions)) {
double rBraMedian = mResult.median(Result::Measure::branchinstructions);
columns.emplace_back(17, 2, "bra/" + mBench.unit(), "", rBraMedian / mBench.batch());
if (mResult.has(Result::Measure::branchmisses)) {
@@ -2402,6 +2404,14 @@ public:
return (a + divisor / 2) / divisor;
}
+ ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined")
+ static inline uint32_t mix(uint32_t x) noexcept {
+ x ^= x << 13;
+ x ^= x >> 17;
+ x ^= x << 5;
+ return x;
+ }
+
template <typename Op>
ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined")
void calibrate(Op&& op) {
@@ -2441,15 +2451,10 @@ public:
uint64_t const numIters = 100000U + (std::random_device{}() & 3);
uint64_t n = numIters;
uint32_t x = 1234567;
- auto fn = [&]() {
- x ^= x << 13;
- x ^= x >> 17;
- x ^= x << 5;
- };
beginMeasure();
while (n-- > 0) {
- fn();
+ x = mix(x);
}
endMeasure();
detail::doNotOptimizeAway(x);
@@ -2459,8 +2464,8 @@ public:
beginMeasure();
while (n-- > 0) {
// we now run *twice* so we can easily calculate the overhead
- fn();
- fn();
+ x = mix(x);
+ x = mix(x);
}
endMeasure();
detail::doNotOptimizeAway(x);
diff --git a/src/bench/peer_eviction.cpp b/src/bench/peer_eviction.cpp
index 46fd9d999e..8429f18613 100644
--- a/src/bench/peer_eviction.cpp
+++ b/src/bench/peer_eviction.cpp
@@ -20,19 +20,17 @@ static void EvictionProtectionCommon(
{
using Candidates = std::vector<NodeEvictionCandidate>;
FastRandomContext random_context{true};
- bench.warmup(100).epochIterations(1100);
Candidates candidates{GetRandomNodeEvictionCandidates(num_candidates, random_context)};
for (auto& c : candidates) {
candidate_setup_fn(c);
}
- std::vector<Candidates> copies{
- static_cast<size_t>(bench.epochs() * bench.epochIterations()), candidates};
- size_t i{0};
+
bench.run([&] {
- ProtectEvictionCandidatesByRatio(copies.at(i));
- ++i;
+ // creating a copy has an overhead of about 3%, so it does not influence the benchmark results much.
+ auto copy = candidates;
+ ProtectEvictionCandidatesByRatio(copy);
});
}
diff --git a/src/bench/rollingbloom.cpp b/src/bench/rollingbloom.cpp
index 997ab56549..28167767db 100644
--- a/src/bench/rollingbloom.cpp
+++ b/src/bench/rollingbloom.cpp
@@ -13,16 +13,16 @@ static void RollingBloom(benchmark::Bench& bench)
uint32_t count = 0;
bench.run([&] {
count++;
- data[0] = count;
- data[1] = count >> 8;
- data[2] = count >> 16;
- data[3] = count >> 24;
+ data[0] = count & 0xFF;
+ data[1] = (count >> 8) & 0xFF;
+ data[2] = (count >> 16) & 0xFF;
+ data[3] = (count >> 24) & 0xFF;
filter.insert(data);
- data[0] = count >> 24;
- data[1] = count >> 16;
- data[2] = count >> 8;
- data[3] = count;
+ data[0] = (count >> 24) & 0xFF;
+ data[1] = (count >> 16) & 0xFF;
+ data[2] = (count >> 8) & 0xFF;
+ data[3] = count & 0xFF;
filter.contains(data);
});
}
diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp
index 297f3066ff..3c22ee0f67 100644
--- a/src/bitcoin-cli.cpp
+++ b/src/bitcoin-cli.cpp
@@ -93,9 +93,6 @@ static void SetupCliArgs(ArgsManager& argsman)
/** libevent event log callback */
static void libevent_log_cb(int severity, const char *msg)
{
-#ifndef EVENT_LOG_ERR // EVENT_LOG_ERR was added in 2.0.19; but before then _EVENT_LOG_ERR existed.
-# define EVENT_LOG_ERR _EVENT_LOG_ERR
-#endif
// Ignore everything other than errors
if (severity >= EVENT_LOG_ERR) {
throw std::runtime_error(strprintf("libevent error: %s", msg));
@@ -245,7 +242,7 @@ public:
class AddrinfoRequestHandler : public BaseRequestHandler
{
private:
- static constexpr std::array m_networks{"ipv4", "ipv6", "torv2", "torv3", "i2p"};
+ static constexpr std::array m_networks{"ipv4", "ipv6", "onion", "i2p"};
int8_t NetworkStringToId(const std::string& str) const
{
for (size_t i = 0; i < m_networks.size(); ++i) {
@@ -271,13 +268,10 @@ public:
if (!nodes.empty() && nodes.at(0)["network"].isNull()) {
throw std::runtime_error("-addrinfo requires bitcoind server to be running v22.0 and up");
}
- // Count the number of peers we know by network, including torv2 versus torv3.
+ // Count the number of peers known to our node, by network.
std::array<uint64_t, m_networks.size()> counts{{}};
for (const UniValue& node : nodes) {
std::string network_name{node["network"].get_str()};
- if (network_name == "onion") {
- network_name = node["address"].get_str().size() > 22 ? "torv3" : "torv2";
- }
const int8_t network_id{NetworkStringToId(network_name)};
if (network_id == UNKNOWN_NETWORK) continue;
++counts.at(network_id);
@@ -343,7 +337,7 @@ public:
connections.pushKV("total", batch[ID_NETWORKINFO]["result"]["connections"]);
result.pushKV("connections", connections);
- result.pushKV("proxy", batch[ID_NETWORKINFO]["result"]["networks"][0]["proxy"]);
+ result.pushKV("networks", batch[ID_NETWORKINFO]["result"]["networks"]);
result.pushKV("difficulty", batch[ID_BLOCKCHAININFO]["result"]["difficulty"]);
result.pushKV("chain", UniValue(batch[ID_BLOCKCHAININFO]["result"]["chain"]));
if (!batch[ID_WALLETINFO]["result"].isNull()) {
@@ -708,7 +702,7 @@ static UniValue CallRPC(BaseRequestHandler* rh, const std::string& strMethod, co
// 3. default port for chain
uint16_t port{BaseParams().RPCPort()};
SplitHostPort(gArgs.GetArg("-rpcconnect", DEFAULT_RPCCONNECT), port, host);
- port = static_cast<uint16_t>(gArgs.GetArg("-rpcport", port));
+ port = static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", port));
// Obtain event base
raii_event_base base = obtain_event_base();
@@ -718,7 +712,7 @@ static UniValue CallRPC(BaseRequestHandler* rh, const std::string& strMethod, co
// Set connection timeout
{
- const int timeout = gArgs.GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT);
+ const int timeout = gArgs.GetIntArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT);
if (timeout > 0) {
evhttp_connection_set_timeout(evcon.get(), timeout);
} else {
@@ -828,7 +822,7 @@ static UniValue ConnectAndCallRPC(BaseRequestHandler* rh, const std::string& str
UniValue response(UniValue::VOBJ);
// Execute and handle connection failures with -rpcwait.
const bool fWait = gArgs.GetBoolArg("-rpcwait", false);
- const int timeout = gArgs.GetArg("-rpcwaittimeout", DEFAULT_WAIT_CLIENT_TIMEOUT);
+ const int timeout = gArgs.GetIntArg("-rpcwaittimeout", DEFAULT_WAIT_CLIENT_TIMEOUT);
const auto deadline{GetTime<std::chrono::microseconds>() + 1s * timeout};
do {
@@ -992,8 +986,26 @@ static void ParseGetInfoResult(UniValue& result)
RESET);
result_string += strprintf("Version: %s\n", result["version"].getValStr());
result_string += strprintf("Time offset (s): %s\n", result["timeoffset"].getValStr());
- const std::string proxy = result["proxy"].getValStr();
- result_string += strprintf("Proxy: %s\n", proxy.empty() ? "N/A" : proxy);
+
+ // proxies
+ std::map<std::string, std::vector<std::string>> proxy_networks;
+ std::vector<std::string> ordered_proxies;
+
+ for (const UniValue& network : result["networks"].getValues()) {
+ const std::string proxy = network["proxy"].getValStr();
+ if (proxy.empty()) continue;
+ // Add proxy to ordered_proxy if has not been processed
+ if (proxy_networks.find(proxy) == proxy_networks.end()) ordered_proxies.push_back(proxy);
+
+ proxy_networks[proxy].push_back(network["name"].getValStr());
+ }
+
+ std::vector<std::string> formatted_proxies;
+ for (const std::string& proxy : ordered_proxies) {
+ formatted_proxies.emplace_back(strprintf("%s (%s)", proxy, Join(proxy_networks.find(proxy)->second, ", ")));
+ }
+ result_string += strprintf("Proxies: %s\n", formatted_proxies.empty() ? "n/a" : Join(formatted_proxies, ", "));
+
result_string += strprintf("Min tx relay fee rate (%s/kvB): %s\n\n", CURRENCY_UNIT, result["relayfee"].getValStr());
if (!result["has_wallet"].isNull()) {
diff --git a/src/bitcoin-tx.cpp b/src/bitcoin-tx.cpp
index 58c51bd8e0..fc3bc6aa71 100644
--- a/src/bitcoin-tx.cpp
+++ b/src/bitcoin-tx.cpp
@@ -8,6 +8,7 @@
#include <clientversion.h>
#include <coins.h>
+#include <consensus/amount.h>
#include <consensus/consensus.h>
#include <core_io.h>
#include <key_io.h>
@@ -727,7 +728,7 @@ static void MutateTx(CMutableTransaction& tx, const std::string& command,
static void OutputTxJSON(const CTransaction& tx)
{
UniValue entry(UniValue::VOBJ);
- TxToUniv(tx, uint256(), /* include_addresses */ false, entry);
+ TxToUniv(tx, uint256(), entry);
std::string jsonOutput = entry.write(4);
tfm::format(std::cout, "%s\n", jsonOutput);
diff --git a/src/bitcoind.cpp b/src/bitcoind.cpp
index 654679af27..25ec2809e9 100644
--- a/src/bitcoind.cpp
+++ b/src/bitcoind.cpp
@@ -19,6 +19,7 @@
#include <shutdown.h>
#include <util/check.h>
#include <util/strencodings.h>
+#include <util/syscall_sandbox.h>
#include <util/system.h>
#include <util/threadnames.h>
#include <util/tokenpipe.h>
@@ -238,6 +239,7 @@ static bool AppInit(NodeContext& node, int argc, char* argv[])
daemon_ep.Close();
}
#endif
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::SHUTOFF);
if (fRet) {
WaitForShutdown();
}
diff --git a/src/bloom.cpp b/src/bloom.cpp
index d0128a26d7..15e06389de 100644
--- a/src/bloom.cpp
+++ b/src/bloom.cpp
@@ -4,20 +4,22 @@
#include <bloom.h>
-#include <primitives/transaction.h>
#include <hash.h>
+#include <primitives/transaction.h>
+#include <random.h>
#include <script/script.h>
#include <script/standard.h>
-#include <random.h>
+#include <span.h>
#include <streams.h>
-#include <math.h>
-#include <stdlib.h>
-
#include <algorithm>
+#include <cmath>
+#include <cstdlib>
+#include <limits>
+#include <vector>
-#define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455
-#define LN2 0.6931471805599453094172321214581765680755001343602552
+static constexpr double LN2SQUARED = 0.4804530139182014246671025263266649717305529515945455;
+static constexpr double LN2 = 0.6931471805599453094172321214581765680755001343602552;
CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
/**
@@ -37,13 +39,13 @@ CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, c
{
}
-inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const
+inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, Span<const unsigned char> vDataToHash) const
{
// 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
}
-void CBloomFilter::insert(const std::vector<unsigned char>& vKey)
+void CBloomFilter::insert(Span<const unsigned char> vKey)
{
if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
return;
@@ -59,17 +61,10 @@ void CBloomFilter::insert(const COutPoint& outpoint)
{
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << outpoint;
- std::vector<unsigned char> data(stream.begin(), stream.end());
- insert(data);
+ insert(stream);
}
-void CBloomFilter::insert(const uint256& hash)
-{
- std::vector<unsigned char> data(hash.begin(), hash.end());
- insert(data);
-}
-
-bool CBloomFilter::contains(const std::vector<unsigned char>& vKey) const
+bool CBloomFilter::contains(Span<const unsigned char> vKey) const
{
if (vData.empty()) // Avoid divide-by-zero (CVE-2013-5700)
return true;
@@ -87,14 +82,7 @@ bool CBloomFilter::contains(const COutPoint& outpoint) const
{
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << outpoint;
- std::vector<unsigned char> data(stream.begin(), stream.end());
- return contains(data);
-}
-
-bool CBloomFilter::contains(const uint256& hash) const
-{
- std::vector<unsigned char> data(hash.begin(), hash.end());
- return contains(data);
+ return contains(MakeUCharSpan(stream));
}
bool CBloomFilter::IsWithinSizeConstraints() const
@@ -198,7 +186,8 @@ CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const dou
}
/* Similar to CBloomFilter::Hash */
-static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, const std::vector<unsigned char>& vDataToHash) {
+static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, Span<const unsigned char> vDataToHash)
+{
return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
}
@@ -210,7 +199,7 @@ static inline uint32_t FastMod(uint32_t x, size_t n) {
return ((uint64_t)x * (uint64_t)n) >> 32;
}
-void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
+void CRollingBloomFilter::insert(Span<const unsigned char> vKey)
{
if (nEntriesThisGeneration == nEntriesPerGeneration) {
nEntriesThisGeneration = 0;
@@ -241,13 +230,7 @@ void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
}
}
-void CRollingBloomFilter::insert(const uint256& hash)
-{
- std::vector<unsigned char> vData(hash.begin(), hash.end());
- insert(vData);
-}
-
-bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
+bool CRollingBloomFilter::contains(Span<const unsigned char> vKey) const
{
for (int n = 0; n < nHashFuncs; n++) {
uint32_t h = RollingBloomHash(n, nTweak, vKey);
@@ -261,12 +244,6 @@ bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
return true;
}
-bool CRollingBloomFilter::contains(const uint256& hash) const
-{
- std::vector<unsigned char> vData(hash.begin(), hash.end());
- return contains(vData);
-}
-
void CRollingBloomFilter::reset()
{
nTweak = GetRand(std::numeric_limits<unsigned int>::max());
diff --git a/src/bloom.h b/src/bloom.h
index fdaa8abfb2..422646d8b9 100644
--- a/src/bloom.h
+++ b/src/bloom.h
@@ -6,16 +6,16 @@
#define BITCOIN_BLOOM_H
#include <serialize.h>
+#include <span.h>
#include <vector>
class COutPoint;
class CTransaction;
-class uint256;
//! 20,000 items with fp rate < 0.1% or 10,000 items and <0.0001%
-static const unsigned int MAX_BLOOM_FILTER_SIZE = 36000; // bytes
-static const unsigned int MAX_HASH_FUNCS = 50;
+static constexpr unsigned int MAX_BLOOM_FILTER_SIZE = 36000; // bytes
+static constexpr unsigned int MAX_HASH_FUNCS = 50;
/**
* First two bits of nFlags control how much IsRelevantAndUpdate actually updates
@@ -49,7 +49,7 @@ private:
unsigned int nTweak;
unsigned char nFlags;
- unsigned int Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const;
+ unsigned int Hash(unsigned int nHashNum, Span<const unsigned char> vDataToHash) const;
public:
/**
@@ -66,13 +66,11 @@ public:
SERIALIZE_METHODS(CBloomFilter, obj) { READWRITE(obj.vData, obj.nHashFuncs, obj.nTweak, obj.nFlags); }
- void insert(const std::vector<unsigned char>& vKey);
+ void insert(Span<const unsigned char> vKey);
void insert(const COutPoint& outpoint);
- void insert(const uint256& hash);
- bool contains(const std::vector<unsigned char>& vKey) const;
+ bool contains(Span<const unsigned char> vKey) const;
bool contains(const COutPoint& outpoint) const;
- bool contains(const uint256& hash) const;
//! True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS
//! (catch a filter which was just deserialized which was too big)
@@ -112,10 +110,8 @@ class CRollingBloomFilter
public:
CRollingBloomFilter(const unsigned int nElements, const double nFPRate);
- void insert(const std::vector<unsigned char>& vKey);
- void insert(const uint256& hash);
- bool contains(const std::vector<unsigned char>& vKey) const;
- bool contains(const uint256& hash) const;
+ void insert(Span<const unsigned char> vKey);
+ bool contains(Span<const unsigned char> vKey) const;
void reset();
diff --git a/src/chain.h b/src/chain.h
index 84a3a4e1e7..365a7f79b6 100644
--- a/src/chain.h
+++ b/src/chain.h
@@ -126,7 +126,15 @@ enum BlockStatus: uint32_t {
BLOCK_FAILED_CHILD = 64, //!< descends from failed block
BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
- BLOCK_OPT_WITNESS = 128, //!< block data in blk*.data was received with a witness-enforcing client
+ BLOCK_OPT_WITNESS = 128, //!< block data in blk*.dat was received with a witness-enforcing client
+
+ /**
+ * If set, this indicates that the block index entry is assumed-valid.
+ * Certain diagnostics will be skipped in e.g. CheckBlockIndex().
+ * It almost certainly means that the block's full validation is pending
+ * on a background chainstate. See `doc/assumeutxo.md`.
+ */
+ BLOCK_ASSUMED_VALID = 256,
};
/** The block chain is a tree shaped structure starting with the
@@ -300,14 +308,24 @@ public:
return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
}
+ //! @returns true if the block is assumed-valid; this means it is queued to be
+ //! validated by a background chainstate.
+ bool IsAssumedValid() const { return nStatus & BLOCK_ASSUMED_VALID; }
+
//! Raise the validity level of this block index entry.
//! Returns true if the validity was changed.
bool RaiseValidity(enum BlockStatus nUpTo)
{
assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
- if (nStatus & BLOCK_FAILED_MASK)
- return false;
+ if (nStatus & BLOCK_FAILED_MASK) return false;
+
if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
+ // If this block had been marked assumed-valid and we're raising
+ // its validity to a certain point, there is no longer an assumption.
+ if (nStatus & BLOCK_ASSUMED_VALID && nUpTo >= BLOCK_VALID_SCRIPTS) {
+ nStatus &= ~BLOCK_ASSUMED_VALID;
+ }
+
nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
return true;
}
diff --git a/src/chainparams.cpp b/src/chainparams.cpp
index 4cc37560a3..b155745794 100644
--- a/src/chainparams.cpp
+++ b/src/chainparams.cpp
@@ -280,8 +280,10 @@ public:
if (!args.IsArgSet("-signetchallenge")) {
bin = ParseHex("512103ad5e0edad18cb1f0fc0d28a3d4f1f3e445640337489abb10404f2d1e086be430210359ef5021964fe22d6f8e05b2463c9540ce96883fe3b278760f048f5189f2e6c452ae");
+ vSeeds.emplace_back("seed.signet.bitcoin.sprovoost.nl");
+
+ // Hardcoded nodes can be removed once there are more DNS seeds
vSeeds.emplace_back("178.128.221.177");
- vSeeds.emplace_back("2a01:7c8:d005:390::5");
vSeeds.emplace_back("v7ajjeirttkbnt32wpy3c6w3emwnfr3fkla7hpxcfokr3ysd3kqtzmqd.onion:38333");
consensus.nMinimumChainWork = uint256S("0x0000000000000000000000000000000000000000000000000000008546553c03");
@@ -390,12 +392,12 @@ public:
consensus.signet_challenge.clear();
consensus.nSubsidyHalvingInterval = 150;
consensus.BIP16Exception = uint256();
- consensus.BIP34Height = 2; // BIP34 activated on regtest (Block at height 1 not enforced for testing purposes)
+ consensus.BIP34Height = 1; // Always active unless overridden
consensus.BIP34Hash = uint256();
- consensus.BIP65Height = 111; // BIP65 activated on regtest (Block at height 110 and earlier not enforced for testing purposes)
- consensus.BIP66Height = 102; // BIP66 activated on regtest (Block at height 101 and earlier not enforced for testing purposes)
- consensus.CSVHeight = 432; // CSV activated on regtest (Used in rpc activation tests)
- consensus.SegwitHeight = 0; // SEGWIT is always activated on regtest unless overridden
+ consensus.BIP65Height = 1; // Always active unless overridden
+ consensus.BIP66Height = 1; // Always active unless overridden
+ consensus.CSVHeight = 1; // Always active unless overridden
+ consensus.SegwitHeight = 1; // Always active unless overridden
consensus.MinBIP9WarningHeight = 0;
consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks
@@ -487,15 +489,38 @@ public:
void UpdateActivationParametersFromArgs(const ArgsManager& args);
};
-void CRegTestParams::UpdateActivationParametersFromArgs(const ArgsManager& args)
+static void MaybeUpdateHeights(const ArgsManager& args, Consensus::Params& consensus)
{
- if (args.IsArgSet("-segwitheight")) {
- int64_t height = args.GetArg("-segwitheight", consensus.SegwitHeight);
- if (height < 0 || height >= std::numeric_limits<int>::max()) {
- throw std::runtime_error(strprintf("Activation height %ld for segwit is out of valid range.", height));
+ for (const std::string& arg : args.GetArgs("-testactivationheight")) {
+ const auto found{arg.find('@')};
+ if (found == std::string::npos) {
+ throw std::runtime_error(strprintf("Invalid format (%s) for -testactivationheight=name@height.", arg));
+ }
+ const auto name{arg.substr(0, found)};
+ const auto value{arg.substr(found + 1)};
+ int32_t height;
+ if (!ParseInt32(value, &height) || height < 0 || height >= std::numeric_limits<int>::max()) {
+ throw std::runtime_error(strprintf("Invalid height value (%s) for -testactivationheight=name@height.", arg));
+ }
+ if (name == "segwit") {
+ consensus.SegwitHeight = int{height};
+ } else if (name == "bip34") {
+ consensus.BIP34Height = int{height};
+ } else if (name == "dersig") {
+ consensus.BIP66Height = int{height};
+ } else if (name == "cltv") {
+ consensus.BIP65Height = int{height};
+ } else if (name == "csv") {
+ consensus.CSVHeight = int{height};
+ } else {
+ throw std::runtime_error(strprintf("Invalid name (%s) for -testactivationheight=name@height.", arg));
}
- consensus.SegwitHeight = static_cast<int>(height);
}
+}
+
+void CRegTestParams::UpdateActivationParametersFromArgs(const ArgsManager& args)
+{
+ MaybeUpdateHeights(args, consensus);
if (!args.IsArgSet("-vbparams")) return;
diff --git a/src/chainparamsbase.cpp b/src/chainparamsbase.cpp
index 79c1bc25bc..dc484f5c03 100644
--- a/src/chainparamsbase.cpp
+++ b/src/chainparamsbase.cpp
@@ -20,7 +20,7 @@ void SetupChainParamsBaseOptions(ArgsManager& argsman)
argsman.AddArg("-chain=<chain>", "Use the chain <chain> (default: main). Allowed values: main, test, signet, regtest", ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS);
argsman.AddArg("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
"This is intended for regression testing tools and app development. Equivalent to -chain=regtest.", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS);
- argsman.AddArg("-segwitheight=<n>", "Set the activation height of segwit. (regtest-only)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
+ argsman.AddArg("-testactivationheight=name@height.", "Set the activation height of 'name' (segwit, bip34, dersig, cltv, csv). (regtest-only)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
argsman.AddArg("-testnet", "Use the test chain. Equivalent to -chain=test.", ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS);
argsman.AddArg("-vbparams=deployment:start:end[:min_activation_height]", "Use given start/end times and min_activation_height for specified version bits deployment (regtest-only)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS);
argsman.AddArg("-signet", "Use the signet chain. Equivalent to -chain=signet. Note that the network is defined by the -signetchallenge parameter", ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS);
diff --git a/src/checkqueue.h b/src/checkqueue.h
index 4ceeb3600a..7c20e2013c 100644
--- a/src/checkqueue.h
+++ b/src/checkqueue.h
@@ -7,6 +7,7 @@
#include <sync.h>
#include <tinyformat.h>
+#include <util/syscall_sandbox.h>
#include <util/threadnames.h>
#include <algorithm>
@@ -151,6 +152,7 @@ public:
for (int n = 0; n < threads_num; ++n) {
m_worker_threads.emplace_back([this, n]() {
util::ThreadRename(strprintf("scriptch.%i", n));
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::VALIDATION_SCRIPT_CHECK);
Loop(false /* worker thread */);
});
}
diff --git a/src/compat/glibc_compat.cpp b/src/compat/glibc_compat.cpp
deleted file mode 100644
index ff581d4a9e..0000000000
--- a/src/compat/glibc_compat.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright (c) 2009-2020 The Bitcoin Core developers
-// Distributed under the MIT software license, see the accompanying
-// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-
-#if defined(HAVE_CONFIG_H)
-#include <config/bitcoin-config.h>
-#endif
-
-#include <cstddef>
-#include <cstdint>
-
-#if defined(__i386__) || defined(__arm__)
-
-extern "C" int64_t __udivmoddi4(uint64_t u, uint64_t v, uint64_t* rp);
-
-extern "C" int64_t __wrap___divmoddi4(int64_t u, int64_t v, int64_t* rp)
-{
- int32_t c1 = 0, c2 = 0;
- int64_t uu = u, vv = v;
- int64_t w;
- int64_t r;
-
- if (uu < 0) {
- c1 = ~c1, c2 = ~c2, uu = -uu;
- }
- if (vv < 0) {
- c1 = ~c1, vv = -vv;
- }
-
- w = __udivmoddi4(uu, vv, (uint64_t*)&r);
- if (c1)
- w = -w;
- if (c2)
- r = -r;
-
- *rp = r;
- return w;
-}
-#endif
-
-extern "C" float log2f_old(float x);
-#ifdef __i386__
-__asm(".symver log2f_old,log2f@GLIBC_2.1");
-#elif defined(__amd64__)
-__asm(".symver log2f_old,log2f@GLIBC_2.2.5");
-#elif defined(__arm__)
-__asm(".symver log2f_old,log2f@GLIBC_2.4");
-#elif defined(__aarch64__)
-__asm(".symver log2f_old,log2f@GLIBC_2.17");
-#elif defined(__powerpc64__)
-# ifdef WORDS_BIGENDIAN
-__asm(".symver log2f_old,log2f@GLIBC_2.3");
-# else
-__asm(".symver log2f_old,log2f@GLIBC_2.17");
-# endif
-#elif defined(__riscv)
-__asm(".symver log2f_old,log2f@GLIBC_2.27");
-#endif
-extern "C" float __wrap_log2f(float x)
-{
- return log2f_old(x);
-}
diff --git a/src/amount.h b/src/consensus/amount.h
index 47968e80b1..8b41a2277d 100644
--- a/src/amount.h
+++ b/src/consensus/amount.h
@@ -3,15 +3,15 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#ifndef BITCOIN_AMOUNT_H
-#define BITCOIN_AMOUNT_H
+#ifndef BITCOIN_CONSENSUS_AMOUNT_H
+#define BITCOIN_CONSENSUS_AMOUNT_H
-#include <stdint.h>
+#include <cstdint>
/** Amount in satoshis (Can be negative) */
typedef int64_t CAmount;
-static const CAmount COIN = 100000000;
+static constexpr CAmount COIN = 100000000;
/** No amount larger than this (in satoshi) is valid.
*
@@ -22,7 +22,7 @@ static const CAmount COIN = 100000000;
* critical; in unusual circumstances like a(nother) overflow bug that allowed
* for the creation of coins out of thin air modification could lead to a fork.
* */
-static const CAmount MAX_MONEY = 21000000 * COIN;
+static constexpr CAmount MAX_MONEY = 21000000 * COIN;
inline bool MoneyRange(const CAmount& nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
-#endif // BITCOIN_AMOUNT_H
+#endif // BITCOIN_CONSENSUS_AMOUNT_H
diff --git a/src/consensus/tx_check.cpp b/src/consensus/tx_check.cpp
index bb8cd10c63..de4824fadc 100644
--- a/src/consensus/tx_check.cpp
+++ b/src/consensus/tx_check.cpp
@@ -4,6 +4,7 @@
#include <consensus/tx_check.h>
+#include <consensus/amount.h>
#include <primitives/transaction.h>
#include <consensus/validation.h>
diff --git a/src/consensus/tx_verify.cpp b/src/consensus/tx_verify.cpp
index 0ab790ccdc..a07adae536 100644
--- a/src/consensus/tx_verify.cpp
+++ b/src/consensus/tx_verify.cpp
@@ -4,6 +4,7 @@
#include <consensus/tx_verify.h>
+#include <consensus/amount.h>
#include <consensus/consensus.h>
#include <primitives/transaction.h>
#include <script/interpreter.h>
diff --git a/src/consensus/tx_verify.h b/src/consensus/tx_verify.h
index 264433c33d..777556808a 100644
--- a/src/consensus/tx_verify.h
+++ b/src/consensus/tx_verify.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_CONSENSUS_TX_VERIFY_H
#define BITCOIN_CONSENSUS_TX_VERIFY_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <stdint.h>
#include <vector>
diff --git a/src/core_io.h b/src/core_io.h
index 3b9b66574c..be93a17efe 100644
--- a/src/core_io.h
+++ b/src/core_io.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_CORE_IO_H
#define BITCOIN_CORE_IO_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <attributes.h>
#include <string>
@@ -44,8 +44,8 @@ UniValue ValueFromAmount(const CAmount amount);
std::string FormatScript(const CScript& script);
std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags = 0);
std::string SighashToStr(unsigned char sighash_type);
-void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex, bool include_addresses);
-void ScriptToUniv(const CScript& script, UniValue& out, bool include_address);
-void TxToUniv(const CTransaction& tx, const uint256& hashBlock, bool include_addresses, UniValue& entry, bool include_hex = true, int serialize_flags = 0, const CTxUndo* txundo = nullptr);
+void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool include_hex, bool include_address = true);
+void ScriptToUniv(const CScript& script, UniValue& out);
+void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex = true, int serialize_flags = 0, const CTxUndo* txundo = nullptr);
#endif // BITCOIN_CORE_IO_H
diff --git a/src/core_read.cpp b/src/core_read.cpp
index 6108961010..320811b9e9 100644
--- a/src/core_read.cpp
+++ b/src/core_read.cpp
@@ -69,7 +69,7 @@ CScript ParseScript(const std::string& s)
(w->front() == '-' && w->size() > 1 && std::all_of(w->begin()+1, w->end(), ::IsDigit)))
{
// Number
- int64_t n = atoi64(*w);
+ int64_t n = LocaleIndependentAtoi<int64_t>(*w);
//limit the range of numbers ParseScript accepts in decimal
//since numbers outside -0xFFFFFFFF...0xFFFFFFFF are illegal in scripts
diff --git a/src/core_write.cpp b/src/core_write.cpp
index b35f835f42..6b13e4c586 100644
--- a/src/core_write.cpp
+++ b/src/core_write.cpp
@@ -4,6 +4,7 @@
#include <core_io.h>
+#include <consensus/amount.h>
#include <consensus/consensus.h>
#include <consensus/validation.h>
#include <key_io.h>
@@ -141,56 +142,28 @@ std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags)
return HexStr(ssTx);
}
-void ScriptToUniv(const CScript& script, UniValue& out, bool include_address)
+void ScriptToUniv(const CScript& script, UniValue& out)
{
- out.pushKV("asm", ScriptToAsmStr(script));
- out.pushKV("hex", HexStr(script));
-
- std::vector<std::vector<unsigned char>> solns;
- TxoutType type = Solver(script, solns);
- out.pushKV("type", GetTxnOutputType(type));
-
- CTxDestination address;
- if (include_address && ExtractDestination(script, address) && type != TxoutType::PUBKEY) {
- out.pushKV("address", EncodeDestination(address));
- }
+ ScriptPubKeyToUniv(script, out, /* include_hex */ true, /* include_address */ false);
}
-// TODO: from v23 ("addresses" and "reqSigs" deprecated) this method should be refactored to remove the `include_addresses` option
-// this method can also be combined with `ScriptToUniv` as they will overlap
-void ScriptPubKeyToUniv(const CScript& scriptPubKey,
- UniValue& out, bool fIncludeHex, bool include_addresses)
+void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool include_hex, bool include_address)
{
- TxoutType type;
CTxDestination address;
- std::vector<CTxDestination> addresses;
- int nRequired;
out.pushKV("asm", ScriptToAsmStr(scriptPubKey));
- if (fIncludeHex)
- out.pushKV("hex", HexStr(scriptPubKey));
+ if (include_hex) out.pushKV("hex", HexStr(scriptPubKey));
- if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired) || type == TxoutType::PUBKEY) {
- out.pushKV("type", GetTxnOutputType(type));
- return;
- }
+ std::vector<std::vector<unsigned char>> solns;
+ const TxoutType type{Solver(scriptPubKey, solns)};
- if (ExtractDestination(scriptPubKey, address)) {
+ if (include_address && ExtractDestination(scriptPubKey, address) && type != TxoutType::PUBKEY) {
out.pushKV("address", EncodeDestination(address));
}
out.pushKV("type", GetTxnOutputType(type));
-
- if (include_addresses) {
- UniValue a(UniValue::VARR);
- for (const CTxDestination& addr : addresses) {
- a.push_back(EncodeDestination(addr));
- }
- out.pushKV("addresses", a);
- out.pushKV("reqSigs", nRequired);
- }
}
-void TxToUniv(const CTransaction& tx, const uint256& hashBlock, bool include_addresses, UniValue& entry, bool include_hex, int serialize_flags, const CTxUndo* txundo)
+void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex, int serialize_flags, const CTxUndo* txundo)
{
entry.pushKV("txid", tx.GetHash().GetHex());
entry.pushKV("hash", tx.GetWitnessHash().GetHex());
@@ -249,7 +222,7 @@ void TxToUniv(const CTransaction& tx, const uint256& hashBlock, bool include_add
out.pushKV("n", (int64_t)i);
UniValue o(UniValue::VOBJ);
- ScriptPubKeyToUniv(txout.scriptPubKey, o, true, include_addresses);
+ ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
out.pushKV("scriptPubKey", o);
vout.push_back(out);
diff --git a/src/crc32c/.travis.yml b/src/crc32c/.travis.yml
index d990a89f07..183a5fba45 100644
--- a/src/crc32c/.travis.yml
+++ b/src/crc32c/.travis.yml
@@ -4,7 +4,7 @@
language: cpp
dist: bionic
-osx_image: xcode10.3
+osx_image: xcode12.5
compiler:
- gcc
@@ -24,20 +24,20 @@ env:
addons:
apt:
sources:
- - sourceline: 'deb http://apt.llvm.org/bionic/ llvm-toolchain-bionic-9 main'
+ - sourceline: 'deb http://apt.llvm.org/bionic/ llvm-toolchain-bionic-12 main'
key_url: 'https://apt.llvm.org/llvm-snapshot.gpg.key'
- sourceline: 'ppa:ubuntu-toolchain-r/test'
packages:
- - clang-9
+ - clang-12
- cmake
- - gcc-9
- - g++-9
+ - gcc-11
+ - g++-11
- ninja-build
homebrew:
packages:
- cmake
- - gcc@9
- - llvm@9
+ - gcc@11
+ - llvm@12
- ninja
update: true
@@ -48,14 +48,14 @@ install:
export PATH="$(brew --prefix llvm)/bin:$PATH";
fi
# /usr/bin/gcc points to an older compiler on both Linux and macOS.
-- if [ "$CXX" = "g++" ]; then export CXX="g++-9" CC="gcc-9"; fi
+- if [ "$CXX" = "g++" ]; then export CXX="g++-11" CC="gcc-11"; fi
# /usr/bin/clang points to an older compiler on both Linux and macOS.
#
# Homebrew's llvm package doesn't ship a versioned clang++ binary, so the values
# below don't work on macOS. Fortunately, the path change above makes the
# default values (clang and clang++) resolve to the correct compiler on macOS.
- if [ "$TRAVIS_OS_NAME" = "linux" ]; then
- if [ "$CXX" = "clang++" ]; then export CXX="clang++-9" CC="clang-9"; fi;
+ if [ "$CXX" = "clang++" ]; then export CXX="clang++-12" CC="clang-12"; fi;
fi
- echo ${CC}
- echo ${CXX}
diff --git a/src/crc32c/.ycm_extra_conf.py b/src/crc32c/.ycm_extra_conf.py
index 536aadcec8..62daa8a4ac 100644
--- a/src/crc32c/.ycm_extra_conf.py
+++ b/src/crc32c/.ycm_extra_conf.py
@@ -4,10 +4,10 @@
"""YouCompleteMe configuration that interprets a .clang_complete file.
This module implementes the YouCompleteMe configuration API documented at:
-https://github.com/Valloric/ycmd#ycm_extra_confpy-specification
+https://github.com/ycm-core/ycmd#ycm_extra_confpy-specification
The implementation loads and processes a .clang_complete file, documented at:
-https://github.com/Rip-Rip/clang_complete/blob/master/README.md
+https://github.com/xavierd/clang_complete/blob/master/README.md
"""
import os
diff --git a/src/crc32c/README.md b/src/crc32c/README.md
index 0bd69f7f09..58ba38e611 100644
--- a/src/crc32c/README.md
+++ b/src/crc32c/README.md
@@ -65,7 +65,7 @@ apm install autocomplete-clang build build-cmake clang-format language-cmake \
If you don't mind more setup in return for more speed, replace
`autocomplete-clang` and `linter-clang` with `you-complete-me`. This requires
-[setting up ycmd](https://github.com/Valloric/ycmd#building).
+[setting up ycmd](https://github.com/ycm-core/ycmd#building).
```bash
apm install autocomplete-plus build build-cmake clang-format language-cmake \
diff --git a/src/crc32c/src/crc32c_arm64_check.h b/src/crc32c/src/crc32c_arm64_check.h
index 62a07aba09..6b80f70037 100644
--- a/src/crc32c/src/crc32c_arm64_check.h
+++ b/src/crc32c/src/crc32c_arm64_check.h
@@ -40,7 +40,15 @@ inline bool CanUseArm64Crc32() {
// From 'arch/arm64/include/uapi/asm/hwcap.h' in Linux kernel source code.
constexpr unsigned long kHWCAP_PMULL = 1 << 4;
constexpr unsigned long kHWCAP_CRC32 = 1 << 7;
- unsigned long hwcap = (&getauxval != nullptr) ? getauxval(AT_HWCAP) : 0;
+ unsigned long hwcap =
+#if HAVE_STRONG_GETAUXVAL
+ // Some compilers warn on (&getauxval != nullptr) in the block below.
+ getauxval(AT_HWCAP);
+#elif HAVE_WEAK_GETAUXVAL
+ (&getauxval != nullptr) ? getauxval(AT_HWCAP) : 0;
+#else
+#error This is supposed to be nested inside a check for HAVE_*_GETAUXVAL.
+#endif // HAVE_STRONG_GETAUXVAL
return (hwcap & (kHWCAP_PMULL | kHWCAP_CRC32)) ==
(kHWCAP_PMULL | kHWCAP_CRC32);
#elif defined(__APPLE__)
diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp
index 3a1086bf4c..bcaf746167 100644
--- a/src/dbwrapper.cpp
+++ b/src/dbwrapper.cpp
@@ -197,13 +197,15 @@ bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
return true;
}
-size_t CDBWrapper::DynamicMemoryUsage() const {
+size_t CDBWrapper::DynamicMemoryUsage() const
+{
std::string memory;
- if (!pdb->GetProperty("leveldb.approximate-memory-usage", &memory)) {
+ std::optional<size_t> parsed;
+ if (!pdb->GetProperty("leveldb.approximate-memory-usage", &memory) || !(parsed = ToIntegral<size_t>(memory))) {
LogPrint(BCLog::LEVELDB, "Failed to get approximate-memory-usage property\n");
return 0;
}
- return stoul(memory);
+ return parsed.value();
}
// Prefixed with null character to avoid collisions with other keys
diff --git a/src/dummywallet.cpp b/src/dummywallet.cpp
index 2d897f4c40..7f6471740f 100644
--- a/src/dummywallet.cpp
+++ b/src/dummywallet.cpp
@@ -5,12 +5,14 @@
#include <util/system.h>
#include <walletinitinterface.h>
+class ArgsManager;
class CWallet;
namespace interfaces {
class Chain;
class Handler;
class Wallet;
+class WalletClient;
}
class DummyWalletInit : public WalletInitInterface {
@@ -37,8 +39,6 @@ void DummyWalletInit::AddWalletOptions(ArgsManager& argsman) const
"-maxtxfee=<amt>",
"-mintxfee=<amt>",
"-paytxfee=<amt>",
- "-rescan",
- "-salvagewallet",
"-signer=<cmd>",
"-spendzeroconfchange",
"-txconfirmtarget=<n>",
@@ -64,4 +64,9 @@ std::unique_ptr<Wallet> MakeWallet(const std::shared_ptr<CWallet>& wallet)
throw std::logic_error("Wallet function called in non-wallet build.");
}
+std::unique_ptr<WalletClient> MakeWalletClient(Chain& chain, ArgsManager& args)
+{
+ throw std::logic_error("Wallet function called in non-wallet build.");
+}
+
} // namespace interfaces
diff --git a/src/hash.cpp b/src/hash.cpp
index 3465caa3a9..0e5bd975e4 100644
--- a/src/hash.cpp
+++ b/src/hash.cpp
@@ -3,6 +3,7 @@
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <hash.h>
+#include <span.h>
#include <crypto/common.h>
#include <crypto/hmac_sha512.h>
@@ -74,10 +75,7 @@ unsigned int MurmurHash3(unsigned int nHashSeed, Span<const unsigned char> vData
void BIP32Hash(const ChainCode &chainCode, unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64])
{
unsigned char num[4];
- num[0] = (nChild >> 24) & 0xFF;
- num[1] = (nChild >> 16) & 0xFF;
- num[2] = (nChild >> 8) & 0xFF;
- num[3] = (nChild >> 0) & 0xFF;
+ WriteBE32(num, nChild);
CHMAC_SHA512(chainCode.begin(), chainCode.size()).Write(&header, 1).Write(data, 32).Write(num, 4).Finalize(output);
}
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index 8741ad9b86..6e75e28596 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -12,6 +12,7 @@
#include <shutdown.h>
#include <sync.h>
#include <util/strencodings.h>
+#include <util/syscall_sandbox.h>
#include <util/system.h>
#include <util/threadnames.h>
#include <util/translation.h>
@@ -279,6 +280,7 @@ static void http_reject_request_cb(struct evhttp_request* req, void*)
static bool ThreadHTTP(struct event_base* base)
{
util::ThreadRename("http");
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::NET_HTTP_SERVER);
LogPrint(BCLog::HTTP, "Entering http event loop\n");
event_base_dispatch(base);
// Event loop will be interrupted by InterruptHTTPServer()
@@ -289,7 +291,7 @@ static bool ThreadHTTP(struct event_base* base)
/** Bind HTTP server to specified addresses */
static bool HTTPBindAddresses(struct evhttp* http)
{
- uint16_t http_port{static_cast<uint16_t>(gArgs.GetArg("-rpcport", BaseParams().RPCPort()))};
+ uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
std::vector<std::pair<std::string, uint16_t>> endpoints;
// Determine what addresses to bind to
@@ -332,16 +334,13 @@ static bool HTTPBindAddresses(struct evhttp* http)
static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue, int worker_num)
{
util::ThreadRename(strprintf("httpworker.%i", worker_num));
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::NET_HTTP_SERVER_WORKER);
queue->Run();
}
/** libevent event log callback */
static void libevent_log_cb(int severity, const char *msg)
{
-#ifndef EVENT_LOG_WARN
-// EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
-# define EVENT_LOG_WARN _EVENT_LOG_WARN
-#endif
if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
LogPrintf("libevent: %s\n", msg);
else
@@ -378,7 +377,7 @@ bool InitHTTPServer()
return false;
}
- evhttp_set_timeout(http, gArgs.GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
+ evhttp_set_timeout(http, gArgs.GetIntArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
evhttp_set_max_body_size(http, MAX_SIZE);
evhttp_set_gencb(http, http_request_cb, nullptr);
@@ -389,7 +388,7 @@ bool InitHTTPServer()
}
LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
- int workQueueDepth = std::max((long)gArgs.GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
+ int workQueueDepth = std::max((long)gArgs.GetIntArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
g_work_queue = std::make_unique<WorkQueue<HTTPClosure>>(workQueueDepth);
@@ -419,7 +418,7 @@ static std::vector<std::thread> g_thread_http_workers;
void StartHTTPServer()
{
LogPrint(BCLog::HTTP, "Starting HTTP server\n");
- int rpcThreads = std::max((long)gArgs.GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
+ int rpcThreads = std::max((long)gArgs.GetIntArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
g_thread_http = std::thread(ThreadHTTP, eventBase);
diff --git a/src/index/base.cpp b/src/index/base.cpp
index 6fd2701e2e..3ca86a310e 100644
--- a/src/index/base.cpp
+++ b/src/index/base.cpp
@@ -8,6 +8,7 @@
#include <node/ui_interface.h>
#include <shutdown.h>
#include <tinyformat.h>
+#include <util/syscall_sandbox.h>
#include <util/thread.h>
#include <util/translation.h>
#include <validation.h> // For g_chainman
@@ -123,6 +124,7 @@ static const CBlockIndex* NextSyncBlock(const CBlockIndex* pindex_prev, CChain&
void BaseIndex::ThreadSync()
{
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::TX_INDEX);
const CBlockIndex* pindex = m_best_block_index.load();
if (!m_synced) {
auto& consensus_params = Params().GetConsensus();
diff --git a/src/index/base.h b/src/index/base.h
index df4bdff1ea..1390e3e570 100644
--- a/src/index/base.h
+++ b/src/index/base.h
@@ -6,11 +6,10 @@
#define BITCOIN_INDEX_BASE_H
#include <dbwrapper.h>
-#include <primitives/block.h>
-#include <primitives/transaction.h>
#include <threadinterrupt.h>
#include <validationinterface.h>
+class CBlock;
class CBlockIndex;
class CChainState;
diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp
index cde9821f3d..209785d487 100644
--- a/src/index/txindex.cpp
+++ b/src/index/txindex.cpp
@@ -2,18 +2,14 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <index/disktxpos.h>
#include <index/txindex.h>
+
+#include <index/disktxpos.h>
#include <node/blockstorage.h>
-#include <node/ui_interface.h>
-#include <shutdown.h>
#include <util/system.h>
-#include <util/translation.h>
#include <validation.h>
-constexpr uint8_t DB_BEST_BLOCK{'B'};
constexpr uint8_t DB_TXINDEX{'t'};
-constexpr uint8_t DB_TXINDEX_BLOCK{'T'};
std::unique_ptr<TxIndex> g_txindex;
@@ -30,10 +26,6 @@ public:
/// Write a batch of transaction positions to the DB.
bool WriteTxs(const std::vector<std::pair<uint256, CDiskTxPos>>& v_pos);
-
- /// Migrate txindex data from the block tree DB, where it may be for older nodes that have not
- /// been upgraded yet to the new database.
- bool MigrateData(CBlockTreeDB& block_tree_db, const CBlockLocator& best_locator);
};
TxIndex::DB::DB(size_t n_cache_size, bool f_memory, bool f_wipe) :
@@ -54,163 +46,12 @@ bool TxIndex::DB::WriteTxs(const std::vector<std::pair<uint256, CDiskTxPos>>& v_
return WriteBatch(batch);
}
-/*
- * Safely persist a transfer of data from the old txindex database to the new one, and compact the
- * range of keys updated. This is used internally by MigrateData.
- */
-static void WriteTxIndexMigrationBatches(CDBWrapper& newdb, CDBWrapper& olddb,
- CDBBatch& batch_newdb, CDBBatch& batch_olddb,
- const std::pair<uint8_t, uint256>& begin_key,
- const std::pair<uint8_t, uint256>& end_key)
-{
- // Sync new DB changes to disk before deleting from old DB.
- newdb.WriteBatch(batch_newdb, /*fSync=*/ true);
- olddb.WriteBatch(batch_olddb);
- olddb.CompactRange(begin_key, end_key);
-
- batch_newdb.Clear();
- batch_olddb.Clear();
-}
-
-bool TxIndex::DB::MigrateData(CBlockTreeDB& block_tree_db, const CBlockLocator& best_locator)
-{
- // The prior implementation of txindex was always in sync with block index
- // and presence was indicated with a boolean DB flag. If the flag is set,
- // this means the txindex from a previous version is valid and in sync with
- // the chain tip. The first step of the migration is to unset the flag and
- // write the chain hash to a separate key, DB_TXINDEX_BLOCK. After that, the
- // index entries are copied over in batches to the new database. Finally,
- // DB_TXINDEX_BLOCK is erased from the old database and the block hash is
- // written to the new database.
- //
- // Unsetting the boolean flag ensures that if the node is downgraded to a
- // previous version, it will not see a corrupted, partially migrated index
- // -- it will see that the txindex is disabled. When the node is upgraded
- // again, the migration will pick up where it left off and sync to the block
- // with hash DB_TXINDEX_BLOCK.
- bool f_legacy_flag = false;
- block_tree_db.ReadFlag("txindex", f_legacy_flag);
- if (f_legacy_flag) {
- if (!block_tree_db.Write(DB_TXINDEX_BLOCK, best_locator)) {
- return error("%s: cannot write block indicator", __func__);
- }
- if (!block_tree_db.WriteFlag("txindex", false)) {
- return error("%s: cannot write block index db flag", __func__);
- }
- }
-
- CBlockLocator locator;
- if (!block_tree_db.Read(DB_TXINDEX_BLOCK, locator)) {
- return true;
- }
-
- int64_t count = 0;
- LogPrintf("Upgrading txindex database... [0%%]\n");
- uiInterface.ShowProgress(_("Upgrading txindex database").translated, 0, true);
- int report_done = 0;
- const size_t batch_size = 1 << 24; // 16 MiB
-
- CDBBatch batch_newdb(*this);
- CDBBatch batch_olddb(block_tree_db);
-
- std::pair<uint8_t, uint256> key;
- std::pair<uint8_t, uint256> begin_key{DB_TXINDEX, uint256()};
- std::pair<uint8_t, uint256> prev_key = begin_key;
-
- bool interrupted = false;
- std::unique_ptr<CDBIterator> cursor(block_tree_db.NewIterator());
- for (cursor->Seek(begin_key); cursor->Valid(); cursor->Next()) {
- if (ShutdownRequested()) {
- interrupted = true;
- break;
- }
-
- if (!cursor->GetKey(key)) {
- return error("%s: cannot get key from valid cursor", __func__);
- }
- if (key.first != DB_TXINDEX) {
- break;
- }
-
- // Log progress every 10%.
- if (++count % 256 == 0) {
- // Since txids are uniformly random and traversed in increasing order, the high 16 bits
- // of the hash can be used to estimate the current progress.
- const uint256& txid = key.second;
- uint32_t high_nibble =
- (static_cast<uint32_t>(*(txid.begin() + 0)) << 8) +
- (static_cast<uint32_t>(*(txid.begin() + 1)) << 0);
- int percentage_done = (int)(high_nibble * 100.0 / 65536.0 + 0.5);
-
- uiInterface.ShowProgress(_("Upgrading txindex database").translated, percentage_done, true);
- if (report_done < percentage_done/10) {
- LogPrintf("Upgrading txindex database... [%d%%]\n", percentage_done);
- report_done = percentage_done/10;
- }
- }
-
- CDiskTxPos value;
- if (!cursor->GetValue(value)) {
- return error("%s: cannot parse txindex record", __func__);
- }
- batch_newdb.Write(key, value);
- batch_olddb.Erase(key);
-
- if (batch_newdb.SizeEstimate() > batch_size || batch_olddb.SizeEstimate() > batch_size) {
- // NOTE: it's OK to delete the key pointed at by the current DB cursor while iterating
- // because LevelDB iterators are guaranteed to provide a consistent view of the
- // underlying data, like a lightweight snapshot.
- WriteTxIndexMigrationBatches(*this, block_tree_db,
- batch_newdb, batch_olddb,
- prev_key, key);
- prev_key = key;
- }
- }
-
- // If these final DB batches complete the migration, write the best block
- // hash marker to the new database and delete from the old one. This signals
- // that the former is fully caught up to that point in the blockchain and
- // that all txindex entries have been removed from the latter.
- if (!interrupted) {
- batch_olddb.Erase(DB_TXINDEX_BLOCK);
- batch_newdb.Write(DB_BEST_BLOCK, locator);
- }
-
- WriteTxIndexMigrationBatches(*this, block_tree_db,
- batch_newdb, batch_olddb,
- begin_key, key);
-
- if (interrupted) {
- LogPrintf("[CANCELLED].\n");
- return false;
- }
-
- uiInterface.ShowProgress("", 100, false);
-
- LogPrintf("[DONE].\n");
- return true;
-}
-
TxIndex::TxIndex(size_t n_cache_size, bool f_memory, bool f_wipe)
: m_db(std::make_unique<TxIndex::DB>(n_cache_size, f_memory, f_wipe))
{}
TxIndex::~TxIndex() {}
-bool TxIndex::Init()
-{
- LOCK(cs_main);
-
- // Attempt to migrate txindex from the old database to the new one. Even if
- // chain_tip is null, the node could be reindexing and we still want to
- // delete txindex records in the old database.
- if (!m_db->MigrateData(*m_chainstate->m_blockman.m_block_tree_db, m_chainstate->m_chain.GetLocator())) {
- return false;
- }
-
- return BaseIndex::Init();
-}
-
bool TxIndex::WriteBlock(const CBlock& block, const CBlockIndex* pindex)
{
// Exclude genesis block transaction because outputs are not spendable.
diff --git a/src/index/txindex.h b/src/index/txindex.h
index 8202c3c951..59375bc204 100644
--- a/src/index/txindex.h
+++ b/src/index/txindex.h
@@ -5,9 +5,7 @@
#ifndef BITCOIN_INDEX_TXINDEX_H
#define BITCOIN_INDEX_TXINDEX_H
-#include <chain.h>
#include <index/base.h>
-#include <txdb.h>
/**
* TxIndex is used to look up transactions included in the blockchain by hash.
@@ -23,9 +21,6 @@ private:
const std::unique_ptr<DB> m_db;
protected:
- /// Override base class init to migrate from old database.
- bool Init() override;
-
bool WriteBlock(const CBlock& block, const CBlockIndex* pindex) override;
BaseIndex::DB& GetDB() const override;
diff --git a/src/init.cpp b/src/init.cpp
index b744298667..4495ded64d 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -10,12 +10,12 @@
#include <init.h>
#include <addrman.h>
-#include <amount.h>
#include <banman.h>
#include <blockfilter.h>
#include <chain.h>
#include <chainparams.h>
#include <compat/sanity.h>
+#include <consensus/amount.h>
#include <deploymentstatus.h>
#include <fs.h>
#include <hash.h>
@@ -26,6 +26,7 @@
#include <index/txindex.h>
#include <init/common.h>
#include <interfaces/chain.h>
+#include <interfaces/init.h>
#include <interfaces/node.h>
#include <mapport.h>
#include <miner.h>
@@ -59,6 +60,7 @@
#include <util/check.h>
#include <util/moneystr.h>
#include <util/string.h>
+#include <util/syscall_sandbox.h>
#include <util/system.h>
#include <util/thread.h>
#include <util/threadnames.h>
@@ -217,7 +219,7 @@ void Shutdown(NodeContext& node)
node.banman.reset();
node.addrman.reset();
- if (node.mempool && node.mempool->IsLoaded() && node.args->GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
+ if (node.mempool && node.mempool->IsLoaded() && node.args->GetBoolArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
DumpMempool(*node.mempool);
}
@@ -396,7 +398,7 @@ void SetupServerArgs(ArgsManager& argsman)
-GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-persistmempool", strprintf("Whether to save the mempool on shutdown and load on restart (default: %u)", DEFAULT_PERSIST_MEMPOOL), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-pid=<file>", strprintf("Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)", BITCOIN_PID_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
- argsman.AddArg("-prune=<n>", strprintf("Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex, -coinstatsindex and -rescan. "
+ argsman.AddArg("-prune=<n>", strprintf("Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex and -coinstatsindex. "
"Warning: Reverting this setting requires re-downloading the entire blockchain. "
"(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >=%u = automatically prune block files to stay under the specified target size in MiB)", MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-reindex", "Rebuild chain state and block index from the blk*.dat files on disk", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
@@ -561,6 +563,10 @@ void SetupServerArgs(ArgsManager& argsman)
hidden_args.emplace_back("-daemonwait");
#endif
+#if defined(USE_SYSCALL_SANDBOX)
+ argsman.AddArg("-sandbox=<mode>", "Use the experimental syscall sandbox in the specified mode (-sandbox=log-and-abort or -sandbox=abort). Allow only expected syscalls to be used by bitcoind. Note that this is an experimental new feature that may cause bitcoind to exit or crash unexpectedly: use with caution. In the \"log-and-abort\" mode the invocation of an unexpected syscall results in a debug handler being invoked which will log the incident and terminate the program (without executing the unexpected syscall). In the \"abort\" mode the invocation of an unexpected syscall results in the entire process being killed immediately by the kernel without executing the unexpected syscall.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
+#endif // USE_SYSCALL_SANDBOX
+
// Add the hidden options
argsman.AddHiddenArgs(hidden_args);
}
@@ -842,7 +848,7 @@ bool AppInitParameterInteraction(const ArgsManager& args)
}
// if using block pruning, then disallow txindex and coinstatsindex
- if (args.GetArg("-prune", 0)) {
+ if (args.GetIntArg("-prune", 0)) {
if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX))
return InitError(_("Prune mode is incompatible with -txindex."));
if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX))
@@ -867,11 +873,9 @@ bool AppInitParameterInteraction(const ArgsManager& args)
// Make sure enough file descriptors are available
int nBind = std::max(nUserBind, size_t(1));
- nUserMaxConnections = args.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
+ nUserMaxConnections = args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
nMaxConnections = std::max(nUserMaxConnections, 0);
- // Trim requested connection counts, to fit into system limitations
- // <int> in std::min<int>(...) to work around FreeBSD compilation issue described in #2695
nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS + nBind + NUM_FDS_MESSAGE_CAPTURE);
#ifdef USE_POLL
@@ -879,6 +883,8 @@ bool AppInitParameterInteraction(const ArgsManager& args)
#else
int fd_max = FD_SETSIZE;
#endif
+ // Trim requested connection counts, to fit into system limitations
+ // <int> in std::min<int>(...) to work around FreeBSD compilation issue described in #2695
nMaxConnections = std::max(std::min<int>(nMaxConnections, fd_max - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS - NUM_FDS_MESSAGE_CAPTURE), 0);
if (nFD < MIN_CORE_FILEDESCRIPTORS)
return InitError(_("Not enough file descriptors available."));
@@ -914,8 +920,8 @@ bool AppInitParameterInteraction(const ArgsManager& args)
}
// mempool limits
- int64_t nMempoolSizeMax = args.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
- int64_t nMempoolSizeMin = args.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
+ int64_t nMempoolSizeMax = args.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
+ int64_t nMempoolSizeMin = args.GetIntArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
// incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
@@ -929,7 +935,7 @@ bool AppInitParameterInteraction(const ArgsManager& args)
}
// block pruning; get the amount of disk space (in MiB) to allot for block & undo files
- int64_t nPruneArg = args.GetArg("-prune", 0);
+ int64_t nPruneArg = args.GetIntArg("-prune", 0);
if (nPruneArg < 0) {
return InitError(_("Prune cannot be configured with a negative value."));
}
@@ -946,12 +952,12 @@ bool AppInitParameterInteraction(const ArgsManager& args)
fPruneMode = true;
}
- nConnectTimeout = args.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
+ nConnectTimeout = args.GetIntArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
if (nConnectTimeout <= 0) {
nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
}
- peer_connect_timeout = args.GetArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
+ peer_connect_timeout = args.GetIntArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
if (peer_connect_timeout <= 0) {
return InitError(Untranslated("peertimeout cannot be configured with a negative value."));
}
@@ -991,32 +997,63 @@ bool AppInitParameterInteraction(const ArgsManager& args)
if (!chainparams.IsTestChain() && !fRequireStandard) {
return InitError(strprintf(Untranslated("acceptnonstdtxn is not currently supported for %s chain"), chainparams.NetworkIDString()));
}
- nBytesPerSigOp = args.GetArg("-bytespersigop", nBytesPerSigOp);
+ nBytesPerSigOp = args.GetIntArg("-bytespersigop", nBytesPerSigOp);
if (!g_wallet_init_interface.ParameterInteraction()) return false;
fIsBareMultisigStd = args.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
fAcceptDatacarrier = args.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
- nMaxDatacarrierBytes = args.GetArg("-datacarriersize", nMaxDatacarrierBytes);
+ nMaxDatacarrierBytes = args.GetIntArg("-datacarriersize", nMaxDatacarrierBytes);
// Option to startup with mocktime set (used for regression testing):
- SetMockTime(args.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
+ SetMockTime(args.GetIntArg("-mocktime", 0)); // SetMockTime(0) is a no-op
if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
- if (args.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
+ if (args.GetIntArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
return InitError(Untranslated("rpcserialversion must be non-negative."));
- if (args.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
+ if (args.GetIntArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
return InitError(Untranslated("Unknown rpcserialversion requested."));
- nMaxTipAge = args.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
+ nMaxTipAge = args.GetIntArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
if (args.IsArgSet("-proxy") && args.GetArg("-proxy", "").empty()) {
return InitError(_("No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."));
}
+#if defined(USE_SYSCALL_SANDBOX)
+ if (args.IsArgSet("-sandbox") && !args.IsArgNegated("-sandbox")) {
+ const std::string sandbox_arg{args.GetArg("-sandbox", "")};
+ bool log_syscall_violation_before_terminating{false};
+ if (sandbox_arg == "log-and-abort") {
+ log_syscall_violation_before_terminating = true;
+ } else if (sandbox_arg == "abort") {
+ // log_syscall_violation_before_terminating is false by default.
+ } else {
+ return InitError(Untranslated("Unknown syscall sandbox mode (-sandbox=<mode>). Available modes are \"log-and-abort\" and \"abort\"."));
+ }
+ // execve(...) is not allowed by the syscall sandbox.
+ const std::vector<std::string> features_using_execve{
+ "-alertnotify",
+ "-blocknotify",
+ "-signer",
+ "-startupnotify",
+ "-walletnotify",
+ };
+ for (const std::string& feature_using_execve : features_using_execve) {
+ if (!args.GetArg(feature_using_execve, "").empty()) {
+ return InitError(Untranslated(strprintf("The experimental syscall sandbox feature (-sandbox=<mode>) is incompatible with %s (which uses execve).", feature_using_execve)));
+ }
+ }
+ if (!SetupSyscallSandbox(log_syscall_violation_before_terminating)) {
+ return InitError(Untranslated("Installation of the syscall sandbox failed."));
+ }
+ LogPrintf("Experimental syscall sandbox enabled (-sandbox=%s): bitcoind will terminate if an unexpected (not allowlisted) syscall is invoked.\n", sandbox_arg);
+ }
+#endif // USE_SYSCALL_SANDBOX
+
return true;
}
@@ -1063,7 +1100,7 @@ bool AppInitLockDataDirectory()
bool AppInitInterfaces(NodeContext& node)
{
- node.chain = interfaces::MakeChain(node);
+ node.chain = node.init->makeChain();
// Create client interfaces for wallets that are supposed to be loaded
// according to -wallet and -disablewallet options. This only constructs
// the interfaces, it doesn't load wallet data. Wallets actually get loaded
@@ -1100,7 +1137,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
InitSignatureCache();
InitScriptExecutionCache();
- int script_threads = args.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
+ int script_threads = args.GetIntArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
if (script_threads <= 0) {
// -par=0 means autodetect (number of cores - 1 script threads)
// -par=-n means "leave n cores free" (number of cores - n - 1 script threads)
@@ -1189,7 +1226,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
InitError(strprintf(_("Could not find asmap file %s"), asmap_path));
return false;
}
- asmap = CAddrMan::DecodeAsmap(asmap_path);
+ asmap = DecodeAsmap(asmap_path);
if (asmap.size() == 0) {
InitError(strprintf(_("Could not parse asmap file %s"), asmap_path));
return false;
@@ -1200,25 +1237,14 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
LogPrintf("Using /16 prefix for IP bucketing\n");
}
- auto check_addrman = std::clamp<int32_t>(args.GetArg("-checkaddrman", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), 0, 1000000);
- node.addrman = std::make_unique<CAddrMan>(asmap, /* deterministic */ false, /* consistency_check_ratio */ check_addrman);
-
- // Load addresses from peers.dat
uiInterface.InitMessage(_("Loading P2P addresses…").translated);
- int64_t nStart = GetTimeMillis();
- CAddrDB adb;
- if (adb.Read(*node.addrman)) {
- LogPrintf("Loaded %i addresses from peers.dat %dms\n", node.addrman->size(), GetTimeMillis() - nStart);
- } else {
- // Addrman can be in an inconsistent state after failure, reset it
- node.addrman = std::make_unique<CAddrMan>(asmap, /* deterministic */ false, /* consistency_check_ratio */ check_addrman);
- LogPrintf("Recreating peers.dat\n");
- adb.Write(*node.addrman);
+ if (const auto error{LoadAddrman(asmap, args, node.addrman)}) {
+ return InitError(*error);
}
}
assert(!node.banman);
- node.banman = std::make_unique<BanMan>(gArgs.GetDataDirNet() / "banlist", &uiInterface, args.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
+ node.banman = std::make_unique<BanMan>(gArgs.GetDataDirNet() / "banlist", &uiInterface, args.GetIntArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
assert(!node.connman);
node.connman = std::make_unique<CConnman>(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max()), *node.addrman, args.GetBoolArg("-networkactive", true));
@@ -1228,7 +1254,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
if (!ignores_incoming_txs) node.fee_estimator = std::make_unique<CBlockPolicyEstimator>();
assert(!node.mempool);
- int check_ratio = std::min<int>(std::max<int>(args.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
+ int check_ratio = std::min<int>(std::max<int>(args.GetIntArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
node.mempool = std::make_unique<CTxMemPool>(node.fee_estimator.get(), check_ratio);
assert(!node.chainman);
@@ -1335,7 +1361,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false);
// cache size calculations
- int64_t nTotalCache = (args.GetArg("-dbcache", nDefaultDbCache) << 20);
+ int64_t nTotalCache = (args.GetIntArg("-dbcache", nDefaultDbCache) << 20);
nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
int64_t nBlockTreeDBCache = std::min(nTotalCache / 8, nMaxBlockDBCache << 20);
@@ -1353,7 +1379,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
nTotalCache -= nCoinDBCache;
int64_t nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
- int64_t nMempoolSizeMax = args.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
+ int64_t nMempoolSizeMax = args.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
LogPrintf("Cache configuration:\n");
LogPrintf("* Using %.1f MiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
@@ -1509,7 +1535,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
for (CChainState* chainstate : chainman.GetAll()) {
if (!is_coinsview_empty(chainstate)) {
uiInterface.InitMessage(_("Verifying blocks…").translated);
- if (fHavePruned && args.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
+ if (fHavePruned && args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
MIN_BLOCKS_TO_KEEP);
}
@@ -1526,8 +1552,8 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
if (!CVerifyDB().VerifyDB(
*chainstate, chainparams, chainstate->CoinsDB(),
- args.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
- args.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
+ args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL),
+ args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
strLoadError = _("Corrupted block database detected");
failed_verification = true;
break;
@@ -1577,6 +1603,10 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
// ********************************************************* Step 8: start indexers
if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
+ if (const auto error{CheckLegacyTxindex(*Assert(chainman.m_blockman.m_block_tree_db))}) {
+ return InitError(*error);
+ }
+
g_txindex = std::make_unique<TxIndex>(nTxIndexCache, false, fReindex);
if (!g_txindex->Start(chainman.ActiveChainstate())) {
return false;
@@ -1715,11 +1745,11 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
connOptions.uiInterface = &uiInterface;
connOptions.m_banman = node.banman.get();
connOptions.m_msgproc = node.peerman.get();
- connOptions.nSendBufferMaxSize = 1000 * args.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
- connOptions.nReceiveFloodSize = 1000 * args.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
+ connOptions.nSendBufferMaxSize = 1000 * args.GetIntArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
+ connOptions.nReceiveFloodSize = 1000 * args.GetIntArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
connOptions.m_added_nodes = args.GetArgs("-addnode");
- connOptions.nMaxOutboundLimit = 1024 * 1024 * args.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET);
+ connOptions.nMaxOutboundLimit = 1024 * 1024 * args.GetIntArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET);
connOptions.m_peer_connect_timeout = peer_connect_timeout;
for (const std::string& bind_arg : args.GetArgs("-bind")) {
diff --git a/src/init/bitcoin-node.cpp b/src/init/bitcoin-node.cpp
index 6b6157c139..fa56153745 100644
--- a/src/init/bitcoin-node.cpp
+++ b/src/init/bitcoin-node.cpp
@@ -2,9 +2,12 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#include <interfaces/chain.h>
#include <interfaces/echo.h>
#include <interfaces/init.h>
#include <interfaces/ipc.h>
+#include <interfaces/node.h>
+#include <interfaces/wallet.h>
#include <node/context.h>
#include <util/system.h>
@@ -24,6 +27,12 @@ public:
m_node.args = &gArgs;
m_node.init = this;
}
+ std::unique_ptr<interfaces::Node> makeNode() override { return interfaces::MakeNode(m_node); }
+ std::unique_ptr<interfaces::Chain> makeChain() override { return interfaces::MakeChain(m_node); }
+ std::unique_ptr<interfaces::WalletClient> makeWalletClient(interfaces::Chain& chain) override
+ {
+ return MakeWalletClient(chain, *Assert(m_node.args));
+ }
std::unique_ptr<interfaces::Echo> makeEcho() override { return interfaces::MakeEcho(); }
interfaces::Ipc* ipc() override { return m_ipc.get(); }
NodeContext& m_node;
diff --git a/src/init/bitcoind.cpp b/src/init/bitcoind.cpp
index 1d4504c24f..9c8d5bd9bb 100644
--- a/src/init/bitcoind.cpp
+++ b/src/init/bitcoind.cpp
@@ -2,7 +2,11 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#include <interfaces/chain.h>
+#include <interfaces/echo.h>
#include <interfaces/init.h>
+#include <interfaces/node.h>
+#include <interfaces/wallet.h>
#include <node/context.h>
#include <util/system.h>
@@ -18,6 +22,13 @@ public:
m_node.args = &gArgs;
m_node.init = this;
}
+ std::unique_ptr<interfaces::Node> makeNode() override { return interfaces::MakeNode(m_node); }
+ std::unique_ptr<interfaces::Chain> makeChain() override { return interfaces::MakeChain(m_node); }
+ std::unique_ptr<interfaces::WalletClient> makeWalletClient(interfaces::Chain& chain) override
+ {
+ return MakeWalletClient(chain, *Assert(m_node.args));
+ }
+ std::unique_ptr<interfaces::Echo> makeEcho() override { return interfaces::MakeEcho(); }
NodeContext& m_node;
};
} // namespace
diff --git a/src/interfaces/chain.h b/src/interfaces/chain.h
index eceede3c8f..9a97cad1f8 100644
--- a/src/interfaces/chain.h
+++ b/src/interfaces/chain.h
@@ -177,7 +177,7 @@ public:
std::string& err_string) = 0;
//! Calculate mempool ancestor and descendant counts for the given transaction.
- virtual void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants) = 0;
+ virtual void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) = 0;
//! Get the node's package limits.
//! Currently only returns the ancestor and descendant count limits, but could be enhanced to
diff --git a/src/interfaces/node.h b/src/interfaces/node.h
index 77129423db..34fdde3774 100644
--- a/src/interfaces/node.h
+++ b/src/interfaces/node.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_INTERFACES_NODE_H
#define BITCOIN_INTERFACES_NODE_H
-#include <amount.h> // For CAmount
+#include <consensus/amount.h>
#include <external_signer.h>
#include <net.h> // For NodeId
#include <net_types.h> // For banmap_t
@@ -230,7 +230,7 @@ public:
};
//! Return implementation of Node interface.
-std::unique_ptr<Node> MakeNode(NodeContext* context = nullptr);
+std::unique_ptr<Node> MakeNode(NodeContext& context);
//! Block tip (could be a header or not, depends on the subscribed signal).
struct BlockTip {
diff --git a/src/interfaces/wallet.h b/src/interfaces/wallet.h
index a85db04b8b..490563426c 100644
--- a/src/interfaces/wallet.h
+++ b/src/interfaces/wallet.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_INTERFACES_WALLET_H
#define BITCOIN_INTERFACES_WALLET_H
-#include <amount.h> // For CAmount
+#include <consensus/amount.h>
#include <interfaces/chain.h> // For ChainClient
#include <pubkey.h> // For CKeyID and CScriptID (definitions needed in CTxDestination instantiation)
#include <script/standard.h> // For CTxDestination
@@ -122,10 +122,10 @@ public:
virtual bool displayAddress(const CTxDestination& dest) = 0;
//! Lock coin.
- virtual void lockCoin(const COutPoint& output) = 0;
+ virtual bool lockCoin(const COutPoint& output, const bool write_to_db) = 0;
//! Unlock coin.
- virtual void unlockCoin(const COutPoint& output) = 0;
+ virtual bool unlockCoin(const COutPoint& output) = 0;
//! Return whether coin is locked.
virtual bool isLockedCoin(const COutPoint& output) = 0;
diff --git a/src/key.cpp b/src/key.cpp
index 40df248e02..39155e4311 100644
--- a/src/key.cpp
+++ b/src/key.cpp
@@ -343,8 +343,7 @@ CExtPubKey CExtKey::Neuter() const {
void CExtKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
code[0] = nDepth;
memcpy(code+1, vchFingerprint, 4);
- code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
- code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
+ WriteBE32(code+5, nChild);
memcpy(code+9, chaincode.begin(), 32);
code[41] = 0;
assert(key.size() == 32);
@@ -354,7 +353,7 @@ void CExtKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
void CExtKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
nDepth = code[0];
memcpy(vchFingerprint, code+1, 4);
- nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
+ nChild = ReadBE32(code+5);
memcpy(chaincode.begin(), code+9, 32);
key.Set(code+42, code+BIP32_EXTKEY_SIZE, true);
if ((nDepth == 0 && (nChild != 0 || ReadLE32(vchFingerprint) != 0)) || code[41] != 0) key = CKey();
diff --git a/src/key.h b/src/key.h
index 92cbc1e899..9b94baa026 100644
--- a/src/key.h
+++ b/src/key.h
@@ -17,7 +17,6 @@
/**
- * secure_allocator is defined in allocators.h
* CPrivKey is a serialized private key, with all parameters included
* (SIZE bytes)
*/
diff --git a/src/logging.cpp b/src/logging.cpp
index eb2c750296..a352e106e5 100644
--- a/src/logging.cpp
+++ b/src/logging.cpp
@@ -160,6 +160,7 @@ const CLogCategoryDesc LogCategories[] =
{BCLog::I2P, "i2p"},
{BCLog::IPC, "ipc"},
{BCLog::LOCK, "lock"},
+ {BCLog::UTIL, "util"},
{BCLog::ALL, "1"},
{BCLog::ALL, "all"},
};
diff --git a/src/logging.h b/src/logging.h
index 53a89d28bd..02e64a7c48 100644
--- a/src/logging.h
+++ b/src/logging.h
@@ -60,6 +60,7 @@ namespace BCLog {
I2P = (1 << 22),
IPC = (1 << 23),
LOCK = (1 << 24),
+ UTIL = (1 << 25),
ALL = ~(uint32_t)0,
};
diff --git a/src/logging/timer.h b/src/logging/timer.h
index 647e3fa30e..79627b1fe3 100644
--- a/src/logging/timer.h
+++ b/src/logging/timer.h
@@ -9,6 +9,7 @@
#include <logging.h>
#include <util/macros.h>
#include <util/time.h>
+#include <util/types.h>
#include <chrono>
#include <string>
@@ -58,23 +59,15 @@ public:
return strprintf("%s: %s", m_prefix, msg);
}
- if (std::is_same<TimeType, std::chrono::microseconds>::value) {
+ if constexpr (std::is_same<TimeType, std::chrono::microseconds>::value) {
return strprintf("%s: %s (%iμs)", m_prefix, msg, end_time.count());
+ } else if constexpr (std::is_same<TimeType, std::chrono::milliseconds>::value) {
+ return strprintf("%s: %s (%.2fms)", m_prefix, msg, end_time.count() * 0.001);
+ } else if constexpr (std::is_same<TimeType, std::chrono::seconds>::value) {
+ return strprintf("%s: %s (%.2fs)", m_prefix, msg, end_time.count() * 0.000001);
+ } else {
+ static_assert(ALWAYS_FALSE<TimeType>, "Error: unexpected time type");
}
-
- std::string units;
- float divisor = 1;
-
- if (std::is_same<TimeType, std::chrono::milliseconds>::value) {
- units = "ms";
- divisor = 1000.;
- } else if (std::is_same<TimeType, std::chrono::seconds>::value) {
- units = "s";
- divisor = 1000. * 1000.;
- }
-
- const float time_ms = end_time.count() / divisor;
- return strprintf("%s: %s (%.2f%s)", m_prefix, msg, time_ms, units);
}
private:
@@ -89,7 +82,6 @@ private:
//! Forwarded on to LogPrint if specified - has the effect of only
//! outputting the timing log when a particular debug= category is specified.
const BCLog::LogFlags m_log_category{};
-
};
} // namespace BCLog
diff --git a/src/mapport.cpp b/src/mapport.cpp
index 135efb561e..a2d06c68b4 100644
--- a/src/mapport.cpp
+++ b/src/mapport.cpp
@@ -14,6 +14,7 @@
#include <netaddress.h>
#include <netbase.h>
#include <threadinterrupt.h>
+#include <util/syscall_sandbox.h>
#include <util/system.h>
#include <util/thread.h>
@@ -222,6 +223,7 @@ static bool ProcessUpnp()
static void ThreadMapPort()
{
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::INITIALIZATION_MAP_PORT);
bool ok;
do {
ok = false;
diff --git a/src/miner.cpp b/src/miner.cpp
index 168ade5507..1ef246cd14 100644
--- a/src/miner.cpp
+++ b/src/miner.cpp
@@ -5,10 +5,10 @@
#include <miner.h>
-#include <amount.h>
#include <chain.h>
#include <chainparams.h>
#include <coins.h>
+#include <consensus/amount.h>
#include <consensus/consensus.h>
#include <consensus/merkle.h>
#include <consensus/tx_verify.h>
@@ -72,7 +72,7 @@ static BlockAssembler::Options DefaultOptions()
// Block resource limits
// If -blockmaxweight is not given, limit to DEFAULT_BLOCK_MAX_WEIGHT
BlockAssembler::Options options;
- options.nBlockMaxWeight = gArgs.GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
+ options.nBlockMaxWeight = gArgs.GetIntArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
if (gArgs.IsArgSet("-blockmintxfee")) {
std::optional<CAmount> parsed = ParseMoney(gArgs.GetArg("-blockmintxfee", ""));
options.blockMinFeeRate = CFeeRate{parsed.value_or(DEFAULT_BLOCK_MIN_TX_FEE)};
@@ -125,7 +125,7 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (chainparams.MineBlocksOnDemand())
- pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
+ pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
pblock->nTime = GetAdjustedTime();
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
@@ -237,7 +237,7 @@ void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
if (fPrintPriority) {
- LogPrintf("fee %s txid %s\n",
+ LogPrintf("fee rate %s txid %s\n",
CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
iter->GetTx().GetHash().ToString());
}
diff --git a/src/net.cpp b/src/net.cpp
index 35376b89ac..7271ff22b2 100644
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -9,6 +9,7 @@
#include <net.h>
+#include <addrdb.h>
#include <banman.h>
#include <clientversion.h>
#include <compat.h>
@@ -24,6 +25,8 @@
#include <scheduler.h>
#include <util/sock.h>
#include <util/strencodings.h>
+#include <util/syscall_sandbox.h>
+#include <util/system.h>
#include <util/thread.h>
#include <util/trace.h>
#include <util/translation.h>
@@ -121,7 +124,7 @@ void CConnman::AddAddrFetch(const std::string& strDest)
uint16_t GetListenPort()
{
- return static_cast<uint16_t>(gArgs.GetArg("-port", Params().GetDefaultPort()));
+ return static_cast<uint16_t>(gArgs.GetIntArg("-port", Params().GetDefaultPort()));
}
// find 'best' local address for a particular peer
@@ -190,8 +193,8 @@ CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
static int GetnScore(const CService& addr)
{
LOCK(cs_mapLocalHost);
- if (mapLocalHost.count(addr) == 0) return 0;
- return mapLocalHost[addr].nScore;
+ const auto it = mapLocalHost.find(addr);
+ return (it != mapLocalHost.end()) ? it->second.nScore : 0;
}
// Is our peer's addrLocal potentially useful as an external IP source?
@@ -243,10 +246,10 @@ bool AddLocal(const CService& addr, int nScore)
{
LOCK(cs_mapLocalHost);
- bool fAlready = mapLocalHost.count(addr) > 0;
- LocalServiceInfo &info = mapLocalHost[addr];
- if (!fAlready || nScore >= info.nScore) {
- info.nScore = nScore + (fAlready ? 1 : 0);
+ const auto [it, is_newly_added] = mapLocalHost.emplace(addr, LocalServiceInfo());
+ LocalServiceInfo &info = it->second;
+ if (is_newly_added || nScore >= info.nScore) {
+ info.nScore = nScore + (is_newly_added ? 0 : 1);
info.nPort = addr.GetPort();
}
}
@@ -288,12 +291,10 @@ bool IsReachable(const CNetAddr &addr)
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
- {
- LOCK(cs_mapLocalHost);
- if (mapLocalHost.count(addr) == 0)
- return false;
- mapLocalHost[addr].nScore++;
- }
+ LOCK(cs_mapLocalHost);
+ const auto it = mapLocalHost.find(addr);
+ if (it == mapLocalHost.end()) return false;
+ ++it->second.nScore;
return true;
}
@@ -552,14 +553,13 @@ Network CNode::ConnectedThroughNetwork() const
#undef X
#define X(name) stats.name = name
-void CNode::CopyStats(CNodeStats& stats, const std::vector<bool>& asmap)
+void CNode::CopyStats(CNodeStats& stats)
{
stats.nodeid = this->GetId();
X(nServices);
X(addr);
X(addrBind);
stats.m_network = ConnectedThroughNetwork();
- stats.m_mapped_as = addr.GetMappedAS(asmap);
if (m_tx_relay != nullptr) {
LOCK(m_tx_relay->cs_filter);
stats.fRelayTxes = m_tx_relay->fRelayTxes;
@@ -1616,6 +1616,7 @@ void CConnman::SocketHandler()
void CConnman::ThreadSocketHandler()
{
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::NET);
while (!interruptNet)
{
DisconnectNodes();
@@ -1635,6 +1636,7 @@ void CConnman::WakeMessageHandler()
void CConnman::ThreadDNSAddressSeed()
{
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::INITIALIZATION_DNS_SEED);
FastRandomContext rng;
std::vector<std::string> seeds = Params().DNSSeeds();
Shuffle(seeds.begin(), seeds.end(), rng);
@@ -1747,8 +1749,7 @@ void CConnman::DumpAddresses()
{
int64_t nStart = GetTimeMillis();
- CAddrDB adb;
- adb.Write(addrman);
+ DumpPeerAddresses(::gArgs, addrman);
LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
addrman.size(), GetTimeMillis() - nStart);
@@ -1818,6 +1819,7 @@ int CConnman::GetExtraBlockRelayCount() const
void CConnman::ThreadOpenConnections(const std::vector<std::string> connect)
{
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::NET_OPEN_CONNECTION);
// Connect to specific addresses
if (!connect.empty())
{
@@ -2008,17 +2010,18 @@ void CConnman::ThreadOpenConnections(const std::vector<std::string> connect)
if (nTries > 100)
break;
- CAddrInfo addr;
+ CAddress addr;
+ int64_t addr_last_try{0};
if (fFeeler) {
// First, try to get a tried table collision address. This returns
// an empty (invalid) address if there are no collisions to try.
- addr = addrman.SelectTriedCollision();
+ std::tie(addr, addr_last_try) = addrman.SelectTriedCollision();
if (!addr.IsValid()) {
// No tried table collisions. Select a new table address
// for our feeler.
- addr = addrman.Select(true);
+ std::tie(addr, addr_last_try) = addrman.Select(true);
} else if (AlreadyConnectedToAddress(addr)) {
// If test-before-evict logic would have us connect to a
// peer that we're already connected to, just mark that
@@ -2027,11 +2030,11 @@ void CConnman::ThreadOpenConnections(const std::vector<std::string> connect)
// a currently-connected peer.
addrman.Good(addr);
// Select a new table address for our feeler instead.
- addr = addrman.Select(true);
+ std::tie(addr, addr_last_try) = addrman.Select(true);
}
} else {
// Not a feeler
- addr = addrman.Select();
+ std::tie(addr, addr_last_try) = addrman.Select();
}
// Require outbound connections, other than feelers, to be to distinct network groups
@@ -2048,7 +2051,7 @@ void CConnman::ThreadOpenConnections(const std::vector<std::string> connect)
continue;
// only consider very recently tried nodes after 30 failed attempts
- if (nANow - addr.nLastTry < 600 && nTries < 30)
+ if (nANow - addr_last_try < 600 && nTries < 30)
continue;
// for non-feelers, require all the services we'll want,
@@ -2157,6 +2160,7 @@ std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo() const
void CConnman::ThreadOpenAddedConnections()
{
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::NET_ADD_CONNECTION);
while (true)
{
CSemaphoreGrant grant(*semAddnode);
@@ -2220,6 +2224,7 @@ void CConnman::OpenNetworkConnection(const CAddress& addrConnect, bool fCountFai
void CConnman::ThreadMessageHandler()
{
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::MESSAGE_HANDLER);
FastRandomContext rng;
while (!flagInterruptMsgProc)
{
@@ -2439,7 +2444,7 @@ void CConnman::SetNetworkActive(bool active)
}
}
-CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In, CAddrMan& addrman_in, bool network_active)
+CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In, AddrMan& addrman_in, bool network_active)
: addrman(addrman_in), nSeed0(nSeed0In), nSeed1(nSeed1In)
{
SetTryNewOutboundPeer(false);
@@ -2804,7 +2809,8 @@ void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats) const
vstats.reserve(vNodes.size());
for (CNode* pnode : vNodes) {
vstats.emplace_back();
- pnode->CopyStats(vstats.back(), addrman.GetAsmap());
+ pnode->CopyStats(vstats.back());
+ vstats.back().m_mapped_as = pnode->addr.GetMappedAS(addrman.GetAsmap());
}
}
diff --git a/src/net.h b/src/net.h
index a884a4521d..e2071414b4 100644
--- a/src/net.h
+++ b/src/net.h
@@ -6,12 +6,11 @@
#ifndef BITCOIN_NET_H
#define BITCOIN_NET_H
-#include <addrdb.h>
#include <addrman.h>
-#include <amount.h>
#include <bloom.h>
#include <chainparams.h>
#include <compat.h>
+#include <consensus/amount.h>
#include <crypto/siphash.h>
#include <hash.h>
#include <i2p.h>
@@ -652,7 +651,7 @@ public:
void CloseSocketDisconnect();
- void CopyStats(CNodeStats& stats, const std::vector<bool>& asmap);
+ void CopyStats(CNodeStats& stats);
ServiceFlags GetLocalServices() const
{
@@ -768,7 +767,6 @@ public:
bool m_use_addrman_outgoing = true;
std::vector<std::string> m_specified_outgoing;
std::vector<std::string> m_added_nodes;
- std::vector<bool> m_asmap;
bool m_i2p_accept_incoming;
};
@@ -799,7 +797,7 @@ public:
m_onion_binds = connOptions.onion_binds;
}
- CConnman(uint64_t seed0, uint64_t seed1, CAddrMan& addrman, bool network_active = true);
+ CConnman(uint64_t seed0, uint64_t seed1, AddrMan& addrman, bool network_active = true);
~CConnman();
bool Start(CScheduler& scheduler, const Options& options);
@@ -1051,7 +1049,7 @@ private:
std::vector<ListenSocket> vhListenSocket;
std::atomic<bool> fNetworkActive{true};
bool fAddressesInitialized{false};
- CAddrMan& addrman;
+ AddrMan& addrman;
std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
RecursiveMutex m_addr_fetches_mutex;
std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
diff --git a/src/net_processing.cpp b/src/net_processing.cpp
index 3ad34e83ba..66b99aa2bb 100644
--- a/src/net_processing.cpp
+++ b/src/net_processing.cpp
@@ -10,6 +10,7 @@
#include <blockencodings.h>
#include <blockfilter.h>
#include <chainparams.h>
+#include <consensus/amount.h>
#include <consensus/validation.h>
#include <deploymentstatus.h>
#include <hash.h>
@@ -291,7 +292,7 @@ using PeerRef = std::shared_ptr<Peer>;
class PeerManagerImpl final : public PeerManager
{
public:
- PeerManagerImpl(const CChainParams& chainparams, CConnman& connman, CAddrMan& addrman,
+ PeerManagerImpl(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman,
BanMan* banman, ChainstateManager& chainman,
CTxMemPool& pool, bool ignore_incoming_txs);
@@ -409,7 +410,7 @@ private:
const CChainParams& m_chainparams;
CConnman& m_connman;
- CAddrMan& m_addrman;
+ AddrMan& m_addrman;
/** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */
BanMan* const m_banman;
ChainstateManager& m_chainman;
@@ -884,6 +885,12 @@ bool PeerManagerImpl::BlockRequested(NodeId nodeid, const CBlockIndex& block, st
void PeerManagerImpl::MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid)
{
AssertLockHeld(cs_main);
+
+ // Never request high-bandwidth mode from peers if we're blocks-only. Our
+ // mempool will not contain the transactions necessary to reconstruct the
+ // compact block.
+ if (m_ignore_incoming_txs) return;
+
CNodeState* nodestate = State(nodeid);
if (!nodestate || !nodestate->fSupportsDesiredCmpctVersion) {
// Never ask from peers who can't provide witnesses.
@@ -1300,7 +1307,7 @@ bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) c
void PeerManagerImpl::AddToCompactExtraTransactions(const CTransactionRef& tx)
{
- size_t max_extra_txn = gArgs.GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
+ size_t max_extra_txn = gArgs.GetIntArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
if (max_extra_txn <= 0)
return;
if (!vExtraTxnForCompact.size())
@@ -1419,14 +1426,14 @@ bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
(GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT);
}
-std::unique_ptr<PeerManager> PeerManager::make(const CChainParams& chainparams, CConnman& connman, CAddrMan& addrman,
+std::unique_ptr<PeerManager> PeerManager::make(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman,
BanMan* banman, ChainstateManager& chainman,
CTxMemPool& pool, bool ignore_incoming_txs)
{
return std::make_unique<PeerManagerImpl>(chainparams, connman, addrman, banman, chainman, pool, ignore_incoming_txs);
}
-PeerManagerImpl::PeerManagerImpl(const CChainParams& chainparams, CConnman& connman, CAddrMan& addrman,
+PeerManagerImpl::PeerManagerImpl(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman,
BanMan* banman, ChainstateManager& chainman,
CTxMemPool& pool, bool ignore_incoming_txs)
: m_chainparams(chainparams),
@@ -2165,7 +2172,11 @@ void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, const Peer& peer,
pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
}
if (vGetData.size() > 0) {
- if (nodestate->fSupportsDesiredCmpctVersion && vGetData.size() == 1 && mapBlocksInFlight.size() == 1 && pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
+ if (!m_ignore_incoming_txs &&
+ nodestate->fSupportsDesiredCmpctVersion &&
+ vGetData.size() == 1 &&
+ mapBlocksInFlight.size() == 1 &&
+ pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
// In any case, we want to download using a compact block, not a regular one
vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
}
@@ -2653,7 +2664,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
// table is also potentially detrimental because new-table entries
// are subject to eviction in the event of addrman collisions. We
// mitigate the information-leak by never calling
- // CAddrMan::Connected() on block-relay-only peers; see
+ // AddrMan::Connected() on block-relay-only peers; see
// FinalizeNode().
//
// This moves an address from New to Tried table in Addrman,
@@ -2909,13 +2920,13 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
return;
}
- // We won't accept tx inv's if we're in blocks-only mode, or this is a
+ // Reject tx INVs when the -blocksonly setting is enabled, or this is a
// block-relay-only peer
- bool fBlocksOnly = m_ignore_incoming_txs || (pfrom.m_tx_relay == nullptr);
+ bool reject_tx_invs{m_ignore_incoming_txs || (pfrom.m_tx_relay == nullptr)};
// Allow peers with relay permission to send data other than blocks in blocks only mode
if (pfrom.HasPermission(NetPermissionFlags::Relay)) {
- fBlocksOnly = false;
+ reject_tx_invs = false;
}
LOCK(cs_main);
@@ -2954,7 +2965,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
pfrom.AddKnownTx(inv.hash);
- if (fBlocksOnly) {
+ if (reject_tx_invs) {
LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol, disconnecting peer=%d\n", inv.hash.ToString(), pfrom.GetId());
pfrom.fDisconnect = true;
return;
@@ -3315,7 +3326,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
m_txrequest.ForgetTxHash(tx.GetWitnessHash());
// DoS prevention: do not allow m_orphanage to grow unbounded (see CVE-2012-3789)
- unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, gArgs.GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
+ unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, gArgs.GetIntArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
unsigned int nEvicted = m_orphanage.LimitOrphans(nMaxOrphanTx);
if (nEvicted > 0) {
LogPrint(BCLog::MEMPOOL, "orphanage overflow, removed %u tx\n", nEvicted);
@@ -4416,7 +4427,7 @@ void PeerManagerImpl::MaybeSendFeefilter(CNode& pto, std::chrono::microseconds c
// peers with the forcerelay permission should not filter txs to us
if (pto.HasPermission(NetPermissionFlags::ForceRelay)) return;
- CAmount currentFilter = m_mempool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
+ CAmount currentFilter = m_mempool.GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
static FeeFilterRounder g_filter_rounder{CFeeRate{DEFAULT_MIN_RELAY_TX_FEE}};
if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
diff --git a/src/net_processing.h b/src/net_processing.h
index 9d8d788583..27bc40687a 100644
--- a/src/net_processing.h
+++ b/src/net_processing.h
@@ -9,7 +9,7 @@
#include <net.h>
#include <validationinterface.h>
-class CAddrMan;
+class AddrMan;
class CChainParams;
class CTxMemPool;
class ChainstateManager;
@@ -37,7 +37,7 @@ struct CNodeStateStats {
class PeerManager : public CValidationInterface, public NetEventsInterface
{
public:
- static std::unique_ptr<PeerManager> make(const CChainParams& chainparams, CConnman& connman, CAddrMan& addrman,
+ static std::unique_ptr<PeerManager> make(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman,
BanMan* banman, ChainstateManager& chainman,
CTxMemPool& pool, bool ignore_incoming_txs);
virtual ~PeerManager() { }
diff --git a/src/netaddress.cpp b/src/netaddress.cpp
index e7b3377475..f9fff5a6d5 100644
--- a/src/netaddress.cpp
+++ b/src/netaddress.cpp
@@ -165,7 +165,7 @@ void CNetAddr::SetLegacyIPv6(Span<const uint8_t> ipv6)
}
/**
- * Create an "internal" address that represents a name or FQDN. CAddrMan uses
+ * Create an "internal" address that represents a name or FQDN. AddrMan uses
* these fake addresses to keep track of which DNS seeds were used.
* @returns Whether or not the operation was successful.
* @see NET_INTERNAL, INTERNAL_IN_IPV6_PREFIX, CNetAddr::IsInternal(), CNetAddr::IsRFC4193()
@@ -1242,8 +1242,3 @@ bool operator<(const CSubNet& a, const CSubNet& b)
{
return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0));
}
-
-bool SanityCheckASMap(const std::vector<bool>& asmap)
-{
- return SanityCheckASMap(asmap, 128); // For IP address lookups, the input is 128 bits
-}
diff --git a/src/netaddress.h b/src/netaddress.h
index eb35ed3fac..66c8c48f08 100644
--- a/src/netaddress.h
+++ b/src/netaddress.h
@@ -62,7 +62,7 @@ enum Network {
NET_CJDNS,
/// A set of addresses that represent the hash of a string or FQDN. We use
- /// them in CAddrMan to keep track of which DNS seeds were used.
+ /// them in AddrMan to keep track of which DNS seeds were used.
NET_INTERNAL,
/// Dummy value to indicate the number of NET_* constants.
@@ -567,6 +567,4 @@ public:
}
};
-bool SanityCheckASMap(const std::vector<bool>& asmap);
-
#endif // BITCOIN_NETADDRESS_H
diff --git a/src/netbase.cpp b/src/netbase.cpp
index 2980bdf459..64d17189a6 100644
--- a/src/netbase.cpp
+++ b/src/netbase.cpp
@@ -23,8 +23,6 @@
#ifndef WIN32
#include <fcntl.h>
-#else
-#include <codecvt>
#endif
#ifdef USE_POLL
diff --git a/src/node/blockstorage.cpp b/src/node/blockstorage.cpp
index 90f7ba191d..0b7df9bd9a 100644
--- a/src/node/blockstorage.cpp
+++ b/src/node/blockstorage.cpp
@@ -16,6 +16,7 @@
#include <signet.h>
#include <streams.h>
#include <undo.h>
+#include <util/syscall_sandbox.h>
#include <util/system.h>
#include <validation.h>
@@ -85,7 +86,7 @@ void CleanupBlockRevFiles()
// start removing block files.
int nContigCounter = 0;
for (const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
- if (atoi(item.first) == nContigCounter) {
+ if (LocaleIndependentAtoi<int>(item.first) == nContigCounter) {
nContigCounter++;
continue;
}
@@ -394,18 +395,14 @@ bool ReadBlockFromDisk(CBlock& block, const FlatFilePos& pos, const Consensus::P
bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
- FlatFilePos blockPos;
- {
- LOCK(cs_main);
- blockPos = pindex->GetBlockPos();
- }
+ const FlatFilePos block_pos{WITH_LOCK(cs_main, return pindex->GetBlockPos())};
- if (!ReadBlockFromDisk(block, blockPos, consensusParams)) {
+ if (!ReadBlockFromDisk(block, block_pos, consensusParams)) {
return false;
}
if (block.GetHash() != pindex->GetBlockHash()) {
return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
- pindex->ToString(), pindex->GetBlockPos().ToString());
+ pindex->ToString(), block_pos.ToString());
}
return true;
}
@@ -493,6 +490,7 @@ struct CImportingNow {
void ThreadImport(ChainstateManager& chainman, std::vector<fs::path> vImportFiles, const ArgsManager& args)
{
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::INITIALIZATION_LOAD_BLOCKS);
ScheduleBatchPriority();
{
diff --git a/src/node/coinstats.h b/src/node/coinstats.h
index 69e856dd15..9e9503ff5d 100644
--- a/src/node/coinstats.h
+++ b/src/node/coinstats.h
@@ -6,9 +6,9 @@
#ifndef BITCOIN_NODE_COINSTATS_H
#define BITCOIN_NODE_COINSTATS_H
-#include <amount.h>
#include <chain.h>
#include <coins.h>
+#include <consensus/amount.h>
#include <streams.h>
#include <uint256.h>
diff --git a/src/node/context.h b/src/node/context.h
index 135f9ea1c6..26873345b4 100644
--- a/src/node/context.h
+++ b/src/node/context.h
@@ -12,7 +12,7 @@
class ArgsManager;
class BanMan;
-class CAddrMan;
+class AddrMan;
class CBlockPolicyEstimator;
class CConnman;
class CScheduler;
@@ -39,7 +39,7 @@ class WalletClient;
struct NodeContext {
//! Init interface for initializing current process and connecting to other processes.
interfaces::Init* init{nullptr};
- std::unique_ptr<CAddrMan> addrman;
+ std::unique_ptr<AddrMan> addrman;
std::unique_ptr<CConnman> connman;
std::unique_ptr<CTxMemPool> mempool;
std::unique_ptr<CBlockPolicyEstimator> fee_estimator;
diff --git a/src/node/interfaces.cpp b/src/node/interfaces.cpp
index b46ad0333e..5b6d8416a7 100644
--- a/src/node/interfaces.cpp
+++ b/src/node/interfaces.cpp
@@ -72,7 +72,7 @@ class NodeImpl : public Node
private:
ChainstateManager& chainman() { return *Assert(m_context->chainman); }
public:
- explicit NodeImpl(NodeContext* context) { setContext(context); }
+ explicit NodeImpl(NodeContext& context) { setContext(&context); }
void initLogging() override { InitLogging(*Assert(m_context->args)); }
void initParameterInteraction() override { InitParameterInteraction(*Assert(m_context->args)); }
bilingual_str getWarnings() override { return GetWarnings(true); }
@@ -575,16 +575,16 @@ public:
// that Chain clients do not need to know about.
return TransactionError::OK == err;
}
- void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants) override
+ void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize, CAmount* ancestorfees) override
{
ancestors = descendants = 0;
if (!m_node.mempool) return;
- m_node.mempool->GetTransactionAncestry(txid, ancestors, descendants);
+ m_node.mempool->GetTransactionAncestry(txid, ancestors, descendants, ancestorsize, ancestorfees);
}
void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) override
{
- limit_ancestor_count = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
- limit_descendant_count = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
+ limit_ancestor_count = gArgs.GetIntArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
+ limit_descendant_count = gArgs.GetIntArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
}
bool checkChainLimits(const CTransactionRef& tx) override
{
@@ -592,10 +592,10 @@ public:
LockPoints lp;
CTxMemPoolEntry entry(tx, 0, 0, 0, false, 0, lp);
CTxMemPool::setEntries ancestors;
- auto limit_ancestor_count = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
- auto limit_ancestor_size = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000;
- auto limit_descendant_count = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
- auto limit_descendant_size = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000;
+ auto limit_ancestor_count = gArgs.GetIntArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
+ auto limit_ancestor_size = gArgs.GetIntArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000;
+ auto limit_descendant_count = gArgs.GetIntArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
+ auto limit_descendant_size = gArgs.GetIntArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000;
std::string unused_error_string;
LOCK(m_node.mempool->cs);
return m_node.mempool->CalculateMemPoolAncestors(
@@ -615,7 +615,7 @@ public:
CFeeRate mempoolMinFee() override
{
if (!m_node.mempool) return {};
- return m_node.mempool->GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
+ return m_node.mempool->GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
}
CFeeRate relayMinFee() override { return ::minRelayTxFee; }
CFeeRate relayIncrementalFee() override { return ::incrementalRelayFee; }
@@ -710,6 +710,6 @@ public:
} // namespace node
namespace interfaces {
-std::unique_ptr<Node> MakeNode(NodeContext* context) { return std::make_unique<node::NodeImpl>(context); }
+std::unique_ptr<Node> MakeNode(NodeContext& context) { return std::make_unique<node::NodeImpl>(context); }
std::unique_ptr<Chain> MakeChain(NodeContext& context) { return std::make_unique<node::ChainImpl>(context); }
} // namespace interfaces
diff --git a/src/node/psbt.cpp b/src/node/psbt.cpp
index b013b6d579..9ad65d15d2 100644
--- a/src/node/psbt.cpp
+++ b/src/node/psbt.cpp
@@ -2,8 +2,8 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <amount.h>
#include <coins.h>
+#include <consensus/amount.h>
#include <consensus/tx_verify.h>
#include <node/psbt.h>
#include <policy/policy.h>
diff --git a/src/policy/feerate.h b/src/policy/feerate.h
index d296d32774..b16f3f8251 100644
--- a/src/policy/feerate.h
+++ b/src/policy/feerate.h
@@ -6,7 +6,7 @@
#ifndef BITCOIN_POLICY_FEERATE_H
#define BITCOIN_POLICY_FEERATE_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <serialize.h>
#include <string>
diff --git a/src/policy/fees.h b/src/policy/fees.h
index c444d71a31..27f9120c64 100644
--- a/src/policy/fees.h
+++ b/src/policy/fees.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_POLICY_FEES_H
#define BITCOIN_POLICY_FEES_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <policy/feerate.h>
#include <uint256.h>
#include <random.h>
diff --git a/src/policy/rbf.cpp b/src/policy/rbf.cpp
index 43624c7993..7ac2e22006 100644
--- a/src/policy/rbf.cpp
+++ b/src/policy/rbf.cpp
@@ -13,7 +13,7 @@ RBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool)
{
AssertLockHeld(pool.cs);
- CTxMemPool::setEntries setAncestors;
+ CTxMemPool::setEntries ancestors;
// First check the transaction itself.
if (SignalsOptInRBF(tx)) {
@@ -31,9 +31,9 @@ RBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool)
uint64_t noLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
CTxMemPoolEntry entry = *pool.mapTx.find(tx.GetHash());
- pool.CalculateMemPoolAncestors(entry, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
+ pool.CalculateMemPoolAncestors(entry, ancestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
- for (CTxMemPool::txiter it : setAncestors) {
+ for (CTxMemPool::txiter it : ancestors) {
if (SignalsOptInRBF(it->GetTx())) {
return RBFTransactionState::REPLACEABLE_BIP125;
}
@@ -47,33 +47,130 @@ RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction& tx)
return SignalsOptInRBF(tx) ? RBFTransactionState::REPLACEABLE_BIP125 : RBFTransactionState::UNKNOWN;
}
-bool GetEntriesForConflicts(const CTransaction& tx,
- CTxMemPool& m_pool,
- const CTxMemPool::setEntries& setIterConflicting,
- CTxMemPool::setEntries& allConflicting,
- std::string& err_string)
+std::optional<std::string> GetEntriesForConflicts(const CTransaction& tx,
+ CTxMemPool& pool,
+ const CTxMemPool::setEntries& iters_conflicting,
+ CTxMemPool::setEntries& all_conflicts)
{
- AssertLockHeld(m_pool.cs);
- const uint256 hash = tx.GetHash();
+ AssertLockHeld(pool.cs);
+ const uint256 txid = tx.GetHash();
uint64_t nConflictingCount = 0;
- for (const auto& mi : setIterConflicting) {
+ for (const auto& mi : iters_conflicting) {
nConflictingCount += mi->GetCountWithDescendants();
- // This potentially overestimates the number of actual descendants
- // but we just want to be conservative to avoid doing too much
- // work.
+ // BIP125 Rule #5: don't consider replacing more than MAX_BIP125_REPLACEMENT_CANDIDATES
+ // entries from the mempool. This potentially overestimates the number of actual
+ // descendants (i.e. if multiple conflicts share a descendant, it will be counted multiple
+ // times), but we just want to be conservative to avoid doing too much work.
if (nConflictingCount > MAX_BIP125_REPLACEMENT_CANDIDATES) {
- err_string = strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
- hash.ToString(),
- nConflictingCount,
- MAX_BIP125_REPLACEMENT_CANDIDATES);
- return false;
+ return strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
+ txid.ToString(),
+ nConflictingCount,
+ MAX_BIP125_REPLACEMENT_CANDIDATES);
}
}
- // If not too many to replace, then calculate the set of
- // transactions that would have to be evicted
- for (CTxMemPool::txiter it : setIterConflicting) {
- m_pool.CalculateDescendants(it, allConflicting);
+ // Calculate the set of all transactions that would have to be evicted.
+ for (CTxMemPool::txiter it : iters_conflicting) {
+ pool.CalculateDescendants(it, all_conflicts);
}
- return true;
+ return std::nullopt;
}
+std::optional<std::string> HasNoNewUnconfirmed(const CTransaction& tx,
+ const CTxMemPool& pool,
+ const CTxMemPool::setEntries& iters_conflicting)
+{
+ AssertLockHeld(pool.cs);
+ std::set<uint256> parents_of_conflicts;
+ for (const auto& mi : iters_conflicting) {
+ for (const CTxIn& txin : mi->GetTx().vin) {
+ parents_of_conflicts.insert(txin.prevout.hash);
+ }
+ }
+
+ for (unsigned int j = 0; j < tx.vin.size(); j++) {
+ // BIP125 Rule #2: We don't want to accept replacements that require low feerate junk to be
+ // mined first. Ideally we'd keep track of the ancestor feerates and make the decision
+ // based on that, but for now requiring all new inputs to be confirmed works.
+ //
+ // Note that if you relax this to make RBF a little more useful, this may break the
+ // CalculateMempoolAncestors RBF relaxation which subtracts the conflict count/size from the
+ // descendant limit.
+ if (!parents_of_conflicts.count(tx.vin[j].prevout.hash)) {
+ // Rather than check the UTXO set - potentially expensive - it's cheaper to just check
+ // if the new input refers to a tx that's in the mempool.
+ if (pool.exists(tx.vin[j].prevout.hash)) {
+ return strprintf("replacement %s adds unconfirmed input, idx %d",
+ tx.GetHash().ToString(), j);
+ }
+ }
+ }
+ return std::nullopt;
+}
+
+std::optional<std::string> EntriesAndTxidsDisjoint(const CTxMemPool::setEntries& ancestors,
+ const std::set<uint256>& direct_conflicts,
+ const uint256& txid)
+{
+ for (CTxMemPool::txiter ancestorIt : ancestors) {
+ const uint256& hashAncestor = ancestorIt->GetTx().GetHash();
+ if (direct_conflicts.count(hashAncestor)) {
+ return strprintf("%s spends conflicting transaction %s",
+ txid.ToString(),
+ hashAncestor.ToString());
+ }
+ }
+ return std::nullopt;
+}
+
+std::optional<std::string> PaysMoreThanConflicts(const CTxMemPool::setEntries& iters_conflicting,
+ CFeeRate replacement_feerate,
+ const uint256& txid)
+{
+ for (const auto& mi : iters_conflicting) {
+ // Don't allow the replacement to reduce the feerate of the mempool.
+ //
+ // We usually don't want to accept replacements with lower feerates than what they replaced
+ // as that would lower the feerate of the next block. Requiring that the feerate always be
+ // increased is also an easy-to-reason about way to prevent DoS attacks via replacements.
+ //
+ // We only consider the feerates of transactions being directly replaced, not their indirect
+ // descendants. While that does mean high feerate children are ignored when deciding whether
+ // or not to replace, we do require the replacement to pay more overall fees too, mitigating
+ // most cases.
+ CFeeRate original_feerate(mi->GetModifiedFee(), mi->GetTxSize());
+ if (replacement_feerate <= original_feerate) {
+ return strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
+ txid.ToString(),
+ replacement_feerate.ToString(),
+ original_feerate.ToString());
+ }
+ }
+ return std::nullopt;
+}
+
+std::optional<std::string> PaysForRBF(CAmount original_fees,
+ CAmount replacement_fees,
+ size_t replacement_vsize,
+ CFeeRate relay_fee,
+ const uint256& txid)
+{
+ // BIP125 Rule #3: The replacement fees must be greater than or equal to fees of the
+ // transactions it replaces, otherwise the bandwidth used by those conflicting transactions
+ // would not be paid for.
+ if (replacement_fees < original_fees) {
+ return strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
+ txid.ToString(), FormatMoney(replacement_fees), FormatMoney(original_fees));
+ }
+
+ // BIP125 Rule #4: The new transaction must pay for its own bandwidth. Otherwise, we have a DoS
+ // vector where attackers can cause a transaction to be replaced (and relayed) repeatedly by
+ // increasing the fee by tiny amounts.
+ CAmount additional_fees = replacement_fees - original_fees;
+ if (additional_fees < relay_fee.GetFee(replacement_vsize)) {
+ return strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
+ txid.ToString(),
+ FormatMoney(additional_fees),
+ FormatMoney(relay_fee.GetFee(replacement_vsize)));
+ }
+ return std::nullopt;
+}
diff --git a/src/policy/rbf.h b/src/policy/rbf.h
index a67e9058df..be8c2e5b8b 100644
--- a/src/policy/rbf.h
+++ b/src/policy/rbf.h
@@ -5,7 +5,12 @@
#ifndef BITCOIN_POLICY_RBF_H
#define BITCOIN_POLICY_RBF_H
+#include <primitives/transaction.h>
#include <txmempool.h>
+#include <uint256.h>
+
+#include <optional>
+#include <string>
/** Maximum number of transactions that can be replaced by BIP125 RBF (Rule #5). This includes all
* mempool conflicts and their descendants. */
@@ -35,19 +40,63 @@ enum class RBFTransactionState {
RBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs);
RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction& tx);
-/** Get all descendants of setIterConflicting. Also enforce BIP125 Rule #5, "The number of original
+/** Get all descendants of iters_conflicting. Also enforce BIP125 Rule #5, "The number of original
* transactions to be replaced and their descendant transactions which will be evicted from the
* mempool must not exceed a total of 100 transactions." Quit as early as possible. There cannot be
* more than MAX_BIP125_REPLACEMENT_CANDIDATES potential entries.
- * @param[in] setIterConflicting The set of iterators to mempool entries.
- * @param[out] err_string Used to return errors, if any.
- * @param[out] allConflicting Populated with all the mempool entries that would be replaced,
- * which includes descendants of setIterConflicting. Not cleared at
+ * @param[in] iters_conflicting The set of iterators to mempool entries.
+ * @param[out] all_conflicts Populated with all the mempool entries that would be replaced,
+ * which includes descendants of iters_conflicting. Not cleared at
* the start; any existing mempool entries will remain in the set.
- * @returns false if Rule 5 is broken.
+ * @returns an error message if Rule #5 is broken, otherwise a std::nullopt.
*/
-bool GetEntriesForConflicts(const CTransaction& tx, CTxMemPool& m_pool,
- const CTxMemPool::setEntries& setIterConflicting,
- CTxMemPool::setEntries& allConflicting,
- std::string& err_string) EXCLUSIVE_LOCKS_REQUIRED(m_pool.cs);
+std::optional<std::string> GetEntriesForConflicts(const CTransaction& tx, CTxMemPool& pool,
+ const CTxMemPool::setEntries& iters_conflicting,
+ CTxMemPool::setEntries& all_conflicts)
+ EXCLUSIVE_LOCKS_REQUIRED(pool.cs);
+
+/** BIP125 Rule #2: "The replacement transaction may only include an unconfirmed input if that input
+ * was included in one of the original transactions."
+ * @returns error message if Rule #2 is broken, otherwise std::nullopt. */
+std::optional<std::string> HasNoNewUnconfirmed(const CTransaction& tx, const CTxMemPool& pool,
+ const CTxMemPool::setEntries& iters_conflicting)
+ EXCLUSIVE_LOCKS_REQUIRED(pool.cs);
+
+/** Check the intersection between two sets of transactions (a set of mempool entries and a set of
+ * txids) to make sure they are disjoint.
+ * @param[in] ancestors Set of mempool entries corresponding to ancestors of the
+ * replacement transactions.
+ * @param[in] direct_conflicts Set of txids corresponding to the mempool conflicts
+ * (candidates to be replaced).
+ * @param[in] txid Transaction ID, included in the error message if violation occurs.
+ * @returns error message if the sets intersect, std::nullopt if they are disjoint.
+ */
+std::optional<std::string> EntriesAndTxidsDisjoint(const CTxMemPool::setEntries& ancestors,
+ const std::set<uint256>& direct_conflicts,
+ const uint256& txid);
+
+/** Check that the feerate of the replacement transaction(s) is higher than the feerate of each
+ * of the transactions in iters_conflicting.
+ * @param[in] iters_conflicting The set of mempool entries.
+ * @returns error message if fees insufficient, otherwise std::nullopt.
+ */
+std::optional<std::string> PaysMoreThanConflicts(const CTxMemPool::setEntries& iters_conflicting,
+ CFeeRate replacement_feerate, const uint256& txid);
+
+/** Enforce BIP125 Rule #3 "The replacement transaction pays an absolute fee of at least the sum
+ * paid by the original transactions." Enforce BIP125 Rule #4 "The replacement transaction must also
+ * pay for its own bandwidth at or above the rate set by the node's minimum relay fee setting."
+ * @param[in] original_fees Total modified fees of original transaction(s).
+ * @param[in] replacement_fees Total modified fees of replacement transaction(s).
+ * @param[in] replacement_vsize Total virtual size of replacement transaction(s).
+ * @param[in] relay_fee The node's minimum feerate for transaction relay.
+ * @param[in] txid Transaction ID, included in the error message if violation occurs.
+ * @returns error string if fees are insufficient, otherwise std::nullopt.
+ */
+std::optional<std::string> PaysForRBF(CAmount original_fees,
+ CAmount replacement_fees,
+ size_t replacement_vsize,
+ CFeeRate relay_fee,
+ const uint256& txid);
+
#endif // BITCOIN_POLICY_RBF_H
diff --git a/src/primitives/transaction.cpp b/src/primitives/transaction.cpp
index 245206b906..a871912225 100644
--- a/src/primitives/transaction.cpp
+++ b/src/primitives/transaction.cpp
@@ -5,6 +5,7 @@
#include <primitives/transaction.h>
+#include <consensus/amount.h>
#include <hash.h>
#include <tinyformat.h>
#include <util/strencodings.h>
diff --git a/src/primitives/transaction.h b/src/primitives/transaction.h
index 6bf36ee854..46db39f8db 100644
--- a/src/primitives/transaction.h
+++ b/src/primitives/transaction.h
@@ -7,7 +7,7 @@
#define BITCOIN_PRIMITIVES_TRANSACTION_H
#include <stdint.h>
-#include <amount.h>
+#include <consensus/amount.h>
#include <script/script.h>
#include <serialize.h>
#include <uint256.h>
diff --git a/src/pubkey.cpp b/src/pubkey.cpp
index d14a20b870..956ff2b34a 100644
--- a/src/pubkey.cpp
+++ b/src/pubkey.cpp
@@ -337,8 +337,7 @@ bool CPubKey::Derive(CPubKey& pubkeyChild, ChainCode &ccChild, unsigned int nChi
void CExtPubKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
code[0] = nDepth;
memcpy(code+1, vchFingerprint, 4);
- code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
- code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
+ WriteBE32(code+5, nChild);
memcpy(code+9, chaincode.begin(), 32);
assert(pubkey.size() == CPubKey::COMPRESSED_SIZE);
memcpy(code+41, pubkey.begin(), CPubKey::COMPRESSED_SIZE);
@@ -347,7 +346,7 @@ void CExtPubKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
void CExtPubKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
nDepth = code[0];
memcpy(vchFingerprint, code+1, 4);
- nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
+ nChild = ReadBE32(code+5);
memcpy(chaincode.begin(), code+9, 32);
pubkey.Set(code+41, code+BIP32_EXTKEY_SIZE);
if ((nDepth == 0 && (nChild != 0 || ReadLE32(vchFingerprint) != 0)) || !pubkey.IsFullyValid()) pubkey = CPubKey();
diff --git a/src/qt/addressbookpage.cpp b/src/qt/addressbookpage.cpp
index c31f0aceea..a617bb4451 100644
--- a/src/qt/addressbookpage.cpp
+++ b/src/qt/addressbookpage.cpp
@@ -182,14 +182,14 @@ void AddressBookPage::onEditAction()
if(indexes.isEmpty())
return;
- EditAddressDialog dlg(
+ auto dlg = new EditAddressDialog(
tab == SendingTab ?
EditAddressDialog::EditSendingAddress :
EditAddressDialog::EditReceivingAddress, this);
- dlg.setModel(model);
+ dlg->setModel(model);
QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
- dlg.loadRow(origIndex.row());
- dlg.exec();
+ dlg->loadRow(origIndex.row());
+ GUIUtil::ShowModalDialogAndDeleteOnClose(dlg);
}
void AddressBookPage::on_newAddress_clicked()
@@ -282,7 +282,7 @@ void AddressBookPage::on_exportButton_clicked()
QString filename = GUIUtil::getSaveFileName(this,
tr("Export Address List"), QString(),
/*: Expanded name of the CSV file format.
- See https://en.wikipedia.org/wiki/Comma-separated_values */
+ See: https://en.wikipedia.org/wiki/Comma-separated_values. */
tr("Comma separated file") + QLatin1String(" (*.csv)"), nullptr);
if (filename.isNull())
diff --git a/src/qt/bantablemodel.h b/src/qt/bantablemodel.h
index 57f559fc14..4b5b38e43f 100644
--- a/src/qt/bantablemodel.h
+++ b/src/qt/bantablemodel.h
@@ -5,6 +5,7 @@
#ifndef BITCOIN_QT_BANTABLEMODEL_H
#define BITCOIN_QT_BANTABLEMODEL_H
+#include <addrdb.h>
#include <net.h>
#include <memory>
diff --git a/src/qt/bitcoin.cpp b/src/qt/bitcoin.cpp
index f6ea147ddb..7de56a648a 100644
--- a/src/qt/bitcoin.cpp
+++ b/src/qt/bitcoin.cpp
@@ -11,6 +11,7 @@
#include <chainparams.h>
#include <init.h>
#include <interfaces/handler.h>
+#include <interfaces/init.h>
#include <interfaces/node.h>
#include <node/context.h>
#include <node/ui_interface.h>
@@ -45,7 +46,6 @@
#include <QApplication>
#include <QDebug>
-#include <QFontDatabase>
#include <QLatin1String>
#include <QLibraryInfo>
#include <QLocale>
@@ -54,6 +54,7 @@
#include <QThread>
#include <QTimer>
#include <QTranslator>
+#include <QWindow>
#if defined(QT_STATICPLUGIN)
#include <QtPlugin>
@@ -258,6 +259,7 @@ void BitcoinApplication::createOptionsModel(bool resetSettings)
void BitcoinApplication::createWindow(const NetworkStyle *networkStyle)
{
window = new BitcoinGUI(node(), platformStyle, networkStyle, nullptr);
+ connect(window, &BitcoinGUI::quitRequested, this, &BitcoinApplication::requestShutdown);
pollShutdownTimer = new QTimer(window);
connect(pollShutdownTimer, &QTimer::timeout, window, &BitcoinGUI::detectShutdown);
@@ -275,10 +277,10 @@ void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle)
connect(this, &BitcoinApplication::requestedShutdown, m_splash, &QWidget::close);
}
-void BitcoinApplication::setNode(interfaces::Node& node)
+void BitcoinApplication::createNode(interfaces::Init& init)
{
assert(!m_node);
- m_node = &node;
+ m_node = init.makeNode();
if (optionsModel) optionsModel->setNode(*m_node);
if (m_splash) m_splash->setNode(*m_node);
}
@@ -295,7 +297,7 @@ void BitcoinApplication::startThread()
/* communication to and from thread */
connect(&m_executor.value(), &InitExecutor::initializeResult, this, &BitcoinApplication::initializeResult);
- connect(&m_executor.value(), &InitExecutor::shutdownResult, this, &BitcoinApplication::shutdownResult);
+ connect(&m_executor.value(), &InitExecutor::shutdownResult, this, &QCoreApplication::quit);
connect(&m_executor.value(), &InitExecutor::runawayException, this, &BitcoinApplication::handleRunawayException);
connect(this, &BitcoinApplication::requestedInitialize, &m_executor.value(), &InitExecutor::initialize);
connect(this, &BitcoinApplication::requestedShutdown, &m_executor.value(), &InitExecutor::shutdown);
@@ -325,13 +327,17 @@ void BitcoinApplication::requestInitialize()
void BitcoinApplication::requestShutdown()
{
+ for (const auto w : QGuiApplication::topLevelWindows()) {
+ w->hide();
+ }
+
// Show a simple window indicating shutdown status
// Do this first as some of the steps may take some time below,
// for example the RPC console may still be executing a command.
shutdownWindow.reset(ShutdownWindow::showShutdownWindow(window));
qDebug() << __func__ << ": Requesting shutdown";
- window->hide();
+
// Must disconnect node signals otherwise current thread can deadlock since
// no event loop is running.
window->unsubscribeFromCoreSignals();
@@ -408,15 +414,10 @@ void BitcoinApplication::initializeResult(bool success, interfaces::BlockAndHead
pollShutdownTimer->start(200);
} else {
Q_EMIT splashFinished(); // Make sure splash screen doesn't stick around during shutdown
- quit(); // Exit first main loop invocation
+ requestShutdown();
}
}
-void BitcoinApplication::shutdownResult()
-{
- quit(); // Exit second main loop invocation after shutdown finished
-}
-
void BitcoinApplication::handleRunawayException(const QString &message)
{
QMessageBox::critical(
@@ -460,11 +461,13 @@ int GuiMain(int argc, char* argv[])
util::WinCmdLineArgs winArgs;
std::tie(argc, argv) = winArgs.get();
#endif
- SetupEnvironment();
- util::ThreadSetInternalName("main");
NodeContext node_context;
- std::unique_ptr<interfaces::Node> node = interfaces::MakeNode(&node_context);
+ int unused_exit_status;
+ std::unique_ptr<interfaces::Init> init = interfaces::MakeNodeInit(node_context, argc, argv, unused_exit_status);
+
+ SetupEnvironment();
+ util::ThreadSetInternalName("main");
// Subscribe to global signals from core
boost::signals2::scoped_connection handler_message_box = ::uiInterface.ThreadSafeMessageBox_connect(noui_ThreadSafeMessageBox);
@@ -488,11 +491,10 @@ int GuiMain(int argc, char* argv[])
#endif
BitcoinApplication app;
- QFontDatabase::addApplicationFont(":/fonts/monospace");
+ GUIUtil::LoadFont(QStringLiteral(":/fonts/monospace"));
/// 2. Parse command-line options. We do this after qt in order to show an error if there are problems parsing these
// Command-line options take precedence:
- node_context.args = &gArgs;
SetupServerArgs(gArgs);
SetupUIArgs(gArgs);
std::string error;
@@ -623,7 +625,7 @@ int GuiMain(int argc, char* argv[])
if (gArgs.GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) && !gArgs.GetBoolArg("-min", false))
app.createSplashScreen(networkStyle.data());
- app.setNode(*node);
+ app.createNode(*init);
int rv = EXIT_SUCCESS;
try
@@ -638,8 +640,6 @@ int GuiMain(int argc, char* argv[])
WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("%1 didn't yet exit safely…").arg(PACKAGE_NAME), (HWND)app.getMainWinId());
#endif
app.exec();
- app.requestShutdown();
- app.exec();
rv = app.getReturnValue();
} else {
// A dialog with detailed error will have been shown by InitError()
diff --git a/src/qt/bitcoin.h b/src/qt/bitcoin.h
index ed2f26b7f3..5678ca90d2 100644
--- a/src/qt/bitcoin.h
+++ b/src/qt/bitcoin.h
@@ -27,6 +27,9 @@ class PlatformStyle;
class SplashScreen;
class WalletController;
class WalletModel;
+namespace interfaces {
+class Init;
+} // namespace interfaces
/** Main Bitcoin application object */
@@ -51,13 +54,13 @@ public:
void createWindow(const NetworkStyle *networkStyle);
/// Create splash screen
void createSplashScreen(const NetworkStyle *networkStyle);
+ /// Create or spawn node
+ void createNode(interfaces::Init& init);
/// Basic initialization, before starting initialization/shutdown thread. Return true on success.
bool baseInitialize();
/// Request core initialization
void requestInitialize();
- /// Request core shutdown
- void requestShutdown();
/// Get process return value
int getReturnValue() const { return returnValue; }
@@ -69,11 +72,11 @@ public:
void setupPlatformStyle();
interfaces::Node& node() const { assert(m_node); return *m_node; }
- void setNode(interfaces::Node& node);
public Q_SLOTS:
void initializeResult(bool success, interfaces::BlockAndHeaderTipInfo tip_info);
- void shutdownResult();
+ /// Request core shutdown
+ void requestShutdown();
/// Handle runaway exceptions. Shows a message box with the problem and quits the program.
void handleRunawayException(const QString &message);
@@ -103,7 +106,7 @@ private:
const PlatformStyle *platformStyle;
std::unique_ptr<QWidget> shutdownWindow;
SplashScreen* m_splash = nullptr;
- interfaces::Node* m_node = nullptr;
+ std::unique_ptr<interfaces::Node> m_node;
void startThread();
};
diff --git a/src/qt/bitcoinamountfield.h b/src/qt/bitcoinamountfield.h
index c60d9a2c90..4855ada513 100644
--- a/src/qt/bitcoinamountfield.h
+++ b/src/qt/bitcoinamountfield.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_QT_BITCOINAMOUNTFIELD_H
#define BITCOIN_QT_BITCOINAMOUNTFIELD_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <QWidget>
diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp
index 862bdd3bfe..610637360b 100644
--- a/src/qt/bitcoingui.cpp
+++ b/src/qt/bitcoingui.cpp
@@ -107,7 +107,6 @@ BitcoinGUI::BitcoinGUI(interfaces::Node& node, const PlatformStyle *_platformSty
walletFrame = new WalletFrame(_platformStyle, this);
connect(walletFrame, &WalletFrame::createWalletButtonClicked, [this] {
auto activity = new CreateWalletActivity(getWalletController(), this);
- connect(activity, &CreateWalletActivity::finished, activity, &QObject::deleteLater);
activity->create();
});
connect(walletFrame, &WalletFrame::message, [this](const QString& title, const QString& message, unsigned int style) {
@@ -171,7 +170,9 @@ BitcoinGUI::BitcoinGUI(interfaces::Node& node, const PlatformStyle *_platformSty
frameBlocksLayout->addWidget(unitDisplayControl);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelWalletEncryptionIcon);
+ labelWalletEncryptionIcon->hide();
frameBlocksLayout->addWidget(labelWalletHDStatusIcon);
+ labelWalletHDStatusIcon->hide();
}
frameBlocksLayout->addWidget(labelProxyIcon);
frameBlocksLayout->addStretch();
@@ -371,7 +372,7 @@ void BitcoinGUI::createActions()
m_mask_values_action->setStatusTip(tr("Mask the values in the Overview tab"));
m_mask_values_action->setCheckable(true);
- connect(quitAction, &QAction::triggered, qApp, QApplication::quit);
+ connect(quitAction, &QAction::triggered, this, &BitcoinGUI::quitRequested);
connect(aboutAction, &QAction::triggered, this, &BitcoinGUI::aboutClicked);
connect(aboutQtAction, &QAction::triggered, qApp, QApplication::aboutQt);
connect(optionsAction, &QAction::triggered, this, &BitcoinGUI::optionsClicked);
@@ -416,7 +417,6 @@ void BitcoinGUI::createActions()
connect(action, &QAction::triggered, [this, path] {
auto activity = new OpenWalletActivity(m_wallet_controller, this);
connect(activity, &OpenWalletActivity::opened, this, &BitcoinGUI::setCurrentWallet);
- connect(activity, &OpenWalletActivity::finished, activity, &QObject::deleteLater);
activity->open(path);
});
}
@@ -431,7 +431,6 @@ void BitcoinGUI::createActions()
connect(m_create_wallet_action, &QAction::triggered, [this] {
auto activity = new CreateWalletActivity(m_wallet_controller, this);
connect(activity, &CreateWalletActivity::created, this, &BitcoinGUI::setCurrentWallet);
- connect(activity, &CreateWalletActivity::finished, activity, &QObject::deleteLater);
activity->create();
});
connect(m_close_all_wallets_action, &QAction::triggered, [this] {
@@ -662,9 +661,8 @@ void BitcoinGUI::setWalletController(WalletController* wallet_controller)
GUIUtil::ExceptionSafeConnect(wallet_controller, &WalletController::walletAdded, this, &BitcoinGUI::addWallet);
connect(wallet_controller, &WalletController::walletRemoved, this, &BitcoinGUI::removeWallet);
- for (WalletModel* wallet_model : m_wallet_controller->getOpenWallets()) {
- addWallet(wallet_model);
- }
+ auto activity = new LoadWalletsActivity(m_wallet_controller, this);
+ activity->load();
}
WalletController* BitcoinGUI::getWalletController()
@@ -848,8 +846,8 @@ void BitcoinGUI::aboutClicked()
if(!clientModel)
return;
- HelpMessageDialog dlg(this, true);
- dlg.exec();
+ auto dlg = new HelpMessageDialog(this, /* about */ true);
+ GUIUtil::ShowModalDialogAndDeleteOnClose(dlg);
}
void BitcoinGUI::showDebugWindow()
@@ -990,10 +988,11 @@ void BitcoinGUI::openOptionsDialogWithTab(OptionsDialog::Tab tab)
if (!clientModel || !clientModel->getOptionsModel())
return;
- OptionsDialog dlg(this, enableWallet);
- dlg.setCurrentTab(tab);
- dlg.setModel(clientModel->getOptionsModel());
- dlg.exec();
+ auto dlg = new OptionsDialog(this, enableWallet);
+ connect(dlg, &OptionsDialog::quitOnReset, this, &BitcoinGUI::quitRequested);
+ dlg->setCurrentTab(tab);
+ dlg->setModel(clientModel->getOptionsModel());
+ GUIUtil::ShowModalDialogAndDeleteOnClose(dlg);
}
void BitcoinGUI::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool header, SynchronizationState sync_state)
@@ -1216,7 +1215,7 @@ void BitcoinGUI::closeEvent(QCloseEvent *event)
// close rpcConsole in case it was open to make some space for the shutdown window
rpcConsole->close();
- QApplication::quit();
+ Q_EMIT quitRequested();
}
else
{
@@ -1410,7 +1409,7 @@ void BitcoinGUI::detectShutdown()
{
if(rpcConsole)
rpcConsole->hide();
- qApp->quit();
+ Q_EMIT quitRequested();
}
}
diff --git a/src/qt/bitcoingui.h b/src/qt/bitcoingui.h
index c83cd446a0..fa7ae4b87d 100644
--- a/src/qt/bitcoingui.h
+++ b/src/qt/bitcoingui.h
@@ -12,7 +12,7 @@
#include <qt/guiutil.h>
#include <qt/optionsdialog.h>
-#include <amount.h>
+#include <consensus/amount.h>
#include <QLabel>
#include <QMainWindow>
@@ -214,6 +214,7 @@ private:
void openOptionsDialogWithTab(OptionsDialog::Tab tab);
Q_SIGNALS:
+ void quitRequested();
/** Signal raised when a URI was entered or dragged to the GUI */
void receivedURI(const QString &uri);
/** Signal raised when RPC console shown */
diff --git a/src/qt/bitcoinunits.cpp b/src/qt/bitcoinunits.cpp
index 9660ba99f7..66d5eea7ac 100644
--- a/src/qt/bitcoinunits.cpp
+++ b/src/qt/bitcoinunits.cpp
@@ -4,6 +4,8 @@
#include <qt/bitcoinunits.h>
+#include <consensus/amount.h>
+
#include <QStringList>
#include <cassert>
diff --git a/src/qt/bitcoinunits.h b/src/qt/bitcoinunits.h
index e22ba0a938..e78a347bb1 100644
--- a/src/qt/bitcoinunits.h
+++ b/src/qt/bitcoinunits.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_QT_BITCOINUNITS_H
#define BITCOIN_QT_BITCOINUNITS_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <QAbstractListModel>
#include <QString>
diff --git a/src/qt/coincontroldialog.cpp b/src/qt/coincontroldialog.cpp
index d2a9365890..e93fedad28 100644
--- a/src/qt/coincontroldialog.cpp
+++ b/src/qt/coincontroldialog.cpp
@@ -55,7 +55,7 @@ CoinControlDialog::CoinControlDialog(CCoinControl& coin_control, WalletModel* _m
contextMenu->addAction(tr("&Copy address"), this, &CoinControlDialog::copyAddress);
contextMenu->addAction(tr("Copy &label"), this, &CoinControlDialog::copyLabel);
contextMenu->addAction(tr("Copy &amount"), this, &CoinControlDialog::copyAmount);
- copyTransactionHashAction = contextMenu->addAction(tr("Copy transaction &ID"), this, &CoinControlDialog::copyTransactionHash);
+ m_copy_transaction_outpoint_action = contextMenu->addAction(tr("Copy transaction &ID and output index"), this, &CoinControlDialog::copyTransactionOutpoint);
contextMenu->addSeparator();
lockAction = contextMenu->addAction(tr("L&ock unspent"), this, &CoinControlDialog::lockCoin);
unlockAction = contextMenu->addAction(tr("&Unlock unspent"), this, &CoinControlDialog::unlockCoin);
@@ -180,7 +180,7 @@ void CoinControlDialog::showMenu(const QPoint &point)
// disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu
if (item->data(COLUMN_ADDRESS, TxHashRole).toString().length() == 64) // transaction hash is 64 characters (this means it is a child node, so it is not a parent node in tree mode)
{
- copyTransactionHashAction->setEnabled(true);
+ m_copy_transaction_outpoint_action->setEnabled(true);
if (model->wallet().isLockedCoin(COutPoint(uint256S(item->data(COLUMN_ADDRESS, TxHashRole).toString().toStdString()), item->data(COLUMN_ADDRESS, VOutRole).toUInt())))
{
lockAction->setEnabled(false);
@@ -194,7 +194,7 @@ void CoinControlDialog::showMenu(const QPoint &point)
}
else // this means click on parent node in tree mode -> disable all
{
- copyTransactionHashAction->setEnabled(false);
+ m_copy_transaction_outpoint_action->setEnabled(false);
lockAction->setEnabled(false);
unlockAction->setEnabled(false);
}
@@ -228,10 +228,14 @@ void CoinControlDialog::copyAddress()
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS));
}
-// context menu action: copy transaction id
-void CoinControlDialog::copyTransactionHash()
+// context menu action: copy transaction id and vout index
+void CoinControlDialog::copyTransactionOutpoint()
{
- GUIUtil::setClipboard(contextMenuItem->data(COLUMN_ADDRESS, TxHashRole).toString());
+ const QString address = contextMenuItem->data(COLUMN_ADDRESS, TxHashRole).toString();
+ const QString vout = contextMenuItem->data(COLUMN_ADDRESS, VOutRole).toString();
+ const QString outpoint = QString("%1:%2").arg(address).arg(vout);
+
+ GUIUtil::setClipboard(outpoint);
}
// context menu action: lock coin
@@ -241,7 +245,7 @@ void CoinControlDialog::lockCoin()
contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
COutPoint outpt(uint256S(contextMenuItem->data(COLUMN_ADDRESS, TxHashRole).toString().toStdString()), contextMenuItem->data(COLUMN_ADDRESS, VOutRole).toUInt());
- model->wallet().lockCoin(outpt);
+ model->wallet().lockCoin(outpt, /* write_to_db = */ true);
contextMenuItem->setDisabled(true);
contextMenuItem->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed"));
updateLabelLocked();
diff --git a/src/qt/coincontroldialog.h b/src/qt/coincontroldialog.h
index 3a03341c9e..ec2619d115 100644
--- a/src/qt/coincontroldialog.h
+++ b/src/qt/coincontroldialog.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_QT_COINCONTROLDIALOG_H
#define BITCOIN_QT_COINCONTROLDIALOG_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <QAbstractButton>
#include <QAction>
@@ -63,7 +63,7 @@ private:
QMenu *contextMenu;
QTreeWidgetItem *contextMenuItem;
- QAction *copyTransactionHashAction;
+ QAction* m_copy_transaction_outpoint_action;
QAction *lockAction;
QAction *unlockAction;
@@ -95,7 +95,7 @@ private Q_SLOTS:
void copyAmount();
void copyLabel();
void copyAddress();
- void copyTransactionHash();
+ void copyTransactionOutpoint();
void lockCoin();
void unlockCoin();
void clipboardQuantity();
diff --git a/src/qt/forms/optionsdialog.ui b/src/qt/forms/optionsdialog.ui
index 2ff1445709..1c22124616 100644
--- a/src/qt/forms/optionsdialog.ui
+++ b/src/qt/forms/optionsdialog.ui
@@ -33,7 +33,7 @@
<string>Automatically start %1 after logging in to the system.</string>
</property>
<property name="text">
- <string>&amp;Start %1 on system login</string>
+ <string>Start %1 on system &amp;login</string>
</property>
</widget>
</item>
@@ -104,6 +104,9 @@
<layout class="QHBoxLayout" name="horizontalLayout_2_Main">
<item>
<widget class="QLabel" name="databaseCacheLabel">
+ <property name="toolTip">
+ <string extracomment="Tooltip text for Options window setting that sets the size of the database cache. Explains the corresponding effects of increasing/decreasing this value.">Maximum database cache size. A larger cache can contribute to faster sync, after which the benefit is less pronounced for most use cases. Lowering the cache size will reduce memory usage. Unused mempool memory is shared for this cache.</string>
+ </property>
<property name="text">
<string>Size of &amp;database cache</string>
</property>
@@ -147,6 +150,9 @@
<layout class="QHBoxLayout" name="horizontalLayout_Main_VerifyLabel">
<item>
<widget class="QLabel" name="threadsScriptVerifLabel">
+ <property name="toolTip">
+ <string extracomment="Tooltip text for Options window setting that sets the number of script verification threads. Explains that negative values mean to leave these many cores free to the system.">Set the number of script verification threads. Negative values correspond to the number of cores you want to leave free to the system.</string>
+ </property>
<property name="text">
<string>Number of script &amp;verification threads</string>
</property>
@@ -173,7 +179,7 @@
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
- <height>20</height>
+ <height>40</height>
</size>
</property>
</spacer>
@@ -181,6 +187,16 @@
</layout>
</item>
<item>
+ <widget class="QCheckBox" name="enableServer">
+ <property name="toolTip">
+ <string extracomment="Tooltip text for Options window setting that enables the RPC server.">This allows you or a third party tool to communicate with the node through command-line and JSON-RPC commands.</string>
+ </property>
+ <property name="text">
+ <string extracomment="An Options window setting to enable the RPC server.">Enable RPC &amp;server</string>
+ </property>
+ </widget>
+ </item>
+ <item>
<spacer name="verticalSpacer_Main">
<property name="orientation">
<enum>Qt::Vertical</enum>
@@ -723,10 +739,10 @@
<item>
<widget class="QLabel" name="thirdPartyTxUrlsLabel">
<property name="toolTip">
- <string>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</string>
+ <string>Third-party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</string>
</property>
<property name="text">
- <string>&amp;Third party transaction URLs</string>
+ <string>&amp;Third-party transaction URLs</string>
</property>
<property name="buddy">
<cstring>thirdPartyTxUrls</cstring>
@@ -736,7 +752,7 @@
<item>
<widget class="QLineEdit" name="thirdPartyTxUrls">
<property name="toolTip">
- <string>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</string>
+ <string>Third-party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</string>
</property>
<property name="placeholderText">
<string notr="true">https://example.com/tx/%s</string>
diff --git a/src/qt/guiutil.cpp b/src/qt/guiutil.cpp
index e98e50ba14..12d3a48d01 100644
--- a/src/qt/guiutil.cpp
+++ b/src/qt/guiutil.cpp
@@ -36,6 +36,7 @@
#include <QClipboard>
#include <QDateTime>
#include <QDesktopServices>
+#include <QDialog>
#include <QDoubleValidator>
#include <QFileDialog>
#include <QFont>
@@ -271,6 +272,12 @@ bool hasEntryData(const QAbstractItemView *view, int column, int role)
return !selection.at(0).data(role).toString().isEmpty();
}
+void LoadFont(const QString& file_name)
+{
+ const int id = QFontDatabase::addApplicationFont(file_name);
+ assert(id != -1);
+}
+
QString getDefaultDataDirectory()
{
return boostPathToQString(GetDefaultDataDir());
@@ -673,14 +680,26 @@ QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction
{
QString prefix;
if (prepend_direction) {
- prefix = (conn_type == ConnectionType::INBOUND) ? QObject::tr("Inbound") : QObject::tr("Outbound") + " ";
+ prefix = (conn_type == ConnectionType::INBOUND) ?
+ /*: An inbound connection from a peer. An inbound connection
+ is a connection initiated by a peer. */
+ QObject::tr("Inbound") :
+ /*: An outbound connection to a peer. An outbound connection
+ is a connection initiated by us. */
+ QObject::tr("Outbound") + " ";
}
switch (conn_type) {
case ConnectionType::INBOUND: return prefix;
+ //: Peer connection type that relays all network information.
case ConnectionType::OUTBOUND_FULL_RELAY: return prefix + QObject::tr("Full Relay");
+ /*: Peer connection type that relays network information about
+ blocks and not transactions or addresses. */
case ConnectionType::BLOCK_RELAY: return prefix + QObject::tr("Block Relay");
+ //: Peer connection type established manually through one of several methods.
case ConnectionType::MANUAL: return prefix + QObject::tr("Manual");
+ //: Short-lived peer connection type that tests the aliveness of known addresses.
case ConnectionType::FEELER: return prefix + QObject::tr("Feeler");
+ //: Short-lived peer connection type that solicits known addresses from a peer.
case ConnectionType::ADDR_FETCH: return prefix + QObject::tr("Address Fetch");
} // no default case, so the compiler can warn about missing cases
assert(false);
@@ -958,4 +977,11 @@ void PrintSlotException(
PrintExceptionContinue(exception, description.c_str());
}
+void ShowModalDialogAndDeleteOnClose(QDialog* dialog)
+{
+ dialog->setAttribute(Qt::WA_DeleteOnClose);
+ dialog->setWindowModality(Qt::ApplicationModal);
+ dialog->show();
+}
+
} // namespace GUIUtil
diff --git a/src/qt/guiutil.h b/src/qt/guiutil.h
index 06a3b63668..211f3f506d 100644
--- a/src/qt/guiutil.h
+++ b/src/qt/guiutil.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_QT_GUIUTIL_H
#define BITCOIN_QT_GUIUTIL_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <fs.h>
#include <net.h>
#include <netaddress.h>
@@ -41,6 +41,7 @@ class QAbstractButton;
class QAbstractItemView;
class QAction;
class QDateTime;
+class QDialog;
class QFont;
class QKeySequence;
class QLineEdit;
@@ -113,6 +114,11 @@ namespace GUIUtil
void setClipboard(const QString& str);
/**
+ * Loads the font from the file specified by file_name, aborts if it fails.
+ */
+ void LoadFont(const QString& file_name);
+
+ /**
* Determine default data directory for operating system.
*/
QString getDefaultDataDirectory();
@@ -417,6 +423,11 @@ namespace GUIUtil
type);
}
+ /**
+ * Shows a QDialog instance asynchronously, and deletes it on close.
+ */
+ void ShowModalDialogAndDeleteOnClose(QDialog* dialog);
+
} // namespace GUIUtil
#endif // BITCOIN_QT_GUIUTIL_H
diff --git a/src/qt/initexecutor.cpp b/src/qt/initexecutor.cpp
index 7060f74dab..24ae7ba73d 100644
--- a/src/qt/initexecutor.cpp
+++ b/src/qt/initexecutor.cpp
@@ -5,6 +5,7 @@
#include <qt/initexecutor.h>
#include <interfaces/node.h>
+#include <qt/guiutil.h>
#include <util/system.h>
#include <util/threadnames.h>
@@ -18,7 +19,7 @@
InitExecutor::InitExecutor(interfaces::Node& node)
: QObject(), m_node(node)
{
- this->moveToThread(&m_thread);
+ m_context.moveToThread(&m_thread);
m_thread.start();
}
@@ -38,29 +39,33 @@ void InitExecutor::handleRunawayException(const std::exception* e)
void InitExecutor::initialize()
{
- try {
- util::ThreadRename("qt-init");
- qDebug() << __func__ << ": Running initialization in thread";
- interfaces::BlockAndHeaderTipInfo tip_info;
- bool rv = m_node.appInitMain(&tip_info);
- Q_EMIT initializeResult(rv, tip_info);
- } catch (const std::exception& e) {
- handleRunawayException(&e);
- } catch (...) {
- handleRunawayException(nullptr);
- }
+ GUIUtil::ObjectInvoke(&m_context, [this] {
+ try {
+ util::ThreadRename("qt-init");
+ qDebug() << "Running initialization in thread";
+ interfaces::BlockAndHeaderTipInfo tip_info;
+ bool rv = m_node.appInitMain(&tip_info);
+ Q_EMIT initializeResult(rv, tip_info);
+ } catch (const std::exception& e) {
+ handleRunawayException(&e);
+ } catch (...) {
+ handleRunawayException(nullptr);
+ }
+ });
}
void InitExecutor::shutdown()
{
- try {
- qDebug() << __func__ << ": Running Shutdown in thread";
- m_node.appShutdown();
- qDebug() << __func__ << ": Shutdown finished";
- Q_EMIT shutdownResult();
- } catch (const std::exception& e) {
- handleRunawayException(&e);
- } catch (...) {
- handleRunawayException(nullptr);
- }
+ GUIUtil::ObjectInvoke(&m_context, [this] {
+ try {
+ qDebug() << "Running Shutdown in thread";
+ m_node.appShutdown();
+ qDebug() << "Shutdown finished";
+ Q_EMIT shutdownResult();
+ } catch (const std::exception& e) {
+ handleRunawayException(&e);
+ } catch (...) {
+ handleRunawayException(nullptr);
+ }
+ });
}
diff --git a/src/qt/initexecutor.h b/src/qt/initexecutor.h
index 319ce40465..410c44fa2d 100644
--- a/src/qt/initexecutor.h
+++ b/src/qt/initexecutor.h
@@ -40,6 +40,7 @@ private:
void handleRunawayException(const std::exception* e);
interfaces::Node& m_node;
+ QObject m_context;
QThread m_thread;
};
diff --git a/src/qt/intro.cpp b/src/qt/intro.cpp
index a698a96857..4c78fba752 100644
--- a/src/qt/intro.cpp
+++ b/src/qt/intro.cpp
@@ -113,7 +113,7 @@ namespace {
//! Return pruning size that will be used if automatic pruning is enabled.
int GetPruneTargetGB()
{
- int64_t prune_target_mib = gArgs.GetArg("-prune", 0);
+ int64_t prune_target_mib = gArgs.GetIntArg("-prune", 0);
// >1 means automatic pruning is enabled by config, 1 means manual pruning, 0 means no pruning.
return prune_target_mib > 1 ? PruneMiBtoGB(prune_target_mib) : DEFAULT_PRUNE_TARGET_GB;
}
@@ -142,7 +142,7 @@ Intro::Intro(QWidget *parent, int64_t blockchain_size_gb, int64_t chain_state_si
const int min_prune_target_GB = std::ceil(MIN_DISK_SPACE_FOR_BLOCK_FILES / 1e9);
ui->pruneGB->setRange(min_prune_target_GB, std::numeric_limits<int>::max());
- if (gArgs.GetArg("-prune", 0) > 1) { // -prune=1 means enabled, above that it's a size in MiB
+ if (gArgs.GetIntArg("-prune", 0) > 1) { // -prune=1 means enabled, above that it's a size in MiB
ui->prune->setChecked(true);
ui->prune->setEnabled(false);
}
diff --git a/src/qt/optionsdialog.cpp b/src/qt/optionsdialog.cpp
index 5ad4fc9b33..0cc2d61df6 100644
--- a/src/qt/optionsdialog.cpp
+++ b/src/qt/optionsdialog.cpp
@@ -210,6 +210,7 @@ void OptionsDialog::setModel(OptionsModel *_model)
connect(ui->spendZeroConfChange, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning);
/* Network */
connect(ui->allowIncoming, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning);
+ connect(ui->enableServer, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning);
connect(ui->connectSocks, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning);
connect(ui->connectSocksTor, &QCheckBox::clicked, this, &OptionsDialog::showRestartWarning);
/* Display */
@@ -246,6 +247,7 @@ void OptionsDialog::setMapper()
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->mapPortNatpmp, OptionsModel::MapPortNatpmp);
mapper->addMapping(ui->allowIncoming, OptionsModel::Listen);
+ mapper->addMapping(ui->enableServer, OptionsModel::Server);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
@@ -290,16 +292,29 @@ void OptionsDialog::on_resetButton_clicked()
/* reset all options and close GUI */
model->Reset();
- QApplication::quit();
+ close();
+ Q_EMIT quitOnReset();
}
}
void OptionsDialog::on_openBitcoinConfButton_clicked()
{
- /* explain the purpose of the config file */
- QMessageBox::information(this, tr("Configuration options"),
- tr("The configuration file is used to specify advanced user options which override GUI settings. "
- "Additionally, any command-line options will override this configuration file."));
+ QMessageBox config_msgbox(this);
+ config_msgbox.setIcon(QMessageBox::Information);
+ //: Window title text of pop-up box that allows opening up of configuration file.
+ config_msgbox.setWindowTitle(tr("Configuration options"));
+ /*: Explanatory text about the priority order of instructions considered by client.
+ The order from high to low being: command-line, configuration file, GUI settings. */
+ config_msgbox.setText(tr("The configuration file is used to specify advanced user options which override GUI settings. "
+ "Additionally, any command-line options will override this configuration file."));
+
+ QPushButton* open_button = config_msgbox.addButton(tr("Continue"), QMessageBox::ActionRole);
+ config_msgbox.addButton(tr("Cancel"), QMessageBox::RejectRole);
+ open_button->setDefault(true);
+
+ config_msgbox.exec();
+
+ if (config_msgbox.clickedButton() != open_button) return;
/* show an error if there was some problem opening the file */
if (!GUIUtil::openBitcoinConf())
diff --git a/src/qt/optionsdialog.h b/src/qt/optionsdialog.h
index ba35ff3b67..f14aec3449 100644
--- a/src/qt/optionsdialog.h
+++ b/src/qt/optionsdialog.h
@@ -68,6 +68,7 @@ private Q_SLOTS:
Q_SIGNALS:
void proxyIpChecks(QValidatedLineEdit *pUiProxyIp, uint16_t nProxyPort);
+ void quitOnReset();
private:
Ui::OptionsDialog *ui;
diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp
index d87fc1f84a..9e2f38f7ec 100644
--- a/src/qt/optionsmodel.cpp
+++ b/src/qt/optionsmodel.cpp
@@ -149,6 +149,13 @@ void OptionsModel::Init(bool resetSettings)
if (!gArgs.SoftSetBoolArg("-listen", settings.value("fListen").toBool()))
addOverriddenOption("-listen");
+ if (!settings.contains("server")) {
+ settings.setValue("server", false);
+ }
+ if (!gArgs.SoftSetBoolArg("-server", settings.value("server").toBool())) {
+ addOverriddenOption("-server");
+ }
+
if (!settings.contains("fUseProxy"))
settings.setValue("fUseProxy", false);
if (!settings.contains("addrProxy"))
@@ -363,6 +370,8 @@ QVariant OptionsModel::data(const QModelIndex & index, int role) const
return settings.value("nThreadsScriptVerif");
case Listen:
return settings.value("fListen");
+ case Server:
+ return settings.value("server");
default:
return QVariant();
}
@@ -528,6 +537,12 @@ bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, in
setRestartRequired(true);
}
break;
+ case Server:
+ if (settings.value("server") != value) {
+ settings.setValue("server", value);
+ setRestartRequired(true);
+ }
+ break;
default:
break;
}
diff --git a/src/qt/optionsmodel.h b/src/qt/optionsmodel.h
index 203ee27ad8..8f1513e48d 100644
--- a/src/qt/optionsmodel.h
+++ b/src/qt/optionsmodel.h
@@ -5,7 +5,6 @@
#ifndef BITCOIN_QT_OPTIONSMODEL_H
#define BITCOIN_QT_OPTIONSMODEL_H
-#include <amount.h>
#include <cstdint>
#include <qt/guiconstants.h>
@@ -69,6 +68,7 @@ public:
ExternalSignerPath, // QString
SpendZeroConfChange, // bool
Listen, // bool
+ Server, // bool
OptionIDRowCount,
};
diff --git a/src/qt/psbtoperationsdialog.cpp b/src/qt/psbtoperationsdialog.cpp
index 289fb9f7c8..34d56e5506 100644
--- a/src/qt/psbtoperationsdialog.cpp
+++ b/src/qt/psbtoperationsdialog.cpp
@@ -71,6 +71,9 @@ void PSBTOperationsDialog::signTransaction()
{
bool complete;
size_t n_signed;
+
+ WalletModel::UnlockContext ctx(m_wallet_model->requestUnlock());
+
TransactionError err = m_wallet_model->wallet().fillPSBT(SIGHASH_ALL, true /* sign */, true /* bip32derivs */, &n_signed, m_transaction_data, complete);
if (err != TransactionError::OK) {
@@ -81,7 +84,9 @@ void PSBTOperationsDialog::signTransaction()
updateTransactionDisplay();
- if (!complete && n_signed < 1) {
+ if (!complete && !ctx.isValid()) {
+ showStatus(tr("Cannot sign inputs while wallet is locked."), StatusLevel::WARN);
+ } else if (!complete && n_signed < 1) {
showStatus(tr("Could not sign any more inputs."), StatusLevel::WARN);
} else if (!complete) {
showStatus(tr("Signed %1 inputs, but more signatures are still required.").arg(n_signed),
diff --git a/src/qt/qrimagewidget.cpp b/src/qt/qrimagewidget.cpp
index 7cdd568644..0799e01aac 100644
--- a/src/qt/qrimagewidget.cpp
+++ b/src/qt/qrimagewidget.cpp
@@ -119,7 +119,7 @@ void QRImageWidget::saveImage()
QString fn = GUIUtil::getSaveFileName(
this, tr("Save QR Code"), QString(),
/*: Expanded name of the PNG file format.
- See https://en.wikipedia.org/wiki/Portable_Network_Graphics */
+ See: https://en.wikipedia.org/wiki/Portable_Network_Graphics. */
tr("PNG Image") + QLatin1String(" (*.png)"), nullptr);
if (!fn.isEmpty())
{
diff --git a/src/qt/rpcconsole.cpp b/src/qt/rpcconsole.cpp
index 829f7add80..0c3332ab76 100644
--- a/src/qt/rpcconsole.cpp
+++ b/src/qt/rpcconsole.cpp
@@ -247,10 +247,11 @@ bool RPCConsole::RPCParseCommandLine(interfaces::Node* node, std::string &strRes
UniValue subelement;
if (lastResult.isArray())
{
- for(char argch: curarg)
- if (!IsDigit(argch))
- throw std::runtime_error("Invalid result query");
- subelement = lastResult[atoi(curarg.c_str())];
+ const auto parsed{ToIntegral<size_t>(curarg)};
+ if (!parsed) {
+ throw std::runtime_error("Invalid result query");
+ }
+ subelement = lastResult[parsed.value()];
}
else if (lastResult.isObject())
subelement = find_value(lastResult, curarg);
@@ -495,14 +496,28 @@ RPCConsole::RPCConsole(interfaces::Node& node, const PlatformStyle *_platformSty
constexpr QChar nonbreaking_hyphen(8209);
const std::vector<QString> CONNECTION_TYPE_DOC{
+ //: Explanatory text for an inbound peer connection.
tr("Inbound: initiated by peer"),
+ /*: Explanatory text for an outbound peer connection that
+ relays all network information. This is the default behavior for
+ outbound connections. */
tr("Outbound Full Relay: default"),
+ /*: Explanatory text for an outbound peer connection that relays
+ network information about blocks and not transactions or addresses. */
tr("Outbound Block Relay: does not relay transactions or addresses"),
+ /*: Explanatory text for an outbound peer connection that was
+ established manually through one of several methods. The numbered
+ arguments are stand-ins for the methods available to establish
+ manual connections. */
tr("Outbound Manual: added using RPC %1 or %2/%3 configuration options")
.arg("addnode")
.arg(QString(nonbreaking_hyphen) + "addnode")
.arg(QString(nonbreaking_hyphen) + "connect"),
+ /*: Explanatory text for a short-lived outbound peer connection that
+ is used to test the aliveness of known addresses. */
tr("Outbound Feeler: short-lived, for testing addresses"),
+ /*: Explanatory text for a short-lived outbound peer connection that is used
+ to request addresses from a peer. */
tr("Outbound Address Fetch: short-lived, for soliciting addresses")};
const QString list{"<ul><li>" + Join(CONNECTION_TYPE_DOC, QString("</li><li>")) + "</li></ul>"};
ui->peerConnectionTypeLabel->setToolTip(ui->peerConnectionTypeLabel->toolTip().arg(list));
@@ -680,6 +695,11 @@ void RPCConsole::setClientModel(ClientModel *model, int bestblock_height, int64_
// create peer table context menu
peersTableContextMenu = new QMenu(this);
+ //: Context menu action to copy the address of a peer.
+ peersTableContextMenu->addAction(tr("&Copy address"), [this] {
+ GUIUtil::copyEntryData(ui->peerWidget, PeerTableModel::Address, Qt::DisplayRole);
+ });
+ peersTableContextMenu->addSeparator();
peersTableContextMenu->addAction(tr("&Disconnect"), this, &RPCConsole::disconnectSelectedNode);
peersTableContextMenu->addAction(ts.ban_for + " " + tr("1 &hour"), [this] { banSelectedNode(60 * 60); });
peersTableContextMenu->addAction(ts.ban_for + " " + tr("1 d&ay"), [this] { banSelectedNode(60 * 60 * 24); });
@@ -708,7 +728,7 @@ void RPCConsole::setClientModel(ClientModel *model, int bestblock_height, int64_
banTableContextMenu = new QMenu(this);
/*: Context menu action to copy the IP/Netmask of a banned peer.
IP/Netmask is the combination of a peer's IP address and its Netmask.
- For IP address see: https://en.wikipedia.org/wiki/IP_address */
+ For IP address, see: https://en.wikipedia.org/wiki/IP_address. */
banTableContextMenu->addAction(tr("&Copy IP/Netmask"), [this] {
GUIUtil::copyEntryData(ui->banlistWidget, BanTableModel::Address, Qt::DisplayRole);
});
diff --git a/src/qt/sendcoinsdialog.cpp b/src/qt/sendcoinsdialog.cpp
index c9bf757dfc..2718392940 100644
--- a/src/qt/sendcoinsdialog.cpp
+++ b/src/qt/sendcoinsdialog.cpp
@@ -200,7 +200,7 @@ void SendCoinsDialog::setModel(WalletModel *_model)
ui->optInRBF->setCheckState(Qt::Checked);
if (model->wallet().hasExternalSigner()) {
- //: "device" usually means a hardware wallet
+ //: "device" usually means a hardware wallet.
ui->sendButton->setText(tr("Sign on device"));
if (gArgs.GetArg("-signer", "") != "") {
ui->sendButton->setEnabled(true);
@@ -399,9 +399,10 @@ void SendCoinsDialog::sendButtonClicked([[maybe_unused]] bool checked)
const QString confirmation = model->wallet().privateKeysDisabled() && !model->wallet().hasExternalSigner() ? tr("Confirm transaction proposal") : tr("Confirm send coins");
const QString confirmButtonText = model->wallet().privateKeysDisabled() && !model->wallet().hasExternalSigner() ? tr("Create Unsigned") : tr("Sign and send");
- SendConfirmationDialog confirmationDialog(confirmation, question_string, informative_text, detailed_text, SEND_CONFIRM_DELAY, confirmButtonText, this);
- confirmationDialog.exec();
- QMessageBox::StandardButton retval = static_cast<QMessageBox::StandardButton>(confirmationDialog.result());
+ auto confirmationDialog = new SendConfirmationDialog(confirmation, question_string, informative_text, detailed_text, SEND_CONFIRM_DELAY, confirmButtonText, this);
+ confirmationDialog->setAttribute(Qt::WA_DeleteOnClose);
+ // TODO: Replace QDialog::exec() with safer QDialog::show().
+ const auto retval = static_cast<QMessageBox::StandardButton>(confirmationDialog->exec());
if(retval != QMessageBox::Yes)
{
@@ -914,9 +915,9 @@ void SendCoinsDialog::coinControlFeatureChanged(bool checked)
// Coin Control: button inputs -> show actual coin control dialog
void SendCoinsDialog::coinControlButtonClicked()
{
- CoinControlDialog dlg(*m_coin_control, model, platformStyle);
- dlg.exec();
- coinControlUpdateLabels();
+ auto dlg = new CoinControlDialog(*m_coin_control, model, platformStyle);
+ connect(dlg, &QDialog::finished, this, &SendCoinsDialog::coinControlUpdateLabels);
+ GUIUtil::ShowModalDialogAndDeleteOnClose(dlg);
}
// Coin Control: checkbox custom change address
diff --git a/src/qt/sendcoinsrecipient.h b/src/qt/sendcoinsrecipient.h
index 01135cdfef..c23afcab24 100644
--- a/src/qt/sendcoinsrecipient.h
+++ b/src/qt/sendcoinsrecipient.h
@@ -9,7 +9,7 @@
#include <config/bitcoin-config.h>
#endif
-#include <amount.h>
+#include <consensus/amount.h>
#include <serialize.h>
#include <string>
diff --git a/src/qt/test/addressbooktests.cpp b/src/qt/test/addressbooktests.cpp
index 022f367422..0de781661a 100644
--- a/src/qt/test/addressbooktests.cpp
+++ b/src/qt/test/addressbooktests.cpp
@@ -60,6 +60,8 @@ void EditAddressAndSubmit(
void TestAddAddressesToSendBook(interfaces::Node& node)
{
TestChain100Setup test;
+ auto wallet_client = interfaces::MakeWalletClient(*test.m_node.chain, *Assert(test.m_node.args));
+ test.m_node.wallet_client = wallet_client.get();
node.setContext(&test.m_node);
std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(node.context()->chain.get(), "", CreateMockWalletDatabase());
wallet->SetupLegacyScriptPubKeyMan();
@@ -112,7 +114,7 @@ void TestAddAddressesToSendBook(interfaces::Node& node)
WalletContext& context = *node.walletClient().context();
AddWallet(context, wallet);
WalletModel walletModel(interfaces::MakeWallet(context, wallet), clientModel, platformStyle.get());
- RemoveWallet(context, wallet, /* load_on_startup= */ std::nullopt);
+ RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
EditAddressDialog editAddressDialog(EditAddressDialog::NewSendingAddress);
editAddressDialog.setModel(walletModel.getAddressTableModel());
diff --git a/src/qt/test/test_main.cpp b/src/qt/test/test_main.cpp
index 7d66f67f8a..55d00bb37e 100644
--- a/src/qt/test/test_main.cpp
+++ b/src/qt/test/test_main.cpp
@@ -6,9 +6,9 @@
#include <config/bitcoin-config.h>
#endif
+#include <interfaces/init.h>
#include <interfaces/node.h>
#include <qt/bitcoin.h>
-#include <qt/initexecutor.h>
#include <qt/test/apptests.h>
#include <qt/test/rpcnestedtests.h>
#include <qt/test/uritests.h>
@@ -53,7 +53,8 @@ int main(int argc, char* argv[])
}
NodeContext node_context;
- std::unique_ptr<interfaces::Node> node = interfaces::MakeNode(&node_context);
+ int unused_exit_status;
+ std::unique_ptr<interfaces::Init> init = interfaces::MakeNodeInit(node_context, argc, argv, unused_exit_status);
gArgs.ForceSetArg("-listen", "0");
gArgs.ForceSetArg("-listenonion", "0");
gArgs.ForceSetArg("-discover", "0");
@@ -76,10 +77,9 @@ int main(int argc, char* argv[])
// Don't remove this, it's needed to access
// QApplication:: and QCoreApplication:: in the tests
BitcoinApplication app;
- app.setNode(*node);
app.setApplicationName("Bitcoin-Qt-test");
+ app.createNode(*init);
- app.node().context()->args = &gArgs; // Make gArgs available in the NodeContext
AppTests app_tests(app);
if (QTest::qExec(&app_tests) != 0) {
fInvalid = true;
diff --git a/src/qt/test/wallettests.cpp b/src/qt/test/wallettests.cpp
index 1976bee74b..62b135d3f1 100644
--- a/src/qt/test/wallettests.cpp
+++ b/src/qt/test/wallettests.cpp
@@ -138,6 +138,8 @@ void TestGUI(interfaces::Node& node)
for (int i = 0; i < 5; ++i) {
test.CreateAndProcessBlock({}, GetScriptForRawPubKey(test.coinbaseKey.GetPubKey()));
}
+ auto wallet_client = interfaces::MakeWalletClient(*test.m_node.chain, *Assert(test.m_node.args));
+ test.m_node.wallet_client = wallet_client.get();
node.setContext(&test.m_node);
std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(node.context()->chain.get(), "", CreateMockWalletDatabase());
wallet->LoadWallet();
@@ -167,7 +169,7 @@ void TestGUI(interfaces::Node& node)
WalletContext& context = *node.walletClient().context();
AddWallet(context, wallet);
WalletModel walletModel(interfaces::MakeWallet(context, wallet), clientModel, platformStyle.get());
- RemoveWallet(context, wallet, /* load_on_startup= */ std::nullopt);
+ RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
sendCoinsDialog.setModel(&walletModel);
transactionView.setModel(&walletModel);
diff --git a/src/qt/transactionfilterproxy.h b/src/qt/transactionfilterproxy.h
index 09bc9e75db..270b8ef78c 100644
--- a/src/qt/transactionfilterproxy.h
+++ b/src/qt/transactionfilterproxy.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_QT_TRANSACTIONFILTERPROXY_H
#define BITCOIN_QT_TRANSACTIONFILTERPROXY_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <QDateTime>
#include <QSortFilterProxyModel>
diff --git a/src/qt/transactionrecord.h b/src/qt/transactionrecord.h
index e10243a28a..fb88ca424f 100644
--- a/src/qt/transactionrecord.h
+++ b/src/qt/transactionrecord.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_QT_TRANSACTIONRECORD_H
#define BITCOIN_QT_TRANSACTIONRECORD_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <uint256.h>
#include <QList>
diff --git a/src/qt/transactionview.cpp b/src/qt/transactionview.cpp
index 908cb917f1..653f3dda6d 100644
--- a/src/qt/transactionview.cpp
+++ b/src/qt/transactionview.cpp
@@ -222,17 +222,21 @@ void TransactionView::setModel(WalletModel *_model)
{
// Add third party transaction URLs to context menu
QStringList listUrls = GUIUtil::SplitSkipEmptyParts(_model->getOptionsModel()->getThirdPartyTxUrls(), "|");
+ bool actions_created = false;
for (int i = 0; i < listUrls.size(); ++i)
{
QString url = listUrls[i].trimmed();
QString host = QUrl(url, QUrl::StrictMode).host();
if (!host.isEmpty())
{
- QAction *thirdPartyTxUrlAction = new QAction(host, this); // use host as menu item label
- if (i == 0)
+ if (!actions_created) {
contextMenu->addSeparator();
- contextMenu->addAction(thirdPartyTxUrlAction);
- connect(thirdPartyTxUrlAction, &QAction::triggered, [this, url] { openThirdPartyTxUrl(url); });
+ actions_created = true;
+ }
+ /*: Transactions table context menu action to show the
+ selected transaction in a third-party block explorer.
+ %1 is a stand-in argument for the URL of the explorer. */
+ contextMenu->addAction(tr("Show in %1").arg(host), [this, url] { openThirdPartyTxUrl(url); });
}
}
}
@@ -353,7 +357,7 @@ void TransactionView::exportClicked()
QString filename = GUIUtil::getSaveFileName(this,
tr("Export Transaction History"), QString(),
/*: Expanded name of the CSV file format.
- See https://en.wikipedia.org/wiki/Comma-separated_values */
+ See: https://en.wikipedia.org/wiki/Comma-separated_values. */
tr("Comma separated file") + QLatin1String(" (*.csv)"), nullptr);
if (filename.isNull())
@@ -500,22 +504,22 @@ void TransactionView::editLabel()
// Determine type of address, launch appropriate editor dialog type
QString type = modelIdx.data(AddressTableModel::TypeRole).toString();
- EditAddressDialog dlg(
+ auto dlg = new EditAddressDialog(
type == AddressTableModel::Receive
? EditAddressDialog::EditReceivingAddress
: EditAddressDialog::EditSendingAddress, this);
- dlg.setModel(addressBook);
- dlg.loadRow(idx);
- dlg.exec();
+ dlg->setModel(addressBook);
+ dlg->loadRow(idx);
+ GUIUtil::ShowModalDialogAndDeleteOnClose(dlg);
}
else
{
// Add sending address
- EditAddressDialog dlg(EditAddressDialog::NewSendingAddress,
+ auto dlg = new EditAddressDialog(EditAddressDialog::NewSendingAddress,
this);
- dlg.setModel(addressBook);
- dlg.setAddress(address);
- dlg.exec();
+ dlg->setModel(addressBook);
+ dlg->setAddress(address);
+ GUIUtil::ShowModalDialogAndDeleteOnClose(dlg);
}
}
}
diff --git a/src/qt/walletcontroller.cpp b/src/qt/walletcontroller.cpp
index 3cceb5ca5a..a0ad59f12a 100644
--- a/src/qt/walletcontroller.cpp
+++ b/src/qt/walletcontroller.cpp
@@ -41,10 +41,6 @@ WalletController::WalletController(ClientModel& client_model, const PlatformStyl
getOrCreateWallet(std::move(wallet));
});
- for (std::unique_ptr<interfaces::Wallet>& wallet : m_node.walletClient().getWallets()) {
- getOrCreateWallet(std::move(wallet));
- }
-
m_activity_worker->moveToThread(m_activity_thread);
m_activity_thread->start();
QTimer::singleShot(0, m_activity_worker, []() {
@@ -61,12 +57,6 @@ WalletController::~WalletController()
delete m_activity_worker;
}
-std::vector<WalletModel*> WalletController::getOpenWallets() const
-{
- QMutexLocker locker(&m_mutex);
- return m_wallets;
-}
-
std::map<std::string, bool> WalletController::listWalletDir() const
{
QMutexLocker locker(&m_mutex);
@@ -191,33 +181,24 @@ WalletControllerActivity::WalletControllerActivity(WalletController* wallet_cont
, m_wallet_controller(wallet_controller)
, m_parent_widget(parent_widget)
{
+ connect(this, &WalletControllerActivity::finished, this, &QObject::deleteLater);
}
-WalletControllerActivity::~WalletControllerActivity()
+void WalletControllerActivity::showProgressDialog(const QString& title_text, const QString& label_text)
{
- delete m_progress_dialog;
-}
-
-void WalletControllerActivity::showProgressDialog(const QString& label_text)
-{
- assert(!m_progress_dialog);
- m_progress_dialog = new QProgressDialog(m_parent_widget);
-
- m_progress_dialog->setLabelText(label_text);
- m_progress_dialog->setRange(0, 0);
- m_progress_dialog->setCancelButton(nullptr);
- m_progress_dialog->setWindowModality(Qt::ApplicationModal);
- GUIUtil::PolishProgressDialog(m_progress_dialog);
+ auto progress_dialog = new QProgressDialog(m_parent_widget);
+ progress_dialog->setAttribute(Qt::WA_DeleteOnClose);
+ connect(this, &WalletControllerActivity::finished, progress_dialog, &QWidget::close);
+
+ progress_dialog->setWindowTitle(title_text);
+ progress_dialog->setLabelText(label_text);
+ progress_dialog->setRange(0, 0);
+ progress_dialog->setCancelButton(nullptr);
+ progress_dialog->setWindowModality(Qt::ApplicationModal);
+ GUIUtil::PolishProgressDialog(progress_dialog);
// The setValue call forces QProgressDialog to start the internal duration estimation.
// See details in https://bugreports.qt.io/browse/QTBUG-47042.
- m_progress_dialog->setValue(0);
-}
-
-void WalletControllerActivity::destroyProgressDialog()
-{
- assert(m_progress_dialog);
- delete m_progress_dialog;
- m_progress_dialog = nullptr;
+ progress_dialog->setValue(0);
}
CreateWalletActivity::CreateWalletActivity(WalletController* wallet_controller, QWidget* parent_widget)
@@ -251,7 +232,12 @@ void CreateWalletActivity::askPassphrase()
void CreateWalletActivity::createWallet()
{
- showProgressDialog(tr("Creating Wallet <b>%1</b>…").arg(m_create_wallet_dialog->walletName().toHtmlEscaped()));
+ showProgressDialog(
+ //: Title of window indicating the progress of creation of a new wallet.
+ tr("Create Wallet"),
+ /*: Descriptive text of the create wallet progress window which indicates
+ to the user which wallet is currently being created. */
+ tr("Creating Wallet <b>%1</b>…").arg(m_create_wallet_dialog->walletName().toHtmlEscaped()));
std::string name = m_create_wallet_dialog->walletName().toStdString();
uint64_t flags = 0;
@@ -279,8 +265,6 @@ void CreateWalletActivity::createWallet()
void CreateWalletActivity::finish()
{
- destroyProgressDialog();
-
if (!m_error_message.empty()) {
QMessageBox::critical(m_parent_widget, tr("Create wallet failed"), QString::fromStdString(m_error_message.translated));
} else if (!m_warning_message.empty()) {
@@ -329,8 +313,6 @@ OpenWalletActivity::OpenWalletActivity(WalletController* wallet_controller, QWid
void OpenWalletActivity::finish()
{
- destroyProgressDialog();
-
if (!m_error_message.empty()) {
QMessageBox::critical(m_parent_widget, tr("Open wallet failed"), QString::fromStdString(m_error_message.translated));
} else if (!m_warning_message.empty()) {
@@ -346,7 +328,12 @@ void OpenWalletActivity::open(const std::string& path)
{
QString name = path.empty() ? QString("["+tr("default wallet")+"]") : QString::fromStdString(path);
- showProgressDialog(tr("Opening Wallet <b>%1</b>…").arg(name.toHtmlEscaped()));
+ showProgressDialog(
+ //: Title of window indicating the progress of opening of a wallet.
+ tr("Open Wallet"),
+ /*: Descriptive text of the open wallet progress window which indicates
+ to the user which wallet is currently being opened. */
+ tr("Opening Wallet <b>%1</b>…").arg(name.toHtmlEscaped()));
QTimer::singleShot(0, worker(), [this, path] {
std::unique_ptr<interfaces::Wallet> wallet = node().walletClient().loadWallet(path, m_error_message, m_warning_message);
@@ -356,3 +343,26 @@ void OpenWalletActivity::open(const std::string& path)
QTimer::singleShot(0, this, &OpenWalletActivity::finish);
});
}
+
+LoadWalletsActivity::LoadWalletsActivity(WalletController* wallet_controller, QWidget* parent_widget)
+ : WalletControllerActivity(wallet_controller, parent_widget)
+{
+}
+
+void LoadWalletsActivity::load()
+{
+ showProgressDialog(
+ //: Title of progress window which is displayed when wallets are being loaded.
+ tr("Load Wallets"),
+ /*: Descriptive text of the load wallets progress window which indicates to
+ the user that wallets are currently being loaded.*/
+ tr("Loading wallets…"));
+
+ QTimer::singleShot(0, worker(), [this] {
+ for (auto& wallet : node().walletClient().getWallets()) {
+ m_wallet_controller->getOrCreateWallet(std::move(wallet));
+ }
+
+ QTimer::singleShot(0, this, [this] { Q_EMIT finished(); });
+ });
+}
diff --git a/src/qt/walletcontroller.h b/src/qt/walletcontroller.h
index f7e366878d..bbd990228f 100644
--- a/src/qt/walletcontroller.h
+++ b/src/qt/walletcontroller.h
@@ -52,9 +52,6 @@ public:
WalletController(ClientModel& client_model, const PlatformStyle* platform_style, QObject* parent);
~WalletController();
- //! Returns wallet models currently open.
- std::vector<WalletModel*> getOpenWallets() const;
-
WalletModel* getOrCreateWallet(std::unique_ptr<interfaces::Wallet> wallet);
//! Returns all wallet names in the wallet dir mapped to whether the wallet
@@ -90,7 +87,7 @@ class WalletControllerActivity : public QObject
public:
WalletControllerActivity(WalletController* wallet_controller, QWidget* parent_widget);
- virtual ~WalletControllerActivity();
+ virtual ~WalletControllerActivity() = default;
Q_SIGNALS:
void finished();
@@ -99,12 +96,10 @@ protected:
interfaces::Node& node() const { return m_wallet_controller->m_node; }
QObject* worker() const { return m_wallet_controller->m_activity_worker; }
- void showProgressDialog(const QString& label_text);
- void destroyProgressDialog();
+ void showProgressDialog(const QString& title_text, const QString& label_text);
WalletController* const m_wallet_controller;
QWidget* const m_parent_widget;
- QProgressDialog* m_progress_dialog{nullptr};
WalletModel* m_wallet_model{nullptr};
bilingual_str m_error_message;
std::vector<bilingual_str> m_warning_message;
@@ -150,4 +145,14 @@ private:
void finish();
};
+class LoadWalletsActivity : public WalletControllerActivity
+{
+ Q_OBJECT
+
+public:
+ LoadWalletsActivity(WalletController* wallet_controller, QWidget* parent_widget);
+
+ void load();
+};
+
#endif // BITCOIN_QT_WALLETCONTROLLER_H
diff --git a/src/qt/walletframe.cpp b/src/qt/walletframe.cpp
index f694fbecb5..4ff92bf82c 100644
--- a/src/qt/walletframe.cpp
+++ b/src/qt/walletframe.cpp
@@ -11,6 +11,7 @@
#include <qt/psbtoperationsdialog.h>
#include <qt/walletmodel.h>
#include <qt/walletview.h>
+#include <util/system.h>
#include <cassert>
@@ -220,10 +221,9 @@ void WalletFrame::gotoLoadPSBT(bool from_clipboard)
return;
}
- PSBTOperationsDialog* dlg = new PSBTOperationsDialog(this, currentWalletModel(), clientModel);
+ auto dlg = new PSBTOperationsDialog(this, currentWalletModel(), clientModel);
dlg->openWithPSBT(psbtx);
- dlg->setAttribute(Qt::WA_DeleteOnClose);
- dlg->exec();
+ GUIUtil::ShowModalDialogAndDeleteOnClose(dlg);
}
void WalletFrame::encryptWallet()
diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp
index 967dd588b4..052453cf65 100644
--- a/src/qt/walletmodel.cpp
+++ b/src/qt/walletmodel.cpp
@@ -506,9 +506,10 @@ bool WalletModel::bumpFee(uint256 hash, uint256& new_hash)
questionString.append(tr("Warning: This may pay the additional fee by reducing change outputs or adding inputs, when necessary. It may add a new change output if one does not already exist. These changes may potentially leak privacy."));
}
- SendConfirmationDialog confirmationDialog(tr("Confirm fee bump"), questionString);
- confirmationDialog.exec();
- QMessageBox::StandardButton retval = static_cast<QMessageBox::StandardButton>(confirmationDialog.result());
+ auto confirmationDialog = new SendConfirmationDialog(tr("Confirm fee bump"), questionString);
+ confirmationDialog->setAttribute(Qt::WA_DeleteOnClose);
+ // TODO: Replace QDialog::exec() with safer QDialog::show().
+ const auto retval = static_cast<QMessageBox::StandardButton>(confirmationDialog->exec());
// cancel sign&broadcast if user doesn't want to bump the fee
if (retval != QMessageBox::Yes) {
diff --git a/src/qt/walletmodeltransaction.h b/src/qt/walletmodeltransaction.h
index 120d240d91..0bae4bade3 100644
--- a/src/qt/walletmodeltransaction.h
+++ b/src/qt/walletmodeltransaction.h
@@ -8,7 +8,7 @@
#include <primitives/transaction.h>
#include <qt/sendcoinsrecipient.h>
-#include <amount.h>
+#include <consensus/amount.h>
#include <QObject>
diff --git a/src/qt/walletview.cpp b/src/qt/walletview.cpp
index 309806a1c4..7813b89e41 100644
--- a/src/qt/walletview.cpp
+++ b/src/qt/walletview.cpp
@@ -205,11 +205,10 @@ void WalletView::showOutOfSyncWarning(bool fShow)
void WalletView::encryptWallet()
{
- AskPassphraseDialog dlg(AskPassphraseDialog::Encrypt, this);
- dlg.setModel(walletModel);
- dlg.exec();
-
- Q_EMIT encryptionStatusChanged();
+ auto dlg = new AskPassphraseDialog(AskPassphraseDialog::Encrypt, this);
+ dlg->setModel(walletModel);
+ connect(dlg, &QDialog::finished, this, &WalletView::encryptionStatusChanged);
+ GUIUtil::ShowModalDialogAndDeleteOnClose(dlg);
}
void WalletView::backupWallet()
@@ -234,19 +233,18 @@ void WalletView::backupWallet()
void WalletView::changePassphrase()
{
- AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
- dlg.setModel(walletModel);
- dlg.exec();
+ auto dlg = new AskPassphraseDialog(AskPassphraseDialog::ChangePass, this);
+ dlg->setModel(walletModel);
+ GUIUtil::ShowModalDialogAndDeleteOnClose(dlg);
}
void WalletView::unlockWallet()
{
// Unlock wallet when requested by wallet model
- if (walletModel->getEncryptionStatus() == WalletModel::Locked)
- {
- AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
- dlg.setModel(walletModel);
- dlg.exec();
+ if (walletModel->getEncryptionStatus() == WalletModel::Locked) {
+ auto dlg = new AskPassphraseDialog(AskPassphraseDialog::Unlock, this);
+ dlg->setModel(walletModel);
+ GUIUtil::ShowModalDialogAndDeleteOnClose(dlg);
}
}
diff --git a/src/qt/walletview.h b/src/qt/walletview.h
index eebc163624..86a835c484 100644
--- a/src/qt/walletview.h
+++ b/src/qt/walletview.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_QT_WALLETVIEW_H
#define BITCOIN_QT_WALLETVIEW_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <QStackedWidget>
diff --git a/src/randomenv.cpp b/src/randomenv.cpp
index fa2a3a0607..bf23ea4a12 100644
--- a/src/randomenv.cpp
+++ b/src/randomenv.cpp
@@ -53,7 +53,7 @@
#include <sys/vmmeter.h>
#endif
#endif
-#if defined(HAVE_STRONG_GETAUXVAL) || defined(HAVE_WEAK_GETAUXVAL)
+#if defined(HAVE_STRONG_GETAUXVAL)
#include <sys/auxv.h>
#endif
@@ -326,7 +326,7 @@ void RandAddStaticEnv(CSHA512& hasher)
// Bitcoin client version
hasher << CLIENT_VERSION;
-#if defined(HAVE_STRONG_GETAUXVAL) || defined(HAVE_WEAK_GETAUXVAL)
+#if defined(HAVE_STRONG_GETAUXVAL)
// Information available through getauxval()
# ifdef AT_HWCAP
hasher << getauxval(AT_HWCAP);
@@ -346,7 +346,7 @@ void RandAddStaticEnv(CSHA512& hasher)
const char* exec_str = (const char*)getauxval(AT_EXECFN);
if (exec_str) hasher.Write((const unsigned char*)exec_str, strlen(exec_str) + 1);
# endif
-#endif // HAVE_STRONG_GETAUXVAL || HAVE_WEAK_GETAUXVAL
+#endif // HAVE_STRONG_GETAUXVAL
#ifdef HAVE_GETCPUID
AddAllCPUID(hasher);
diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp
index 909019d796..ac746de32f 100644
--- a/src/rpc/blockchain.cpp
+++ b/src/rpc/blockchain.cpp
@@ -5,11 +5,11 @@
#include <rpc/blockchain.h>
-#include <amount.h>
#include <blockfilter.h>
#include <chain.h>
#include <chainparams.h>
#include <coins.h>
+#include <consensus/amount.h>
#include <consensus/params.h>
#include <consensus/validation.h>
#include <core_io.h>
@@ -1115,11 +1115,11 @@ static RPCHelpMan gettxoutsetinfo()
{RPCResult::Type::NUM, "bogosize", "Database-independent, meaningless metric indicating the UTXO set size"},
{RPCResult::Type::STR_HEX, "hash_serialized_2", /* optional */ true, "The serialized hash (only present if 'hash_serialized_2' hash_type is chosen)"},
{RPCResult::Type::STR_HEX, "muhash", /* optional */ true, "The serialized hash (only present if 'muhash' hash_type is chosen)"},
- {RPCResult::Type::NUM, "transactions", "The number of transactions with unspent outputs (not available when coinstatsindex is used)"},
- {RPCResult::Type::NUM, "disk_size", "The estimated size of the chainstate on disk (not available when coinstatsindex is used)"},
+ {RPCResult::Type::NUM, "transactions", /* optional */ true, "The number of transactions with unspent outputs (not available when coinstatsindex is used)"},
+ {RPCResult::Type::NUM, "disk_size", /* optional */ true, "The estimated size of the chainstate on disk (not available when coinstatsindex is used)"},
{RPCResult::Type::STR_AMOUNT, "total_amount", "The total amount of coins in the UTXO set"},
- {RPCResult::Type::STR_AMOUNT, "total_unspendable_amount", "The total amount of coins permanently excluded from the UTXO set (only available if coinstatsindex is used)"},
- {RPCResult::Type::OBJ, "block_info", "Info on amounts in the block at this block height (only available if coinstatsindex is used)",
+ {RPCResult::Type::STR_AMOUNT, "total_unspendable_amount", /* optional */ true, "The total amount of coins permanently excluded from the UTXO set (only available if coinstatsindex is used)"},
+ {RPCResult::Type::OBJ, "block_info", /* optional */ true, "Info on amounts in the block at this block height (only available if coinstatsindex is used)",
{
{RPCResult::Type::STR_AMOUNT, "prevout_spent", "Total amount of all prevouts spent in this block"},
{RPCResult::Type::STR_AMOUNT, "coinbase", "Coinbase subsidy amount of this block"},
@@ -1256,11 +1256,8 @@ static RPCHelpMan gettxout()
{RPCResult::Type::OBJ, "scriptPubKey", "", {
{RPCResult::Type::STR, "asm", ""},
{RPCResult::Type::STR_HEX, "hex", ""},
- {RPCResult::Type::NUM, "reqSigs", /* optional */ true, "(DEPRECATED, returned only if config option -deprecatedrpc=addresses is passed) Number of required signatures"},
{RPCResult::Type::STR, "type", "The type, eg pubkeyhash"},
- {RPCResult::Type::STR, "address", /* optional */ true, "bitcoin address (only if a well-defined address exists)"},
- {RPCResult::Type::ARR, "addresses", /* optional */ true, "(DEPRECATED, returned only if config option -deprecatedrpc=addresses is passed) Array of bitcoin addresses",
- {{RPCResult::Type::STR, "address", "bitcoin address"}}},
+ {RPCResult::Type::STR, "address", /* optional */ true, "The Bitcoin address (only if a well-defined address exists)"},
}},
{RPCResult::Type::BOOL, "coinbase", "Coinbase or not"},
}},
@@ -1436,32 +1433,32 @@ RPCHelpMan getblockchaininfo()
{RPCResult::Type::STR_HEX, "chainwork", "total amount of work in active chain, in hexadecimal"},
{RPCResult::Type::NUM, "size_on_disk", "the estimated size of the block and undo files on disk"},
{RPCResult::Type::BOOL, "pruned", "if the blocks are subject to pruning"},
- {RPCResult::Type::NUM, "pruneheight", "lowest-height complete block stored (only present if pruning is enabled)"},
- {RPCResult::Type::BOOL, "automatic_pruning", "whether automatic pruning is enabled (only present if pruning is enabled)"},
- {RPCResult::Type::NUM, "prune_target_size", "the target size used by pruning (only present if automatic pruning is enabled)"},
+ {RPCResult::Type::NUM, "pruneheight", /* optional */ true, "lowest-height complete block stored (only present if pruning is enabled)"},
+ {RPCResult::Type::BOOL, "automatic_pruning", /* optional */ true, "whether automatic pruning is enabled (only present if pruning is enabled)"},
+ {RPCResult::Type::NUM, "prune_target_size", /* optional */ true, "the target size used by pruning (only present if automatic pruning is enabled)"},
{RPCResult::Type::OBJ_DYN, "softforks", "status of softforks",
{
{RPCResult::Type::OBJ, "xxxx", "name of the softfork",
{
{RPCResult::Type::STR, "type", "one of \"buried\", \"bip9\""},
- {RPCResult::Type::OBJ, "bip9", "status of bip9 softforks (only for \"bip9\" type)",
+ {RPCResult::Type::OBJ, "bip9", /* optional */ true, "status of bip9 softforks (only for \"bip9\" type)",
{
{RPCResult::Type::STR, "status", "one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\""},
- {RPCResult::Type::NUM, "bit", "the bit (0-28) in the block version field used to signal this softfork (only for \"started\" and \"locked_in\" status)"},
+ {RPCResult::Type::NUM, "bit", /* optional */ true, "the bit (0-28) in the block version field used to signal this softfork (only for \"started\" and \"locked_in\" status)"},
{RPCResult::Type::NUM_TIME, "start_time", "the minimum median time past of a block at which the bit gains its meaning"},
{RPCResult::Type::NUM_TIME, "timeout", "the median time past of a block at which the deployment is considered failed if not yet locked in"},
{RPCResult::Type::NUM, "since", "height of the first block to which the status applies"},
{RPCResult::Type::NUM, "min_activation_height", "minimum height of blocks for which the rules may be enforced"},
- {RPCResult::Type::OBJ, "statistics", "numeric statistics about signalling for a softfork (only for \"started\" and \"locked_in\" status)",
+ {RPCResult::Type::OBJ, "statistics", /* optional */ true, "numeric statistics about signalling for a softfork (only for \"started\" and \"locked_in\" status)",
{
{RPCResult::Type::NUM, "period", "the length in blocks of the signalling period"},
- {RPCResult::Type::NUM, "threshold", "the number of blocks with the version bit set required to activate the feature (only for \"started\" status)"},
+ {RPCResult::Type::NUM, "threshold", /* optional */ true, "the number of blocks with the version bit set required to activate the feature (only for \"started\" status)"},
{RPCResult::Type::NUM, "elapsed", "the number of blocks elapsed since the beginning of the current period"},
{RPCResult::Type::NUM, "count", "the number of blocks with the version bit set in the current period"},
- {RPCResult::Type::BOOL, "possible", "returns false if there are not enough blocks left in this period to pass activation threshold (only for \"started\" status)"},
+ {RPCResult::Type::BOOL, "possible", /* optional */ true, "returns false if there are not enough blocks left in this period to pass activation threshold (only for \"started\" status)"},
}},
}},
- {RPCResult::Type::NUM, "height", "height of the first block which the rules are or will be enforced (only for \"buried\" type, or \"bip9\" type with \"active\" status)"},
+ {RPCResult::Type::NUM, "height", /* optional */ true, "height of the first block which the rules are or will be enforced (only for \"buried\" type, or \"bip9\" type with \"active\" status)"},
{RPCResult::Type::BOOL, "active", "true if the rules are enforced for the mempool and the next block"},
}},
}},
@@ -1503,7 +1500,7 @@ RPCHelpMan getblockchaininfo()
obj.pushKV("pruneheight", block->nHeight);
// if 0, execution bypasses the whole if block.
- bool automatic_pruning = (gArgs.GetArg("-prune", 0) != 1);
+ bool automatic_pruning = (gArgs.GetIntArg("-prune", 0) != 1);
obj.pushKV("automatic_pruning", automatic_pruning);
if (automatic_pruning) {
obj.pushKV("prune_target_size", nPruneTarget);
@@ -1650,7 +1647,7 @@ UniValue MempoolInfoToJSON(const CTxMemPool& pool)
ret.pushKV("bytes", (int64_t)pool.GetTotalTxSize());
ret.pushKV("usage", (int64_t)pool.DynamicMemoryUsage());
ret.pushKV("total_fee", ValueFromAmount(pool.GetTotalFee()));
- size_t maxmempool = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
+ size_t maxmempool = gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
ret.pushKV("maxmempool", (int64_t) maxmempool);
ret.pushKV("mempoolminfee", ValueFromAmount(std::max(pool.GetMinFee(maxmempool), ::minRelayTxFee).GetFeePerK()));
ret.pushKV("minrelaytxfee", ValueFromAmount(::minRelayTxFee.GetFeePerK()));
@@ -1933,16 +1930,6 @@ void CalculatePercentilesByWeight(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES],
}
}
-void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex)
-{
- ScriptPubKeyToUniv(scriptPubKey, out, fIncludeHex, IsDeprecatedRPCEnabled("addresses"));
-}
-
-void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex, int serialize_flags, const CTxUndo* txundo)
-{
- TxToUniv(tx, hashBlock, IsDeprecatedRPCEnabled("addresses"), entry, include_hex, serialize_flags, txundo);
-}
-
template<typename T>
static inline bool SetHasKeys(const std::set<T>& set) {return false;}
template<typename T, typename Tk, typename... Args>
@@ -1971,11 +1958,11 @@ static RPCHelpMan getblockstats()
RPCResult{
RPCResult::Type::OBJ, "", "",
{
- {RPCResult::Type::NUM, "avgfee", "Average fee in the block"},
- {RPCResult::Type::NUM, "avgfeerate", "Average feerate (in satoshis per virtual byte)"},
- {RPCResult::Type::NUM, "avgtxsize", "Average transaction size"},
- {RPCResult::Type::STR_HEX, "blockhash", "The block hash (to check for potential reorgs)"},
- {RPCResult::Type::ARR_FIXED, "feerate_percentiles", "Feerates at the 10th, 25th, 50th, 75th, and 90th percentile weight unit (in satoshis per virtual byte)",
+ {RPCResult::Type::NUM, "avgfee", /* optional */ true, "Average fee in the block"},
+ {RPCResult::Type::NUM, "avgfeerate", /* optional */ true, "Average feerate (in satoshis per virtual byte)"},
+ {RPCResult::Type::NUM, "avgtxsize", /* optional */ true, "Average transaction size"},
+ {RPCResult::Type::STR_HEX, "blockhash", /* optional */ true, "The block hash (to check for potential reorgs)"},
+ {RPCResult::Type::ARR_FIXED, "feerate_percentiles", /* optional */ true, "Feerates at the 10th, 25th, 50th, 75th, and 90th percentile weight unit (in satoshis per virtual byte)",
{
{RPCResult::Type::NUM, "10th_percentile_feerate", "The 10th percentile feerate"},
{RPCResult::Type::NUM, "25th_percentile_feerate", "The 25th percentile feerate"},
@@ -1983,30 +1970,30 @@ static RPCHelpMan getblockstats()
{RPCResult::Type::NUM, "75th_percentile_feerate", "The 75th percentile feerate"},
{RPCResult::Type::NUM, "90th_percentile_feerate", "The 90th percentile feerate"},
}},
- {RPCResult::Type::NUM, "height", "The height of the block"},
- {RPCResult::Type::NUM, "ins", "The number of inputs (excluding coinbase)"},
- {RPCResult::Type::NUM, "maxfee", "Maximum fee in the block"},
- {RPCResult::Type::NUM, "maxfeerate", "Maximum feerate (in satoshis per virtual byte)"},
- {RPCResult::Type::NUM, "maxtxsize", "Maximum transaction size"},
- {RPCResult::Type::NUM, "medianfee", "Truncated median fee in the block"},
- {RPCResult::Type::NUM, "mediantime", "The block median time past"},
- {RPCResult::Type::NUM, "mediantxsize", "Truncated median transaction size"},
- {RPCResult::Type::NUM, "minfee", "Minimum fee in the block"},
- {RPCResult::Type::NUM, "minfeerate", "Minimum feerate (in satoshis per virtual byte)"},
- {RPCResult::Type::NUM, "mintxsize", "Minimum transaction size"},
- {RPCResult::Type::NUM, "outs", "The number of outputs"},
- {RPCResult::Type::NUM, "subsidy", "The block subsidy"},
- {RPCResult::Type::NUM, "swtotal_size", "Total size of all segwit transactions"},
- {RPCResult::Type::NUM, "swtotal_weight", "Total weight of all segwit transactions"},
- {RPCResult::Type::NUM, "swtxs", "The number of segwit transactions"},
- {RPCResult::Type::NUM, "time", "The block time"},
- {RPCResult::Type::NUM, "total_out", "Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])"},
- {RPCResult::Type::NUM, "total_size", "Total size of all non-coinbase transactions"},
- {RPCResult::Type::NUM, "total_weight", "Total weight of all non-coinbase transactions"},
- {RPCResult::Type::NUM, "totalfee", "The fee total"},
- {RPCResult::Type::NUM, "txs", "The number of transactions (including coinbase)"},
- {RPCResult::Type::NUM, "utxo_increase", "The increase/decrease in the number of unspent outputs"},
- {RPCResult::Type::NUM, "utxo_size_inc", "The increase/decrease in size for the utxo index (not discounting op_return and similar)"},
+ {RPCResult::Type::NUM, "height", /* optional */ true, "The height of the block"},
+ {RPCResult::Type::NUM, "ins", /* optional */ true, "The number of inputs (excluding coinbase)"},
+ {RPCResult::Type::NUM, "maxfee", /* optional */ true, "Maximum fee in the block"},
+ {RPCResult::Type::NUM, "maxfeerate", /* optional */ true, "Maximum feerate (in satoshis per virtual byte)"},
+ {RPCResult::Type::NUM, "maxtxsize", /* optional */ true, "Maximum transaction size"},
+ {RPCResult::Type::NUM, "medianfee", /* optional */ true, "Truncated median fee in the block"},
+ {RPCResult::Type::NUM, "mediantime", /* optional */ true, "The block median time past"},
+ {RPCResult::Type::NUM, "mediantxsize", /* optional */ true, "Truncated median transaction size"},
+ {RPCResult::Type::NUM, "minfee", /* optional */ true, "Minimum fee in the block"},
+ {RPCResult::Type::NUM, "minfeerate", /* optional */ true, "Minimum feerate (in satoshis per virtual byte)"},
+ {RPCResult::Type::NUM, "mintxsize", /* optional */ true, "Minimum transaction size"},
+ {RPCResult::Type::NUM, "outs", /* optional */ true, "The number of outputs"},
+ {RPCResult::Type::NUM, "subsidy", /* optional */ true, "The block subsidy"},
+ {RPCResult::Type::NUM, "swtotal_size", /* optional */ true, "Total size of all segwit transactions"},
+ {RPCResult::Type::NUM, "swtotal_weight", /* optional */ true, "Total weight of all segwit transactions"},
+ {RPCResult::Type::NUM, "swtxs", /* optional */ true, "The number of segwit transactions"},
+ {RPCResult::Type::NUM, "time", /* optional */ true, "The block time"},
+ {RPCResult::Type::NUM, "total_out", /* optional */ true, "Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])"},
+ {RPCResult::Type::NUM, "total_size", /* optional */ true, "Total size of all non-coinbase transactions"},
+ {RPCResult::Type::NUM, "total_weight", /* optional */ true, "Total weight of all non-coinbase transactions"},
+ {RPCResult::Type::NUM, "totalfee", /* optional */ true, "The fee total"},
+ {RPCResult::Type::NUM, "txs", /* optional */ true, "The number of transactions (including coinbase)"},
+ {RPCResult::Type::NUM, "utxo_increase", /* optional */ true, "The increase/decrease in the number of unspent outputs"},
+ {RPCResult::Type::NUM, "utxo_size_inc", /* optional */ true, "The increase/decrease in size for the utxo index (not discounting op_return and similar)"},
}},
RPCExamples{
HelpExampleCli("getblockstats", R"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
diff --git a/src/rpc/blockchain.h b/src/rpc/blockchain.h
index ffb6f03b47..09e471afdd 100644
--- a/src/rpc/blockchain.h
+++ b/src/rpc/blockchain.h
@@ -5,8 +5,7 @@
#ifndef BITCOIN_RPC_BLOCKCHAIN_H
#define BITCOIN_RPC_BLOCKCHAIN_H
-#include <amount.h>
-#include <core_io.h>
+#include <consensus/amount.h>
#include <streams.h>
#include <sync.h>
@@ -53,9 +52,6 @@ UniValue blockheaderToJSON(const CBlockIndex* tip, const CBlockIndex* blockindex
/** Used by getblockstats to get feerates at different percentiles by weight */
void CalculatePercentilesByWeight(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES], std::vector<std::pair<CAmount, int64_t>>& scores, int64_t total_weight);
-void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
-void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex = true, int serialize_flags = 0, const CTxUndo* txundo = nullptr);
-
NodeContext& EnsureAnyNodeContext(const std::any& context);
CTxMemPool& EnsureMemPool(const NodeContext& node);
CTxMemPool& EnsureAnyMemPool(const std::any& context);
diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp
index 4357ab2bb3..93e49cb9a8 100644
--- a/src/rpc/client.cpp
+++ b/src/rpc/client.cpp
@@ -131,6 +131,7 @@ static const CRPCConvertParam vRPCConvertParams[] =
{ "gettxoutsetinfo", 2, "use_index"},
{ "lockunspent", 0, "unlock" },
{ "lockunspent", 1, "transactions" },
+ { "lockunspent", 2, "persistent" },
{ "send", 0, "outputs" },
{ "send", 1, "conf_target" },
{ "send", 3, "fee_rate"},
@@ -192,6 +193,7 @@ static const CRPCConvertParam vRPCConvertParams[] =
{ "unloadwallet", 1, "load_on_startup"},
{ "getnodeaddresses", 0, "count"},
{ "addpeeraddress", 1, "port"},
+ { "addpeeraddress", 2, "tried"},
{ "stop", 0, "wait" },
};
// clang-format on
diff --git a/src/rpc/external_signer.cpp b/src/rpc/external_signer.cpp
index 6ec2b1a07f..60ec15e904 100644
--- a/src/rpc/external_signer.cpp
+++ b/src/rpc/external_signer.cpp
@@ -24,8 +24,11 @@ static RPCHelpMan enumeratesigners()
{
{RPCResult::Type::ARR, "signers", /* optional */ false, "",
{
- {RPCResult::Type::STR_HEX, "masterkeyfingerprint", "Master key fingerprint"},
- {RPCResult::Type::STR, "name", "Device name"},
+ {RPCResult::Type::OBJ, "", "",
+ {
+ {RPCResult::Type::STR_HEX, "fingerprint", "Master key fingerprint"},
+ {RPCResult::Type::STR, "name", "Device name"},
+ }},
},
}
}
diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp
index 27cbb3a702..518c41d12a 100644
--- a/src/rpc/mining.cpp
+++ b/src/rpc/mining.cpp
@@ -3,9 +3,9 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <amount.h>
#include <chain.h>
#include <chainparams.h>
+#include <consensus/amount.h>
#include <consensus/consensus.h>
#include <consensus/params.h>
#include <consensus/validation.h>
@@ -553,6 +553,10 @@ static RPCHelpMan getblocktemplate()
{
{RPCResult::Type::NUM, "rulename", "identifies the bit number as indicating acceptance and readiness for the named softfork rule"},
}},
+ {RPCResult::Type::ARR, "capabilities", "",
+ {
+ {RPCResult::Type::STR, "value", "A supported feature, for example 'proposal'"},
+ }},
{RPCResult::Type::NUM, "vbrequired", "bit mask of versionbits the server requires set in submissions"},
{RPCResult::Type::STR, "previousblockhash", "The hash of current highest block"},
{RPCResult::Type::ARR, "transactions", "contents of non-coinbase transactions that should be included in the next block",
@@ -586,11 +590,12 @@ static RPCHelpMan getblocktemplate()
{RPCResult::Type::STR_HEX, "noncerange", "A range of valid nonces"},
{RPCResult::Type::NUM, "sigoplimit", "limit of sigops in blocks"},
{RPCResult::Type::NUM, "sizelimit", "limit of block size"},
- {RPCResult::Type::NUM, "weightlimit", "limit of block weight"},
+ {RPCResult::Type::NUM, "weightlimit", /* optional */ true, "limit of block weight"},
{RPCResult::Type::NUM_TIME, "curtime", "current timestamp in " + UNIX_EPOCH_TIME},
{RPCResult::Type::STR, "bits", "compressed target of next block"},
{RPCResult::Type::NUM, "height", "The height of the next block"},
- {RPCResult::Type::STR, "default_witness_commitment", /* optional */ true, "a valid witness commitment for the unmodified block template"},
+ {RPCResult::Type::STR_HEX, "signet_challenge", /* optional */ true, "Only on signet"},
+ {RPCResult::Type::STR_HEX, "default_witness_commitment", /* optional */ true, "a valid witness commitment for the unmodified block template"},
}},
},
RPCExamples{
@@ -697,7 +702,7 @@ static RPCHelpMan getblocktemplate()
std::string lpstr = lpval.get_str();
hashWatchedChain = ParseHashV(lpstr.substr(0, 64), "longpollid");
- nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
+ nTransactionsUpdatedLastLP = LocaleIndependentAtoi<int64_t>(lpstr.substr(64));
}
else
{
@@ -1098,6 +1103,8 @@ static RPCHelpMan estimatesmartfee()
RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
CBlockPolicyEstimator& fee_estimator = EnsureAnyFeeEstimator(request.context);
+ const NodeContext& node = EnsureAnyNodeContext(request.context);
+ const CTxMemPool& mempool = EnsureMemPool(node);
unsigned int max_target = fee_estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target);
@@ -1113,7 +1120,10 @@ static RPCHelpMan estimatesmartfee()
UniValue result(UniValue::VOBJ);
UniValue errors(UniValue::VARR);
FeeCalculation feeCalc;
- CFeeRate feeRate = fee_estimator.estimateSmartFee(conf_target, &feeCalc, conservative);
+ CFeeRate feeRate{fee_estimator.estimateSmartFee(conf_target, &feeCalc, conservative)};
+ CFeeRate min_mempool_feerate{mempool.GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000)};
+ CFeeRate min_relay_feerate{::minRelayTxFee};
+ feeRate = std::max({feeRate, min_mempool_feerate, min_relay_feerate});
if (feeRate != CFeeRate(0)) {
result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK()));
} else {
diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp
index e5804211f3..39bd9c6091 100644
--- a/src/rpc/misc.cpp
+++ b/src/rpc/misc.cpp
@@ -22,6 +22,7 @@
#include <util/check.h>
#include <util/message.h> // For MessageSign(), MessageVerify()
#include <util/strencodings.h>
+#include <util/syscall_sandbox.h>
#include <util/system.h>
#include <optional>
@@ -44,10 +45,10 @@ static RPCHelpMan validateaddress()
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::BOOL, "isvalid", "If the address is valid or not"},
- {RPCResult::Type::STR, "address", "The bitcoin address validated"},
- {RPCResult::Type::STR_HEX, "scriptPubKey", "The hex-encoded scriptPubKey generated by the address"},
- {RPCResult::Type::BOOL, "isscript", "If the key is a script"},
- {RPCResult::Type::BOOL, "iswitness", "If the address is a witness address"},
+ {RPCResult::Type::STR, "address", /* optional */ true, "The bitcoin address validated"},
+ {RPCResult::Type::STR_HEX, "scriptPubKey", /* optional */ true, "The hex-encoded scriptPubKey generated by the address"},
+ {RPCResult::Type::BOOL, "isscript", /* optional */ true, "If the key is a script"},
+ {RPCResult::Type::BOOL, "iswitness", /* optional */ true, "If the address is a witness address"},
{RPCResult::Type::NUM, "witness_version", /* optional */ true, "The version number of the witness program"},
{RPCResult::Type::STR_HEX, "witness_program", /* optional */ true, "The hex value of the witness program"},
{RPCResult::Type::STR, "error", /* optional */ true, "Error message, if any"},
@@ -417,6 +418,27 @@ static RPCHelpMan setmocktime()
};
}
+#if defined(USE_SYSCALL_SANDBOX)
+static RPCHelpMan invokedisallowedsyscall()
+{
+ return RPCHelpMan{
+ "invokedisallowedsyscall",
+ "\nInvoke a disallowed syscall to trigger a syscall sandbox violation. Used for testing purposes.\n",
+ {},
+ RPCResult{RPCResult::Type::NONE, "", ""},
+ RPCExamples{
+ HelpExampleCli("invokedisallowedsyscall", "") + HelpExampleRpc("invokedisallowedsyscall", "")},
+ [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
+ if (!Params().IsTestChain()) {
+ throw std::runtime_error("invokedisallowedsyscall is used for testing only.");
+ }
+ TestDisallowedSandboxCall();
+ return NullUniValue;
+ },
+ };
+}
+#endif // USE_SYSCALL_SANDBOX
+
static RPCHelpMan mockscheduler()
{
return RPCHelpMan{"mockscheduler",
@@ -670,8 +692,9 @@ static RPCHelpMan echoipc()
RPCExamples{HelpExampleCli("echo", "\"Hello world\"") +
HelpExampleRpc("echo", "\"Hello world\"")},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
+ interfaces::Init& local_init = *EnsureAnyNodeContext(request.context).init;
std::unique_ptr<interfaces::Echo> echo;
- if (interfaces::Ipc* ipc = Assert(EnsureAnyNodeContext(request.context).init)->ipc()) {
+ if (interfaces::Ipc* ipc = local_init.ipc()) {
// Spawn a new bitcoin-node process and call makeEcho to get a
// client pointer to a interfaces::Echo instance running in
// that process. This is just for testing. A slightly more
@@ -689,7 +712,7 @@ static RPCHelpMan echoipc()
// interfaces::Echo object and return it so the `echoipc` RPC
// method will work, and the python test calling `echoipc`
// can expect the same result.
- echo = interfaces::MakeEcho();
+ echo = local_init.makeEcho();
}
return echo->echo(request.params[0].get_str());
},
@@ -716,7 +739,7 @@ static RPCHelpMan getindexinfo()
{"index_name", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "Filter results for an index with a specific name."},
},
RPCResult{
- RPCResult::Type::OBJ, "", "", {
+ RPCResult::Type::OBJ_DYN, "", "", {
{
RPCResult::Type::OBJ, "name", "The name of the index",
{
@@ -776,6 +799,9 @@ static const CRPCCommand commands[] =
{ "hidden", &echo, },
{ "hidden", &echojson, },
{ "hidden", &echoipc, },
+#if defined(USE_SYSCALL_SANDBOX)
+ { "hidden", &invokedisallowedsyscall, },
+#endif // USE_SYSCALL_SANDBOX
};
// clang-format on
for (const auto& c : commands) {
diff --git a/src/rpc/net.cpp b/src/rpc/net.cpp
index 0f554ec5e7..a9bee33c5d 100644
--- a/src/rpc/net.cpp
+++ b/src/rpc/net.cpp
@@ -116,10 +116,10 @@ static RPCHelpMan getpeerinfo()
{
{RPCResult::Type::NUM, "id", "Peer index"},
{RPCResult::Type::STR, "addr", "(host:port) The IP address and port of the peer"},
- {RPCResult::Type::STR, "addrbind", "(ip:port) Bind address of the connection to the peer"},
- {RPCResult::Type::STR, "addrlocal", "(ip:port) Local address as reported by the peer"},
+ {RPCResult::Type::STR, "addrbind", /* optional */ true, "(ip:port) Bind address of the connection to the peer"},
+ {RPCResult::Type::STR, "addrlocal", /* optional */ true, "(ip:port) Local address as reported by the peer"},
{RPCResult::Type::STR, "network", "Network (" + Join(GetNetworkNames(/* append_unroutable */ true), ", ") + ")"},
- {RPCResult::Type::NUM, "mapped_as", "The AS in the BGP route to the peer used for diversifying\n"
+ {RPCResult::Type::NUM, "mapped_as", /* optional */ true, "The AS in the BGP route to the peer used for diversifying\n"
"peer selection (only available if the asmap config flag is set)"},
{RPCResult::Type::STR_HEX, "services", "The services offered"},
{RPCResult::Type::ARR, "servicesnames", "the services offered, in human-readable form",
@@ -135,9 +135,9 @@ static RPCHelpMan getpeerinfo()
{RPCResult::Type::NUM, "bytesrecv", "The total bytes received"},
{RPCResult::Type::NUM_TIME, "conntime", "The " + UNIX_EPOCH_TIME + " of the connection"},
{RPCResult::Type::NUM, "timeoffset", "The time offset in seconds"},
- {RPCResult::Type::NUM, "pingtime", "ping time (if available)"},
- {RPCResult::Type::NUM, "minping", "minimum observed ping time (if any at all)"},
- {RPCResult::Type::NUM, "pingwait", "ping wait (if non-zero)"},
+ {RPCResult::Type::NUM, "pingtime", /* optional */ true, "ping time (if available)"},
+ {RPCResult::Type::NUM, "minping", /* optional */ true, "minimum observed ping time (if any at all)"},
+ {RPCResult::Type::NUM, "pingwait", /* optional */ true, "ping wait (if non-zero)"},
{RPCResult::Type::NUM, "version", "The peer version, such as 70001"},
{RPCResult::Type::STR, "subver", "The string version"},
{RPCResult::Type::BOOL, "inbound", "Inbound (true) or Outbound (false)"},
@@ -921,6 +921,7 @@ static RPCHelpMan addpeeraddress()
{
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The IP address of the peer"},
{"port", RPCArg::Type::NUM, RPCArg::Optional::NO, "The port of the peer"},
+ {"tried", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, attempt to add the peer to the tried addresses table"},
},
RPCResult{
RPCResult::Type::OBJ, "", "",
@@ -929,8 +930,8 @@ static RPCHelpMan addpeeraddress()
},
},
RPCExamples{
- HelpExampleCli("addpeeraddress", "\"1.2.3.4\" 8333")
- + HelpExampleRpc("addpeeraddress", "\"1.2.3.4\", 8333")
+ HelpExampleCli("addpeeraddress", "\"1.2.3.4\" 8333 true")
+ + HelpExampleRpc("addpeeraddress", "\"1.2.3.4\", 8333, true")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
@@ -941,6 +942,7 @@ static RPCHelpMan addpeeraddress()
const std::string& addr_string{request.params[0].get_str()};
const uint16_t port{static_cast<uint16_t>(request.params[1].get_int())};
+ const bool tried{request.params[2].isTrue()};
UniValue obj(UniValue::VOBJ);
CNetAddr net_addr;
@@ -951,7 +953,13 @@ static RPCHelpMan addpeeraddress()
address.nTime = GetAdjustedTime();
// The source address is set equal to the address. This is equivalent to the peer
// announcing itself.
- if (node.addrman->Add({address}, address)) success = true;
+ if (node.addrman->Add({address}, address)) {
+ success = true;
+ if (tried) {
+ // Attempt to move the address to the tried addresses table.
+ node.addrman->Good(address);
+ }
+ }
}
obj.pushKV("success", success);
diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index 00e77d89e5..483717aa7a 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -5,6 +5,7 @@
#include <chain.h>
#include <coins.h>
+#include <consensus/amount.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <index/txindex.h>
@@ -94,7 +95,7 @@ static RPCHelpMan getrawtransaction()
RPCResult{"if verbose is set to true",
RPCResult::Type::OBJ, "", "",
{
- {RPCResult::Type::BOOL, "in_active_chain", "Whether specified block is in the active chain or not (only present with explicit \"blockhash\" argument)"},
+ {RPCResult::Type::BOOL, "in_active_chain", /* optional */ true, "Whether specified block is in the active chain or not (only present with explicit \"blockhash\" argument)"},
{RPCResult::Type::STR_HEX, "hex", "The serialized, hex-encoded data for 'txid'"},
{RPCResult::Type::STR_HEX, "txid", "The transaction id (same as provided)"},
{RPCResult::Type::STR_HEX, "hash", "The transaction hash (differs from txid for witness transactions)"},
@@ -115,7 +116,7 @@ static RPCHelpMan getrawtransaction()
{RPCResult::Type::STR_HEX, "hex", "hex"},
}},
{RPCResult::Type::NUM, "sequence", "The script sequence number"},
- {RPCResult::Type::ARR, "txinwitness", "",
+ {RPCResult::Type::ARR, "txinwitness", /* optional */ true, "",
{
{RPCResult::Type::STR_HEX, "hex", "hex-encoded witness data (if any)"},
}},
@@ -131,20 +132,15 @@ static RPCHelpMan getrawtransaction()
{
{RPCResult::Type::STR, "asm", "the asm"},
{RPCResult::Type::STR, "hex", "the hex"},
- {RPCResult::Type::NUM, "reqSigs", /* optional */ true, "(DEPRECATED, returned only if config option -deprecatedrpc=addresses is passed) Number of required signatures"},
{RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
- {RPCResult::Type::STR, "address", /* optional */ true, "bitcoin address (only if a well-defined address exists)"},
- {RPCResult::Type::ARR, "addresses", /* optional */ true, "(DEPRECATED, returned only if config option -deprecatedrpc=addresses is passed) Array of bitcoin addresses",
- {
- {RPCResult::Type::STR, "address", "bitcoin address"},
- }},
+ {RPCResult::Type::STR, "address", /* optional */ true, "The Bitcoin address (only if a well-defined address exists)"},
}},
}},
}},
- {RPCResult::Type::STR_HEX, "blockhash", "the block hash"},
- {RPCResult::Type::NUM, "confirmations", "The confirmations"},
- {RPCResult::Type::NUM_TIME, "blocktime", "The block time expressed in " + UNIX_EPOCH_TIME},
- {RPCResult::Type::NUM, "time", "Same as \"blocktime\""},
+ {RPCResult::Type::STR_HEX, "blockhash", /* optional */ true, "the block hash"},
+ {RPCResult::Type::NUM, "confirmations", /* optional */ true, "The confirmations"},
+ {RPCResult::Type::NUM_TIME, "blocktime", /* optional */ true, "The block time expressed in " + UNIX_EPOCH_TIME},
+ {RPCResult::Type::NUM, "time", /* optional */ true, "Same as \"blocktime\""},
}
},
},
@@ -470,14 +466,15 @@ static RPCHelpMan decoderawtransaction()
{
{RPCResult::Type::OBJ, "", "",
{
- {RPCResult::Type::STR_HEX, "txid", "The transaction id"},
- {RPCResult::Type::NUM, "vout", "The output number"},
- {RPCResult::Type::OBJ, "scriptSig", "The script",
+ {RPCResult::Type::STR_HEX, "coinbase", /* optional */ true, ""},
+ {RPCResult::Type::STR_HEX, "txid", /* optional */ true, "The transaction id"},
+ {RPCResult::Type::NUM, "vout", /* optional */ true, "The output number"},
+ {RPCResult::Type::OBJ, "scriptSig", /* optional */ true, "The script",
{
{RPCResult::Type::STR, "asm", "asm"},
{RPCResult::Type::STR_HEX, "hex", "hex"},
}},
- {RPCResult::Type::ARR, "txinwitness", "",
+ {RPCResult::Type::ARR, "txinwitness", /* optional */ true, "",
{
{RPCResult::Type::STR_HEX, "hex", "hex-encoded witness data (if any)"},
}},
@@ -494,13 +491,8 @@ static RPCHelpMan decoderawtransaction()
{
{RPCResult::Type::STR, "asm", "the asm"},
{RPCResult::Type::STR_HEX, "hex", "the hex"},
- {RPCResult::Type::NUM, "reqSigs", /* optional */ true, "(DEPRECATED, returned only if config option -deprecatedrpc=addresses is passed) Number of required signatures"},
{RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
- {RPCResult::Type::STR, "address", /* optional */ true, "bitcoin address (only if a well-defined address exists)"},
- {RPCResult::Type::ARR, "addresses", /* optional */ true, "(DEPRECATED, returned only if config option -deprecatedrpc=addresses is passed) Array of bitcoin addresses",
- {
- {RPCResult::Type::STR, "address", "bitcoin address"},
- }},
+ {RPCResult::Type::STR, "address", /* optional */ true, "The Bitcoin address (only if a well-defined address exists)"},
}},
}},
}},
@@ -553,24 +545,14 @@ static RPCHelpMan decodescript()
{
{RPCResult::Type::STR, "asm", "Script public key"},
{RPCResult::Type::STR, "type", "The output type (e.g. "+GetAllOutputTypes()+")"},
- {RPCResult::Type::STR, "address", /* optional */ true, "bitcoin address (only if a well-defined address exists)"},
- {RPCResult::Type::NUM, "reqSigs", /* optional */ true, "(DEPRECATED, returned only if config option -deprecatedrpc=addresses is passed) Number of required signatures"},
- {RPCResult::Type::ARR, "addresses", /* optional */ true, "(DEPRECATED, returned only if config option -deprecatedrpc=addresses is passed) Array of bitcoin addresses",
- {
- {RPCResult::Type::STR, "address", "bitcoin address"},
- }},
- {RPCResult::Type::STR, "p2sh", "address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH)"},
- {RPCResult::Type::OBJ, "segwit", "Result of a witness script public key wrapping this redeem script (not returned if the script is a P2SH or witness)",
+ {RPCResult::Type::STR, "address", /* optional */ true, "The Bitcoin address (only if a well-defined address exists)"},
+ {RPCResult::Type::STR, "p2sh", /* optional */ true, "address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH)"},
+ {RPCResult::Type::OBJ, "segwit", /* optional */ true, "Result of a witness script public key wrapping this redeem script (not returned if the script is a P2SH or witness)",
{
{RPCResult::Type::STR, "asm", "String representation of the script public key"},
{RPCResult::Type::STR_HEX, "hex", "Hex string of the script public key"},
{RPCResult::Type::STR, "type", "The type of the script public key (e.g. witness_v0_keyhash or witness_v0_scripthash)"},
- {RPCResult::Type::STR, "address", /* optional */ true, "bitcoin address (only if a well-defined address exists)"},
- {RPCResult::Type::NUM, "reqSigs", /* optional */ true, "(DEPRECATED, returned only if config option -deprecatedrpc=addresses is passed) Number of required signatures"},
- {RPCResult::Type::ARR, "addresses", /* optional */ true, "(DEPRECATED, returned only if config option -deprecatedrpc=addresses is passed) Array of bitcoin addresses",
- {
- {RPCResult::Type::STR, "address", "segwit address"},
- }},
+ {RPCResult::Type::STR, "address", /* optional */ true, "The Bitcoin address (only if a well-defined address exists)"},
{RPCResult::Type::STR, "p2sh-segwit", "address of the P2SH script wrapping this witness redeem script"},
}},
}
@@ -591,7 +573,7 @@ static RPCHelpMan decodescript()
} else {
// Empty scripts are valid
}
- ScriptPubKeyToUniv(script, r, /* fIncludeHex */ false);
+ ScriptPubKeyToUniv(script, r, /* include_hex */ false);
UniValue type;
type = find_value(r, "type");
@@ -625,7 +607,7 @@ static RPCHelpMan decodescript()
// Newer segwit program versions should be considered when then become available.
segwitScr = GetScriptForDestination(WitnessV0ScriptHash(script));
}
- ScriptPubKeyToUniv(segwitScr, sr, /* fIncludeHex */ true);
+ ScriptPubKeyToUniv(segwitScr, sr, /* include_hex */ true);
sr.pushKV("p2sh-segwit", EncodeDestination(ScriptHash(segwitScr)));
r.pushKV("segwit", sr);
}
@@ -772,6 +754,10 @@ static RPCHelpMan signrawtransactionwithkey()
{
{RPCResult::Type::STR_HEX, "txid", "The hash of the referenced, previous transaction"},
{RPCResult::Type::NUM, "vout", "The index of the output to spent and used as input"},
+ {RPCResult::Type::ARR, "witness", "",
+ {
+ {RPCResult::Type::STR_HEX, "witness", ""},
+ }},
{RPCResult::Type::STR_HEX, "scriptSig", "The hex-encoded signature script"},
{RPCResult::Type::NUM, "sequence", "Script sequence number"},
{RPCResult::Type::STR, "error", "Verification or signing error related to the input"},
@@ -909,15 +895,15 @@ static RPCHelpMan testmempoolaccept()
{
{RPCResult::Type::STR_HEX, "txid", "The transaction hash in hex"},
{RPCResult::Type::STR_HEX, "wtxid", "The transaction witness hash in hex"},
- {RPCResult::Type::STR, "package-error", "Package validation error, if any (only possible if rawtxs had more than 1 transaction)."},
- {RPCResult::Type::BOOL, "allowed", "Whether this tx would be accepted to the mempool and pass client-specified maxfeerate."
+ {RPCResult::Type::STR, "package-error", /* optional */ true, "Package validation error, if any (only possible if rawtxs had more than 1 transaction)."},
+ {RPCResult::Type::BOOL, "allowed", /* optional */ true, "Whether this tx would be accepted to the mempool and pass client-specified maxfeerate. "
"If not present, the tx was not fully validated due to a failure in another tx in the list."},
- {RPCResult::Type::NUM, "vsize", "Virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted (only present when 'allowed' is true)"},
- {RPCResult::Type::OBJ, "fees", "Transaction fees (only present if 'allowed' is true)",
+ {RPCResult::Type::NUM, "vsize", /* optional */ true, "Virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted (only present when 'allowed' is true)"},
+ {RPCResult::Type::OBJ, "fees", /* optional */ true, "Transaction fees (only present if 'allowed' is true)",
{
{RPCResult::Type::STR_AMOUNT, "base", "transaction fee in " + CURRENCY_UNIT},
}},
- {RPCResult::Type::STR, "reject-reason", "Rejection string (only present when 'allowed' is false)"},
+ {RPCResult::Type::STR, "reject-reason", /* optional */ true, "Rejection string (only present when 'allowed' is false)"},
}},
}
},
@@ -1056,7 +1042,7 @@ static RPCHelpMan decodepsbt()
{RPCResult::Type::STR, "asm", "The asm"},
{RPCResult::Type::STR_HEX, "hex", "The hex"},
{RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
- {RPCResult::Type::STR, "address"," Bitcoin address if there is one"},
+ {RPCResult::Type::STR, "address", /* optional */ true, "The Bitcoin address (only if a well-defined address exists)"},
}},
}},
{RPCResult::Type::OBJ_DYN, "partial_signatures", /* optional */ true, "",
@@ -1078,22 +1064,23 @@ static RPCHelpMan decodepsbt()
}},
{RPCResult::Type::ARR, "bip32_derivs", /* optional */ true, "",
{
- {RPCResult::Type::OBJ, "pubkey", /* optional */ true, "The public key with the derivation path as the value.",
+ {RPCResult::Type::OBJ, "", "",
{
+ {RPCResult::Type::STR, "pubkey", "The public key with the derivation path as the value."},
{RPCResult::Type::STR, "master_fingerprint", "The fingerprint of the master key"},
{RPCResult::Type::STR, "path", "The path"},
}},
}},
- {RPCResult::Type::OBJ, "final_scriptsig", /* optional */ true, "",
+ {RPCResult::Type::OBJ, "final_scriptSig", /* optional */ true, "",
{
{RPCResult::Type::STR, "asm", "The asm"},
{RPCResult::Type::STR, "hex", "The hex"},
}},
- {RPCResult::Type::ARR, "final_scriptwitness", "",
+ {RPCResult::Type::ARR, "final_scriptwitness", /* optional */ true, "",
{
{RPCResult::Type::STR_HEX, "", "hex-encoded witness data (if any)"},
}},
- {RPCResult::Type::OBJ_DYN, "unknown", "The unknown global fields",
+ {RPCResult::Type::OBJ_DYN, "unknown", /* optional */ true, "The unknown global fields",
{
{RPCResult::Type::STR_HEX, "key", "(key-value pair) An unknown key-value pair"},
}},
@@ -1124,7 +1111,7 @@ static RPCHelpMan decodepsbt()
{RPCResult::Type::STR, "path", "The path"},
}},
}},
- {RPCResult::Type::OBJ_DYN, "unknown", "The unknown global fields",
+ {RPCResult::Type::OBJ_DYN, "unknown", /* optional */ true, "The unknown global fields",
{
{RPCResult::Type::STR_HEX, "key", "(key-value pair) An unknown key-value pair"},
}},
@@ -1175,7 +1162,7 @@ static RPCHelpMan decodepsbt()
txout = input.witness_utxo;
UniValue o(UniValue::VOBJ);
- ScriptToUniv(txout.scriptPubKey, o, true);
+ ScriptPubKeyToUniv(txout.scriptPubKey, o, /* include_hex */ true);
UniValue out(UniValue::VOBJ);
out.pushKV("amount", ValueFromAmount(txout.nValue));
@@ -1222,12 +1209,12 @@ static RPCHelpMan decodepsbt()
// Redeem script and witness script
if (!input.redeem_script.empty()) {
UniValue r(UniValue::VOBJ);
- ScriptToUniv(input.redeem_script, r, false);
+ ScriptToUniv(input.redeem_script, r);
in.pushKV("redeem_script", r);
}
if (!input.witness_script.empty()) {
UniValue r(UniValue::VOBJ);
- ScriptToUniv(input.witness_script, r, false);
+ ScriptToUniv(input.witness_script, r);
in.pushKV("witness_script", r);
}
@@ -1282,12 +1269,12 @@ static RPCHelpMan decodepsbt()
// Redeem script and witness script
if (!output.redeem_script.empty()) {
UniValue r(UniValue::VOBJ);
- ScriptToUniv(output.redeem_script, r, false);
+ ScriptToUniv(output.redeem_script, r);
out.pushKV("redeem_script", r);
}
if (!output.witness_script.empty()) {
UniValue r(UniValue::VOBJ);
- ScriptToUniv(output.witness_script, r, false);
+ ScriptToUniv(output.witness_script, r);
out.pushKV("witness_script", r);
}
@@ -1398,8 +1385,8 @@ static RPCHelpMan finalizepsbt()
RPCResult{
RPCResult::Type::OBJ, "", "",
{
- {RPCResult::Type::STR, "psbt", "The base64-encoded partially signed transaction if not extracted"},
- {RPCResult::Type::STR_HEX, "hex", "The hex-encoded network transaction if extracted"},
+ {RPCResult::Type::STR, "psbt", /* optional */ true, "The base64-encoded partially signed transaction if not extracted"},
+ {RPCResult::Type::STR_HEX, "hex", /* optional */ true, "The hex-encoded network transaction if extracted"},
{RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
}
},
@@ -1791,7 +1778,7 @@ static RPCHelpMan analyzepsbt()
RPCResult {
RPCResult::Type::OBJ, "", "",
{
- {RPCResult::Type::ARR, "inputs", "",
+ {RPCResult::Type::ARR, "inputs", /* optional */ true, "",
{
{RPCResult::Type::OBJ, "", "",
{
diff --git a/src/rpc/rawtransaction_util.cpp b/src/rpc/rawtransaction_util.cpp
index f21eddf56c..d550160260 100644
--- a/src/rpc/rawtransaction_util.cpp
+++ b/src/rpc/rawtransaction_util.cpp
@@ -6,6 +6,7 @@
#include <rpc/rawtransaction_util.h>
#include <coins.h>
+#include <consensus/amount.h>
#include <core_io.h>
#include <key_io.h>
#include <policy/policy.h>
diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp
index cf80b08b96..0d02ec5c47 100644
--- a/src/rpc/server.cpp
+++ b/src/rpc/server.cpp
@@ -540,7 +540,7 @@ void RPCRunLater(const std::string& name, std::function<void()> func, int64_t nS
int RPCSerializationFlags()
{
int flag = 0;
- if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) == 0)
+ if (gArgs.GetIntArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) == 0)
flag |= SERIALIZE_TRANSACTION_NO_WITNESS;
return flag;
}
diff --git a/src/rpc/server.h b/src/rpc/server.h
index 03967020c2..e6bb35fc33 100644
--- a/src/rpc/server.h
+++ b/src/rpc/server.h
@@ -6,7 +6,6 @@
#ifndef BITCOIN_RPC_SERVER_H
#define BITCOIN_RPC_SERVER_H
-#include <amount.h>
#include <rpc/request.h>
#include <rpc/util.h>
diff --git a/src/rpc/util.cpp b/src/rpc/util.cpp
index 2059628b54..2d7f5f2894 100644
--- a/src/rpc/util.cpp
+++ b/src/rpc/util.cpp
@@ -2,6 +2,7 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#include <consensus/amount.h>
#include <key_io.h>
#include <outputtype.h>
#include <rpc/util.h>
diff --git a/src/scheduler.cpp b/src/scheduler.cpp
index 02ada969a4..162cced6c7 100644
--- a/src/scheduler.cpp
+++ b/src/scheduler.cpp
@@ -5,6 +5,7 @@
#include <scheduler.h>
#include <random.h>
+#include <util/syscall_sandbox.h>
#include <util/time.h>
#include <assert.h>
@@ -24,6 +25,7 @@ CScheduler::~CScheduler()
void CScheduler::serviceQueue()
{
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::SCHEDULER);
WAIT_LOCK(newTaskMutex, lock);
++nThreadsServicingQueue;
diff --git a/src/script/sigcache.cpp b/src/script/sigcache.cpp
index 65867c1c14..6f911f4fe7 100644
--- a/src/script/sigcache.cpp
+++ b/src/script/sigcache.cpp
@@ -96,7 +96,7 @@ void InitSignatureCache()
{
// nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
// setup_bytes creates the minimum possible cache (2 elements).
- size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
+ size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetIntArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
size_t nElems = signatureCache.setup_bytes(nMaxCacheSize);
LogPrintf("Using %zu MiB out of %zu/2 requested for signature cache, able to store %zu elements\n",
(nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
diff --git a/src/script/sign.cpp b/src/script/sign.cpp
index b912b00365..4cb2125747 100644
--- a/src/script/sign.cpp
+++ b/src/script/sign.cpp
@@ -5,6 +5,7 @@
#include <script/sign.h>
+#include <consensus/amount.h>
#include <key.h>
#include <policy/policy.h>
#include <primitives/transaction.h>
diff --git a/src/script/standard.cpp b/src/script/standard.cpp
index 67a79a157c..d9656c781d 100644
--- a/src/script/standard.cpp
+++ b/src/script/standard.cpp
@@ -266,47 +266,6 @@ bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
assert(false);
}
-// TODO: from v23 ("addresses" and "reqSigs" deprecated) "ExtractDestinations" should be removed
-bool ExtractDestinations(const CScript& scriptPubKey, TxoutType& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet)
-{
- addressRet.clear();
- std::vector<valtype> vSolutions;
- typeRet = Solver(scriptPubKey, vSolutions);
- if (typeRet == TxoutType::NONSTANDARD) {
- return false;
- } else if (typeRet == TxoutType::NULL_DATA) {
- // This is data, not addresses
- return false;
- }
-
- if (typeRet == TxoutType::MULTISIG)
- {
- nRequiredRet = vSolutions.front()[0];
- for (unsigned int i = 1; i < vSolutions.size()-1; i++)
- {
- CPubKey pubKey(vSolutions[i]);
- if (!pubKey.IsValid())
- continue;
-
- CTxDestination address = PKHash(pubKey);
- addressRet.push_back(address);
- }
-
- if (addressRet.empty())
- return false;
- }
- else
- {
- nRequiredRet = 1;
- CTxDestination address;
- if (!ExtractDestination(scriptPubKey, address))
- return false;
- addressRet.push_back(address);
- }
-
- return true;
-}
-
namespace {
class CScriptVisitor
{
diff --git a/src/script/standard.h b/src/script/standard.h
index 78492733db..a8e57231bf 100644
--- a/src/script/standard.h
+++ b/src/script/standard.h
@@ -176,28 +176,12 @@ TxoutType Solver(const CScript& scriptPubKey, std::vector<std::vector<unsigned c
/**
* Parse a standard scriptPubKey for the destination address. Assigns result to
- * the addressRet parameter and returns true if successful. For multisig
- * scripts, instead use ExtractDestinations. Currently only works for P2PK,
+ * the addressRet parameter and returns true if successful. Currently only works for P2PK,
* P2PKH, P2SH, P2WPKH, and P2WSH scripts.
*/
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
/**
- * Parse a standard scriptPubKey with one or more destination addresses. For
- * multisig scripts, this populates the addressRet vector with the pubkey IDs
- * and nRequiredRet with the n required to spend. For other destinations,
- * addressRet is populated with a single value and nRequiredRet is set to 1.
- * Returns true if successful.
- *
- * Note: this function confuses destinations (a subset of CScripts that are
- * encodable as an address) with key identifiers (of keys involved in a
- * CScript), and its use should be phased out.
- *
- * TODO: from v23 ("addresses" and "reqSigs" deprecated) "ExtractDestinations" should be removed
- */
-bool ExtractDestinations(const CScript& scriptPubKey, TxoutType& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
-
-/**
* Generate a Bitcoin scriptPubKey for the given CTxDestination. Returns a P2PKH
* script for a CKeyID destination, a P2SH script for a CScriptID, and an empty
* script for CNoDestination.
diff --git a/src/signet.cpp b/src/signet.cpp
index 1ba8502287..aafd1999ee 100644
--- a/src/signet.cpp
+++ b/src/signet.cpp
@@ -141,7 +141,7 @@ bool CheckSignetBlockSolution(const CBlock& block, const Consensus::Params& cons
PrecomputedTransactionData txdata;
txdata.Init(signet_txs->m_to_sign, {signet_txs->m_to_spend.vout[0]});
- TransactionSignatureChecker sigcheck(&signet_txs->m_to_sign, /*nIn=*/ 0, /*amount=*/ signet_txs->m_to_spend.vout[0].nValue, txdata, MissingDataBehavior::ASSERT_FAIL);
+ TransactionSignatureChecker sigcheck(&signet_txs->m_to_sign, /* nInIn= */ 0, /* amountIn= */ signet_txs->m_to_spend.vout[0].nValue, txdata, MissingDataBehavior::ASSERT_FAIL);
if (!VerifyScript(scriptSig, signet_txs->m_to_spend.vout[0].scriptPubKey, &witness, BLOCK_SCRIPT_VERIFY_FLAGS, sigcheck)) {
LogPrint(BCLog::VALIDATION, "CheckSignetBlockSolution: Errors in block (block solution invalid)\n");
diff --git a/src/sync.cpp b/src/sync.cpp
index eace86d9dd..c9fd8e347e 100644
--- a/src/sync.cpp
+++ b/src/sync.cpp
@@ -9,7 +9,6 @@
#include <sync.h>
#include <logging.h>
-#include <logging/timer.h>
#include <tinyformat.h>
#include <util/strencodings.h>
#include <util/threadnames.h>
@@ -24,11 +23,6 @@
#include <utility>
#include <vector>
-void LockContention(const char* pszName, const char* pszFile, int nLine)
-{
- LOG_TIME_MICROS_WITH_CATEGORY(strprintf("%s, %s:%d", pszName, pszFile, nLine), BCLog::LOCK);
-}
-
#ifdef DEBUG_LOCKORDER
//
// Early deadlock detection.
@@ -103,27 +97,29 @@ static void potential_deadlock_detected(const LockPair& mismatch, const LockStac
LogPrintf("POTENTIAL DEADLOCK DETECTED\n");
LogPrintf("Previous lock order was:\n");
for (const LockStackItem& i : s1) {
+ std::string prefix{};
if (i.first == mismatch.first) {
- LogPrintf(" (1)"); /* Continued */
+ prefix = " (1)";
}
if (i.first == mismatch.second) {
- LogPrintf(" (2)"); /* Continued */
+ prefix = " (2)";
}
- LogPrintf(" %s\n", i.second.ToString());
+ LogPrintf("%s %s\n", prefix, i.second.ToString());
}
std::string mutex_a, mutex_b;
LogPrintf("Current lock order is:\n");
for (const LockStackItem& i : s2) {
+ std::string prefix{};
if (i.first == mismatch.first) {
- LogPrintf(" (1)"); /* Continued */
+ prefix = " (1)";
mutex_a = i.second.Name();
}
if (i.first == mismatch.second) {
- LogPrintf(" (2)"); /* Continued */
+ prefix = " (2)";
mutex_b = i.second.Name();
}
- LogPrintf(" %s\n", i.second.ToString());
+ LogPrintf("%s %s\n", prefix, i.second.ToString());
}
if (g_debug_lockorder_abort) {
tfm::format(std::cerr, "Assertion failed: detected inconsistent lock order for %s, details in debug log.\n", s2.back().second.ToString());
@@ -137,10 +133,11 @@ static void double_lock_detected(const void* mutex, const LockStack& lock_stack)
LogPrintf("DOUBLE LOCK DETECTED\n");
LogPrintf("Lock order:\n");
for (const LockStackItem& i : lock_stack) {
+ std::string prefix{};
if (i.first == mutex) {
- LogPrintf(" (*)"); /* Continued */
+ prefix = " (*)";
}
- LogPrintf(" %s\n", i.second.ToString());
+ LogPrintf("%s %s\n", prefix, i.second.ToString());
}
if (g_debug_lockorder_abort) {
tfm::format(std::cerr,
diff --git a/src/sync.h b/src/sync.h
index bf15c0b4eb..6ba63d5e4d 100644
--- a/src/sync.h
+++ b/src/sync.h
@@ -6,6 +6,8 @@
#ifndef BITCOIN_SYNC_H
#define BITCOIN_SYNC_H
+#include <logging.h>
+#include <logging/timer.h>
#include <threadsafety.h>
#include <util/macros.h>
@@ -126,9 +128,6 @@ using RecursiveMutex = AnnotatedMixin<std::recursive_mutex>;
/** Wrapped mutex: supports waiting but not recursive locking */
typedef AnnotatedMixin<std::mutex> Mutex;
-/** Prints a lock contention to the log */
-void LockContention(const char* pszName, const char* pszFile, int nLine);
-
/** Wrapper around std::unique_lock style lock for Mutex. */
template <typename Mutex, typename Base = typename Mutex::UniqueLock>
class SCOPED_LOCKABLE UniqueLock : public Base
@@ -138,7 +137,7 @@ private:
{
EnterCritical(pszName, pszFile, nLine, Base::mutex());
if (Base::try_lock()) return;
- LockContention(pszName, pszFile, nLine); // log the contention
+ LOG_TIME_MICROS_WITH_CATEGORY(strprintf("lock contention %s, %s:%d", pszName, pszFile, nLine), BCLog::LOCK);
Base::lock();
}
diff --git a/src/test/README.md b/src/test/README.md
index 57cda26d7c..d03411c3ed 100644
--- a/src/test/README.md
+++ b/src/test/README.md
@@ -74,3 +74,29 @@ start debugging, just like you would with any other program:
```bash
gdb src/test/test_bitcoin
```
+
+#### Segmentation faults
+
+If you hit a segmentation fault during a test run, you can diagnose where the fault
+is happening by running `gdb ./src/test/test_bitcoin` and then using the `bt` command
+within gdb.
+
+Another tool that can be used to resolve segmentation faults is
+[valgrind](https://valgrind.org/).
+
+If for whatever reason you want to produce a core dump file for this fault, you can do
+that as well. By default, the boost test runner will intercept system errors and not
+produce a core file. To bypass this, add `--catch_system_errors=no` to the
+`test_bitcoin` arguments and ensure that your ulimits are set properly (e.g. `ulimit -c
+unlimited`).
+
+Running the tests and hitting a segmentation fault should now produce a file called `core`
+(on Linux platforms, the file name will likely depend on the contents of
+`/proc/sys/kernel/core_pattern`).
+
+You can then explore the core dump using
+``` bash
+gdb src/test/test_bitcoin core
+
+(gbd) bt # produce a backtrace for where a segfault occurred
+```
diff --git a/src/test/addrman_tests.cpp b/src/test/addrman_tests.cpp
index e1b5df9502..bd6f470219 100644
--- a/src/test/addrman_tests.cpp
+++ b/src/test/addrman_tests.cpp
@@ -4,14 +4,16 @@
#include <addrdb.h>
#include <addrman.h>
+#include <addrman_impl.h>
#include <chainparams.h>
+#include <clientversion.h>
+#include <hash.h>
+#include <netbase.h>
+#include <random.h>
#include <test/data/asmap.raw.h>
#include <test/util/setup_common.h>
#include <util/asmap.h>
#include <util/string.h>
-#include <hash.h>
-#include <netbase.h>
-#include <random.h>
#include <boost/test/unit_test.hpp>
@@ -20,26 +22,26 @@
using namespace std::literals;
-class CAddrManSerializationMock : public CAddrMan
+class AddrManSerializationMock : public AddrMan
{
public:
virtual void Serialize(CDataStream& s) const = 0;
- CAddrManSerializationMock()
- : CAddrMan(/* asmap */ std::vector<bool>(), /* deterministic */ true, /* consistency_check_ratio */ 100)
+ AddrManSerializationMock()
+ : AddrMan(/* asmap */ std::vector<bool>(), /* deterministic */ true, /* consistency_check_ratio */ 100)
{}
};
-class CAddrManUncorrupted : public CAddrManSerializationMock
+class AddrManUncorrupted : public AddrManSerializationMock
{
public:
void Serialize(CDataStream& s) const override
{
- CAddrMan::Serialize(s);
+ AddrMan::Serialize(s);
}
};
-class CAddrManCorrupted : public CAddrManSerializationMock
+class AddrManCorrupted : public AddrManSerializationMock
{
public:
void Serialize(CDataStream& s) const override
@@ -60,12 +62,12 @@ public:
CAddress addr = CAddress(serv, NODE_NONE);
CNetAddr resolved;
BOOST_CHECK(LookupHost("252.2.2.2", resolved, false));
- CAddrInfo info = CAddrInfo(addr, resolved);
+ AddrInfo info = AddrInfo(addr, resolved);
s << info;
}
};
-static CDataStream AddrmanToStream(const CAddrManSerializationMock& _addrman)
+static CDataStream AddrmanToStream(const AddrManSerializationMock& _addrman)
{
CDataStream ssPeersIn(SER_DISK, CLIENT_VERSION);
ssPeersIn << Params().MessageStart();
@@ -75,44 +77,44 @@ static CDataStream AddrmanToStream(const CAddrManSerializationMock& _addrman)
return CDataStream(vchData, SER_DISK, CLIENT_VERSION);
}
-class CAddrManTest : public CAddrMan
+class AddrManTest : public AddrMan
{
private:
bool deterministic;
public:
- explicit CAddrManTest(bool makeDeterministic = true,
- std::vector<bool> asmap = std::vector<bool>())
- : CAddrMan(asmap, makeDeterministic, /* consistency_check_ratio */ 100)
+ explicit AddrManTest(bool makeDeterministic = true,
+ std::vector<bool> asmap = std::vector<bool>())
+ : AddrMan(asmap, makeDeterministic, /* consistency_check_ratio */ 100)
{
deterministic = makeDeterministic;
}
- CAddrInfo* Find(const CNetAddr& addr, int* pnId = nullptr)
+ AddrInfo* Find(const CNetAddr& addr, int* pnId = nullptr)
{
- LOCK(cs);
- return CAddrMan::Find(addr, pnId);
+ LOCK(m_impl->cs);
+ return m_impl->Find(addr, pnId);
}
- CAddrInfo* Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId = nullptr)
+ AddrInfo* Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId = nullptr)
{
- LOCK(cs);
- return CAddrMan::Create(addr, addrSource, pnId);
+ LOCK(m_impl->cs);
+ return m_impl->Create(addr, addrSource, pnId);
}
void Delete(int nId)
{
- LOCK(cs);
- CAddrMan::Delete(nId);
+ LOCK(m_impl->cs);
+ m_impl->Delete(nId);
}
// Used to test deserialization
std::pair<int, int> GetBucketAndEntry(const CAddress& addr)
{
- LOCK(cs);
- int nId = mapAddr[addr];
+ LOCK(m_impl->cs);
+ int nId = m_impl->mapAddr[addr];
for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; ++bucket) {
for (int entry = 0; entry < ADDRMAN_BUCKET_SIZE; ++entry) {
- if (nId == vvNew[bucket][entry]) {
+ if (nId == m_impl->vvNew[bucket][entry]) {
return std::pair<int, int>(bucket, entry);
}
}
@@ -164,20 +166,20 @@ BOOST_FIXTURE_TEST_SUITE(addrman_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(addrman_simple)
{
- auto addrman = std::make_unique<CAddrManTest>();
+ auto addrman = std::make_unique<AddrManTest>();
CNetAddr source = ResolveIP("252.2.2.2");
// Test: Does Addrman respond correctly when empty.
BOOST_CHECK_EQUAL(addrman->size(), 0U);
- CAddrInfo addr_null = addrman->Select();
+ auto addr_null = addrman->Select().first;
BOOST_CHECK_EQUAL(addr_null.ToString(), "[::]:0");
// Test: Does Addrman::Add work as expected.
CService addr1 = ResolveService("250.1.1.1", 8333);
BOOST_CHECK(addrman->Add({CAddress(addr1, NODE_NONE)}, source));
BOOST_CHECK_EQUAL(addrman->size(), 1U);
- CAddrInfo addr_ret1 = addrman->Select();
+ auto addr_ret1 = addrman->Select().first;
BOOST_CHECK_EQUAL(addr_ret1.ToString(), "250.1.1.1:8333");
// Test: Does IP address deduplication work correctly.
@@ -198,7 +200,7 @@ BOOST_AUTO_TEST_CASE(addrman_simple)
BOOST_CHECK(addrman->size() >= 1);
// Test: reset addrman and test AddrMan::Add multiple addresses works as expected
- addrman = std::make_unique<CAddrManTest>();
+ addrman = std::make_unique<AddrManTest>();
std::vector<CAddress> vAddr;
vAddr.push_back(CAddress(ResolveService("250.1.1.3", 8333), NODE_NONE));
vAddr.push_back(CAddress(ResolveService("250.1.1.4", 8333), NODE_NONE));
@@ -208,7 +210,7 @@ BOOST_AUTO_TEST_CASE(addrman_simple)
BOOST_AUTO_TEST_CASE(addrman_ports)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
CNetAddr source = ResolveIP("252.2.2.2");
@@ -222,7 +224,7 @@ BOOST_AUTO_TEST_CASE(addrman_ports)
CService addr1_port = ResolveService("250.1.1.1", 8334);
BOOST_CHECK(!addrman.Add({CAddress(addr1_port, NODE_NONE)}, source));
BOOST_CHECK_EQUAL(addrman.size(), 1U);
- CAddrInfo addr_ret2 = addrman.Select();
+ auto addr_ret2 = addrman.Select().first;
BOOST_CHECK_EQUAL(addr_ret2.ToString(), "250.1.1.1:8333");
// Test: Add same IP but diff port to tried table, it doesn't get added.
@@ -230,14 +232,14 @@ BOOST_AUTO_TEST_CASE(addrman_ports)
addrman.Good(CAddress(addr1_port, NODE_NONE));
BOOST_CHECK_EQUAL(addrman.size(), 1U);
bool newOnly = true;
- CAddrInfo addr_ret3 = addrman.Select(newOnly);
+ auto addr_ret3 = addrman.Select(newOnly).first;
BOOST_CHECK_EQUAL(addr_ret3.ToString(), "250.1.1.1:8333");
}
BOOST_AUTO_TEST_CASE(addrman_select)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
CNetAddr source = ResolveIP("252.2.2.2");
@@ -247,16 +249,16 @@ BOOST_AUTO_TEST_CASE(addrman_select)
BOOST_CHECK_EQUAL(addrman.size(), 1U);
bool newOnly = true;
- CAddrInfo addr_ret1 = addrman.Select(newOnly);
+ auto addr_ret1 = addrman.Select(newOnly).first;
BOOST_CHECK_EQUAL(addr_ret1.ToString(), "250.1.1.1:8333");
// Test: move addr to tried, select from new expected nothing returned.
addrman.Good(CAddress(addr1, NODE_NONE));
BOOST_CHECK_EQUAL(addrman.size(), 1U);
- CAddrInfo addr_ret2 = addrman.Select(newOnly);
+ auto addr_ret2 = addrman.Select(newOnly).first;
BOOST_CHECK_EQUAL(addr_ret2.ToString(), "[::]:0");
- CAddrInfo addr_ret3 = addrman.Select();
+ auto addr_ret3 = addrman.Select().first;
BOOST_CHECK_EQUAL(addr_ret3.ToString(), "250.1.1.1:8333");
BOOST_CHECK_EQUAL(addrman.size(), 1U);
@@ -289,14 +291,14 @@ BOOST_AUTO_TEST_CASE(addrman_select)
// Test: Select pulls from new and tried regardless of port number.
std::set<uint16_t> ports;
for (int i = 0; i < 20; ++i) {
- ports.insert(addrman.Select().GetPort());
+ ports.insert(addrman.Select().first.GetPort());
}
BOOST_CHECK_EQUAL(ports.size(), 3U);
}
BOOST_AUTO_TEST_CASE(addrman_new_collisions)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
CNetAddr source = ResolveIP("252.2.2.2");
@@ -325,7 +327,7 @@ BOOST_AUTO_TEST_CASE(addrman_new_collisions)
BOOST_AUTO_TEST_CASE(addrman_tried_collisions)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
CNetAddr source = ResolveIP("252.2.2.2");
@@ -355,7 +357,7 @@ BOOST_AUTO_TEST_CASE(addrman_tried_collisions)
BOOST_AUTO_TEST_CASE(addrman_find)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
BOOST_CHECK_EQUAL(addrman.size(), 0U);
@@ -371,24 +373,24 @@ BOOST_AUTO_TEST_CASE(addrman_find)
BOOST_CHECK(addrman.Add({addr3}, source1));
// Test: ensure Find returns an IP matching what we searched on.
- CAddrInfo* info1 = addrman.Find(addr1);
+ AddrInfo* info1 = addrman.Find(addr1);
BOOST_REQUIRE(info1);
BOOST_CHECK_EQUAL(info1->ToString(), "250.1.2.1:8333");
// Test 18; Find does not discriminate by port number.
- CAddrInfo* info2 = addrman.Find(addr2);
+ AddrInfo* info2 = addrman.Find(addr2);
BOOST_REQUIRE(info2);
BOOST_CHECK_EQUAL(info2->ToString(), info1->ToString());
// Test: Find returns another IP matching what we searched on.
- CAddrInfo* info3 = addrman.Find(addr3);
+ AddrInfo* info3 = addrman.Find(addr3);
BOOST_REQUIRE(info3);
BOOST_CHECK_EQUAL(info3->ToString(), "251.255.2.1:8333");
}
BOOST_AUTO_TEST_CASE(addrman_create)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
BOOST_CHECK_EQUAL(addrman.size(), 0U);
@@ -396,19 +398,19 @@ BOOST_AUTO_TEST_CASE(addrman_create)
CNetAddr source1 = ResolveIP("250.1.2.1");
int nId;
- CAddrInfo* pinfo = addrman.Create(addr1, source1, &nId);
+ AddrInfo* pinfo = addrman.Create(addr1, source1, &nId);
// Test: The result should be the same as the input addr.
BOOST_CHECK_EQUAL(pinfo->ToString(), "250.1.2.1:8333");
- CAddrInfo* info2 = addrman.Find(addr1);
+ AddrInfo* info2 = addrman.Find(addr1);
BOOST_CHECK_EQUAL(info2->ToString(), "250.1.2.1:8333");
}
BOOST_AUTO_TEST_CASE(addrman_delete)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
BOOST_CHECK_EQUAL(addrman.size(), 0U);
@@ -422,13 +424,13 @@ BOOST_AUTO_TEST_CASE(addrman_delete)
BOOST_CHECK_EQUAL(addrman.size(), 1U);
addrman.Delete(nId);
BOOST_CHECK_EQUAL(addrman.size(), 0U);
- CAddrInfo* info2 = addrman.Find(addr1);
+ AddrInfo* info2 = addrman.Find(addr1);
BOOST_CHECK(info2 == nullptr);
}
BOOST_AUTO_TEST_CASE(addrman_getaddr)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
// Test: Sanity check, GetAddr should never return anything if addrman
// is empty.
@@ -488,7 +490,7 @@ BOOST_AUTO_TEST_CASE(addrman_getaddr)
BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket_legacy)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
CAddress addr1 = CAddress(ResolveService("250.1.1.1", 8333), NODE_NONE);
CAddress addr2 = CAddress(ResolveService("250.1.1.1", 9999), NODE_NONE);
@@ -496,7 +498,7 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket_legacy)
CNetAddr source1 = ResolveIP("250.1.1.1");
- CAddrInfo info1 = CAddrInfo(addr1, source1);
+ AddrInfo info1 = AddrInfo(addr1, source1);
uint256 nKey1 = (uint256)(CHashWriter(SER_GETHASH, 0) << 1).GetHash();
uint256 nKey2 = (uint256)(CHashWriter(SER_GETHASH, 0) << 2).GetHash();
@@ -511,14 +513,14 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket_legacy)
// Test: Two addresses with same IP but different ports can map to
// different buckets because they have different keys.
- CAddrInfo info2 = CAddrInfo(addr2, source1);
+ AddrInfo info2 = AddrInfo(addr2, source1);
BOOST_CHECK(info1.GetKey() != info2.GetKey());
BOOST_CHECK(info1.GetTriedBucket(nKey1, asmap) != info2.GetTriedBucket(nKey1, asmap));
std::set<int> buckets;
for (int i = 0; i < 255; i++) {
- CAddrInfo infoi = CAddrInfo(
+ AddrInfo infoi = AddrInfo(
CAddress(ResolveService("250.1.1." + ToString(i)), NODE_NONE),
ResolveIP("250.1.1." + ToString(i)));
int bucket = infoi.GetTriedBucket(nKey1, asmap);
@@ -530,7 +532,7 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket_legacy)
buckets.clear();
for (int j = 0; j < 255; j++) {
- CAddrInfo infoj = CAddrInfo(
+ AddrInfo infoj = AddrInfo(
CAddress(ResolveService("250." + ToString(j) + ".1.1"), NODE_NONE),
ResolveIP("250." + ToString(j) + ".1.1"));
int bucket = infoj.GetTriedBucket(nKey1, asmap);
@@ -543,14 +545,14 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket_legacy)
BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket_legacy)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE);
CAddress addr2 = CAddress(ResolveService("250.1.2.1", 9999), NODE_NONE);
CNetAddr source1 = ResolveIP("250.1.2.1");
- CAddrInfo info1 = CAddrInfo(addr1, source1);
+ AddrInfo info1 = AddrInfo(addr1, source1);
uint256 nKey1 = (uint256)(CHashWriter(SER_GETHASH, 0) << 1).GetHash();
uint256 nKey2 = (uint256)(CHashWriter(SER_GETHASH, 0) << 2).GetHash();
@@ -566,13 +568,13 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket_legacy)
BOOST_CHECK(info1.GetNewBucket(nKey1, asmap) != info1.GetNewBucket(nKey2, asmap));
// Test: Ports should not affect bucket placement in the addr
- CAddrInfo info2 = CAddrInfo(addr2, source1);
+ AddrInfo info2 = AddrInfo(addr2, source1);
BOOST_CHECK(info1.GetKey() != info2.GetKey());
BOOST_CHECK_EQUAL(info1.GetNewBucket(nKey1, asmap), info2.GetNewBucket(nKey1, asmap));
std::set<int> buckets;
for (int i = 0; i < 255; i++) {
- CAddrInfo infoi = CAddrInfo(
+ AddrInfo infoi = AddrInfo(
CAddress(ResolveService("250.1.1." + ToString(i)), NODE_NONE),
ResolveIP("250.1.1." + ToString(i)));
int bucket = infoi.GetNewBucket(nKey1, asmap);
@@ -584,7 +586,7 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket_legacy)
buckets.clear();
for (int j = 0; j < 4 * 255; j++) {
- CAddrInfo infoj = CAddrInfo(CAddress(
+ AddrInfo infoj = AddrInfo(CAddress(
ResolveService(
ToString(250 + (j / 255)) + "." + ToString(j % 256) + ".1.1"), NODE_NONE),
ResolveIP("251.4.1.1"));
@@ -597,7 +599,7 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket_legacy)
buckets.clear();
for (int p = 0; p < 255; p++) {
- CAddrInfo infoj = CAddrInfo(
+ AddrInfo infoj = AddrInfo(
CAddress(ResolveService("250.1.1.1"), NODE_NONE),
ResolveIP("250." + ToString(p) + ".1.1"));
int bucket = infoj.GetNewBucket(nKey1, asmap);
@@ -621,7 +623,7 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket_legacy)
// 101.8.0.0/16 AS8
BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
CAddress addr1 = CAddress(ResolveService("250.1.1.1", 8333), NODE_NONE);
CAddress addr2 = CAddress(ResolveService("250.1.1.1", 9999), NODE_NONE);
@@ -629,7 +631,7 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket)
CNetAddr source1 = ResolveIP("250.1.1.1");
- CAddrInfo info1 = CAddrInfo(addr1, source1);
+ AddrInfo info1 = AddrInfo(addr1, source1);
uint256 nKey1 = (uint256)(CHashWriter(SER_GETHASH, 0) << 1).GetHash();
uint256 nKey2 = (uint256)(CHashWriter(SER_GETHASH, 0) << 2).GetHash();
@@ -644,14 +646,14 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket)
// Test: Two addresses with same IP but different ports can map to
// different buckets because they have different keys.
- CAddrInfo info2 = CAddrInfo(addr2, source1);
+ AddrInfo info2 = AddrInfo(addr2, source1);
BOOST_CHECK(info1.GetKey() != info2.GetKey());
BOOST_CHECK(info1.GetTriedBucket(nKey1, asmap) != info2.GetTriedBucket(nKey1, asmap));
std::set<int> buckets;
for (int j = 0; j < 255; j++) {
- CAddrInfo infoj = CAddrInfo(
+ AddrInfo infoj = AddrInfo(
CAddress(ResolveService("101." + ToString(j) + ".1.1"), NODE_NONE),
ResolveIP("101." + ToString(j) + ".1.1"));
int bucket = infoj.GetTriedBucket(nKey1, asmap);
@@ -663,7 +665,7 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket)
buckets.clear();
for (int j = 0; j < 255; j++) {
- CAddrInfo infoj = CAddrInfo(
+ AddrInfo infoj = AddrInfo(
CAddress(ResolveService("250." + ToString(j) + ".1.1"), NODE_NONE),
ResolveIP("250." + ToString(j) + ".1.1"));
int bucket = infoj.GetTriedBucket(nKey1, asmap);
@@ -676,14 +678,14 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket)
BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE);
CAddress addr2 = CAddress(ResolveService("250.1.2.1", 9999), NODE_NONE);
CNetAddr source1 = ResolveIP("250.1.2.1");
- CAddrInfo info1 = CAddrInfo(addr1, source1);
+ AddrInfo info1 = AddrInfo(addr1, source1);
uint256 nKey1 = (uint256)(CHashWriter(SER_GETHASH, 0) << 1).GetHash();
uint256 nKey2 = (uint256)(CHashWriter(SER_GETHASH, 0) << 2).GetHash();
@@ -699,13 +701,13 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket)
BOOST_CHECK(info1.GetNewBucket(nKey1, asmap) != info1.GetNewBucket(nKey2, asmap));
// Test: Ports should not affect bucket placement in the addr
- CAddrInfo info2 = CAddrInfo(addr2, source1);
+ AddrInfo info2 = AddrInfo(addr2, source1);
BOOST_CHECK(info1.GetKey() != info2.GetKey());
BOOST_CHECK_EQUAL(info1.GetNewBucket(nKey1, asmap), info2.GetNewBucket(nKey1, asmap));
std::set<int> buckets;
for (int i = 0; i < 255; i++) {
- CAddrInfo infoi = CAddrInfo(
+ AddrInfo infoi = AddrInfo(
CAddress(ResolveService("250.1.1." + ToString(i)), NODE_NONE),
ResolveIP("250.1.1." + ToString(i)));
int bucket = infoi.GetNewBucket(nKey1, asmap);
@@ -717,7 +719,7 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket)
buckets.clear();
for (int j = 0; j < 4 * 255; j++) {
- CAddrInfo infoj = CAddrInfo(CAddress(
+ AddrInfo infoj = AddrInfo(CAddress(
ResolveService(
ToString(250 + (j / 255)) + "." + ToString(j % 256) + ".1.1"), NODE_NONE),
ResolveIP("251.4.1.1"));
@@ -730,7 +732,7 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket)
buckets.clear();
for (int p = 0; p < 255; p++) {
- CAddrInfo infoj = CAddrInfo(
+ AddrInfo infoj = AddrInfo(
CAddress(ResolveService("250.1.1.1"), NODE_NONE),
ResolveIP("101." + ToString(p) + ".1.1"));
int bucket = infoj.GetNewBucket(nKey1, asmap);
@@ -742,7 +744,7 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket)
buckets.clear();
for (int p = 0; p < 255; p++) {
- CAddrInfo infoj = CAddrInfo(
+ AddrInfo infoj = AddrInfo(
CAddress(ResolveService("250.1.1.1"), NODE_NONE),
ResolveIP("250." + ToString(p) + ".1.1"));
int bucket = infoj.GetNewBucket(nKey1, asmap);
@@ -758,9 +760,9 @@ BOOST_AUTO_TEST_CASE(addrman_serialization)
{
std::vector<bool> asmap1 = FromBytes(asmap_raw, sizeof(asmap_raw) * 8);
- auto addrman_asmap1 = std::make_unique<CAddrManTest>(true, asmap1);
- auto addrman_asmap1_dup = std::make_unique<CAddrManTest>(true, asmap1);
- auto addrman_noasmap = std::make_unique<CAddrManTest>();
+ auto addrman_asmap1 = std::make_unique<AddrManTest>(true, asmap1);
+ auto addrman_asmap1_dup = std::make_unique<AddrManTest>(true, asmap1);
+ auto addrman_noasmap = std::make_unique<AddrManTest>();
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
CAddress addr = CAddress(ResolveService("250.1.1.1"), NODE_NONE);
@@ -790,8 +792,8 @@ BOOST_AUTO_TEST_CASE(addrman_serialization)
BOOST_CHECK(bucketAndEntry_asmap1.second != bucketAndEntry_noasmap.second);
// deserializing non-asmaped peers.dat to asmaped addrman
- addrman_asmap1 = std::make_unique<CAddrManTest>(true, asmap1);
- addrman_noasmap = std::make_unique<CAddrManTest>();
+ addrman_asmap1 = std::make_unique<AddrManTest>(true, asmap1);
+ addrman_noasmap = std::make_unique<AddrManTest>();
addrman_noasmap->Add({addr}, default_source);
stream << *addrman_noasmap;
stream >> *addrman_asmap1;
@@ -802,8 +804,8 @@ BOOST_AUTO_TEST_CASE(addrman_serialization)
BOOST_CHECK(bucketAndEntry_asmap1_deser.second == bucketAndEntry_asmap1_dup.second);
// used to map to different buckets, now maps to the same bucket.
- addrman_asmap1 = std::make_unique<CAddrManTest>(true, asmap1);
- addrman_noasmap = std::make_unique<CAddrManTest>();
+ addrman_asmap1 = std::make_unique<AddrManTest>(true, asmap1);
+ addrman_noasmap = std::make_unique<AddrManTest>();
CAddress addr1 = CAddress(ResolveService("250.1.1.1"), NODE_NONE);
CAddress addr2 = CAddress(ResolveService("250.2.1.1"), NODE_NONE);
addrman_noasmap->Add({addr, addr2}, default_source);
@@ -823,7 +825,7 @@ BOOST_AUTO_TEST_CASE(remove_invalid)
{
// Confirm that invalid addresses are ignored in unserialization.
- auto addrman = std::make_unique<CAddrManTest>();
+ auto addrman = std::make_unique<AddrManTest>();
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
const CAddress new1{ResolveService("5.5.5.5"), NODE_NONE};
@@ -855,19 +857,19 @@ BOOST_AUTO_TEST_CASE(remove_invalid)
BOOST_REQUIRE(pos + sizeof(tried2_raw_replacement) <= stream.size());
memcpy(stream.data() + pos, tried2_raw_replacement, sizeof(tried2_raw_replacement));
- addrman = std::make_unique<CAddrManTest>();
+ addrman = std::make_unique<AddrManTest>();
stream >> *addrman;
BOOST_CHECK_EQUAL(addrman->size(), 2);
}
BOOST_AUTO_TEST_CASE(addrman_selecttriedcollision)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
BOOST_CHECK(addrman.size() == 0);
// Empty addrman should return blank addrman info.
- BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
+ BOOST_CHECK(addrman.SelectTriedCollision().first.ToString() == "[::]:0");
// Add twenty two addresses.
CNetAddr source = ResolveIP("252.2.2.2");
@@ -878,7 +880,7 @@ BOOST_AUTO_TEST_CASE(addrman_selecttriedcollision)
// No collisions yet.
BOOST_CHECK(addrman.size() == i);
- BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
+ BOOST_CHECK(addrman.SelectTriedCollision().first.ToString() == "[::]:0");
}
// Ensure Good handles duplicates well.
@@ -887,14 +889,14 @@ BOOST_AUTO_TEST_CASE(addrman_selecttriedcollision)
addrman.Good(addr);
BOOST_CHECK(addrman.size() == 22);
- BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
+ BOOST_CHECK(addrman.SelectTriedCollision().first.ToString() == "[::]:0");
}
}
BOOST_AUTO_TEST_CASE(addrman_noevict)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
// Add 35 addresses.
CNetAddr source = ResolveIP("252.2.2.2");
@@ -905,7 +907,7 @@ BOOST_AUTO_TEST_CASE(addrman_noevict)
// No collision yet.
BOOST_CHECK(addrman.size() == i);
- BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
+ BOOST_CHECK(addrman.SelectTriedCollision().first.ToString() == "[::]:0");
}
// Collision between 36 and 19.
@@ -914,11 +916,11 @@ BOOST_AUTO_TEST_CASE(addrman_noevict)
addrman.Good(addr36);
BOOST_CHECK(addrman.size() == 36);
- BOOST_CHECK_EQUAL(addrman.SelectTriedCollision().ToString(), "250.1.1.19:0");
+ BOOST_CHECK_EQUAL(addrman.SelectTriedCollision().first.ToString(), "250.1.1.19:0");
// 36 should be discarded and 19 not evicted.
addrman.ResolveCollisions();
- BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
+ BOOST_CHECK(addrman.SelectTriedCollision().first.ToString() == "[::]:0");
// Lets create two collisions.
for (unsigned int i = 37; i < 59; i++) {
@@ -927,7 +929,7 @@ BOOST_AUTO_TEST_CASE(addrman_noevict)
addrman.Good(addr);
BOOST_CHECK(addrman.size() == i);
- BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
+ BOOST_CHECK(addrman.SelectTriedCollision().first.ToString() == "[::]:0");
}
// Cause a collision.
@@ -936,26 +938,26 @@ BOOST_AUTO_TEST_CASE(addrman_noevict)
addrman.Good(addr59);
BOOST_CHECK(addrman.size() == 59);
- BOOST_CHECK_EQUAL(addrman.SelectTriedCollision().ToString(), "250.1.1.10:0");
+ BOOST_CHECK_EQUAL(addrman.SelectTriedCollision().first.ToString(), "250.1.1.10:0");
// Cause a second collision.
BOOST_CHECK(!addrman.Add({CAddress(addr36, NODE_NONE)}, source));
addrman.Good(addr36);
BOOST_CHECK(addrman.size() == 59);
- BOOST_CHECK(addrman.SelectTriedCollision().ToString() != "[::]:0");
+ BOOST_CHECK(addrman.SelectTriedCollision().first.ToString() != "[::]:0");
addrman.ResolveCollisions();
- BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
+ BOOST_CHECK(addrman.SelectTriedCollision().first.ToString() == "[::]:0");
}
BOOST_AUTO_TEST_CASE(addrman_evictionworks)
{
- CAddrManTest addrman;
+ AddrManTest addrman;
BOOST_CHECK(addrman.size() == 0);
// Empty addrman should return blank addrman info.
- BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
+ BOOST_CHECK(addrman.SelectTriedCollision().first.ToString() == "[::]:0");
// Add 35 addresses
CNetAddr source = ResolveIP("252.2.2.2");
@@ -966,7 +968,7 @@ BOOST_AUTO_TEST_CASE(addrman_evictionworks)
// No collision yet.
BOOST_CHECK(addrman.size() == i);
- BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
+ BOOST_CHECK(addrman.SelectTriedCollision().first.ToString() == "[::]:0");
}
// Collision between 36 and 19.
@@ -975,7 +977,7 @@ BOOST_AUTO_TEST_CASE(addrman_evictionworks)
addrman.Good(addr);
BOOST_CHECK_EQUAL(addrman.size(), 36);
- CAddrInfo info = addrman.SelectTriedCollision();
+ auto info = addrman.SelectTriedCollision().first;
BOOST_CHECK_EQUAL(info.ToString(), "250.1.1.19:0");
// Ensure test of address fails, so that it is evicted.
@@ -983,28 +985,28 @@ BOOST_AUTO_TEST_CASE(addrman_evictionworks)
// Should swap 36 for 19.
addrman.ResolveCollisions();
- BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
+ BOOST_CHECK(addrman.SelectTriedCollision().first.ToString() == "[::]:0");
// If 36 was swapped for 19, then this should cause no collisions.
BOOST_CHECK(!addrman.Add({CAddress(addr, NODE_NONE)}, source));
addrman.Good(addr);
- BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
+ BOOST_CHECK(addrman.SelectTriedCollision().first.ToString() == "[::]:0");
// If we insert 19 it should collide with 36
CService addr19 = ResolveService("250.1.1.19");
BOOST_CHECK(!addrman.Add({CAddress(addr19, NODE_NONE)}, source));
addrman.Good(addr19);
- BOOST_CHECK_EQUAL(addrman.SelectTriedCollision().ToString(), "250.1.1.36:0");
+ BOOST_CHECK_EQUAL(addrman.SelectTriedCollision().first.ToString(), "250.1.1.36:0");
addrman.ResolveCollisions();
- BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
+ BOOST_CHECK(addrman.SelectTriedCollision().first.ToString() == "[::]:0");
}
-BOOST_AUTO_TEST_CASE(caddrdb_read)
+BOOST_AUTO_TEST_CASE(load_addrman)
{
- CAddrManUncorrupted addrmanUncorrupted;
+ AddrManUncorrupted addrmanUncorrupted;
CService addr1, addr2, addr3;
BOOST_CHECK(Lookup("250.7.1.1", addr1, 8333, false));
@@ -1023,7 +1025,7 @@ BOOST_AUTO_TEST_CASE(caddrdb_read)
// Test that the de-serialization does not throw an exception.
CDataStream ssPeers1 = AddrmanToStream(addrmanUncorrupted);
bool exceptionThrown = false;
- CAddrMan addrman1(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 100);
+ AddrMan addrman1(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 100);
BOOST_CHECK(addrman1.size() == 0);
try {
@@ -1037,24 +1039,24 @@ BOOST_AUTO_TEST_CASE(caddrdb_read)
BOOST_CHECK(addrman1.size() == 3);
BOOST_CHECK(exceptionThrown == false);
- // Test that CAddrDB::Read creates an addrman with the correct number of addrs.
+ // Test that ReadFromStream creates an addrman with the correct number of addrs.
CDataStream ssPeers2 = AddrmanToStream(addrmanUncorrupted);
- CAddrMan addrman2(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 100);
+ AddrMan addrman2(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 100);
BOOST_CHECK(addrman2.size() == 0);
- BOOST_CHECK(CAddrDB::Read(addrman2, ssPeers2));
+ ReadFromStream(addrman2, ssPeers2);
BOOST_CHECK(addrman2.size() == 3);
}
-BOOST_AUTO_TEST_CASE(caddrdb_read_corrupted)
+BOOST_AUTO_TEST_CASE(load_addrman_corrupted)
{
- CAddrManCorrupted addrmanCorrupted;
+ AddrManCorrupted addrmanCorrupted;
// Test that the de-serialization of corrupted addrman throws an exception.
CDataStream ssPeers1 = AddrmanToStream(addrmanCorrupted);
bool exceptionThrown = false;
- CAddrMan addrman1(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 100);
+ AddrMan addrman1(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 100);
BOOST_CHECK(addrman1.size() == 0);
try {
unsigned char pchMsgTmp[4];
@@ -1063,16 +1065,16 @@ BOOST_AUTO_TEST_CASE(caddrdb_read_corrupted)
} catch (const std::exception&) {
exceptionThrown = true;
}
- // Even through de-serialization failed addrman is not left in a clean state.
+ // Even though de-serialization failed addrman is not left in a clean state.
BOOST_CHECK(addrman1.size() == 1);
BOOST_CHECK(exceptionThrown);
- // Test that CAddrDB::Read fails if peers.dat is corrupt
+ // Test that ReadFromStream fails if peers.dat is corrupt
CDataStream ssPeers2 = AddrmanToStream(addrmanCorrupted);
- CAddrMan addrman2(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 100);
+ AddrMan addrman2(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 100);
BOOST_CHECK(addrman2.size() == 0);
- BOOST_CHECK(!CAddrDB::Read(addrman2, ssPeers2));
+ BOOST_CHECK_THROW(ReadFromStream(addrman2, ssPeers2), std::ios_base::failure);
}
diff --git a/src/test/amount_tests.cpp b/src/test/amount_tests.cpp
index 77b7758a17..114fe3907c 100644
--- a/src/test/amount_tests.cpp
+++ b/src/test/amount_tests.cpp
@@ -2,7 +2,7 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <amount.h>
+#include <consensus/amount.h>
#include <policy/feerate.h>
#include <limits>
diff --git a/src/test/bloom_tests.cpp b/src/test/bloom_tests.cpp
index 5a98558240..23ef2062ef 100644
--- a/src/test/bloom_tests.cpp
+++ b/src/test/bloom_tests.cpp
@@ -83,7 +83,7 @@ BOOST_AUTO_TEST_CASE(bloom_create_insert_key)
CBloomFilter filter(2, 0.001, 0, BLOOM_UPDATE_ALL);
filter.insert(vchPubKey);
uint160 hash = pubkey.GetID();
- filter.insert(std::vector<unsigned char>(hash.begin(), hash.end()));
+ filter.insert(hash);
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << filter;
diff --git a/src/test/data/README.md b/src/test/data/README.md
index 2463daa42a..a05d9c668b 100644
--- a/src/test/data/README.md
+++ b/src/test/data/README.md
@@ -8,5 +8,5 @@ License
The data files in this directory are distributed under the MIT software
license, see the accompanying file COPYING or
-http://www.opensource.org/licenses/mit-license.php.
+https://www.opensource.org/licenses/mit-license.php.
diff --git a/src/test/fuzz/addrman.cpp b/src/test/fuzz/addrman.cpp
index e95126a80f..8df3707fc9 100644
--- a/src/test/fuzz/addrman.cpp
+++ b/src/test/fuzz/addrman.cpp
@@ -4,8 +4,10 @@
#include <addrdb.h>
#include <addrman.h>
+#include <addrman_impl.h>
#include <chainparams.h>
#include <merkleblock.h>
+#include <random.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
@@ -23,111 +25,97 @@ void initialize_addrman()
SelectParams(CBaseChainParams::REGTEST);
}
-class CAddrManDeterministic : public CAddrMan
+FUZZ_TARGET_INIT(data_stream_addr_man, initialize_addrman)
{
-public:
- FuzzedDataProvider& m_fuzzed_data_provider;
-
- explicit CAddrManDeterministic(std::vector<bool> asmap, FuzzedDataProvider& fuzzed_data_provider)
- : CAddrMan(std::move(asmap), /* deterministic */ true, /* consistency_check_ratio */ 0)
- , m_fuzzed_data_provider(fuzzed_data_provider)
- {
- WITH_LOCK(cs, insecure_rand = FastRandomContext{ConsumeUInt256(fuzzed_data_provider)});
+ FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
+ CDataStream data_stream = ConsumeDataStream(fuzzed_data_provider);
+ AddrMan addr_man(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
+ try {
+ ReadFromStream(addr_man, data_stream);
+ } catch (const std::exception&) {
}
+}
- /**
- * Generate a random address. Always returns a valid address.
- */
- CNetAddr RandAddr() EXCLUSIVE_LOCKS_REQUIRED(cs)
- {
- CNetAddr addr;
- if (m_fuzzed_data_provider.remaining_bytes() > 1 && m_fuzzed_data_provider.ConsumeBool()) {
- addr = ConsumeNetAddr(m_fuzzed_data_provider);
- } else {
- // The networks [1..6] correspond to CNetAddr::BIP155Network (private).
- static const std::map<uint8_t, uint8_t> net_len_map = {{1, ADDR_IPV4_SIZE},
- {2, ADDR_IPV6_SIZE},
- {4, ADDR_TORV3_SIZE},
- {5, ADDR_I2P_SIZE},
- {6, ADDR_CJDNS_SIZE}};
- uint8_t net = insecure_rand.randrange(5) + 1; // [1..5]
- if (net == 3) {
- net = 6;
- }
-
- CDataStream s(SER_NETWORK, PROTOCOL_VERSION | ADDRV2_FORMAT);
+/**
+ * Generate a random address. Always returns a valid address.
+ */
+CNetAddr RandAddr(FuzzedDataProvider& fuzzed_data_provider, FastRandomContext& fast_random_context)
+{
+ CNetAddr addr;
+ if (fuzzed_data_provider.remaining_bytes() > 1 && fuzzed_data_provider.ConsumeBool()) {
+ addr = ConsumeNetAddr(fuzzed_data_provider);
+ } else {
+ // The networks [1..6] correspond to CNetAddr::BIP155Network (private).
+ static const std::map<uint8_t, uint8_t> net_len_map = {{1, ADDR_IPV4_SIZE},
+ {2, ADDR_IPV6_SIZE},
+ {4, ADDR_TORV3_SIZE},
+ {5, ADDR_I2P_SIZE},
+ {6, ADDR_CJDNS_SIZE}};
+ uint8_t net = fast_random_context.randrange(5) + 1; // [1..5]
+ if (net == 3) {
+ net = 6;
+ }
- s << net;
- s << insecure_rand.randbytes(net_len_map.at(net));
+ CDataStream s(SER_NETWORK, PROTOCOL_VERSION | ADDRV2_FORMAT);
- s >> addr;
- }
+ s << net;
+ s << fast_random_context.randbytes(net_len_map.at(net));
- // Return a dummy IPv4 5.5.5.5 if we generated an invalid address.
- if (!addr.IsValid()) {
- in_addr v4_addr = {};
- v4_addr.s_addr = 0x05050505;
- addr = CNetAddr{v4_addr};
- }
+ s >> addr;
+ }
- return addr;
+ // Return a dummy IPv4 5.5.5.5 if we generated an invalid address.
+ if (!addr.IsValid()) {
+ in_addr v4_addr = {};
+ v4_addr.s_addr = 0x05050505;
+ addr = CNetAddr{v4_addr};
}
- /**
- * Fill this addrman with lots of addresses from lots of sources.
- */
- void Fill()
- {
- LOCK(cs);
-
- // Add some of the addresses directly to the "tried" table.
-
- // 0, 1, 2, 3 corresponding to 0%, 100%, 50%, 33%
- const size_t n = m_fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 3);
-
- const size_t num_sources = m_fuzzed_data_provider.ConsumeIntegralInRange<size_t>(10, 50);
- CNetAddr prev_source;
- // Use insecure_rand inside the loops instead of m_fuzzed_data_provider because when
- // the latter is exhausted it just returns 0.
- for (size_t i = 0; i < num_sources; ++i) {
- const auto source = RandAddr();
- const size_t num_addresses = insecure_rand.randrange(500) + 1; // [1..500]
-
- for (size_t j = 0; j < num_addresses; ++j) {
- const auto addr = CAddress{CService{RandAddr(), 8333}, NODE_NETWORK};
- const auto time_penalty = insecure_rand.randrange(100000001);
-#if 1
- // 2.83 sec to fill.
- if (n > 0 && mapInfo.size() % n == 0 && mapAddr.find(addr) == mapAddr.end()) {
- // Add to the "tried" table (if the bucket slot is free).
- const CAddrInfo dummy{addr, source};
- const int bucket = dummy.GetTriedBucket(nKey, m_asmap);
- const int bucket_pos = dummy.GetBucketPosition(nKey, false, bucket);
- if (vvTried[bucket][bucket_pos] == -1) {
- int id;
- CAddrInfo* addr_info = Create(addr, source, &id);
- vvTried[bucket][bucket_pos] = id;
- addr_info->fInTried = true;
- ++nTried;
- }
- } else {
- // Add to the "new" table.
- Add_(addr, source, time_penalty);
- }
-#else
- // 261.91 sec to fill.
- Add_(addr, source, time_penalty);
- if (n > 0 && mapInfo.size() % n == 0) {
- Good_(addr, false, GetTime());
- }
-#endif
- // Add 10% of the addresses from more than one source.
- if (insecure_rand.randrange(10) == 0 && prev_source.IsValid()) {
- Add_(addr, prev_source, time_penalty);
- }
+ return addr;
+}
+
+/** Fill addrman with lots of addresses from lots of sources. */
+void FillAddrman(AddrMan& addrman, FuzzedDataProvider& fuzzed_data_provider)
+{
+ // Add a fraction of the addresses to the "tried" table.
+ // 0, 1, 2, 3 corresponding to 0%, 100%, 50%, 33%
+ const size_t n = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 3);
+
+ const size_t num_sources = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 50);
+ CNetAddr prev_source;
+ // Generate a FastRandomContext seed to use inside the loops instead of
+ // fuzzed_data_provider. When fuzzed_data_provider is exhausted it
+ // just returns 0.
+ FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)};
+ for (size_t i = 0; i < num_sources; ++i) {
+ const auto source = RandAddr(fuzzed_data_provider, fast_random_context);
+ const size_t num_addresses = fast_random_context.randrange(500) + 1; // [1..500]
+
+ for (size_t j = 0; j < num_addresses; ++j) {
+ const auto addr = CAddress{CService{RandAddr(fuzzed_data_provider, fast_random_context), 8333}, NODE_NETWORK};
+ const auto time_penalty = fast_random_context.randrange(100000001);
+ addrman.Add({addr}, source, time_penalty);
+
+ if (n > 0 && addrman.size() % n == 0) {
+ addrman.Good(addr, GetTime());
+ }
+
+ // Add 10% of the addresses from more than one source.
+ if (fast_random_context.randrange(10) == 0 && prev_source.IsValid()) {
+ addrman.Add({addr}, prev_source, time_penalty);
}
- prev_source = source;
}
+ prev_source = source;
+ }
+}
+
+class AddrManDeterministic : public AddrMan
+{
+public:
+ explicit AddrManDeterministic(std::vector<bool> asmap, FuzzedDataProvider& fuzzed_data_provider)
+ : AddrMan(std::move(asmap), /* deterministic */ true, /* consistency_check_ratio */ 0)
+ {
+ WITH_LOCK(m_impl->cs, m_impl->insecure_rand = FastRandomContext{ConsumeUInt256(fuzzed_data_provider)});
}
/**
@@ -137,46 +125,46 @@ public:
* - vvNew entries refer to the same addresses
* - vvTried entries refer to the same addresses
*/
- bool operator==(const CAddrManDeterministic& other)
+ bool operator==(const AddrManDeterministic& other)
{
- LOCK2(cs, other.cs);
+ LOCK2(m_impl->cs, other.m_impl->cs);
- if (mapInfo.size() != other.mapInfo.size() || nNew != other.nNew ||
- nTried != other.nTried) {
+ if (m_impl->mapInfo.size() != other.m_impl->mapInfo.size() || m_impl->nNew != other.m_impl->nNew ||
+ m_impl->nTried != other.m_impl->nTried) {
return false;
}
// Check that all values in `mapInfo` are equal to all values in `other.mapInfo`.
// Keys may be different.
- using CAddrInfoHasher = std::function<size_t(const CAddrInfo&)>;
- using CAddrInfoEq = std::function<bool(const CAddrInfo&, const CAddrInfo&)>;
+ using AddrInfoHasher = std::function<size_t(const AddrInfo&)>;
+ using AddrInfoEq = std::function<bool(const AddrInfo&, const AddrInfo&)>;
CNetAddrHash netaddr_hasher;
- CAddrInfoHasher addrinfo_hasher = [&netaddr_hasher](const CAddrInfo& a) {
+ AddrInfoHasher addrinfo_hasher = [&netaddr_hasher](const AddrInfo& a) {
return netaddr_hasher(static_cast<CNetAddr>(a)) ^ netaddr_hasher(a.source) ^
a.nLastSuccess ^ a.nAttempts ^ a.nRefCount ^ a.fInTried;
};
- CAddrInfoEq addrinfo_eq = [](const CAddrInfo& lhs, const CAddrInfo& rhs) {
+ AddrInfoEq addrinfo_eq = [](const AddrInfo& lhs, const AddrInfo& rhs) {
return static_cast<CNetAddr>(lhs) == static_cast<CNetAddr>(rhs) &&
lhs.source == rhs.source && lhs.nLastSuccess == rhs.nLastSuccess &&
lhs.nAttempts == rhs.nAttempts && lhs.nRefCount == rhs.nRefCount &&
lhs.fInTried == rhs.fInTried;
};
- using Addresses = std::unordered_set<CAddrInfo, CAddrInfoHasher, CAddrInfoEq>;
+ using Addresses = std::unordered_set<AddrInfo, AddrInfoHasher, AddrInfoEq>;
- const size_t num_addresses{mapInfo.size()};
+ const size_t num_addresses{m_impl->mapInfo.size()};
Addresses addresses{num_addresses, addrinfo_hasher, addrinfo_eq};
- for (const auto& [id, addr] : mapInfo) {
+ for (const auto& [id, addr] : m_impl->mapInfo) {
addresses.insert(addr);
}
Addresses other_addresses{num_addresses, addrinfo_hasher, addrinfo_eq};
- for (const auto& [id, addr] : other.mapInfo) {
+ for (const auto& [id, addr] : other.m_impl->mapInfo) {
other_addresses.insert(addr);
}
@@ -184,14 +172,14 @@ public:
return false;
}
- auto IdsReferToSameAddress = [&](int id, int other_id) EXCLUSIVE_LOCKS_REQUIRED(cs, other.cs) {
+ auto IdsReferToSameAddress = [&](int id, int other_id) EXCLUSIVE_LOCKS_REQUIRED(m_impl->cs, other.m_impl->cs) {
if (id == -1 && other_id == -1) {
return true;
}
if ((id == -1 && other_id != -1) || (id != -1 && other_id == -1)) {
return false;
}
- return mapInfo.at(id) == other.mapInfo.at(other_id);
+ return m_impl->mapInfo.at(id) == other.m_impl->mapInfo.at(other_id);
};
// Check that `vvNew` contains the same addresses as `other.vvNew`. Notice - `vvNew[i][j]`
@@ -199,7 +187,7 @@ public:
// themselves may differ between `vvNew` and `other.vvNew`.
for (size_t i = 0; i < ADDRMAN_NEW_BUCKET_COUNT; ++i) {
for (size_t j = 0; j < ADDRMAN_BUCKET_SIZE; ++j) {
- if (!IdsReferToSameAddress(vvNew[i][j], other.vvNew[i][j])) {
+ if (!IdsReferToSameAddress(m_impl->vvNew[i][j], other.m_impl->vvNew[i][j])) {
return false;
}
}
@@ -208,7 +196,7 @@ public:
// Same for `vvTried`.
for (size_t i = 0; i < ADDRMAN_TRIED_BUCKET_COUNT; ++i) {
for (size_t j = 0; j < ADDRMAN_BUCKET_SIZE; ++j) {
- if (!IdsReferToSameAddress(vvTried[i][j], other.vvTried[i][j])) {
+ if (!IdsReferToSameAddress(m_impl->vvTried[i][j], other.m_impl->vvTried[i][j])) {
return false;
}
}
@@ -221,7 +209,7 @@ public:
[[nodiscard]] inline std::vector<bool> ConsumeAsmap(FuzzedDataProvider& fuzzed_data_provider) noexcept
{
std::vector<bool> asmap = ConsumeRandomLengthBitVector(fuzzed_data_provider);
- if (!SanityCheckASMap(asmap)) asmap.clear();
+ if (!SanityCheckASMap(asmap, 128)) asmap.clear();
return asmap;
}
@@ -230,7 +218,7 @@ FUZZ_TARGET_INIT(addrman, initialize_addrman)
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
SetMockTime(ConsumeTime(fuzzed_data_provider));
std::vector<bool> asmap = ConsumeAsmap(fuzzed_data_provider);
- auto addr_man_ptr = std::make_unique<CAddrManDeterministic>(asmap, fuzzed_data_provider);
+ auto addr_man_ptr = std::make_unique<AddrManDeterministic>(asmap, fuzzed_data_provider);
if (fuzzed_data_provider.ConsumeBool()) {
const std::vector<uint8_t> serialized_data{ConsumeRandomLengthByteVector(fuzzed_data_provider)};
CDataStream ds(serialized_data, SER_DISK, INIT_PROTO_VERSION);
@@ -239,10 +227,10 @@ FUZZ_TARGET_INIT(addrman, initialize_addrman)
try {
ds >> *addr_man_ptr;
} catch (const std::ios_base::failure&) {
- addr_man_ptr = std::make_unique<CAddrManDeterministic>(asmap, fuzzed_data_provider);
+ addr_man_ptr = std::make_unique<AddrManDeterministic>(asmap, fuzzed_data_provider);
}
}
- CAddrManDeterministic& addr_man = *addr_man_ptr;
+ AddrManDeterministic& addr_man = *addr_man_ptr;
while (fuzzed_data_provider.ConsumeBool()) {
CallOneOf(
fuzzed_data_provider,
@@ -291,7 +279,7 @@ FUZZ_TARGET_INIT(addrman, initialize_addrman)
}
});
}
- const CAddrMan& const_addr_man{addr_man};
+ const AddrMan& const_addr_man{addr_man};
(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),
@@ -309,12 +297,12 @@ FUZZ_TARGET_INIT(addrman_serdeser, initialize_addrman)
SetMockTime(ConsumeTime(fuzzed_data_provider));
std::vector<bool> asmap = ConsumeAsmap(fuzzed_data_provider);
- CAddrManDeterministic addr_man1{asmap, fuzzed_data_provider};
- CAddrManDeterministic addr_man2{asmap, fuzzed_data_provider};
+ AddrManDeterministic addr_man1{asmap, fuzzed_data_provider};
+ AddrManDeterministic addr_man2{asmap, fuzzed_data_provider};
CDataStream data_stream(SER_NETWORK, PROTOCOL_VERSION);
- addr_man1.Fill();
+ FillAddrman(addr_man1, fuzzed_data_provider);
data_stream << addr_man1;
data_stream >> addr_man2;
assert(addr_man1 == addr_man2);
diff --git a/src/test/fuzz/asmap.cpp b/src/test/fuzz/asmap.cpp
index 4c5bc0cbf2..d402f8632c 100644
--- a/src/test/fuzz/asmap.cpp
+++ b/src/test/fuzz/asmap.cpp
@@ -4,6 +4,7 @@
#include <netaddress.h>
#include <test/fuzz/fuzz.h>
+#include <util/asmap.h>
#include <cstdint>
#include <vector>
@@ -42,7 +43,7 @@ FUZZ_TARGET(asmap)
asmap.push_back((buffer[1 + i] >> j) & 1);
}
}
- if (!SanityCheckASMap(asmap)) return;
+ if (!SanityCheckASMap(asmap, 128)) return;
const uint8_t* addr_data = buffer.data() + 1 + asmap_size;
CNetAddr net_addr;
diff --git a/src/test/fuzz/coins_view.cpp b/src/test/fuzz/coins_view.cpp
index bbdb2c6917..87e70861fa 100644
--- a/src/test/fuzz/coins_view.cpp
+++ b/src/test/fuzz/coins_view.cpp
@@ -2,10 +2,10 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <amount.h>
#include <chainparams.h>
#include <chainparamsbase.h>
#include <coins.h>
+#include <consensus/amount.h>
#include <consensus/tx_check.h>
#include <consensus/tx_verify.h>
#include <consensus/validation.h>
diff --git a/src/test/fuzz/connman.cpp b/src/test/fuzz/connman.cpp
index 01741103e4..d381345a0d 100644
--- a/src/test/fuzz/connman.cpp
+++ b/src/test/fuzz/connman.cpp
@@ -25,7 +25,7 @@ FUZZ_TARGET_INIT(connman, initialize_connman)
{
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
SetMockTime(ConsumeTime(fuzzed_data_provider));
- CAddrMan addrman(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
+ AddrMan addrman(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
CConnman connman{fuzzed_data_provider.ConsumeIntegral<uint64_t>(), fuzzed_data_provider.ConsumeIntegral<uint64_t>(), addrman, fuzzed_data_provider.ConsumeBool()};
CNetAddr random_netaddr;
CNode random_node = ConsumeNode(fuzzed_data_provider);
diff --git a/src/test/fuzz/data_stream.cpp b/src/test/fuzz/data_stream.cpp
deleted file mode 100644
index 8178878c30..0000000000
--- a/src/test/fuzz/data_stream.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2020-2021 The Bitcoin Core developers
-// Distributed under the MIT software license, see the accompanying
-// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-
-#include <addrman.h>
-#include <net.h>
-#include <test/fuzz/FuzzedDataProvider.h>
-#include <test/fuzz/fuzz.h>
-#include <test/fuzz/util.h>
-#include <test/util/setup_common.h>
-
-#include <cstdint>
-#include <vector>
-
-void initialize_data_stream_addr_man()
-{
- static const auto testing_setup = MakeNoLogFileContext<>();
-}
-
-FUZZ_TARGET_INIT(data_stream_addr_man, initialize_data_stream_addr_man)
-{
- FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
- CDataStream data_stream = ConsumeDataStream(fuzzed_data_provider);
- CAddrMan addr_man(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
- CAddrDB::Read(addr_man, data_stream);
-}
diff --git a/src/test/fuzz/deserialize.cpp b/src/test/fuzz/deserialize.cpp
index 83ae1680e3..a9325fa738 100644
--- a/src/test/fuzz/deserialize.cpp
+++ b/src/test/fuzz/deserialize.cpp
@@ -4,6 +4,7 @@
#include <addrdb.h>
#include <addrman.h>
+#include <addrman_impl.h>
#include <blockencodings.h>
#include <blockfilter.h>
#include <chain.h>
@@ -104,7 +105,7 @@ FUZZ_TARGET_DESERIALIZE(block_filter_deserialize, {
DeserializeFromFuzzingInput(buffer, block_filter);
})
FUZZ_TARGET_DESERIALIZE(addr_info_deserialize, {
- CAddrInfo addr_info;
+ AddrInfo addr_info;
DeserializeFromFuzzingInput(buffer, addr_info);
})
FUZZ_TARGET_DESERIALIZE(block_file_info_deserialize, {
@@ -188,7 +189,7 @@ FUZZ_TARGET_DESERIALIZE(blockmerkleroot, {
BlockMerkleRoot(block, &mutated);
})
FUZZ_TARGET_DESERIALIZE(addrman_deserialize, {
- CAddrMan am(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
+ AddrMan am(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
DeserializeFromFuzzingInput(buffer, am);
})
FUZZ_TARGET_DESERIALIZE(blockheader_deserialize, {
diff --git a/src/test/fuzz/fee_rate.cpp b/src/test/fuzz/fee_rate.cpp
index dff0e58000..a852f8fb60 100644
--- a/src/test/fuzz/fee_rate.cpp
+++ b/src/test/fuzz/fee_rate.cpp
@@ -2,7 +2,7 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <amount.h>
+#include <consensus/amount.h>
#include <policy/feerate.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
diff --git a/src/test/fuzz/fees.cpp b/src/test/fuzz/fees.cpp
index 61c7681bf9..b5a07c7ba3 100644
--- a/src/test/fuzz/fees.cpp
+++ b/src/test/fuzz/fees.cpp
@@ -2,7 +2,7 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <amount.h>
+#include <consensus/amount.h>
#include <policy/fees.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
diff --git a/src/test/fuzz/integer.cpp b/src/test/fuzz/integer.cpp
index 5d26529837..b6c40809e3 100644
--- a/src/test/fuzz/integer.cpp
+++ b/src/test/fuzz/integer.cpp
@@ -2,9 +2,9 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <amount.h>
#include <arith_uint256.h>
#include <compressor.h>
+#include <consensus/amount.h>
#include <consensus/merkle.h>
#include <core_io.h>
#include <crypto/common.h>
@@ -23,6 +23,7 @@
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <uint256.h>
+#include <univalue.h>
#include <util/check.h>
#include <util/moneystr.h>
#include <util/strencodings.h>
diff --git a/src/test/fuzz/locale.cpp b/src/test/fuzz/locale.cpp
index 5b1acae57b..4ad8123554 100644
--- a/src/test/fuzz/locale.cpp
+++ b/src/test/fuzz/locale.cpp
@@ -50,8 +50,6 @@ FUZZ_TARGET(locale)
const bool parseint32_without_locale = ParseInt32(random_string, &parseint32_out_without_locale);
int64_t parseint64_out_without_locale;
const bool parseint64_without_locale = ParseInt64(random_string, &parseint64_out_without_locale);
- const int64_t atoi64_without_locale = atoi64(random_string);
- const int atoi_without_locale = atoi(random_string);
const int64_t random_int64 = fuzzed_data_provider.ConsumeIntegral<int64_t>();
const std::string tostring_without_locale = ToString(random_int64);
// The variable `random_int32` is no longer used, but the harness still needs to
@@ -77,10 +75,6 @@ FUZZ_TARGET(locale)
if (parseint64_without_locale) {
assert(parseint64_out_without_locale == parseint64_out_with_locale);
}
- const int64_t atoi64_with_locale = atoi64(random_string);
- assert(atoi64_without_locale == atoi64_with_locale);
- const int atoi_with_locale = atoi(random_string);
- assert(atoi_without_locale == atoi_with_locale);
const std::string tostring_with_locale = ToString(random_int64);
assert(tostring_without_locale == tostring_with_locale);
const std::string strprintf_int_with_locale = strprintf("%d", random_int64);
diff --git a/src/test/fuzz/muhash.cpp b/src/test/fuzz/muhash.cpp
index 4ea9511870..8304e6fdb8 100644
--- a/src/test/fuzz/muhash.cpp
+++ b/src/test/fuzz/muhash.cpp
@@ -12,52 +12,47 @@
FUZZ_TARGET(muhash)
{
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
- std::vector<uint8_t> data = ConsumeRandomLengthByteVector(fuzzed_data_provider);
- std::vector<uint8_t> data2 = ConsumeRandomLengthByteVector(fuzzed_data_provider);
- if (data.empty()) {
- data.resize(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 4096), fuzzed_data_provider.ConsumeIntegral<uint8_t>());
- }
- if (data2.empty()) {
- data2.resize(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 4096), fuzzed_data_provider.ConsumeIntegral<uint8_t>());
- }
-
- data = ConsumeRandomLengthByteVector(fuzzed_data_provider);
- data2 = ConsumeRandomLengthByteVector(fuzzed_data_provider);
+ std::vector<uint8_t> data{ConsumeRandomLengthByteVector(fuzzed_data_provider)};
+ std::vector<uint8_t> data2{ConsumeRandomLengthByteVector(fuzzed_data_provider)};
MuHash3072 muhash;
- // Test that MuHash result is consistent independent of order of operations
muhash.Insert(data);
muhash.Insert(data2);
+ const std::string initial_state_hash{"dd5ad2a105c2d29495f577245c357409002329b9f4d6182c0af3dc2f462555c8"};
uint256 out;
- muhash.Finalize(out);
-
- muhash = MuHash3072();
- muhash.Insert(data2);
- muhash.Insert(data);
-
uint256 out2;
- muhash.Finalize(out2);
-
+ CallOneOf(
+ fuzzed_data_provider,
+ [&] {
+ // Test that MuHash result is consistent independent of order of operations
+ muhash.Finalize(out);
+
+ muhash = MuHash3072();
+ muhash.Insert(data2);
+ muhash.Insert(data);
+ muhash.Finalize(out2);
+ },
+ [&] {
+ // Test that multiplication with the initial state never changes the finalized result
+ muhash.Finalize(out);
+ MuHash3072 muhash3;
+ muhash3 *= muhash;
+ muhash3.Finalize(out2);
+ },
+ [&] {
+ // Test that dividing a MuHash by itself brings it back to it's initial state
+ muhash /= muhash;
+ muhash.Finalize(out);
+ out2 = uint256S(initial_state_hash);
+ },
+ [&] {
+ // Test that removing all added elements brings the object back to it's initial state
+ muhash.Remove(data);
+ muhash.Remove(data2);
+ muhash.Finalize(out);
+ out2 = uint256S(initial_state_hash);
+ });
assert(out == out2);
- MuHash3072 muhash3;
- muhash3 *= muhash;
- uint256 out3;
- muhash3.Finalize(out3);
- assert(out == out3);
-
- // Test that removing all added elements brings the object back to it's initial state
- muhash /= muhash;
- muhash.Finalize(out);
-
- MuHash3072 muhash2;
- muhash2.Finalize(out2);
-
- assert(out == out2);
-
- muhash3.Remove(data);
- muhash3.Remove(data2);
- muhash3.Finalize(out3);
- assert(out == out3);
}
diff --git a/src/test/fuzz/net.cpp b/src/test/fuzz/net.cpp
index ff0259c182..bd1bb79d0e 100644
--- a/src/test/fuzz/net.cpp
+++ b/src/test/fuzz/net.cpp
@@ -14,6 +14,7 @@
#include <test/fuzz/util.h>
#include <test/util/net.h>
#include <test/util/setup_common.h>
+#include <util/asmap.h>
#include <cstdint>
#include <optional>
@@ -38,12 +39,8 @@ FUZZ_TARGET_INIT(net, initialize_net)
node.CloseSocketDisconnect();
},
[&] {
- const std::vector<bool> asmap = ConsumeRandomLengthBitVector(fuzzed_data_provider);
- if (!SanityCheckASMap(asmap)) {
- return;
- }
CNodeStats stats;
- node.CopyStats(stats, asmap);
+ node.CopyStats(stats);
},
[&] {
const CNode* add_ref_node = node.AddRef();
diff --git a/src/test/fuzz/parse_numbers.cpp b/src/test/fuzz/parse_numbers.cpp
index 69e58c3f63..85fee062f0 100644
--- a/src/test/fuzz/parse_numbers.cpp
+++ b/src/test/fuzz/parse_numbers.cpp
@@ -14,9 +14,6 @@ FUZZ_TARGET(parse_numbers)
(void)ParseMoney(random_string);
- double d;
- (void)ParseDouble(random_string, &d);
-
uint8_t u8;
(void)ParseUInt8(random_string, &u8);
@@ -25,13 +22,13 @@ FUZZ_TARGET(parse_numbers)
int32_t i32;
(void)ParseInt32(random_string, &i32);
- (void)atoi(random_string);
+ (void)LocaleIndependentAtoi<int>(random_string);
uint32_t u32;
(void)ParseUInt32(random_string, &u32);
int64_t i64;
- (void)atoi64(random_string);
+ (void)LocaleIndependentAtoi<int64_t>(random_string);
(void)ParseFixedPoint(random_string, 3, &i64);
(void)ParseInt64(random_string, &i64);
diff --git a/src/test/fuzz/script.cpp b/src/test/fuzz/script.cpp
index 950ee45d1d..74c576322a 100644
--- a/src/test/fuzz/script.cpp
+++ b/src/test/fuzz/script.cpp
@@ -56,46 +56,8 @@ FUZZ_TARGET_INIT(script, initialize_script)
assert(script == decompressed_script);
}
- CTxDestination address;
- TxoutType type_ret;
- std::vector<CTxDestination> addresses;
- int required_ret;
- bool extract_destinations_ret = ExtractDestinations(script, type_ret, addresses, required_ret);
- bool extract_destination_ret = ExtractDestination(script, address);
- if (!extract_destinations_ret) {
- assert(!extract_destination_ret);
- if (type_ret == TxoutType::MULTISIG) {
- assert(addresses.empty() && required_ret == 0);
- } else {
- assert(type_ret == TxoutType::PUBKEY ||
- type_ret == TxoutType::NONSTANDARD ||
- type_ret == TxoutType::NULL_DATA);
- }
- } else {
- assert(required_ret >= 1 && required_ret <= 16);
- assert((unsigned long)required_ret == addresses.size());
- assert(type_ret == TxoutType::MULTISIG || required_ret == 1);
- }
- if (type_ret == TxoutType::NONSTANDARD || type_ret == TxoutType::NULL_DATA) {
- assert(!extract_destinations_ret);
- }
- if (!extract_destination_ret) {
- assert(type_ret == TxoutType::PUBKEY ||
- type_ret == TxoutType::NONSTANDARD ||
- type_ret == TxoutType::NULL_DATA ||
- type_ret == TxoutType::MULTISIG);
- } else {
- assert(address == addresses[0]);
- }
- if (type_ret == TxoutType::NONSTANDARD ||
- type_ret == TxoutType::NULL_DATA ||
- type_ret == TxoutType::MULTISIG) {
- assert(!extract_destination_ret);
- }
-
TxoutType which_type;
bool is_standard_ret = IsStandard(script, which_type);
- assert(type_ret == which_type);
if (!is_standard_ret) {
assert(which_type == TxoutType::NONSTANDARD ||
which_type == TxoutType::NULL_DATA ||
@@ -112,6 +74,20 @@ FUZZ_TARGET_INIT(script, initialize_script)
which_type == TxoutType::NONSTANDARD);
}
+ CTxDestination address;
+ bool extract_destination_ret = ExtractDestination(script, address);
+ if (!extract_destination_ret) {
+ assert(which_type == TxoutType::PUBKEY ||
+ which_type == TxoutType::NONSTANDARD ||
+ which_type == TxoutType::NULL_DATA ||
+ which_type == TxoutType::MULTISIG);
+ }
+ if (which_type == TxoutType::NONSTANDARD ||
+ which_type == TxoutType::NULL_DATA ||
+ which_type == TxoutType::MULTISIG) {
+ assert(!extract_destination_ret);
+ }
+
const FlatSigningProvider signing_provider;
(void)InferDescriptor(script, signing_provider);
(void)IsSegWitOutput(signing_provider, script);
@@ -133,15 +109,11 @@ FUZZ_TARGET_INIT(script, initialize_script)
(void)ScriptToAsmStr(script, true);
UniValue o1(UniValue::VOBJ);
- ScriptPubKeyToUniv(script, o1, true, true);
- ScriptPubKeyToUniv(script, o1, true, false);
+ ScriptPubKeyToUniv(script, o1, true);
UniValue o2(UniValue::VOBJ);
- ScriptPubKeyToUniv(script, o2, false, true);
- ScriptPubKeyToUniv(script, o2, false, false);
+ ScriptPubKeyToUniv(script, o2, false);
UniValue o3(UniValue::VOBJ);
- ScriptToUniv(script, o3, true);
- UniValue o4(UniValue::VOBJ);
- ScriptToUniv(script, o4, false);
+ ScriptToUniv(script, o3);
{
const std::vector<uint8_t> bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider);
diff --git a/src/test/fuzz/script_flags.cpp b/src/test/fuzz/script_flags.cpp
index 1278dc87d4..43927772ae 100644
--- a/src/test/fuzz/script_flags.cpp
+++ b/src/test/fuzz/script_flags.cpp
@@ -2,6 +2,7 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#include <consensus/amount.h>
#include <pubkey.h>
#include <script/interpreter.h>
#include <streams.h>
diff --git a/src/test/fuzz/string.cpp b/src/test/fuzz/string.cpp
index 0c1b45b86c..ab646c68fc 100644
--- a/src/test/fuzz/string.cpp
+++ b/src/test/fuzz/string.cpp
@@ -31,9 +31,105 @@
#include <version.h>
#include <cstdint>
+#include <cstdlib>
#include <string>
#include <vector>
+namespace {
+bool LegacyParsePrechecks(const std::string& str)
+{
+ if (str.empty()) // No empty string allowed
+ return false;
+ if (str.size() >= 1 && (IsSpace(str[0]) || IsSpace(str[str.size() - 1]))) // No padding allowed
+ return false;
+ if (!ValidAsCString(str)) // No embedded NUL characters allowed
+ return false;
+ return true;
+}
+
+bool LegacyParseInt32(const std::string& str, int32_t* out)
+{
+ if (!LegacyParsePrechecks(str))
+ return false;
+ char* endp = nullptr;
+ errno = 0; // strtol will not set errno if valid
+ long int n = strtol(str.c_str(), &endp, 10);
+ if (out) *out = (int32_t)n;
+ // Note that strtol returns a *long int*, so even if strtol doesn't report an over/underflow
+ // we still have to check that the returned value is within the range of an *int32_t*. On 64-bit
+ // platforms the size of these types may be different.
+ return endp && *endp == 0 && !errno &&
+ n >= std::numeric_limits<int32_t>::min() &&
+ n <= std::numeric_limits<int32_t>::max();
+}
+
+bool LegacyParseInt64(const std::string& str, int64_t* out)
+{
+ if (!LegacyParsePrechecks(str))
+ return false;
+ char* endp = nullptr;
+ errno = 0; // strtoll will not set errno if valid
+ long long int n = strtoll(str.c_str(), &endp, 10);
+ if (out) *out = (int64_t)n;
+ // Note that strtoll returns a *long long int*, so even if strtol doesn't report an over/underflow
+ // we still have to check that the returned value is within the range of an *int64_t*.
+ return endp && *endp == 0 && !errno &&
+ n >= std::numeric_limits<int64_t>::min() &&
+ n <= std::numeric_limits<int64_t>::max();
+}
+
+bool LegacyParseUInt32(const std::string& str, uint32_t* out)
+{
+ if (!LegacyParsePrechecks(str))
+ return false;
+ if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoul accepts these by default if they fit in the range
+ return false;
+ char* endp = nullptr;
+ errno = 0; // strtoul will not set errno if valid
+ unsigned long int n = strtoul(str.c_str(), &endp, 10);
+ if (out) *out = (uint32_t)n;
+ // Note that strtoul returns a *unsigned long int*, so even if it doesn't report an over/underflow
+ // we still have to check that the returned value is within the range of an *uint32_t*. On 64-bit
+ // platforms the size of these types may be different.
+ return endp && *endp == 0 && !errno &&
+ n <= std::numeric_limits<uint32_t>::max();
+}
+
+bool LegacyParseUInt8(const std::string& str, uint8_t* out)
+{
+ uint32_t u32;
+ if (!LegacyParseUInt32(str, &u32) || u32 > std::numeric_limits<uint8_t>::max()) {
+ return false;
+ }
+ if (out != nullptr) {
+ *out = static_cast<uint8_t>(u32);
+ }
+ return true;
+}
+
+bool LegacyParseUInt64(const std::string& str, uint64_t* out)
+{
+ if (!LegacyParsePrechecks(str))
+ return false;
+ if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoull accepts these by default if they fit in the range
+ return false;
+ char* endp = nullptr;
+ errno = 0; // strtoull will not set errno if valid
+ unsigned long long int n = strtoull(str.c_str(), &endp, 10);
+ if (out) *out = (uint64_t)n;
+ // Note that strtoull returns a *unsigned long long int*, so even if it doesn't report an over/underflow
+ // we still have to check that the returned value is within the range of an *uint64_t*.
+ return endp && *endp == 0 && !errno &&
+ n <= std::numeric_limits<uint64_t>::max();
+}
+
+// For backwards compatibility checking.
+int64_t atoi64_legacy(const std::string& str)
+{
+ return strtoll(str.c_str(), nullptr, 10);
+}
+}; // namespace
+
FUZZ_TARGET(string)
{
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
@@ -133,4 +229,67 @@ FUZZ_TARGET(string)
const bilingual_str bs2{random_string_2, random_string_1};
(void)(bs1 + bs2);
}
+ {
+ int32_t i32;
+ int64_t i64;
+ uint32_t u32;
+ uint64_t u64;
+ uint8_t u8;
+ const bool ok_i32 = ParseInt32(random_string_1, &i32);
+ const bool ok_i64 = ParseInt64(random_string_1, &i64);
+ const bool ok_u32 = ParseUInt32(random_string_1, &u32);
+ const bool ok_u64 = ParseUInt64(random_string_1, &u64);
+ const bool ok_u8 = ParseUInt8(random_string_1, &u8);
+
+ int32_t i32_legacy;
+ int64_t i64_legacy;
+ uint32_t u32_legacy;
+ uint64_t u64_legacy;
+ uint8_t u8_legacy;
+ const bool ok_i32_legacy = LegacyParseInt32(random_string_1, &i32_legacy);
+ const bool ok_i64_legacy = LegacyParseInt64(random_string_1, &i64_legacy);
+ const bool ok_u32_legacy = LegacyParseUInt32(random_string_1, &u32_legacy);
+ const bool ok_u64_legacy = LegacyParseUInt64(random_string_1, &u64_legacy);
+ const bool ok_u8_legacy = LegacyParseUInt8(random_string_1, &u8_legacy);
+
+ assert(ok_i32 == ok_i32_legacy);
+ assert(ok_i64 == ok_i64_legacy);
+ assert(ok_u32 == ok_u32_legacy);
+ assert(ok_u64 == ok_u64_legacy);
+ assert(ok_u8 == ok_u8_legacy);
+
+ if (ok_i32) {
+ assert(i32 == i32_legacy);
+ }
+ if (ok_i64) {
+ assert(i64 == i64_legacy);
+ }
+ if (ok_u32) {
+ assert(u32 == u32_legacy);
+ }
+ if (ok_u64) {
+ assert(u64 == u64_legacy);
+ }
+ if (ok_u8) {
+ assert(u8 == u8_legacy);
+ }
+ }
+
+ {
+ const int atoi_result = atoi(random_string_1.c_str());
+ const int locale_independent_atoi_result = LocaleIndependentAtoi<int>(random_string_1);
+ const int64_t atoi64_result = atoi64_legacy(random_string_1);
+ const bool out_of_range = atoi64_result < std::numeric_limits<int>::min() || atoi64_result > std::numeric_limits<int>::max();
+ if (out_of_range) {
+ assert(locale_independent_atoi_result == 0);
+ } else {
+ assert(atoi_result == locale_independent_atoi_result);
+ }
+ }
+
+ {
+ const int64_t atoi64_result = atoi64_legacy(random_string_1);
+ const int64_t locale_independent_atoi_result = LocaleIndependentAtoi<int64_t>(random_string_1);
+ assert(atoi64_result == locale_independent_atoi_result || locale_independent_atoi_result == 0);
+ }
}
diff --git a/src/test/fuzz/system.cpp b/src/test/fuzz/system.cpp
index 0f53939eac..dc3f9c8b8f 100644
--- a/src/test/fuzz/system.cpp
+++ b/src/test/fuzz/system.cpp
@@ -5,6 +5,7 @@
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
+#include <test/util/setup_common.h>
#include <util/system.h>
#include <cstdint>
@@ -12,6 +13,11 @@
#include <vector>
namespace {
+void initialize_system()
+{
+ static const auto testing_setup = MakeNoLogFileContext<>();
+}
+
std::string GetArgumentName(const std::string& name)
{
size_t idx = name.find('=');
@@ -20,9 +26,8 @@ std::string GetArgumentName(const std::string& name)
}
return name.substr(0, idx);
}
-} // namespace
-FUZZ_TARGET(system)
+FUZZ_TARGET_INIT(system, initialize_system)
{
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
ArgsManager args_manager{};
@@ -97,7 +102,7 @@ FUZZ_TARGET(system)
const int64_t i64 = fuzzed_data_provider.ConsumeIntegral<int64_t>();
const bool b = fuzzed_data_provider.ConsumeBool();
- (void)args_manager.GetArg(s1, i64);
+ (void)args_manager.GetIntArg(s1, i64);
(void)args_manager.GetArg(s1, s2);
(void)args_manager.GetArgFlags(s1);
(void)args_manager.GetArgs(s1);
@@ -114,3 +119,4 @@ FUZZ_TARGET(system)
(void)HelpRequested(args_manager);
}
+} // namespace
diff --git a/src/test/fuzz/transaction.cpp b/src/test/fuzz/transaction.cpp
index ff34cc87b2..a21e5cea0c 100644
--- a/src/test/fuzz/transaction.cpp
+++ b/src/test/fuzz/transaction.cpp
@@ -103,6 +103,6 @@ FUZZ_TARGET_INIT(transaction, initialize_transaction)
(void)IsWitnessStandard(tx, coins_view_cache);
UniValue u(UniValue::VOBJ);
- TxToUniv(tx, /* hashBlock */ uint256::ZERO, /* include_addresses */ true, u);
- TxToUniv(tx, /* hashBlock */ uint256::ONE, /* include_addresses */ false, u);
+ TxToUniv(tx, /* hashBlock */ uint256::ZERO, u);
+ TxToUniv(tx, /* hashBlock */ uint256::ONE, u);
}
diff --git a/src/test/fuzz/util.cpp b/src/test/fuzz/util.cpp
index 0d87f687d3..d83d2924bb 100644
--- a/src/test/fuzz/util.cpp
+++ b/src/test/fuzz/util.cpp
@@ -2,6 +2,7 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#include <consensus/amount.h>
#include <pubkey.h>
#include <test/fuzz/util.h>
#include <test/util/script.h>
diff --git a/src/test/fuzz/util.h b/src/test/fuzz/util.h
index bb017b3497..1bc6f1db45 100644
--- a/src/test/fuzz/util.h
+++ b/src/test/fuzz/util.h
@@ -5,12 +5,12 @@
#ifndef BITCOIN_TEST_FUZZ_UTIL_H
#define BITCOIN_TEST_FUZZ_UTIL_H
-#include <amount.h>
#include <arith_uint256.h>
#include <attributes.h>
#include <chainparamsbase.h>
#include <coins.h>
#include <compat.h>
+#include <consensus/amount.h>
#include <consensus/consensus.h>
#include <merkleblock.h>
#include <net.h>
diff --git a/src/test/fuzz/utxo_snapshot.cpp b/src/test/fuzz/utxo_snapshot.cpp
index 6f2bc081c6..8d2a06f11a 100644
--- a/src/test/fuzz/utxo_snapshot.cpp
+++ b/src/test/fuzz/utxo_snapshot.cpp
@@ -4,6 +4,7 @@
#include <chainparams.h>
#include <consensus/validation.h>
+#include <node/utxo_snapshot.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
diff --git a/src/test/fuzz/versionbits.cpp b/src/test/fuzz/versionbits.cpp
index 9186821836..73a7d24971 100644
--- a/src/test/fuzz/versionbits.cpp
+++ b/src/test/fuzz/versionbits.cpp
@@ -6,6 +6,7 @@
#include <chainparams.h>
#include <consensus/params.h>
#include <primitives/block.h>
+#include <util/system.h>
#include <versionbits.h>
#include <test/fuzz/FuzzedDataProvider.h>
diff --git a/src/test/getarg_tests.cpp b/src/test/getarg_tests.cpp
index 2a217f3455..17e904fcff 100644
--- a/src/test/getarg_tests.cpp
+++ b/src/test/getarg_tests.cpp
@@ -137,20 +137,20 @@ BOOST_AUTO_TEST_CASE(intarg)
const auto bar = std::make_pair("-bar", ArgsManager::ALLOW_ANY);
SetupArgs({foo, bar});
ResetArgs("");
- BOOST_CHECK_EQUAL(m_local_args.GetArg("-foo", 11), 11);
- BOOST_CHECK_EQUAL(m_local_args.GetArg("-foo", 0), 0);
+ BOOST_CHECK_EQUAL(m_local_args.GetIntArg("-foo", 11), 11);
+ BOOST_CHECK_EQUAL(m_local_args.GetIntArg("-foo", 0), 0);
ResetArgs("-foo -bar");
- BOOST_CHECK_EQUAL(m_local_args.GetArg("-foo", 11), 0);
- BOOST_CHECK_EQUAL(m_local_args.GetArg("-bar", 11), 0);
+ BOOST_CHECK_EQUAL(m_local_args.GetIntArg("-foo", 11), 0);
+ BOOST_CHECK_EQUAL(m_local_args.GetIntArg("-bar", 11), 0);
ResetArgs("-foo=11 -bar=12");
- BOOST_CHECK_EQUAL(m_local_args.GetArg("-foo", 0), 11);
- BOOST_CHECK_EQUAL(m_local_args.GetArg("-bar", 11), 12);
+ BOOST_CHECK_EQUAL(m_local_args.GetIntArg("-foo", 0), 11);
+ BOOST_CHECK_EQUAL(m_local_args.GetIntArg("-bar", 11), 12);
ResetArgs("-foo=NaN -bar=NotANumber");
- BOOST_CHECK_EQUAL(m_local_args.GetArg("-foo", 1), 0);
- BOOST_CHECK_EQUAL(m_local_args.GetArg("-bar", 11), 0);
+ BOOST_CHECK_EQUAL(m_local_args.GetIntArg("-foo", 1), 0);
+ BOOST_CHECK_EQUAL(m_local_args.GetIntArg("-bar", 11), 0);
}
BOOST_AUTO_TEST_CASE(doubledash)
@@ -163,7 +163,7 @@ BOOST_AUTO_TEST_CASE(doubledash)
ResetArgs("--foo=verbose --bar=1");
BOOST_CHECK_EQUAL(m_local_args.GetArg("-foo", ""), "verbose");
- BOOST_CHECK_EQUAL(m_local_args.GetArg("-bar", 0), 1);
+ BOOST_CHECK_EQUAL(m_local_args.GetIntArg("-bar", 0), 1);
}
BOOST_AUTO_TEST_CASE(boolargno)
diff --git a/src/test/logging_tests.cpp b/src/test/logging_tests.cpp
index e2e31c62d7..84ddbc50c6 100644
--- a/src/test/logging_tests.cpp
+++ b/src/test/logging_tests.cpp
@@ -15,9 +15,9 @@ BOOST_FIXTURE_TEST_SUITE(logging_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(logging_timer)
{
SetMockTime(1);
- auto sec_timer = BCLog::Timer<std::chrono::seconds>("tests", "end_msg");
+ auto micro_timer = BCLog::Timer<std::chrono::microseconds>("tests", "end_msg");
SetMockTime(2);
- BOOST_CHECK_EQUAL(sec_timer.LogMsg("test secs"), "tests: test secs (1.00s)");
+ BOOST_CHECK_EQUAL(micro_timer.LogMsg("test micros"), "tests: test micros (1000000μs)");
SetMockTime(1);
auto ms_timer = BCLog::Timer<std::chrono::milliseconds>("tests", "end_msg");
@@ -25,9 +25,9 @@ BOOST_AUTO_TEST_CASE(logging_timer)
BOOST_CHECK_EQUAL(ms_timer.LogMsg("test ms"), "tests: test ms (1000.00ms)");
SetMockTime(1);
- auto micro_timer = BCLog::Timer<std::chrono::microseconds>("tests", "end_msg");
+ auto sec_timer = BCLog::Timer<std::chrono::seconds>("tests", "end_msg");
SetMockTime(2);
- BOOST_CHECK_EQUAL(micro_timer.LogMsg("test micros"), "tests: test micros (1000000μs)");
+ BOOST_CHECK_EQUAL(sec_timer.LogMsg("test secs"), "tests: test secs (1.00s)");
}
BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/test/policy_fee_tests.cpp b/src/test/policy_fee_tests.cpp
index 4a15be6ca6..f9c7d04d6c 100644
--- a/src/test/policy_fee_tests.cpp
+++ b/src/test/policy_fee_tests.cpp
@@ -2,7 +2,7 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <amount.h>
+#include <consensus/amount.h>
#include <policy/fees.h>
#include <boost/test/unit_test.hpp>
diff --git a/src/test/script_parse_tests.cpp b/src/test/script_parse_tests.cpp
new file mode 100644
index 0000000000..5b8b6a725f
--- /dev/null
+++ b/src/test/script_parse_tests.cpp
@@ -0,0 +1,55 @@
+// Copyright (c) 2021 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include <core_io.h>
+#include <script/script.h>
+#include <util/strencodings.h>
+#include <test/util/setup_common.h>
+
+#include <boost/test/unit_test.hpp>
+
+BOOST_AUTO_TEST_SUITE(script_parse_tests)
+BOOST_AUTO_TEST_CASE(parse_script)
+{
+ const std::vector<std::pair<std::string,std::string>> IN_OUT{
+ // {IN: script string , OUT: hex string }
+ {"", ""},
+ {"0", "00"},
+ {"1", "51"},
+ {"2", "52"},
+ {"3", "53"},
+ {"4", "54"},
+ {"5", "55"},
+ {"6", "56"},
+ {"7", "57"},
+ {"8", "58"},
+ {"9", "59"},
+ {"10", "5a"},
+ {"11", "5b"},
+ {"12", "5c"},
+ {"13", "5d"},
+ {"14", "5e"},
+ {"15", "5f"},
+ {"16", "60"},
+ {"17", "0111"},
+ {"-9", "0189"},
+ {"0x17", "17"},
+ {"'17'", "023137"},
+ {"ELSE", "67"},
+ {"NOP10", "b9"},
+ {"11111111111111111111", "00"},
+ };
+ std::string all_in;
+ std::string all_out;
+ for (const auto& [in, out] : IN_OUT) {
+ BOOST_CHECK_EQUAL(HexStr(ParseScript(in)), out);
+ all_in += " " + in + " ";
+ all_out += out;
+ }
+ BOOST_CHECK_EQUAL(HexStr(ParseScript(all_in)), all_out);
+
+ BOOST_CHECK_EXCEPTION(ParseScript("11111111111"), std::runtime_error, HasReason("script parse error: decimal numeric value only allowed in the range -0xFFFFFFFF...0xFFFFFFFF"));
+ BOOST_CHECK_EXCEPTION(ParseScript("OP_CHECKSIGADD"), std::runtime_error, HasReason("script parse error: unknown opcode"));
+}
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/test/script_standard_tests.cpp b/src/test/script_standard_tests.cpp
index a01d3fa03a..bf8ff5f5e2 100644
--- a/src/test/script_standard_tests.cpp
+++ b/src/test/script_standard_tests.cpp
@@ -252,67 +252,6 @@ BOOST_AUTO_TEST_CASE(script_standard_ExtractDestination)
BOOST_CHECK(std::get<WitnessUnknown>(address) == unk);
}
-BOOST_AUTO_TEST_CASE(script_standard_ExtractDestinations)
-{
- CKey keys[3];
- CPubKey pubkeys[3];
- for (int i = 0; i < 3; i++) {
- keys[i].MakeNewKey(true);
- pubkeys[i] = keys[i].GetPubKey();
- }
-
- CScript s;
- TxoutType whichType;
- std::vector<CTxDestination> addresses;
- int nRequired;
-
- // TxoutType::PUBKEY
- s.clear();
- s << ToByteVector(pubkeys[0]) << OP_CHECKSIG;
- BOOST_CHECK(ExtractDestinations(s, whichType, addresses, nRequired));
- BOOST_CHECK_EQUAL(whichType, TxoutType::PUBKEY);
- BOOST_CHECK_EQUAL(addresses.size(), 1U);
- BOOST_CHECK_EQUAL(nRequired, 1);
- BOOST_CHECK(std::get<PKHash>(addresses[0]) == PKHash(pubkeys[0]));
-
- // TxoutType::PUBKEYHASH
- s.clear();
- s << OP_DUP << OP_HASH160 << ToByteVector(pubkeys[0].GetID()) << OP_EQUALVERIFY << OP_CHECKSIG;
- BOOST_CHECK(ExtractDestinations(s, whichType, addresses, nRequired));
- BOOST_CHECK_EQUAL(whichType, TxoutType::PUBKEYHASH);
- BOOST_CHECK_EQUAL(addresses.size(), 1U);
- BOOST_CHECK_EQUAL(nRequired, 1);
- BOOST_CHECK(std::get<PKHash>(addresses[0]) == PKHash(pubkeys[0]));
-
- // TxoutType::SCRIPTHASH
- CScript redeemScript(s); // initialize with leftover P2PKH script
- s.clear();
- s << OP_HASH160 << ToByteVector(CScriptID(redeemScript)) << OP_EQUAL;
- BOOST_CHECK(ExtractDestinations(s, whichType, addresses, nRequired));
- BOOST_CHECK_EQUAL(whichType, TxoutType::SCRIPTHASH);
- BOOST_CHECK_EQUAL(addresses.size(), 1U);
- BOOST_CHECK_EQUAL(nRequired, 1);
- BOOST_CHECK(std::get<ScriptHash>(addresses[0]) == ScriptHash(redeemScript));
-
- // TxoutType::MULTISIG
- s.clear();
- s << OP_2 <<
- ToByteVector(pubkeys[0]) <<
- ToByteVector(pubkeys[1]) <<
- OP_2 << OP_CHECKMULTISIG;
- BOOST_CHECK(ExtractDestinations(s, whichType, addresses, nRequired));
- BOOST_CHECK_EQUAL(whichType, TxoutType::MULTISIG);
- BOOST_CHECK_EQUAL(addresses.size(), 2U);
- BOOST_CHECK_EQUAL(nRequired, 2);
- BOOST_CHECK(std::get<PKHash>(addresses[0]) == PKHash(pubkeys[0]));
- BOOST_CHECK(std::get<PKHash>(addresses[1]) == PKHash(pubkeys[1]));
-
- // TxoutType::NULL_DATA
- s.clear();
- s << OP_RETURN << std::vector<unsigned char>({75});
- BOOST_CHECK(!ExtractDestinations(s, whichType, addresses, nRequired));
-}
-
BOOST_AUTO_TEST_CASE(script_standard_GetScriptFor_)
{
CKey keys[3];
diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp
index 24029ea02e..c813fbea32 100644
--- a/src/test/transaction_tests.cpp
+++ b/src/test/transaction_tests.cpp
@@ -8,6 +8,7 @@
#include <checkqueue.h>
#include <clientversion.h>
+#include <consensus/amount.h>
#include <consensus/tx_check.h>
#include <consensus/validation.h>
#include <core_io.h>
diff --git a/src/test/txvalidationcache_tests.cpp b/src/test/txvalidationcache_tests.cpp
index 1924ea55b1..afb3ad0cfd 100644
--- a/src/test/txvalidationcache_tests.cpp
+++ b/src/test/txvalidationcache_tests.cpp
@@ -13,6 +13,11 @@
#include <boost/test/unit_test.hpp>
+struct Dersig100Setup : public TestChain100Setup {
+ Dersig100Setup()
+ : TestChain100Setup{{"-testactivationheight=dersig@102"}} {}
+};
+
bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
const CCoinsViewCache& inputs, unsigned int flags, bool cacheSigStore,
bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
@@ -20,7 +25,7 @@ bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
BOOST_AUTO_TEST_SUITE(txvalidationcache_tests)
-BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, TestChain100Setup)
+BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, Dersig100Setup)
{
// Make sure skipping validation of transactions that were
// validated going into the memory pool does not allow
@@ -153,7 +158,7 @@ static void ValidateCheckInputsForAllFlags(const CTransaction &tx, uint32_t fail
}
}
-BOOST_FIXTURE_TEST_CASE(checkinputs_test, TestChain100Setup)
+BOOST_FIXTURE_TEST_CASE(checkinputs_test, Dersig100Setup)
{
// Test that passing CheckInputScripts with one set of script flags doesn't imply
// that we would pass again with a different set of flags.
diff --git a/src/test/util/chainstate.h b/src/test/util/chainstate.h
new file mode 100644
index 0000000000..81ea4c38f5
--- /dev/null
+++ b/src/test/util/chainstate.h
@@ -0,0 +1,54 @@
+// Copyright (c) 2021 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+//
+#ifndef BITCOIN_TEST_UTIL_CHAINSTATE_H
+#define BITCOIN_TEST_UTIL_CHAINSTATE_H
+
+#include <clientversion.h>
+#include <fs.h>
+#include <node/context.h>
+#include <node/utxo_snapshot.h>
+#include <rpc/blockchain.h>
+#include <validation.h>
+
+#include <univalue.h>
+
+#include <boost/test/unit_test.hpp>
+
+const auto NoMalleation = [](CAutoFile& file, SnapshotMetadata& meta){};
+
+/**
+ * Create and activate a UTXO snapshot, optionally providing a function to
+ * malleate the snapshot.
+ */
+template<typename F = decltype(NoMalleation)>
+static bool
+CreateAndActivateUTXOSnapshot(NodeContext& node, const fs::path root, F malleation = NoMalleation)
+{
+ // Write out a snapshot to the test's tempdir.
+ //
+ int height;
+ WITH_LOCK(::cs_main, height = node.chainman->ActiveHeight());
+ fs::path snapshot_path = root / tfm::format("test_snapshot.%d.dat", height);
+ FILE* outfile{fsbridge::fopen(snapshot_path, "wb")};
+ CAutoFile auto_outfile{outfile, SER_DISK, CLIENT_VERSION};
+
+ UniValue result = CreateUTXOSnapshot(node, node.chainman->ActiveChainstate(), auto_outfile);
+ BOOST_TEST_MESSAGE(
+ "Wrote UTXO snapshot to " << snapshot_path.make_preferred().string() << ": " << result.write());
+
+ // Read the written snapshot in and then activate it.
+ //
+ FILE* infile{fsbridge::fopen(snapshot_path, "rb")};
+ CAutoFile auto_infile{infile, SER_DISK, CLIENT_VERSION};
+ SnapshotMetadata metadata;
+ auto_infile >> metadata;
+
+ malleation(auto_infile, metadata);
+
+ return node.chainman->ActivateSnapshot(auto_infile, metadata, /*in_memory*/ true);
+}
+
+
+#endif // BITCOIN_TEST_UTIL_CHAINSTATE_H
diff --git a/src/test/util/setup_common.cpp b/src/test/util/setup_common.cpp
index ba6b3e32ea..ebefa9974e 100644
--- a/src/test/util/setup_common.cpp
+++ b/src/test/util/setup_common.cpp
@@ -114,7 +114,6 @@ BasicTestingSetup::BasicTestingSetup(const std::string& chainName, const std::ve
InitSignatureCache();
InitScriptExecutionCache();
m_node.chain = interfaces::MakeChain(m_node);
- g_wallet_init_interface.Construct(m_node);
fCheckBlockIndex = true;
static bool noui_connected = false;
if (!noui_connected) {
@@ -193,7 +192,7 @@ TestingSetup::TestingSetup(const std::string& chainName, const std::vector<const
throw std::runtime_error(strprintf("ActivateBestChain failed. (%s)", state.ToString()));
}
- m_node.addrman = std::make_unique<CAddrMan>(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
+ m_node.addrman = std::make_unique<AddrMan>(/* asmap */ std::vector<bool>(), /* deterministic */ false, /* consistency_check_ratio */ 0);
m_node.banman = std::make_unique<BanMan>(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME);
m_node.connman = std::make_unique<CConnman>(0x1337, 0x1337, *m_node.addrman); // Deterministic randomness for tests.
m_node.peerman = PeerManager::make(chainparams, *m_node.connman, *m_node.addrman,
@@ -206,7 +205,8 @@ TestingSetup::TestingSetup(const std::string& chainName, const std::vector<const
}
}
-TestChain100Setup::TestChain100Setup()
+TestChain100Setup::TestChain100Setup(const std::vector<const char*>& extra_args)
+ : TestingSetup{CBaseChainParams::REGTEST, extra_args}
{
SetMockTime(1598887952);
constexpr std::array<unsigned char, 32> vchKey = {
@@ -235,11 +235,14 @@ void TestChain100Setup::mineBlocks(int num_blocks)
}
}
-CBlock TestChain100Setup::CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns, const CScript& scriptPubKey)
+CBlock TestChain100Setup::CreateBlock(
+ const std::vector<CMutableTransaction>& txns,
+ const CScript& scriptPubKey,
+ CChainState& chainstate)
{
const CChainParams& chainparams = Params();
CTxMemPool empty_pool;
- CBlock block = BlockAssembler(m_node.chainman->ActiveChainstate(), empty_pool, chainparams).CreateNewBlock(scriptPubKey)->block;
+ CBlock block = BlockAssembler(chainstate, empty_pool, chainparams).CreateNewBlock(scriptPubKey)->block;
Assert(block.vtx.size() == 1);
for (const CMutableTransaction& tx : txns) {
@@ -249,6 +252,20 @@ CBlock TestChain100Setup::CreateAndProcessBlock(const std::vector<CMutableTransa
while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())) ++block.nNonce;
+ return block;
+}
+
+CBlock TestChain100Setup::CreateAndProcessBlock(
+ const std::vector<CMutableTransaction>& txns,
+ const CScript& scriptPubKey,
+ CChainState* chainstate)
+{
+ if (!chainstate) {
+ chainstate = &Assert(m_node.chainman)->ActiveChainstate();
+ }
+
+ const CChainParams& chainparams = Params();
+ const CBlock block = this->CreateBlock(txns, scriptPubKey, *chainstate);
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block);
Assert(m_node.chainman)->ProcessNewBlock(chainparams, shared_pblock, true, nullptr);
@@ -305,11 +322,6 @@ CMutableTransaction TestChain100Setup::CreateValidMempoolTransaction(CTransactio
return mempool_txn;
}
-TestChain100Setup::~TestChain100Setup()
-{
- gArgs.ForceSetArg("-segwitheight", "0");
-}
-
CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CMutableTransaction& tx) const
{
return FromTx(MakeTransactionRef(tx));
diff --git a/src/test/util/setup_common.h b/src/test/util/setup_common.h
index 5d12dc2323..7518cdb042 100644
--- a/src/test/util/setup_common.h
+++ b/src/test/util/setup_common.h
@@ -113,15 +113,26 @@ class CScript;
/**
* Testing fixture that pre-creates a 100-block REGTEST-mode block chain
*/
-struct TestChain100Setup : public RegTestingSetup {
- TestChain100Setup();
+struct TestChain100Setup : public TestingSetup {
+ TestChain100Setup(const std::vector<const char*>& extra_args = {});
/**
* Create a new block with just given transactions, coinbase paying to
* scriptPubKey, and try to add it to the current chain.
+ * If no chainstate is specified, default to the active.
*/
CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
- const CScript& scriptPubKey);
+ const CScript& scriptPubKey,
+ CChainState* chainstate = nullptr);
+
+ /**
+ * Create a new block with just given transactions, coinbase paying to
+ * scriptPubKey.
+ */
+ CBlock CreateBlock(
+ const std::vector<CMutableTransaction>& txns,
+ const CScript& scriptPubKey,
+ CChainState& chainstate);
//! Mine a series of new blocks on the active chain.
void mineBlocks(int num_blocks);
@@ -145,8 +156,6 @@ struct TestChain100Setup : public RegTestingSetup {
CAmount output_amount = CAmount(1 * COIN),
bool submit = true);
- ~TestChain100Setup();
-
std::vector<CTransactionRef> m_coinbase_txns; // For convenience, coinbase transactions
CKey coinbaseKey; // private/public key needed to spend coinbase transactions
};
diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp
index a62abf9b9c..b5088d3c33 100644
--- a/src/test/util_tests.cpp
+++ b/src/test/util_tests.cpp
@@ -300,9 +300,9 @@ public:
}
if (expect.default_int) {
- BOOST_CHECK_EQUAL(test.GetArg("-value", 99999), 99999);
+ BOOST_CHECK_EQUAL(test.GetIntArg("-value", 99999), 99999);
} else if (expect.int_value) {
- BOOST_CHECK_EQUAL(test.GetArg("-value", 99999), *expect.int_value);
+ BOOST_CHECK_EQUAL(test.GetIntArg("-value", 99999), *expect.int_value);
} else {
BOOST_CHECK(!success);
}
@@ -432,8 +432,8 @@ static void TestParse(const std::string& str, bool expected_bool, int64_t expect
BOOST_CHECK(test.ParseParameters(2, (char**)argv, error));
BOOST_CHECK_EQUAL(test.GetBoolArg("-value", false), expected_bool);
BOOST_CHECK_EQUAL(test.GetBoolArg("-value", true), expected_bool);
- BOOST_CHECK_EQUAL(test.GetArg("-value", 99998), expected_int);
- BOOST_CHECK_EQUAL(test.GetArg("-value", 99999), expected_int);
+ BOOST_CHECK_EQUAL(test.GetIntArg("-value", 99998), expected_int);
+ BOOST_CHECK_EQUAL(test.GetIntArg("-value", 99999), expected_int);
}
// Test bool and int parsing.
@@ -784,9 +784,9 @@ BOOST_AUTO_TEST_CASE(util_GetArg)
BOOST_CHECK_EQUAL(testArgs.GetArg("strtest1", "default"), "string...");
BOOST_CHECK_EQUAL(testArgs.GetArg("strtest2", "default"), "default");
- BOOST_CHECK_EQUAL(testArgs.GetArg("inttest1", -1), 12345);
- BOOST_CHECK_EQUAL(testArgs.GetArg("inttest2", -1), 81985529216486895LL);
- BOOST_CHECK_EQUAL(testArgs.GetArg("inttest3", -1), -1);
+ BOOST_CHECK_EQUAL(testArgs.GetIntArg("inttest1", -1), 12345);
+ BOOST_CHECK_EQUAL(testArgs.GetIntArg("inttest2", -1), 81985529216486895LL);
+ BOOST_CHECK_EQUAL(testArgs.GetIntArg("inttest3", -1), -1);
BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest1", false), true);
BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest2", false), false);
BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest3", false), false);
@@ -1239,6 +1239,11 @@ BOOST_AUTO_TEST_CASE(util_FormatMoney)
BOOST_AUTO_TEST_CASE(util_ParseMoney)
{
BOOST_CHECK_EQUAL(ParseMoney("0.0").value(), 0);
+ BOOST_CHECK_EQUAL(ParseMoney(".").value(), 0);
+ BOOST_CHECK_EQUAL(ParseMoney("0.").value(), 0);
+ BOOST_CHECK_EQUAL(ParseMoney(".0").value(), 0);
+ BOOST_CHECK_EQUAL(ParseMoney(".6789").value(), 6789'0000);
+ BOOST_CHECK_EQUAL(ParseMoney("12345.").value(), COIN * 12345);
BOOST_CHECK_EQUAL(ParseMoney("12345.6789").value(), (COIN/10000)*123456789);
@@ -1276,11 +1281,18 @@ BOOST_AUTO_TEST_CASE(util_ParseMoney)
BOOST_CHECK(!ParseMoney(" "));
// Parsing two numbers should fail
+ BOOST_CHECK(!ParseMoney(".."));
+ BOOST_CHECK(!ParseMoney("0..0"));
BOOST_CHECK(!ParseMoney("1 2"));
BOOST_CHECK(!ParseMoney(" 1 2 "));
BOOST_CHECK(!ParseMoney(" 1.2 3 "));
BOOST_CHECK(!ParseMoney(" 1 2.3 "));
+ // Embedded whitespace should fail
+ BOOST_CHECK(!ParseMoney(" -1 .2 "));
+ BOOST_CHECK(!ParseMoney(" 1 .2 "));
+ BOOST_CHECK(!ParseMoney(" +1 .2 "));
+
// Attempted 63 bit overflow should fail
BOOST_CHECK(!ParseMoney("92233720368.54775808"));
@@ -1474,6 +1486,168 @@ BOOST_AUTO_TEST_CASE(test_ParseInt32)
BOOST_CHECK(!ParseInt32("32482348723847471234", nullptr));
}
+template <typename T>
+static void RunToIntegralTests()
+{
+ BOOST_CHECK(!ToIntegral<T>(STRING_WITH_EMBEDDED_NULL_CHAR));
+ BOOST_CHECK(!ToIntegral<T>(" 1"));
+ BOOST_CHECK(!ToIntegral<T>("1 "));
+ BOOST_CHECK(!ToIntegral<T>("1a"));
+ BOOST_CHECK(!ToIntegral<T>("1.1"));
+ BOOST_CHECK(!ToIntegral<T>("1.9"));
+ BOOST_CHECK(!ToIntegral<T>("+01.9"));
+ BOOST_CHECK(!ToIntegral<T>("-"));
+ BOOST_CHECK(!ToIntegral<T>("+"));
+ BOOST_CHECK(!ToIntegral<T>(" -1"));
+ BOOST_CHECK(!ToIntegral<T>("-1 "));
+ BOOST_CHECK(!ToIntegral<T>(" -1 "));
+ BOOST_CHECK(!ToIntegral<T>("+1"));
+ BOOST_CHECK(!ToIntegral<T>(" +1"));
+ BOOST_CHECK(!ToIntegral<T>(" +1 "));
+ BOOST_CHECK(!ToIntegral<T>("+-1"));
+ BOOST_CHECK(!ToIntegral<T>("-+1"));
+ BOOST_CHECK(!ToIntegral<T>("++1"));
+ BOOST_CHECK(!ToIntegral<T>("--1"));
+ BOOST_CHECK(!ToIntegral<T>(""));
+ BOOST_CHECK(!ToIntegral<T>("aap"));
+ BOOST_CHECK(!ToIntegral<T>("0x1"));
+ BOOST_CHECK(!ToIntegral<T>("-32482348723847471234"));
+ BOOST_CHECK(!ToIntegral<T>("32482348723847471234"));
+}
+
+BOOST_AUTO_TEST_CASE(test_ToIntegral)
+{
+ BOOST_CHECK_EQUAL(ToIntegral<int32_t>("1234").value(), 1'234);
+ BOOST_CHECK_EQUAL(ToIntegral<int32_t>("0").value(), 0);
+ BOOST_CHECK_EQUAL(ToIntegral<int32_t>("01234").value(), 1'234);
+ BOOST_CHECK_EQUAL(ToIntegral<int32_t>("00000000000000001234").value(), 1'234);
+ BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-00000000000000001234").value(), -1'234);
+ BOOST_CHECK_EQUAL(ToIntegral<int32_t>("00000000000000000000").value(), 0);
+ BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-00000000000000000000").value(), 0);
+ BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-1234").value(), -1'234);
+ BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-1").value(), -1);
+
+ RunToIntegralTests<uint64_t>();
+ RunToIntegralTests<int64_t>();
+ RunToIntegralTests<uint32_t>();
+ RunToIntegralTests<int32_t>();
+ RunToIntegralTests<uint16_t>();
+ RunToIntegralTests<int16_t>();
+ RunToIntegralTests<uint8_t>();
+ RunToIntegralTests<int8_t>();
+
+ BOOST_CHECK(!ToIntegral<int64_t>("-9223372036854775809"));
+ BOOST_CHECK_EQUAL(ToIntegral<int64_t>("-9223372036854775808").value(), -9'223'372'036'854'775'807LL - 1LL);
+ BOOST_CHECK_EQUAL(ToIntegral<int64_t>("9223372036854775807").value(), 9'223'372'036'854'775'807);
+ BOOST_CHECK(!ToIntegral<int64_t>("9223372036854775808"));
+
+ BOOST_CHECK(!ToIntegral<uint64_t>("-1"));
+ BOOST_CHECK_EQUAL(ToIntegral<uint64_t>("0").value(), 0U);
+ BOOST_CHECK_EQUAL(ToIntegral<uint64_t>("18446744073709551615").value(), 18'446'744'073'709'551'615ULL);
+ BOOST_CHECK(!ToIntegral<uint64_t>("18446744073709551616"));
+
+ BOOST_CHECK(!ToIntegral<int32_t>("-2147483649"));
+ BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-2147483648").value(), -2'147'483'648LL);
+ BOOST_CHECK_EQUAL(ToIntegral<int32_t>("2147483647").value(), 2'147'483'647);
+ BOOST_CHECK(!ToIntegral<int32_t>("2147483648"));
+
+ BOOST_CHECK(!ToIntegral<uint32_t>("-1"));
+ BOOST_CHECK_EQUAL(ToIntegral<uint32_t>("0").value(), 0U);
+ BOOST_CHECK_EQUAL(ToIntegral<uint32_t>("4294967295").value(), 4'294'967'295U);
+ BOOST_CHECK(!ToIntegral<uint32_t>("4294967296"));
+
+ BOOST_CHECK(!ToIntegral<int16_t>("-32769"));
+ BOOST_CHECK_EQUAL(ToIntegral<int16_t>("-32768").value(), -32'768);
+ BOOST_CHECK_EQUAL(ToIntegral<int16_t>("32767").value(), 32'767);
+ BOOST_CHECK(!ToIntegral<int16_t>("32768"));
+
+ BOOST_CHECK(!ToIntegral<uint16_t>("-1"));
+ BOOST_CHECK_EQUAL(ToIntegral<uint16_t>("0").value(), 0U);
+ BOOST_CHECK_EQUAL(ToIntegral<uint16_t>("65535").value(), 65'535U);
+ BOOST_CHECK(!ToIntegral<uint16_t>("65536"));
+
+ BOOST_CHECK(!ToIntegral<int8_t>("-129"));
+ BOOST_CHECK_EQUAL(ToIntegral<int8_t>("-128").value(), -128);
+ BOOST_CHECK_EQUAL(ToIntegral<int8_t>("127").value(), 127);
+ BOOST_CHECK(!ToIntegral<int8_t>("128"));
+
+ BOOST_CHECK(!ToIntegral<uint8_t>("-1"));
+ BOOST_CHECK_EQUAL(ToIntegral<uint8_t>("0").value(), 0U);
+ BOOST_CHECK_EQUAL(ToIntegral<uint8_t>("255").value(), 255U);
+ BOOST_CHECK(!ToIntegral<uint8_t>("256"));
+}
+
+BOOST_AUTO_TEST_CASE(test_LocaleIndependentAtoi)
+{
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1234"), 1'234);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("0"), 0);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("01234"), 1'234);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-1234"), -1'234);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" 1"), 1);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1 "), 1);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1a"), 1);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1.1"), 1);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1.9"), 1);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("+01.9"), 1);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-1"), -1);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" -1"), -1);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-1 "), -1);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" -1 "), -1);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("+1"), 1);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" +1"), 1);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" +1 "), 1);
+
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("+-1"), 0);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-+1"), 0);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("++1"), 0);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("--1"), 0);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(""), 0);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("aap"), 0);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("0x1"), 0);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-32482348723847471234"), 0);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("32482348723847471234"), 0);
+
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("-9223372036854775809"), 0);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("-9223372036854775808"), -9'223'372'036'854'775'807LL - 1LL);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("9223372036854775807"), 9'223'372'036'854'775'807);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("9223372036854775808"), 0);
+
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("-1"), 0U);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("0"), 0U);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("18446744073709551615"), 18'446'744'073'709'551'615ULL);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("18446744073709551616"), 0U);
+
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-2147483649"), 0);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-2147483648"), -2'147'483'648LL);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("2147483647"), 2'147'483'647);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("2147483648"), 0);
+
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("-1"), 0U);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("0"), 0U);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("4294967295"), 4'294'967'295U);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("4294967296"), 0U);
+
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int16_t>("-32769"), 0);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int16_t>("-32768"), -32'768);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int16_t>("32767"), 32'767);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int16_t>("32768"), 0);
+
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint16_t>("-1"), 0U);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint16_t>("0"), 0U);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint16_t>("65535"), 65'535U);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint16_t>("65536"), 0U);
+
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int8_t>("-129"), 0);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int8_t>("-128"), -128);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int8_t>("127"), 127);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int8_t>("128"), 0);
+
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint8_t>("-1"), 0U);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint8_t>("0"), 0U);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint8_t>("255"), 255U);
+ BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint8_t>("256"), 0U);
+}
+
BOOST_AUTO_TEST_CASE(test_ParseInt64)
{
int64_t n;
@@ -1639,32 +1813,6 @@ BOOST_AUTO_TEST_CASE(test_ParseUInt64)
BOOST_CHECK(!ParseUInt64("-1234", &n));
}
-BOOST_AUTO_TEST_CASE(test_ParseDouble)
-{
- double n;
- // Valid values
- BOOST_CHECK(ParseDouble("1234", nullptr));
- BOOST_CHECK(ParseDouble("0", &n) && n == 0.0);
- BOOST_CHECK(ParseDouble("1234", &n) && n == 1234.0);
- BOOST_CHECK(ParseDouble("01234", &n) && n == 1234.0); // no octal
- BOOST_CHECK(ParseDouble("2147483647", &n) && n == 2147483647.0);
- BOOST_CHECK(ParseDouble("-2147483648", &n) && n == -2147483648.0);
- BOOST_CHECK(ParseDouble("-1234", &n) && n == -1234.0);
- BOOST_CHECK(ParseDouble("1e6", &n) && n == 1e6);
- BOOST_CHECK(ParseDouble("-1e6", &n) && n == -1e6);
- // Invalid values
- BOOST_CHECK(!ParseDouble("", &n));
- BOOST_CHECK(!ParseDouble(" 1", &n)); // no padding inside
- BOOST_CHECK(!ParseDouble("1 ", &n));
- BOOST_CHECK(!ParseDouble("1a", &n));
- BOOST_CHECK(!ParseDouble("aap", &n));
- BOOST_CHECK(!ParseDouble("0x1", &n)); // no hex
- BOOST_CHECK(!ParseDouble(STRING_WITH_EMBEDDED_NULL_CHAR, &n));
- // Overflow and underflow
- BOOST_CHECK(!ParseDouble("-1e10000", nullptr));
- BOOST_CHECK(!ParseDouble("1e10000", nullptr));
-}
-
BOOST_AUTO_TEST_CASE(test_FormatParagraph)
{
BOOST_CHECK_EQUAL(FormatParagraph("", 79, 0), "");
diff --git a/src/test/validation_chainstate_tests.cpp b/src/test/validation_chainstate_tests.cpp
index 315ef22599..726c9ebbb8 100644
--- a/src/test/validation_chainstate_tests.cpp
+++ b/src/test/validation_chainstate_tests.cpp
@@ -2,10 +2,13 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
+#include <chainparams.h>
#include <random.h>
#include <uint256.h>
#include <consensus/validation.h>
#include <sync.h>
+#include <rpc/blockchain.h>
+#include <test/util/chainstate.h>
#include <test/util/setup_common.h>
#include <validation.h>
@@ -73,4 +76,77 @@ BOOST_AUTO_TEST_CASE(validation_chainstate_resize_caches)
WITH_LOCK(::cs_main, manager.Unload());
}
+//! Test UpdateTip behavior for both active and background chainstates.
+//!
+//! When run on the background chainstate, UpdateTip should do a subset
+//! of what it does for the active chainstate.
+BOOST_FIXTURE_TEST_CASE(chainstate_update_tip, TestChain100Setup)
+{
+ ChainstateManager& chainman = *Assert(m_node.chainman);
+ uint256 curr_tip = ::g_best_block;
+
+ // Mine 10 more blocks, putting at us height 110 where a valid assumeutxo value can
+ // be found.
+ mineBlocks(10);
+
+ // After adding some blocks to the tip, best block should have changed.
+ BOOST_CHECK(::g_best_block != curr_tip);
+
+ BOOST_REQUIRE(CreateAndActivateUTXOSnapshot(m_node, m_path_root));
+
+ // Ensure our active chain is the snapshot chainstate.
+ BOOST_CHECK(chainman.IsSnapshotActive());
+
+ curr_tip = ::g_best_block;
+
+ // Mine a new block on top of the activated snapshot chainstate.
+ mineBlocks(1); // Defined in TestChain100Setup.
+
+ // After adding some blocks to the snapshot tip, best block should have changed.
+ BOOST_CHECK(::g_best_block != curr_tip);
+
+ curr_tip = ::g_best_block;
+
+ CChainState* background_cs;
+
+ BOOST_CHECK_EQUAL(chainman.GetAll().size(), 2);
+ for (CChainState* cs : chainman.GetAll()) {
+ if (cs != &chainman.ActiveChainstate()) {
+ background_cs = cs;
+ }
+ }
+ BOOST_CHECK(background_cs);
+
+ // Create a block to append to the validation chain.
+ std::vector<CMutableTransaction> noTxns;
+ CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
+ CBlock validation_block = this->CreateBlock(noTxns, scriptPubKey, *background_cs);
+ auto pblock = std::make_shared<const CBlock>(validation_block);
+ BlockValidationState state;
+ CBlockIndex* pindex = nullptr;
+ const CChainParams& chainparams = Params();
+ bool newblock = false;
+
+ // TODO: much of this is inlined from ProcessNewBlock(); just reuse PNB()
+ // once it is changed to support multiple chainstates.
+ {
+ LOCK(::cs_main);
+ bool checked = CheckBlock(*pblock, state, chainparams.GetConsensus());
+ BOOST_CHECK(checked);
+ bool accepted = background_cs->AcceptBlock(
+ pblock, state, &pindex, true, nullptr, &newblock);
+ BOOST_CHECK(accepted);
+ }
+ // UpdateTip is called here
+ bool block_added = background_cs->ActivateBestChain(state, pblock);
+
+ // Ensure tip is as expected
+ BOOST_CHECK_EQUAL(background_cs->m_chain.Tip()->GetBlockHash(), validation_block.GetHash());
+
+ // g_best_block should be unchanged after adding a block to the background
+ // validation chain.
+ BOOST_CHECK(block_added);
+ BOOST_CHECK_EQUAL(curr_tip, ::g_best_block);
+}
+
BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/test/validation_chainstatemanager_tests.cpp b/src/test/validation_chainstatemanager_tests.cpp
index 0bd378631b..be9e05a65e 100644
--- a/src/test/validation_chainstatemanager_tests.cpp
+++ b/src/test/validation_chainstatemanager_tests.cpp
@@ -8,13 +8,13 @@
#include <random.h>
#include <rpc/blockchain.h>
#include <sync.h>
+#include <test/util/chainstate.h>
#include <test/util/setup_common.h>
#include <uint256.h>
#include <validation.h>
#include <validationinterface.h>
#include <tinyformat.h>
-#include <univalue.h>
#include <vector>
@@ -44,7 +44,6 @@ BOOST_AUTO_TEST_CASE(chainstatemanager)
BOOST_CHECK(!manager.IsSnapshotActive());
BOOST_CHECK(!manager.IsSnapshotValidated());
- BOOST_CHECK(!manager.IsBackgroundIBD(&c1));
auto all = manager.GetAll();
BOOST_CHECK_EQUAL_COLLECTIONS(all.begin(), all.end(), chainstates.begin(), chainstates.end());
@@ -57,9 +56,6 @@ BOOST_AUTO_TEST_CASE(chainstatemanager)
auto exp_tip = c1.m_chain.Tip();
BOOST_CHECK_EQUAL(active_tip, exp_tip);
- auto& validated_cs = manager.ValidatedChainstate();
- BOOST_CHECK_EQUAL(&validated_cs, &c1);
-
BOOST_CHECK(!manager.SnapshotBlockhash().has_value());
// Create a snapshot-based chainstate.
@@ -81,8 +77,8 @@ BOOST_AUTO_TEST_CASE(chainstatemanager)
BOOST_CHECK(manager.IsSnapshotActive());
BOOST_CHECK(!manager.IsSnapshotValidated());
- BOOST_CHECK(manager.IsBackgroundIBD(&c1));
- BOOST_CHECK(!manager.IsBackgroundIBD(&c2));
+ BOOST_CHECK_EQUAL(&c2, &manager.ActiveChainstate());
+ BOOST_CHECK(&c1 != &manager.ActiveChainstate());
auto all2 = manager.GetAll();
BOOST_CHECK_EQUAL_COLLECTIONS(all2.begin(), all2.end(), chainstates.begin(), chainstates.end());
@@ -99,16 +95,6 @@ BOOST_AUTO_TEST_CASE(chainstatemanager)
// CCoinsViewCache instances.
BOOST_CHECK(exp_tip != exp_tip2);
- auto& validated_cs2 = manager.ValidatedChainstate();
- BOOST_CHECK_EQUAL(&validated_cs2, &c1);
-
- auto& validated_chain = manager.ValidatedChain();
- BOOST_CHECK_EQUAL(&validated_chain, &c1.m_chain);
-
- auto validated_tip = manager.ValidatedTip();
- exp_tip = c1.m_chain.Tip();
- BOOST_CHECK_EQUAL(validated_tip, exp_tip);
-
// Let scheduler events finish running to avoid accessing memory that is going to be unloaded
SyncWithValidationInterfaceQueue();
@@ -168,36 +154,6 @@ BOOST_AUTO_TEST_CASE(chainstatemanager_rebalance_caches)
BOOST_CHECK_CLOSE(c2.m_coinsdb_cache_size_bytes, max_cache * 0.95, 1);
}
-auto NoMalleation = [](CAutoFile& file, SnapshotMetadata& meta){};
-
-template<typename F = decltype(NoMalleation)>
-static bool
-CreateAndActivateUTXOSnapshot(NodeContext& node, const fs::path root, F malleation = NoMalleation)
-{
- // Write out a snapshot to the test's tempdir.
- //
- int height;
- WITH_LOCK(::cs_main, height = node.chainman->ActiveHeight());
- fs::path snapshot_path = root / tfm::format("test_snapshot.%d.dat", height);
- FILE* outfile{fsbridge::fopen(snapshot_path, "wb")};
- CAutoFile auto_outfile{outfile, SER_DISK, CLIENT_VERSION};
-
- UniValue result = CreateUTXOSnapshot(node, node.chainman->ActiveChainstate(), auto_outfile);
- BOOST_TEST_MESSAGE(
- "Wrote UTXO snapshot to " << snapshot_path.make_preferred().string() << ": " << result.write());
-
- // Read the written snapshot in and then activate it.
- //
- FILE* infile{fsbridge::fopen(snapshot_path, "rb")};
- CAutoFile auto_infile{infile, SER_DISK, CLIENT_VERSION};
- SnapshotMetadata metadata;
- auto_infile >> metadata;
-
- malleation(auto_infile, metadata);
-
- return node.chainman->ActivateSnapshot(auto_infile, metadata, /*in_memory*/ true);
-}
-
//! Test basic snapshot activation.
BOOST_FIXTURE_TEST_CASE(chainstatemanager_activate_snapshot, TestChain100Setup)
{
@@ -321,27 +277,27 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_activate_snapshot, TestChain100Setup)
{
LOCK(::cs_main);
size_t coins_in_active{0};
- size_t coins_in_ibd{0};
- size_t coins_missing_ibd{0};
+ size_t coins_in_background{0};
+ size_t coins_missing_from_background{0};
for (CChainState* chainstate : chainman.GetAll()) {
BOOST_TEST_MESSAGE("Checking coins in " << chainstate->ToString());
CCoinsViewCache& coinscache = chainstate->CoinsTip();
- bool is_ibd = chainman.IsBackgroundIBD(chainstate);
+ bool is_background = chainstate != &chainman.ActiveChainstate();
for (CTransactionRef& txn : m_coinbase_txns) {
COutPoint op{txn->GetHash(), 0};
if (coinscache.HaveCoin(op)) {
- (is_ibd ? coins_in_ibd : coins_in_active)++;
- } else if (is_ibd) {
- coins_missing_ibd++;
+ (is_background ? coins_in_background : coins_in_active)++;
+ } else if (is_background) {
+ coins_missing_from_background++;
}
}
}
BOOST_CHECK_EQUAL(coins_in_active, initial_total_coins + new_coins);
- BOOST_CHECK_EQUAL(coins_in_ibd, initial_total_coins);
- BOOST_CHECK_EQUAL(coins_missing_ibd, new_coins);
+ BOOST_CHECK_EQUAL(coins_in_background, initial_total_coins);
+ BOOST_CHECK_EQUAL(coins_missing_from_background, new_coins);
}
// Snapshot should refuse to load after one has already loaded.
diff --git a/src/test/validation_flush_tests.cpp b/src/test/validation_flush_tests.cpp
index 22aafcaa6c..9136c497ea 100644
--- a/src/test/validation_flush_tests.cpp
+++ b/src/test/validation_flush_tests.cpp
@@ -9,7 +9,7 @@
#include <boost/test/unit_test.hpp>
-BOOST_FIXTURE_TEST_SUITE(validation_flush_tests, BasicTestingSetup)
+BOOST_FIXTURE_TEST_SUITE(validation_flush_tests, ChainTestingSetup)
//! Test utilities for detecting when we need to flush the coins cache based
//! on estimated memory usage.
@@ -20,7 +20,7 @@ BOOST_AUTO_TEST_CASE(getcoinscachesizestate)
{
CTxMemPool mempool;
BlockManager blockman{};
- CChainState chainstate{&mempool, blockman};
+ CChainState chainstate{&mempool, blockman, *Assert(m_node.chainman)};
chainstate.InitCoinsDB(/*cache_size_bytes*/ 1 << 10, /*in_memory*/ true, /*should_wipe*/ false);
WITH_LOCK(::cs_main, chainstate.InitCoinsCache(1 << 10));
diff --git a/src/test/validation_tests.cpp b/src/test/validation_tests.cpp
index a0c2e76f00..ca52ecba2f 100644
--- a/src/test/validation_tests.cpp
+++ b/src/test/validation_tests.cpp
@@ -3,6 +3,7 @@
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparams.h>
+#include <consensus/amount.h>
#include <net.h>
#include <signet.h>
#include <uint256.h>
diff --git a/src/timedata.cpp b/src/timedata.cpp
index 354092752d..69d0273e79 100644
--- a/src/timedata.cpp
+++ b/src/timedata.cpp
@@ -11,6 +11,7 @@
#include <netaddress.h>
#include <node/ui_interface.h>
#include <sync.h>
+#include <tinyformat.h>
#include <util/system.h>
#include <util/translation.h>
#include <warnings.h>
@@ -74,7 +75,7 @@ void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
- int64_t max_adjustment = std::max<int64_t>(0, gArgs.GetArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT));
+ int64_t max_adjustment = std::max<int64_t>(0, gArgs.GetIntArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT));
if (nMedian >= -max_adjustment && nMedian <= max_adjustment) {
nTimeOffset = nMedian;
} else {
@@ -98,11 +99,12 @@ void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
}
if (LogAcceptCategory(BCLog::NET)) {
+ std::string log_message{"time data samples: "};
for (const int64_t n : vSorted) {
- LogPrint(BCLog::NET, "%+d ", n); /* Continued */
+ log_message += strprintf("%+d ", n);
}
- LogPrint(BCLog::NET, "| "); /* Continued */
- LogPrint(BCLog::NET, "nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset / 60);
+ log_message += strprintf("| median offset = %+d (%+d minutes)", nTimeOffset, nTimeOffset / 60);
+ LogPrint(BCLog::NET, "%s\n", log_message);
}
}
}
diff --git a/src/torcontrol.cpp b/src/torcontrol.cpp
index bb296456ba..f9caf48df8 100644
--- a/src/torcontrol.cpp
+++ b/src/torcontrol.cpp
@@ -14,6 +14,7 @@
#include <netbase.h>
#include <util/readwritefile.h>
#include <util/strencodings.h>
+#include <util/syscall_sandbox.h>
#include <util/system.h>
#include <util/thread.h>
#include <util/time.h>
@@ -83,7 +84,7 @@ void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
if (s.size() < 4) // Short line
continue;
// <status>(-|+| )<data><CRLF>
- self->message.code = atoi(s.substr(0,3));
+ self->message.code = LocaleIndependentAtoi<int>(s.substr(0,3));
self->message.lines.push_back(s.substr(4));
char ch = s[3]; // '-','+' or ' '
if (ch == ' ') {
@@ -585,6 +586,7 @@ static std::thread torControlThread;
static void TorControlThread(CService onion_service_target)
{
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::TOR_CONTROL);
TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL), onion_service_target);
event_base_dispatch(gBase);
diff --git a/src/txdb.cpp b/src/txdb.cpp
index 4b76bee5ab..3839c9083c 100644
--- a/src/txdb.cpp
+++ b/src/txdb.cpp
@@ -5,6 +5,7 @@
#include <txdb.h>
+#include <chain.h>
#include <node/ui_interface.h>
#include <pow.h>
#include <random.h>
@@ -27,6 +28,28 @@ static constexpr uint8_t DB_FLAG{'F'};
static constexpr uint8_t DB_REINDEX_FLAG{'R'};
static constexpr uint8_t DB_LAST_BLOCK{'l'};
+// Keys used in previous version that might still be found in the DB:
+static constexpr uint8_t DB_TXINDEX_BLOCK{'T'};
+// uint8_t DB_TXINDEX{'t'}
+
+std::optional<bilingual_str> CheckLegacyTxindex(CBlockTreeDB& block_tree_db)
+{
+ CBlockLocator ignored{};
+ if (block_tree_db.Read(DB_TXINDEX_BLOCK, ignored)) {
+ return _("The -txindex upgrade started by a previous version can not be completed. Restart with the previous version or run a full -reindex.");
+ }
+ bool txindex_legacy_flag{false};
+ block_tree_db.ReadFlag("txindex", txindex_legacy_flag);
+ if (txindex_legacy_flag) {
+ // Disable legacy txindex and warn once about occupied disk space
+ if (!block_tree_db.WriteFlag("txindex", false)) {
+ return Untranslated("Failed to write block index db flag 'txindex'='0'");
+ }
+ return _("The block index db contains a legacy 'txindex'. To clear the occupied disk space, run a full -reindex, otherwise ignore this error. This error message will not be displayed again.");
+ }
+ return std::nullopt;
+}
+
namespace {
struct CoinEntry {
@@ -84,8 +107,8 @@ bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
CDBBatch batch(*m_db);
size_t count = 0;
size_t changed = 0;
- size_t batch_size = (size_t)gArgs.GetArg("-dbbatchsize", nDefaultDbBatchSize);
- int crash_simulate = gArgs.GetArg("-dbcrashratio", 0);
+ size_t batch_size = (size_t)gArgs.GetIntArg("-dbbatchsize", nDefaultDbBatchSize);
+ int crash_simulate = gArgs.GetIntArg("-dbcrashratio", 0);
assert(!hashBlock.IsNull());
uint256 old_tip = GetBestBlock();
diff --git a/src/txdb.h b/src/txdb.h
index 845d80788f..1bdce71126 100644
--- a/src/txdb.h
+++ b/src/txdb.h
@@ -8,17 +8,20 @@
#include <coins.h>
#include <dbwrapper.h>
-#include <chain.h>
-#include <primitives/block.h>
#include <memory>
+#include <optional>
#include <string>
#include <utility>
#include <vector>
+class CBlockFileInfo;
class CBlockIndex;
-class CCoinsViewDBCursor;
class uint256;
+namespace Consensus {
+struct Params;
+};
+struct bilingual_str;
//! -dbcache default (MiB)
static const int64_t nDefaultDbCache = 450;
@@ -86,4 +89,6 @@ public:
bool LoadBlockIndexGuts(const Consensus::Params& consensusParams, std::function<CBlockIndex*(const uint256&)> insertBlockIndex);
};
+std::optional<bilingual_str> CheckLegacyTxindex(CBlockTreeDB& block_tree_db);
+
#endif // BITCOIN_TXDB_H
diff --git a/src/txmempool.cpp b/src/txmempool.cpp
index d5a888ac67..5a93f30c8a 100644
--- a/src/txmempool.cpp
+++ b/src/txmempool.cpp
@@ -21,23 +21,23 @@
#include <cmath>
#include <optional>
-CTxMemPoolEntry::CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFee,
- int64_t _nTime, unsigned int _entryHeight,
- bool _spendsCoinbase, int64_t _sigOpsCost, LockPoints lp)
- : tx(_tx), nFee(_nFee), nTxWeight(GetTransactionWeight(*tx)), nUsageSize(RecursiveDynamicUsage(tx)), nTime(_nTime), entryHeight(_entryHeight),
- spendsCoinbase(_spendsCoinbase), sigOpCost(_sigOpsCost), lockPoints(lp)
-{
- nCountWithDescendants = 1;
- nSizeWithDescendants = GetTxSize();
- nModFeesWithDescendants = nFee;
-
- feeDelta = 0;
-
- nCountWithAncestors = 1;
- nSizeWithAncestors = GetTxSize();
- nModFeesWithAncestors = nFee;
- nSigOpCostWithAncestors = sigOpCost;
-}
+CTxMemPoolEntry::CTxMemPoolEntry(const CTransactionRef& tx, CAmount fee,
+ int64_t time, unsigned int entry_height,
+ bool spends_coinbase, int64_t sigops_cost, LockPoints lp)
+ : tx{tx},
+ nFee{fee},
+ nTxWeight(GetTransactionWeight(*tx)),
+ nUsageSize{RecursiveDynamicUsage(tx)},
+ nTime{time},
+ entryHeight{entry_height},
+ spendsCoinbase{spends_coinbase},
+ sigOpCost{sigops_cost},
+ lockPoints{lp},
+ nSizeWithDescendants{GetTxSize()},
+ nModFeesWithDescendants{nFee},
+ nSizeWithAncestors{GetTxSize()},
+ nModFeesWithAncestors{nFee},
+ nSigOpCostWithAncestors{sigOpCost} {}
void CTxMemPoolEntry::UpdateFeeDelta(int64_t newFeeDelta)
{
@@ -924,7 +924,7 @@ void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeD
++nTransactionsUpdated;
}
}
- LogPrintf("PrioritiseTransaction: %s feerate += %s\n", hash.ToString(), FormatMoney(nFeeDelta));
+ LogPrintf("PrioritiseTransaction: %s fee += %s\n", hash.ToString(), FormatMoney(nFeeDelta));
}
void CTxMemPool::ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const
@@ -1174,12 +1174,14 @@ uint64_t CTxMemPool::CalculateDescendantMaximum(txiter entry) const {
return maximum;
}
-void CTxMemPool::GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants) const {
+void CTxMemPool::GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* const ancestorsize, CAmount* const ancestorfees) const {
LOCK(cs);
auto it = mapTx.find(txid);
ancestors = descendants = 0;
if (it != mapTx.end()) {
ancestors = it->GetCountWithAncestors();
+ if (ancestorsize) *ancestorsize = it->GetSizeWithAncestors();
+ if (ancestorfees) *ancestorfees = it->GetModFeesWithAncestors();
descendants = CalculateDescendantMaximum(it);
}
}
diff --git a/src/txmempool.h b/src/txmempool.h
index 0a84a6e6b1..0be51db181 100644
--- a/src/txmempool.h
+++ b/src/txmempool.h
@@ -14,8 +14,8 @@
#include <utility>
#include <vector>
-#include <amount.h>
#include <coins.h>
+#include <consensus/amount.h>
#include <indirectmap.h>
#include <policy/feerate.h>
#include <policy/packages.h>
@@ -37,19 +37,16 @@ extern RecursiveMutex cs_main;
/** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */
static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
-struct LockPoints
-{
+struct LockPoints {
// Will be set to the blockchain height and median time past
// values that would be necessary to satisfy all relative locktime
// constraints (BIP68) of this tx given our view of block chain history
- int height;
- int64_t time;
+ int height{0};
+ int64_t time{0};
// As long as the current chain descends from the highest height block
// containing one of the inputs used in the calculation, then the cached
// values are still valid even after a reorg.
- CBlockIndex* maxInputBlock;
-
- LockPoints() : height(0), time(0), maxInputBlock(nullptr) { }
+ CBlockIndex* maxInputBlock{nullptr};
};
struct CompareIteratorByHash {
@@ -98,27 +95,27 @@ private:
const unsigned int entryHeight; //!< Chain height when entering the mempool
const bool spendsCoinbase; //!< keep track of transactions that spend a coinbase
const int64_t sigOpCost; //!< Total sigop cost
- int64_t feeDelta; //!< Used for determining the priority of the transaction for mining in a block
+ int64_t feeDelta{0}; //!< Used for determining the priority of the transaction for mining in a block
LockPoints lockPoints; //!< Track the height and time at which tx was final
// Information about descendants of this transaction that are in the
// mempool; if we remove this transaction we must remove all of these
// descendants as well.
- uint64_t nCountWithDescendants; //!< number of descendant transactions
+ uint64_t nCountWithDescendants{1}; //!< number of descendant transactions
uint64_t nSizeWithDescendants; //!< ... and size
CAmount nModFeesWithDescendants; //!< ... and total fees (all including us)
// Analogous statistics for ancestor transactions
- uint64_t nCountWithAncestors;
+ uint64_t nCountWithAncestors{1};
uint64_t nSizeWithAncestors;
CAmount nModFeesWithAncestors;
int64_t nSigOpCostWithAncestors;
public:
- CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFee,
- int64_t _nTime, unsigned int _entryHeight,
- bool spendsCoinbase,
- int64_t nSigOpsCost, LockPoints lp);
+ CTxMemPoolEntry(const CTransactionRef& tx, CAmount fee,
+ int64_t time, unsigned int entry_height,
+ bool spends_coinbase,
+ int64_t sigops_cost, LockPoints lp);
const CTransaction& GetTx() const { return *this->tx; }
CTransactionRef GetSharedTx() const { return this->tx; }
@@ -748,8 +745,10 @@ public:
/**
* Calculate the ancestor and descendant count for the given transaction.
* The counts include the transaction itself.
+ * When ancestors is non-zero (ie, the transaction itself is in the mempool),
+ * ancestorsize and ancestorfees will also be set to the appropriate values.
*/
- void GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants) const;
+ void GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) const;
/** @returns true if the mempool is fully loaded */
bool IsLoaded() const;
diff --git a/src/util/asmap.cpp b/src/util/asmap.cpp
index bacc3690a2..5695c62012 100644
--- a/src/util/asmap.cpp
+++ b/src/util/asmap.cpp
@@ -2,10 +2,16 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#include <util/asmap.h>
+
+#include <clientversion.h>
+#include <crypto/common.h>
+#include <logging.h>
+#include <streams.h>
+
+#include <cassert>
#include <map>
#include <vector>
-#include <assert.h>
-#include <crypto/common.h>
namespace {
@@ -183,3 +189,31 @@ bool SanityCheckASMap(const std::vector<bool>& asmap, int bits)
}
return false; // Reached EOF without RETURN instruction
}
+
+std::vector<bool> DecodeAsmap(fs::path path)
+{
+ std::vector<bool> bits;
+ FILE *filestr = fsbridge::fopen(path, "rb");
+ CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
+ if (file.IsNull()) {
+ LogPrintf("Failed to open asmap file from disk\n");
+ return bits;
+ }
+ fseek(filestr, 0, SEEK_END);
+ int length = ftell(filestr);
+ LogPrintf("Opened asmap file %s (%d bytes) from disk\n", path, length);
+ fseek(filestr, 0, SEEK_SET);
+ uint8_t cur_byte;
+ for (int i = 0; i < length; ++i) {
+ file >> cur_byte;
+ for (int bit = 0; bit < 8; ++bit) {
+ bits.push_back((cur_byte >> bit) & 1);
+ }
+ }
+ if (!SanityCheckASMap(bits, 128)) {
+ LogPrintf("Sanity check of asmap file %s failed\n", path);
+ return {};
+ }
+ return bits;
+}
+
diff --git a/src/util/asmap.h b/src/util/asmap.h
index d0588bc8c3..810d70b9a1 100644
--- a/src/util/asmap.h
+++ b/src/util/asmap.h
@@ -5,11 +5,16 @@
#ifndef BITCOIN_UTIL_ASMAP_H
#define BITCOIN_UTIL_ASMAP_H
-#include <stdint.h>
+#include <fs.h>
+
+#include <cstdint>
#include <vector>
uint32_t Interpret(const std::vector<bool> &asmap, const std::vector<bool> &ip);
bool SanityCheckASMap(const std::vector<bool>& asmap, int bits);
+/** Read asmap from provided binary file */
+std::vector<bool> DecodeAsmap(fs::path path);
+
#endif // BITCOIN_UTIL_ASMAP_H
diff --git a/src/util/moneystr.cpp b/src/util/moneystr.cpp
index d3f4029607..1aed7daacf 100644
--- a/src/util/moneystr.cpp
+++ b/src/util/moneystr.cpp
@@ -5,7 +5,7 @@
#include <util/moneystr.h>
-#include <amount.h>
+#include <consensus/amount.h>
#include <tinyformat.h>
#include <util/strencodings.h>
#include <util/string.h>
@@ -77,8 +77,7 @@ std::optional<CAmount> ParseMoney(const std::string& money_string)
return std::nullopt;
if (nUnits < 0 || nUnits > COIN)
return std::nullopt;
- int64_t nWhole = atoi64(strWhole);
-
+ int64_t nWhole = LocaleIndependentAtoi<int64_t>(strWhole);
CAmount value = nWhole * COIN + nUnits;
if (!MoneyRange(value)) {
diff --git a/src/util/moneystr.h b/src/util/moneystr.h
index b71dffd0db..f37dc1cffd 100644
--- a/src/util/moneystr.h
+++ b/src/util/moneystr.h
@@ -9,8 +9,8 @@
#ifndef BITCOIN_UTIL_MONEYSTR_H
#define BITCOIN_UTIL_MONEYSTR_H
-#include <amount.h>
#include <attributes.h>
+#include <consensus/amount.h>
#include <optional>
#include <string>
diff --git a/src/util/rbf.h b/src/util/rbf.h
index 4eb44b904f..aa522d8bfb 100644
--- a/src/util/rbf.h
+++ b/src/util/rbf.h
@@ -9,17 +9,15 @@
class CTransaction;
-static const uint32_t MAX_BIP125_RBF_SEQUENCE = 0xfffffffd;
+static constexpr uint32_t MAX_BIP125_RBF_SEQUENCE{0xfffffffd};
-/** Check whether the sequence numbers on this transaction are signaling
-* opt-in to replace-by-fee, according to BIP 125.
-* Allow opt-out of transaction replacement by setting
-* nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
+/** Check whether the sequence numbers on this transaction are signaling opt-in to replace-by-fee,
+ * according to BIP 125. Allow opt-out of transaction replacement by setting nSequence >
+ * MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
*
-* SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
-* non-replaceable transactions. All inputs rather than just one
-* is for the sake of multi-party protocols, where we don't
-* want a single party to be able to disable replacement. */
-bool SignalsOptInRBF(const CTransaction &tx);
+* SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by non-replaceable transactions. All
+* inputs rather than just one is for the sake of multi-party protocols, where we don't want a single
+* party to be able to disable replacement by opting out in their own input. */
+bool SignalsOptInRBF(const CTransaction& tx);
#endif // BITCOIN_UTIL_RBF_H
diff --git a/src/util/sock.cpp b/src/util/sock.cpp
index b6c2a47434..1a4d67a65e 100644
--- a/src/util/sock.cpp
+++ b/src/util/sock.cpp
@@ -10,12 +10,14 @@
#include <util/system.h>
#include <util/time.h>
-#include <codecvt>
-#include <cwchar>
-#include <locale>
#include <stdexcept>
#include <string>
+#ifdef WIN32
+#include <codecvt>
+#include <locale>
+#endif
+
#ifdef USE_POLL
#include <poll.h>
#endif
diff --git a/src/util/strencodings.cpp b/src/util/strencodings.cpp
index f514613f0d..15bd07b374 100644
--- a/src/util/strencodings.cpp
+++ b/src/util/strencodings.cpp
@@ -11,8 +11,7 @@
#include <algorithm>
#include <cstdlib>
#include <cstring>
-#include <errno.h>
-#include <limits>
+#include <optional>
static const std::string CHARS_ALPHA_NUM = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
@@ -282,118 +281,55 @@ std::string DecodeBase32(const std::string& str, bool* pf_invalid)
return std::string((const char*)vchRet.data(), vchRet.size());
}
-[[nodiscard]] static bool ParsePrechecks(const std::string& str)
+namespace {
+template <typename T>
+bool ParseIntegral(const std::string& str, T* out)
{
- if (str.empty()) // No empty string allowed
+ static_assert(std::is_integral<T>::value);
+ // Replicate the exact behavior of strtol/strtoll/strtoul/strtoull when
+ // handling leading +/- for backwards compatibility.
+ if (str.length() >= 2 && str[0] == '+' && str[1] == '-') {
return false;
- if (str.size() >= 1 && (IsSpace(str[0]) || IsSpace(str[str.size()-1]))) // No padding allowed
- return false;
- if (!ValidAsCString(str)) // No embedded NUL characters allowed
+ }
+ const std::optional<T> opt_int = ToIntegral<T>((!str.empty() && str[0] == '+') ? str.substr(1) : str);
+ if (!opt_int) {
return false;
+ }
+ if (out != nullptr) {
+ *out = *opt_int;
+ }
return true;
}
+}; // namespace
-bool ParseInt32(const std::string& str, int32_t *out)
+bool ParseInt32(const std::string& str, int32_t* out)
{
- if (!ParsePrechecks(str))
- return false;
- char *endp = nullptr;
- errno = 0; // strtol will not set errno if valid
- long int n = strtol(str.c_str(), &endp, 10);
- if(out) *out = (int32_t)n;
- // Note that strtol returns a *long int*, so even if strtol doesn't report an over/underflow
- // we still have to check that the returned value is within the range of an *int32_t*. On 64-bit
- // platforms the size of these types may be different.
- return endp && *endp == 0 && !errno &&
- n >= std::numeric_limits<int32_t>::min() &&
- n <= std::numeric_limits<int32_t>::max();
+ return ParseIntegral<int32_t>(str, out);
}
-bool ParseInt64(const std::string& str, int64_t *out)
+bool ParseInt64(const std::string& str, int64_t* out)
{
- if (!ParsePrechecks(str))
- return false;
- char *endp = nullptr;
- errno = 0; // strtoll will not set errno if valid
- long long int n = strtoll(str.c_str(), &endp, 10);
- if(out) *out = (int64_t)n;
- // Note that strtoll returns a *long long int*, so even if strtol doesn't report an over/underflow
- // we still have to check that the returned value is within the range of an *int64_t*.
- return endp && *endp == 0 && !errno &&
- n >= std::numeric_limits<int64_t>::min() &&
- n <= std::numeric_limits<int64_t>::max();
+ return ParseIntegral<int64_t>(str, out);
}
-bool ParseUInt8(const std::string& str, uint8_t *out)
+bool ParseUInt8(const std::string& str, uint8_t* out)
{
- uint32_t u32;
- if (!ParseUInt32(str, &u32) || u32 > std::numeric_limits<uint8_t>::max()) {
- return false;
- }
- if (out != nullptr) {
- *out = static_cast<uint8_t>(u32);
- }
- return true;
+ return ParseIntegral<uint8_t>(str, out);
}
bool ParseUInt16(const std::string& str, uint16_t* out)
{
- uint32_t u32;
- if (!ParseUInt32(str, &u32) || u32 > std::numeric_limits<uint16_t>::max()) {
- return false;
- }
- if (out != nullptr) {
- *out = static_cast<uint16_t>(u32);
- }
- return true;
+ return ParseIntegral<uint16_t>(str, out);
}
-bool ParseUInt32(const std::string& str, uint32_t *out)
+bool ParseUInt32(const std::string& str, uint32_t* out)
{
- if (!ParsePrechecks(str))
- return false;
- if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoul accepts these by default if they fit in the range
- return false;
- char *endp = nullptr;
- errno = 0; // strtoul will not set errno if valid
- unsigned long int n = strtoul(str.c_str(), &endp, 10);
- if(out) *out = (uint32_t)n;
- // Note that strtoul returns a *unsigned long int*, so even if it doesn't report an over/underflow
- // we still have to check that the returned value is within the range of an *uint32_t*. On 64-bit
- // platforms the size of these types may be different.
- return endp && *endp == 0 && !errno &&
- n <= std::numeric_limits<uint32_t>::max();
-}
-
-bool ParseUInt64(const std::string& str, uint64_t *out)
-{
- if (!ParsePrechecks(str))
- return false;
- if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoull accepts these by default if they fit in the range
- return false;
- char *endp = nullptr;
- errno = 0; // strtoull will not set errno if valid
- unsigned long long int n = strtoull(str.c_str(), &endp, 10);
- if(out) *out = (uint64_t)n;
- // Note that strtoull returns a *unsigned long long int*, so even if it doesn't report an over/underflow
- // we still have to check that the returned value is within the range of an *uint64_t*.
- return endp && *endp == 0 && !errno &&
- n <= std::numeric_limits<uint64_t>::max();
+ return ParseIntegral<uint32_t>(str, out);
}
-
-bool ParseDouble(const std::string& str, double *out)
+bool ParseUInt64(const std::string& str, uint64_t* out)
{
- if (!ParsePrechecks(str))
- return false;
- if (str.size() >= 2 && str[0] == '0' && str[1] == 'x') // No hexadecimal floats allowed
- return false;
- std::istringstream text(str);
- text.imbue(std::locale::classic());
- double result;
- text >> result;
- if(out) *out = result;
- return text.eof() && !text.fail();
+ return ParseIntegral<uint64_t>(str, out);
}
std::string FormatParagraph(const std::string& in, size_t width, size_t indent)
@@ -437,20 +373,6 @@ std::string FormatParagraph(const std::string& in, size_t width, size_t indent)
return out.str();
}
-int64_t atoi64(const std::string& str)
-{
-#ifdef _MSC_VER
- return _atoi64(str.c_str());
-#else
- return strtoll(str.c_str(), nullptr, 10);
-#endif
-}
-
-int atoi(const std::string& str)
-{
- return atoi(str.c_str());
-}
-
/** Upper bound for mantissa.
* 10^18-1 is the largest arbitrary decimal that will fit in a signed 64-bit integer.
* Larger integers cannot consist of arbitrary combinations of 0-9:
diff --git a/src/util/strencodings.h b/src/util/strencodings.h
index 26dc0a0ce3..1f7762aeef 100644
--- a/src/util/strencodings.h
+++ b/src/util/strencodings.h
@@ -11,9 +11,12 @@
#include <attributes.h>
#include <span.h>
+#include <util/string.h>
+#include <charconv>
#include <cstdint>
#include <iterator>
+#include <optional>
#include <string>
#include <vector>
@@ -66,8 +69,33 @@ std::string EncodeBase32(Span<const unsigned char> input, bool pad = true);
std::string EncodeBase32(const std::string& str, bool pad = true);
void SplitHostPort(std::string in, uint16_t& portOut, std::string& hostOut);
-int64_t atoi64(const std::string& str);
-int atoi(const std::string& str);
+
+// LocaleIndependentAtoi is provided for backwards compatibility reasons.
+//
+// New code should use the ParseInt64/ParseUInt64/ParseInt32/ParseUInt32 functions
+// which provide parse error feedback.
+//
+// The goal of LocaleIndependentAtoi is to replicate the exact defined behaviour
+// of atoi and atoi64 as they behave under the "C" locale.
+template <typename T>
+T LocaleIndependentAtoi(const std::string& str)
+{
+ static_assert(std::is_integral<T>::value);
+ T result;
+ // Emulate atoi(...) handling of white space and leading +/-.
+ std::string s = TrimString(str);
+ if (!s.empty() && s[0] == '+') {
+ if (s.length() >= 2 && s[1] == '-') {
+ return 0;
+ }
+ s = s.substr(1);
+ }
+ auto [_, error_condition] = std::from_chars(s.data(), s.data() + s.size(), result);
+ if (error_condition != std::errc{}) {
+ return 0;
+ }
+ return result;
+}
/**
* Tests if the given character is a decimal digit.
@@ -95,6 +123,26 @@ constexpr inline bool IsSpace(char c) noexcept {
}
/**
+ * Convert string to integral type T. Leading whitespace, a leading +, or any
+ * trailing character fail the parsing. The required format expressed as regex
+ * is `-?[0-9]+`.
+ *
+ * @returns std::nullopt if the entire string could not be parsed, or if the
+ * parsed value is not in the range representable by the type T.
+ */
+template <typename T>
+std::optional<T> ToIntegral(const std::string& str)
+{
+ static_assert(std::is_integral<T>::value);
+ T result;
+ const auto [first_nonmatching, error_condition] = std::from_chars(str.data(), str.data() + str.size(), result);
+ if (first_nonmatching != str.data() + str.size() || error_condition != std::errc{}) {
+ return std::nullopt;
+ }
+ return result;
+}
+
+/**
* Convert string to signed 32-bit integer with strict parse error feedback.
* @returns true if the entire string could be parsed as valid integer,
* false if not the entire string could be parsed or when overflow or underflow occurred.
@@ -137,13 +185,6 @@ constexpr inline bool IsSpace(char c) noexcept {
[[nodiscard]] bool ParseUInt64(const std::string& str, uint64_t *out);
/**
- * Convert string to double with strict parse error feedback.
- * @returns true if the entire string could be parsed as valid double,
- * false if not the entire string could be parsed or when overflow or underflow occurred.
- */
-[[nodiscard]] bool ParseDouble(const std::string& str, double *out);
-
-/**
* Convert a span of bytes to a lower-case hexadecimal string.
*/
std::string HexStr(const Span<const uint8_t> s);
diff --git a/src/util/syscall_sandbox.cpp b/src/util/syscall_sandbox.cpp
new file mode 100644
index 0000000000..7e76ecbf3a
--- /dev/null
+++ b/src/util/syscall_sandbox.cpp
@@ -0,0 +1,909 @@
+// Copyright (c) 2020 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#if defined(HAVE_CONFIG_H)
+#include <config/bitcoin-config.h>
+#endif // defined(HAVE_CONFIG_H)
+
+#include <util/syscall_sandbox.h>
+
+#if defined(USE_SYSCALL_SANDBOX)
+#include <array>
+#include <cassert>
+#include <cstdint>
+#include <exception>
+#include <map>
+#include <new>
+#include <set>
+#include <string>
+#include <vector>
+
+#include <logging.h>
+#include <tinyformat.h>
+#include <util/threadnames.h>
+
+#include <linux/audit.h>
+#include <linux/filter.h>
+#include <linux/seccomp.h>
+#include <linux/unistd.h>
+#include <signal.h>
+#include <sys/prctl.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+namespace {
+bool g_syscall_sandbox_enabled{false};
+bool g_syscall_sandbox_log_violation_before_terminating{false};
+
+#if !defined(__x86_64__)
+#error Syscall sandbox is an experimental feature currently available only under Linux x86-64.
+#endif // defined(__x86_64__)
+
+#ifndef SECCOMP_RET_KILL_PROCESS
+#define SECCOMP_RET_KILL_PROCESS 0x80000000U
+#endif
+
+// Define system call numbers for x86_64 that are referenced in the system call profile
+// but not provided by the kernel headers used in the GUIX build.
+#ifndef __NR_statx
+#define __NR_statx 332
+#endif
+
+#ifndef __NR_getrandom
+#define __NR_getrandom 318
+#endif
+
+#ifndef __NR_membarrier
+#define __NR_membarrier 324
+#endif
+
+#ifndef __NR_copy_file_range
+#define __NR_copy_file_range 326
+#endif
+
+// This list of syscalls in LINUX_SYSCALLS is only used to map syscall numbers to syscall names in
+// order to be able to print user friendly error messages which include the syscall name in addition
+// to the syscall number.
+//
+// Example output in case of a syscall violation where the syscall is present in LINUX_SYSCALLS:
+//
+// ```
+// 2021-06-09T12:34:56Z ERROR: The syscall "execve" (syscall number 59) is not allowed by the syscall sandbox in thread "msghand". Please report.
+// ```
+//
+// Example output in case of a syscall violation where the syscall is not present in LINUX_SYSCALLS:
+//
+// ```
+// 2021-06-09T12:34:56Z ERROR: The syscall "*unknown*" (syscall number 314) is not allowed by the syscall sandbox in thread "msghand". Please report.
+// ``
+//
+// LINUX_SYSCALLS contains two types of syscalls:
+// 1.) Syscalls that are present under all architectures or relevant Linux kernel versions for which
+// we support the syscall sandbox feature (currently only Linux x86-64). Examples include read,
+// write, open, close, etc.
+// 2.) Syscalls that are present under a subset of architectures or relevant Linux kernel versions
+// for which we support the syscall sandbox feature. This type of syscalls should be added to
+// LINUX_SYSCALLS conditional on availability like in the following example:
+// ...
+// #if defined(__NR_arch_dependent_syscall)
+// {__NR_arch_dependent_syscall, "arch_dependent_syscall"},
+// #endif // defined(__NR_arch_dependent_syscall)
+// ...
+const std::map<uint32_t, std::string> LINUX_SYSCALLS{
+ {__NR_accept, "accept"},
+ {__NR_accept4, "accept4"},
+ {__NR_access, "access"},
+ {__NR_acct, "acct"},
+ {__NR_add_key, "add_key"},
+ {__NR_adjtimex, "adjtimex"},
+ {__NR_afs_syscall, "afs_syscall"},
+ {__NR_alarm, "alarm"},
+ {__NR_arch_prctl, "arch_prctl"},
+ {__NR_bind, "bind"},
+ {__NR_bpf, "bpf"},
+ {__NR_brk, "brk"},
+ {__NR_capget, "capget"},
+ {__NR_capset, "capset"},
+ {__NR_chdir, "chdir"},
+ {__NR_chmod, "chmod"},
+ {__NR_chown, "chown"},
+ {__NR_chroot, "chroot"},
+ {__NR_clock_adjtime, "clock_adjtime"},
+ {__NR_clock_getres, "clock_getres"},
+ {__NR_clock_gettime, "clock_gettime"},
+ {__NR_clock_nanosleep, "clock_nanosleep"},
+ {__NR_clock_settime, "clock_settime"},
+ {__NR_clone, "clone"},
+ {__NR_close, "close"},
+ {__NR_connect, "connect"},
+ {__NR_copy_file_range, "copy_file_range"},
+ {__NR_creat, "creat"},
+ {__NR_create_module, "create_module"},
+ {__NR_delete_module, "delete_module"},
+ {__NR_dup, "dup"},
+ {__NR_dup2, "dup2"},
+ {__NR_dup3, "dup3"},
+ {__NR_epoll_create, "epoll_create"},
+ {__NR_epoll_create1, "epoll_create1"},
+ {__NR_epoll_ctl, "epoll_ctl"},
+ {__NR_epoll_ctl_old, "epoll_ctl_old"},
+ {__NR_epoll_pwait, "epoll_pwait"},
+ {__NR_epoll_wait, "epoll_wait"},
+ {__NR_epoll_wait_old, "epoll_wait_old"},
+ {__NR_eventfd, "eventfd"},
+ {__NR_eventfd2, "eventfd2"},
+ {__NR_execve, "execve"},
+ {__NR_execveat, "execveat"},
+ {__NR_exit, "exit"},
+ {__NR_exit_group, "exit_group"},
+ {__NR_faccessat, "faccessat"},
+ {__NR_fadvise64, "fadvise64"},
+ {__NR_fallocate, "fallocate"},
+ {__NR_fanotify_init, "fanotify_init"},
+ {__NR_fanotify_mark, "fanotify_mark"},
+ {__NR_fchdir, "fchdir"},
+ {__NR_fchmod, "fchmod"},
+ {__NR_fchmodat, "fchmodat"},
+ {__NR_fchown, "fchown"},
+ {__NR_fchownat, "fchownat"},
+ {__NR_fcntl, "fcntl"},
+ {__NR_fdatasync, "fdatasync"},
+ {__NR_fgetxattr, "fgetxattr"},
+ {__NR_finit_module, "finit_module"},
+ {__NR_flistxattr, "flistxattr"},
+ {__NR_flock, "flock"},
+ {__NR_fork, "fork"},
+ {__NR_fremovexattr, "fremovexattr"},
+ {__NR_fsetxattr, "fsetxattr"},
+ {__NR_fstat, "fstat"},
+ {__NR_fstatfs, "fstatfs"},
+ {__NR_fsync, "fsync"},
+ {__NR_ftruncate, "ftruncate"},
+ {__NR_futex, "futex"},
+ {__NR_futimesat, "futimesat"},
+ {__NR_getcpu, "getcpu"},
+ {__NR_getcwd, "getcwd"},
+ {__NR_getdents, "getdents"},
+ {__NR_getdents64, "getdents64"},
+ {__NR_getegid, "getegid"},
+ {__NR_geteuid, "geteuid"},
+ {__NR_getgid, "getgid"},
+ {__NR_getgroups, "getgroups"},
+ {__NR_getitimer, "getitimer"},
+ {__NR_get_kernel_syms, "get_kernel_syms"},
+ {__NR_get_mempolicy, "get_mempolicy"},
+ {__NR_getpeername, "getpeername"},
+ {__NR_getpgid, "getpgid"},
+ {__NR_getpgrp, "getpgrp"},
+ {__NR_getpid, "getpid"},
+ {__NR_getpmsg, "getpmsg"},
+ {__NR_getppid, "getppid"},
+ {__NR_getpriority, "getpriority"},
+ {__NR_getrandom, "getrandom"},
+ {__NR_getresgid, "getresgid"},
+ {__NR_getresuid, "getresuid"},
+ {__NR_getrlimit, "getrlimit"},
+ {__NR_get_robust_list, "get_robust_list"},
+ {__NR_getrusage, "getrusage"},
+ {__NR_getsid, "getsid"},
+ {__NR_getsockname, "getsockname"},
+ {__NR_getsockopt, "getsockopt"},
+ {__NR_get_thread_area, "get_thread_area"},
+ {__NR_gettid, "gettid"},
+ {__NR_gettimeofday, "gettimeofday"},
+ {__NR_getuid, "getuid"},
+ {__NR_getxattr, "getxattr"},
+ {__NR_init_module, "init_module"},
+ {__NR_inotify_add_watch, "inotify_add_watch"},
+ {__NR_inotify_init, "inotify_init"},
+ {__NR_inotify_init1, "inotify_init1"},
+ {__NR_inotify_rm_watch, "inotify_rm_watch"},
+ {__NR_io_cancel, "io_cancel"},
+ {__NR_ioctl, "ioctl"},
+ {__NR_io_destroy, "io_destroy"},
+ {__NR_io_getevents, "io_getevents"},
+ {__NR_ioperm, "ioperm"},
+ {__NR_iopl, "iopl"},
+ {__NR_ioprio_get, "ioprio_get"},
+ {__NR_ioprio_set, "ioprio_set"},
+ {__NR_io_setup, "io_setup"},
+ {__NR_io_submit, "io_submit"},
+ {__NR_kcmp, "kcmp"},
+ {__NR_kexec_file_load, "kexec_file_load"},
+ {__NR_kexec_load, "kexec_load"},
+ {__NR_keyctl, "keyctl"},
+ {__NR_kill, "kill"},
+ {__NR_lchown, "lchown"},
+ {__NR_lgetxattr, "lgetxattr"},
+ {__NR_link, "link"},
+ {__NR_linkat, "linkat"},
+ {__NR_listen, "listen"},
+ {__NR_listxattr, "listxattr"},
+ {__NR_llistxattr, "llistxattr"},
+ {__NR_lookup_dcookie, "lookup_dcookie"},
+ {__NR_lremovexattr, "lremovexattr"},
+ {__NR_lseek, "lseek"},
+ {__NR_lsetxattr, "lsetxattr"},
+ {__NR_lstat, "lstat"},
+ {__NR_madvise, "madvise"},
+ {__NR_mbind, "mbind"},
+ {__NR_membarrier, "membarrier"},
+ {__NR_memfd_create, "memfd_create"},
+ {__NR_migrate_pages, "migrate_pages"},
+ {__NR_mincore, "mincore"},
+ {__NR_mkdir, "mkdir"},
+ {__NR_mkdirat, "mkdirat"},
+ {__NR_mknod, "mknod"},
+ {__NR_mknodat, "mknodat"},
+ {__NR_mlock, "mlock"},
+ {__NR_mlock2, "mlock2"},
+ {__NR_mlockall, "mlockall"},
+ {__NR_mmap, "mmap"},
+ {__NR_modify_ldt, "modify_ldt"},
+ {__NR_mount, "mount"},
+ {__NR_move_pages, "move_pages"},
+ {__NR_mprotect, "mprotect"},
+ {__NR_mq_getsetattr, "mq_getsetattr"},
+ {__NR_mq_notify, "mq_notify"},
+ {__NR_mq_open, "mq_open"},
+ {__NR_mq_timedreceive, "mq_timedreceive"},
+ {__NR_mq_timedsend, "mq_timedsend"},
+ {__NR_mq_unlink, "mq_unlink"},
+ {__NR_mremap, "mremap"},
+ {__NR_msgctl, "msgctl"},
+ {__NR_msgget, "msgget"},
+ {__NR_msgrcv, "msgrcv"},
+ {__NR_msgsnd, "msgsnd"},
+ {__NR_msync, "msync"},
+ {__NR_munlock, "munlock"},
+ {__NR_munlockall, "munlockall"},
+ {__NR_munmap, "munmap"},
+ {__NR_name_to_handle_at, "name_to_handle_at"},
+ {__NR_nanosleep, "nanosleep"},
+ {__NR_newfstatat, "newfstatat"},
+ {__NR_nfsservctl, "nfsservctl"},
+ {__NR_open, "open"},
+ {__NR_openat, "openat"},
+ {__NR_open_by_handle_at, "open_by_handle_at"},
+ {__NR_pause, "pause"},
+ {__NR_perf_event_open, "perf_event_open"},
+ {__NR_personality, "personality"},
+ {__NR_pipe, "pipe"},
+ {__NR_pipe2, "pipe2"},
+ {__NR_pivot_root, "pivot_root"},
+#ifdef __NR_pkey_alloc
+ {__NR_pkey_alloc, "pkey_alloc"},
+#endif
+#ifdef __NR_pkey_free
+ {__NR_pkey_free, "pkey_free"},
+#endif
+#ifdef __NR_pkey_mprotect
+ {__NR_pkey_mprotect, "pkey_mprotect"},
+#endif
+ {__NR_poll, "poll"},
+ {__NR_ppoll, "ppoll"},
+ {__NR_prctl, "prctl"},
+ {__NR_pread64, "pread64"},
+ {__NR_preadv, "preadv"},
+#ifdef __NR_preadv2
+ {__NR_preadv2, "preadv2"},
+#endif
+ {__NR_prlimit64, "prlimit64"},
+ {__NR_process_vm_readv, "process_vm_readv"},
+ {__NR_process_vm_writev, "process_vm_writev"},
+ {__NR_pselect6, "pselect6"},
+ {__NR_ptrace, "ptrace"},
+ {__NR_putpmsg, "putpmsg"},
+ {__NR_pwrite64, "pwrite64"},
+ {__NR_pwritev, "pwritev"},
+#ifdef __NR_pwritev2
+ {__NR_pwritev2, "pwritev2"},
+#endif
+ {__NR_query_module, "query_module"},
+ {__NR_quotactl, "quotactl"},
+ {__NR_read, "read"},
+ {__NR_readahead, "readahead"},
+ {__NR_readlink, "readlink"},
+ {__NR_readlinkat, "readlinkat"},
+ {__NR_readv, "readv"},
+ {__NR_reboot, "reboot"},
+ {__NR_recvfrom, "recvfrom"},
+ {__NR_recvmmsg, "recvmmsg"},
+ {__NR_recvmsg, "recvmsg"},
+ {__NR_remap_file_pages, "remap_file_pages"},
+ {__NR_removexattr, "removexattr"},
+ {__NR_rename, "rename"},
+ {__NR_renameat, "renameat"},
+ {__NR_renameat2, "renameat2"},
+ {__NR_request_key, "request_key"},
+ {__NR_restart_syscall, "restart_syscall"},
+ {__NR_rmdir, "rmdir"},
+ {__NR_rt_sigaction, "rt_sigaction"},
+ {__NR_rt_sigpending, "rt_sigpending"},
+ {__NR_rt_sigprocmask, "rt_sigprocmask"},
+ {__NR_rt_sigqueueinfo, "rt_sigqueueinfo"},
+ {__NR_rt_sigreturn, "rt_sigreturn"},
+ {__NR_rt_sigsuspend, "rt_sigsuspend"},
+ {__NR_rt_sigtimedwait, "rt_sigtimedwait"},
+ {__NR_rt_tgsigqueueinfo, "rt_tgsigqueueinfo"},
+ {__NR_sched_getaffinity, "sched_getaffinity"},
+ {__NR_sched_getattr, "sched_getattr"},
+ {__NR_sched_getparam, "sched_getparam"},
+ {__NR_sched_get_priority_max, "sched_get_priority_max"},
+ {__NR_sched_get_priority_min, "sched_get_priority_min"},
+ {__NR_sched_getscheduler, "sched_getscheduler"},
+ {__NR_sched_rr_get_interval, "sched_rr_get_interval"},
+ {__NR_sched_setaffinity, "sched_setaffinity"},
+ {__NR_sched_setattr, "sched_setattr"},
+ {__NR_sched_setparam, "sched_setparam"},
+ {__NR_sched_setscheduler, "sched_setscheduler"},
+ {__NR_sched_yield, "sched_yield"},
+ {__NR_seccomp, "seccomp"},
+ {__NR_security, "security"},
+ {__NR_select, "select"},
+ {__NR_semctl, "semctl"},
+ {__NR_semget, "semget"},
+ {__NR_semop, "semop"},
+ {__NR_semtimedop, "semtimedop"},
+ {__NR_sendfile, "sendfile"},
+ {__NR_sendmmsg, "sendmmsg"},
+ {__NR_sendmsg, "sendmsg"},
+ {__NR_sendto, "sendto"},
+ {__NR_setdomainname, "setdomainname"},
+ {__NR_setfsgid, "setfsgid"},
+ {__NR_setfsuid, "setfsuid"},
+ {__NR_setgid, "setgid"},
+ {__NR_setgroups, "setgroups"},
+ {__NR_sethostname, "sethostname"},
+ {__NR_setitimer, "setitimer"},
+ {__NR_set_mempolicy, "set_mempolicy"},
+ {__NR_setns, "setns"},
+ {__NR_setpgid, "setpgid"},
+ {__NR_setpriority, "setpriority"},
+ {__NR_setregid, "setregid"},
+ {__NR_setresgid, "setresgid"},
+ {__NR_setresuid, "setresuid"},
+ {__NR_setreuid, "setreuid"},
+ {__NR_setrlimit, "setrlimit"},
+ {__NR_set_robust_list, "set_robust_list"},
+ {__NR_setsid, "setsid"},
+ {__NR_setsockopt, "setsockopt"},
+ {__NR_set_thread_area, "set_thread_area"},
+ {__NR_set_tid_address, "set_tid_address"},
+ {__NR_settimeofday, "settimeofday"},
+ {__NR_setuid, "setuid"},
+ {__NR_setxattr, "setxattr"},
+ {__NR_shmat, "shmat"},
+ {__NR_shmctl, "shmctl"},
+ {__NR_shmdt, "shmdt"},
+ {__NR_shmget, "shmget"},
+ {__NR_shutdown, "shutdown"},
+ {__NR_sigaltstack, "sigaltstack"},
+ {__NR_signalfd, "signalfd"},
+ {__NR_signalfd4, "signalfd4"},
+ {__NR_socket, "socket"},
+ {__NR_socketpair, "socketpair"},
+ {__NR_splice, "splice"},
+ {__NR_stat, "stat"},
+ {__NR_statfs, "statfs"},
+ {__NR_statx, "statx"},
+ {__NR_swapoff, "swapoff"},
+ {__NR_swapon, "swapon"},
+ {__NR_symlink, "symlink"},
+ {__NR_symlinkat, "symlinkat"},
+ {__NR_sync, "sync"},
+ {__NR_sync_file_range, "sync_file_range"},
+ {__NR_syncfs, "syncfs"},
+ {__NR__sysctl, "_sysctl"},
+ {__NR_sysfs, "sysfs"},
+ {__NR_sysinfo, "sysinfo"},
+ {__NR_syslog, "syslog"},
+ {__NR_tee, "tee"},
+ {__NR_tgkill, "tgkill"},
+ {__NR_time, "time"},
+ {__NR_timer_create, "timer_create"},
+ {__NR_timer_delete, "timer_delete"},
+ {__NR_timerfd_create, "timerfd_create"},
+ {__NR_timerfd_gettime, "timerfd_gettime"},
+ {__NR_timerfd_settime, "timerfd_settime"},
+ {__NR_timer_getoverrun, "timer_getoverrun"},
+ {__NR_timer_gettime, "timer_gettime"},
+ {__NR_timer_settime, "timer_settime"},
+ {__NR_times, "times"},
+ {__NR_tkill, "tkill"},
+ {__NR_truncate, "truncate"},
+ {__NR_tuxcall, "tuxcall"},
+ {__NR_umask, "umask"},
+ {__NR_umount2, "umount2"},
+ {__NR_uname, "uname"},
+ {__NR_unlink, "unlink"},
+ {__NR_unlinkat, "unlinkat"},
+ {__NR_unshare, "unshare"},
+ {__NR_uselib, "uselib"},
+ {__NR_userfaultfd, "userfaultfd"},
+ {__NR_ustat, "ustat"},
+ {__NR_utime, "utime"},
+ {__NR_utimensat, "utimensat"},
+ {__NR_utimes, "utimes"},
+ {__NR_vfork, "vfork"},
+ {__NR_vhangup, "vhangup"},
+ {__NR_vmsplice, "vmsplice"},
+ {__NR_vserver, "vserver"},
+ {__NR_wait4, "wait4"},
+ {__NR_waitid, "waitid"},
+ {__NR_write, "write"},
+ {__NR_writev, "writev"},
+};
+
+std::string GetLinuxSyscallName(uint32_t syscall_number)
+{
+ const auto element = LINUX_SYSCALLS.find(syscall_number);
+ if (element != LINUX_SYSCALLS.end()) {
+ return element->second;
+ }
+ return "*unknown*";
+}
+
+// See Linux kernel developer Kees Cook's seccomp guide at <https://outflux.net/teach-seccomp/> for
+// an accessible introduction to using seccomp.
+//
+// This function largely follows <https://outflux.net/teach-seccomp/step-3/syscall-reporter.c> and
+// <https://outflux.net/teach-seccomp/step-3/seccomp-bpf.h>.
+//
+// Seccomp BPF resources:
+// * Seccomp BPF documentation: <https://www.kernel.org/doc/html/latest/userspace-api/seccomp_filter.html>
+// * seccomp(2) manual page: <https://www.kernel.org/doc/man-pages/online/pages/man2/seccomp.2.html>
+// * Seccomp BPF demo code samples: <https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/samples/seccomp>
+void SyscallSandboxDebugSignalHandler(int, siginfo_t* signal_info, void* void_signal_context)
+{
+ // The si_code field inside the siginfo_t argument that is passed to a SA_SIGINFO signal handler
+ // is a value indicating why the signal was sent.
+ //
+ // The following value can be placed in si_code for a SIGSYS signal:
+ // * SYS_SECCOMP (since Linux 3.5): Triggered by a seccomp(2) filter rule.
+ constexpr int32_t SYS_SECCOMP_SI_CODE{1};
+ assert(signal_info->si_code == SYS_SECCOMP_SI_CODE);
+
+ // The ucontext_t structure contains signal context information that was saved on the user-space
+ // stack by the kernel.
+ const ucontext_t* signal_context = static_cast<ucontext_t*>(void_signal_context);
+ assert(signal_context != nullptr);
+
+ std::set_new_handler(std::terminate);
+ // Portability note: REG_RAX is Linux x86_64 specific.
+ const uint32_t syscall_number = static_cast<uint32_t>(signal_context->uc_mcontext.gregs[REG_RAX]);
+ const std::string syscall_name = GetLinuxSyscallName(syscall_number);
+ const std::string thread_name = !util::ThreadGetInternalName().empty() ? util::ThreadGetInternalName() : "*unnamed*";
+ const std::string error_message = strprintf("ERROR: The syscall \"%s\" (syscall number %d) is not allowed by the syscall sandbox in thread \"%s\". Please report.", syscall_name, syscall_number, thread_name);
+ tfm::format(std::cerr, "%s\n", error_message);
+ LogPrintf("%s\n", error_message);
+ std::terminate();
+}
+
+// This function largely follows install_syscall_reporter from Kees Cook's seccomp guide:
+// <https://outflux.net/teach-seccomp/step-3/syscall-reporter.c>
+bool SetupSyscallSandboxDebugHandler()
+{
+ struct sigaction action = {};
+ sigset_t mask;
+ sigemptyset(&mask);
+ sigaddset(&mask, SIGSYS);
+ action.sa_sigaction = &SyscallSandboxDebugSignalHandler;
+ action.sa_flags = SA_SIGINFO;
+ if (sigaction(SIGSYS, &action, nullptr) < 0) {
+ return false;
+ }
+ if (sigprocmask(SIG_UNBLOCK, &mask, nullptr)) {
+ return false;
+ }
+ return true;
+}
+
+enum class SyscallSandboxAction {
+ KILL_PROCESS,
+ INVOKE_SIGNAL_HANDLER,
+};
+
+class SeccompPolicyBuilder
+{
+ std::set<uint32_t> allowed_syscalls;
+
+public:
+ SeccompPolicyBuilder()
+ {
+ // Allowed by default.
+ AllowAddressSpaceAccess();
+ AllowEpoll();
+ AllowEventFd();
+ AllowFutex();
+ AllowGeneralIo();
+ AllowGetRandom();
+ AllowGetSimpleId();
+ AllowGetTime();
+ AllowGlobalProcessEnvironment();
+ AllowGlobalSystemStatus();
+ AllowKernelInternalApi();
+ AllowNetworkSocketInformation();
+ AllowOperationOnExistingFileDescriptor();
+ AllowPipe();
+ AllowPrctl();
+ AllowProcessStartOrDeath();
+ AllowScheduling();
+ AllowSignalHandling();
+ AllowSleep();
+ AllowUmask();
+ }
+
+ void AllowAddressSpaceAccess()
+ {
+ allowed_syscalls.insert(__NR_brk); // change data segment size
+ allowed_syscalls.insert(__NR_madvise); // give advice about use of memory
+ allowed_syscalls.insert(__NR_membarrier); // issue memory barriers on a set of threads
+ allowed_syscalls.insert(__NR_mlock); // lock memory
+ allowed_syscalls.insert(__NR_mmap); // map files or devices into memory
+ allowed_syscalls.insert(__NR_mprotect); // set protection on a region of memory
+ allowed_syscalls.insert(__NR_mremap); // remap a file in memory
+ allowed_syscalls.insert(__NR_munlock); // unlock memory
+ allowed_syscalls.insert(__NR_munmap); // unmap files or devices into memory
+ }
+
+ void AllowEpoll()
+ {
+ allowed_syscalls.insert(__NR_epoll_create1); // open an epoll file descriptor
+ allowed_syscalls.insert(__NR_epoll_ctl); // control interface for an epoll file descriptor
+ allowed_syscalls.insert(__NR_epoll_pwait); // wait for an I/O event on an epoll file descriptor
+ allowed_syscalls.insert(__NR_epoll_wait); // wait for an I/O event on an epoll file descriptor
+ }
+
+ void AllowEventFd()
+ {
+ allowed_syscalls.insert(__NR_eventfd2); // create a file descriptor for event notification
+ }
+
+ void AllowFileSystem()
+ {
+ allowed_syscalls.insert(__NR_access); // check user's permissions for a file
+ allowed_syscalls.insert(__NR_chdir); // change working directory
+ allowed_syscalls.insert(__NR_chmod); // change permissions of a file
+ allowed_syscalls.insert(__NR_copy_file_range); // copy a range of data from one file to another
+ allowed_syscalls.insert(__NR_fallocate); // manipulate file space
+ allowed_syscalls.insert(__NR_fchmod); // change permissions of a file
+ allowed_syscalls.insert(__NR_fchown); // change ownership of a file
+ allowed_syscalls.insert(__NR_fdatasync); // synchronize a file's in-core state with storage device
+ allowed_syscalls.insert(__NR_flock); // apply or remove an advisory lock on an open file
+ allowed_syscalls.insert(__NR_fstat); // get file status
+ allowed_syscalls.insert(__NR_newfstatat); // get file status
+ allowed_syscalls.insert(__NR_fsync); // synchronize a file's in-core state with storage device
+ allowed_syscalls.insert(__NR_ftruncate); // truncate a file to a specified length
+ allowed_syscalls.insert(__NR_getcwd); // get current working directory
+ allowed_syscalls.insert(__NR_getdents); // get directory entries
+ allowed_syscalls.insert(__NR_getdents64); // get directory entries
+ allowed_syscalls.insert(__NR_lstat); // get file status
+ allowed_syscalls.insert(__NR_mkdir); // create a directory
+ allowed_syscalls.insert(__NR_open); // open and possibly create a file
+ allowed_syscalls.insert(__NR_openat); // open and possibly create a file
+ allowed_syscalls.insert(__NR_readlink); // read value of a symbolic link
+ allowed_syscalls.insert(__NR_rename); // change the name or location of a file
+ allowed_syscalls.insert(__NR_rmdir); // delete a directory
+ allowed_syscalls.insert(__NR_stat); // get file status
+ allowed_syscalls.insert(__NR_statfs); // get filesystem statistics
+ allowed_syscalls.insert(__NR_statx); // get file status (extended)
+ allowed_syscalls.insert(__NR_unlink); // delete a name and possibly the file it refers to
+ }
+
+ void AllowFutex()
+ {
+ allowed_syscalls.insert(__NR_futex); // fast user-space locking
+ allowed_syscalls.insert(__NR_set_robust_list); // set list of robust futexes
+ }
+
+ void AllowGeneralIo()
+ {
+ allowed_syscalls.insert(__NR_ioctl); // control device
+ allowed_syscalls.insert(__NR_lseek); // reposition read/write file offset
+ allowed_syscalls.insert(__NR_poll); // wait for some event on a file descriptor
+ allowed_syscalls.insert(__NR_ppoll); // wait for some event on a file descriptor
+ allowed_syscalls.insert(__NR_pread64); // read from a file descriptor at a given offset
+ allowed_syscalls.insert(__NR_pwrite64); // write to a file descriptor at a given offset
+ allowed_syscalls.insert(__NR_read); // read from a file descriptor
+ allowed_syscalls.insert(__NR_readv); // read data into multiple buffers
+ allowed_syscalls.insert(__NR_recvfrom); // receive a message from a socket
+ allowed_syscalls.insert(__NR_recvmsg); // receive a message from a socket
+ allowed_syscalls.insert(__NR_select); // synchronous I/O multiplexing
+ allowed_syscalls.insert(__NR_sendmmsg); // send multiple messages on a socket
+ allowed_syscalls.insert(__NR_sendmsg); // send a message on a socket
+ allowed_syscalls.insert(__NR_sendto); // send a message on a socket
+ allowed_syscalls.insert(__NR_write); // write to a file descriptor
+ allowed_syscalls.insert(__NR_writev); // write data into multiple buffers
+ }
+
+ void AllowGetRandom()
+ {
+ allowed_syscalls.insert(__NR_getrandom); // obtain a series of random bytes
+ }
+
+ void AllowGetSimpleId()
+ {
+ allowed_syscalls.insert(__NR_getegid); // get group identity
+ allowed_syscalls.insert(__NR_geteuid); // get user identity
+ allowed_syscalls.insert(__NR_getgid); // get group identity
+ allowed_syscalls.insert(__NR_getpgid); // get process group
+ allowed_syscalls.insert(__NR_getpid); // get process identification
+ allowed_syscalls.insert(__NR_getppid); // get process identification
+ allowed_syscalls.insert(__NR_getresgid); // get real, effective and saved group IDs
+ allowed_syscalls.insert(__NR_getresuid); // get real, effective and saved user IDs
+ allowed_syscalls.insert(__NR_getsid); // get session ID
+ allowed_syscalls.insert(__NR_gettid); // get thread identification
+ allowed_syscalls.insert(__NR_getuid); // get user identity
+ }
+
+ void AllowGetTime()
+ {
+ allowed_syscalls.insert(__NR_clock_getres); // find the resolution (precision) of the specified clock
+ allowed_syscalls.insert(__NR_clock_gettime); // retrieve the time of the specified clock
+ }
+
+ void AllowGlobalProcessEnvironment()
+ {
+ allowed_syscalls.insert(__NR_getrlimit); // get resource limits
+ allowed_syscalls.insert(__NR_getrusage); // get resource usage
+ allowed_syscalls.insert(__NR_prlimit64); // get/set resource limits
+ }
+
+ void AllowGlobalSystemStatus()
+ {
+ allowed_syscalls.insert(__NR_sysinfo); // return system information
+ allowed_syscalls.insert(__NR_uname); // get name and information about current kernel
+ }
+
+ void AllowKernelInternalApi()
+ {
+ allowed_syscalls.insert(__NR_restart_syscall); // restart a system call after interruption by a stop signal
+ }
+
+ void AllowNetwork()
+ {
+ allowed_syscalls.insert(__NR_accept); // accept a connection on a socket
+ allowed_syscalls.insert(__NR_accept4); // accept a connection on a socket
+ allowed_syscalls.insert(__NR_bind); // bind a name to a socket
+ allowed_syscalls.insert(__NR_connect); // initiate a connection on a socket
+ allowed_syscalls.insert(__NR_listen); // listen for connections on a socket
+ allowed_syscalls.insert(__NR_setsockopt); // set options on sockets
+ allowed_syscalls.insert(__NR_socket); // create an endpoint for communication
+ allowed_syscalls.insert(__NR_socketpair); // create a pair of connected sockets
+ }
+
+ void AllowNetworkSocketInformation()
+ {
+ allowed_syscalls.insert(__NR_getpeername); // get name of connected peer socket
+ allowed_syscalls.insert(__NR_getsockname); // get socket name
+ allowed_syscalls.insert(__NR_getsockopt); // get options on sockets
+ }
+
+ void AllowOperationOnExistingFileDescriptor()
+ {
+ allowed_syscalls.insert(__NR_close); // close a file descriptor
+ allowed_syscalls.insert(__NR_dup); // duplicate a file descriptor
+ allowed_syscalls.insert(__NR_dup2); // duplicate a file descriptor
+ allowed_syscalls.insert(__NR_fcntl); // manipulate file descriptor
+ allowed_syscalls.insert(__NR_shutdown); // shut down part of a full-duplex connection
+ }
+
+ void AllowPipe()
+ {
+ allowed_syscalls.insert(__NR_pipe); // create pipe
+ allowed_syscalls.insert(__NR_pipe2); // create pipe
+ }
+
+ void AllowPrctl()
+ {
+ allowed_syscalls.insert(__NR_arch_prctl); // set architecture-specific thread state
+ allowed_syscalls.insert(__NR_prctl); // operations on a process
+ }
+
+ void AllowProcessStartOrDeath()
+ {
+ allowed_syscalls.insert(__NR_clone); // create a child process
+ allowed_syscalls.insert(__NR_exit); // terminate the calling process
+ allowed_syscalls.insert(__NR_exit_group); // exit all threads in a process
+ allowed_syscalls.insert(__NR_fork); // create a child process
+ allowed_syscalls.insert(__NR_tgkill); // send a signal to a thread
+ allowed_syscalls.insert(__NR_wait4); // wait for process to change state, BSD style
+ }
+
+ void AllowScheduling()
+ {
+ allowed_syscalls.insert(__NR_sched_getaffinity); // set a thread's CPU affinity mask
+ allowed_syscalls.insert(__NR_sched_getparam); // get scheduling parameters
+ allowed_syscalls.insert(__NR_sched_getscheduler); // get scheduling policy/parameters
+ allowed_syscalls.insert(__NR_sched_setscheduler); // set scheduling policy/parameters
+ allowed_syscalls.insert(__NR_sched_yield); // yield the processor
+ }
+
+ void AllowSignalHandling()
+ {
+ allowed_syscalls.insert(__NR_rt_sigaction); // examine and change a signal action
+ allowed_syscalls.insert(__NR_rt_sigprocmask); // examine and change blocked signals
+ allowed_syscalls.insert(__NR_rt_sigreturn); // return from signal handler and cleanup stack frame
+ allowed_syscalls.insert(__NR_sigaltstack); // set and/or get signal stack context
+ }
+
+ void AllowSleep()
+ {
+ allowed_syscalls.insert(__NR_clock_nanosleep); // high-resolution sleep with specifiable clock
+ allowed_syscalls.insert(__NR_nanosleep); // high-resolution sleep
+ }
+
+ void AllowUmask()
+ {
+ allowed_syscalls.insert(__NR_umask); // set file mode creation mask
+ }
+
+ // See Linux kernel developer Kees Cook's seccomp guide at <https://outflux.net/teach-seccomp/>
+ // for an accessible introduction to using seccomp.
+ //
+ // This function largely follows <https://outflux.net/teach-seccomp/step-3/seccomp-bpf.h>.
+ std::vector<sock_filter> BuildFilter(SyscallSandboxAction default_action)
+ {
+ std::vector<sock_filter> bpf_policy;
+ // See VALIDATE_ARCHITECTURE in seccomp-bpf.h referenced above.
+ bpf_policy.push_back(BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(struct seccomp_data, arch)));
+ // Portability note: AUDIT_ARCH_X86_64 is Linux x86_64 specific.
+ bpf_policy.push_back(BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, AUDIT_ARCH_X86_64, 1, 0));
+ bpf_policy.push_back(BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_KILL_PROCESS));
+ // See EXAMINE_SYSCALL in seccomp-bpf.h referenced above.
+ bpf_policy.push_back(BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(struct seccomp_data, nr)));
+ for (const uint32_t allowed_syscall : allowed_syscalls) {
+ // See ALLOW_SYSCALL in seccomp-bpf.h referenced above.
+ bpf_policy.push_back(BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, allowed_syscall, 0, 1));
+ bpf_policy.push_back(BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ALLOW));
+ }
+ switch (default_action) {
+ case SyscallSandboxAction::KILL_PROCESS:
+ // Disallow syscall and kill the process.
+ //
+ // See KILL_PROCESS in seccomp-bpf.h referenced above.
+ //
+ // Note that we're using SECCOMP_RET_KILL_PROCESS (kill the process) instead
+ // of SECCOMP_RET_KILL_THREAD (kill the thread). The SECCOMP_RET_KILL_PROCESS
+ // action was introduced in Linux 4.14.
+ //
+ // SECCOMP_RET_KILL_PROCESS: Results in the entire process exiting immediately without
+ // executing the system call.
+ //
+ // SECCOMP_RET_KILL_PROCESS documentation:
+ // <https://www.kernel.org/doc/html/latest/userspace-api/seccomp_filter.html>
+ bpf_policy.push_back(BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_KILL_PROCESS));
+ break;
+ case SyscallSandboxAction::INVOKE_SIGNAL_HANDLER:
+ // Disallow syscall and force a SIGSYS to trigger syscall debug reporter.
+ //
+ // SECCOMP_RET_TRAP: Results in the kernel sending a SIGSYS signal to the triggering
+ // task without executing the system call.
+ //
+ // SECCOMP_RET_TRAP documentation:
+ // <https://www.kernel.org/doc/html/latest/userspace-api/seccomp_filter.html>
+ bpf_policy.push_back(BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_TRAP));
+ break;
+ }
+ return bpf_policy;
+ }
+};
+} // namespace
+
+bool SetupSyscallSandbox(bool log_syscall_violation_before_terminating)
+{
+ assert(!g_syscall_sandbox_enabled && "SetupSyscallSandbox(...) should only be called once.");
+ g_syscall_sandbox_enabled = true;
+ g_syscall_sandbox_log_violation_before_terminating = log_syscall_violation_before_terminating;
+ if (log_syscall_violation_before_terminating) {
+ if (!SetupSyscallSandboxDebugHandler()) {
+ return false;
+ }
+ }
+ SetSyscallSandboxPolicy(SyscallSandboxPolicy::INITIALIZATION);
+ return true;
+}
+
+void TestDisallowedSandboxCall()
+{
+ // The getgroups syscall is assumed NOT to be allowed by the syscall sandbox policy.
+ std::array<gid_t, 1> groups;
+ [[maybe_unused]] int32_t ignored = getgroups(groups.size(), groups.data());
+}
+#endif // defined(USE_SYSCALL_SANDBOX)
+
+void SetSyscallSandboxPolicy(SyscallSandboxPolicy syscall_policy)
+{
+#if defined(USE_SYSCALL_SANDBOX)
+ if (!g_syscall_sandbox_enabled) {
+ return;
+ }
+ SeccompPolicyBuilder seccomp_policy_builder;
+ switch (syscall_policy) {
+ case SyscallSandboxPolicy::INITIALIZATION: // Thread: main thread (state: init)
+ // SyscallSandboxPolicy::INITIALIZATION is the first policy loaded.
+ //
+ // Subsequently loaded policies can reduce the abilities further, but
+ // abilities can never be regained.
+ //
+ // SyscallSandboxPolicy::INITIALIZATION must thus be a superset of all
+ // other policies.
+ seccomp_policy_builder.AllowFileSystem();
+ seccomp_policy_builder.AllowNetwork();
+ break;
+ case SyscallSandboxPolicy::INITIALIZATION_DNS_SEED: // Thread: dnsseed
+ seccomp_policy_builder.AllowFileSystem();
+ seccomp_policy_builder.AllowNetwork();
+ break;
+ case SyscallSandboxPolicy::INITIALIZATION_LOAD_BLOCKS: // Thread: loadblk
+ seccomp_policy_builder.AllowFileSystem();
+ break;
+ case SyscallSandboxPolicy::INITIALIZATION_MAP_PORT: // Thread: mapport
+ seccomp_policy_builder.AllowFileSystem();
+ seccomp_policy_builder.AllowNetwork();
+ break;
+ case SyscallSandboxPolicy::MESSAGE_HANDLER: // Thread: msghand
+ seccomp_policy_builder.AllowFileSystem();
+ break;
+ case SyscallSandboxPolicy::NET: // Thread: net
+ seccomp_policy_builder.AllowFileSystem();
+ seccomp_policy_builder.AllowNetwork();
+ break;
+ case SyscallSandboxPolicy::NET_ADD_CONNECTION: // Thread: addcon
+ seccomp_policy_builder.AllowFileSystem();
+ seccomp_policy_builder.AllowNetwork();
+ break;
+ case SyscallSandboxPolicy::NET_HTTP_SERVER: // Thread: http
+ seccomp_policy_builder.AllowFileSystem();
+ seccomp_policy_builder.AllowNetwork();
+ break;
+ case SyscallSandboxPolicy::NET_HTTP_SERVER_WORKER: // Thread: httpworker.<N>
+ seccomp_policy_builder.AllowFileSystem();
+ seccomp_policy_builder.AllowNetwork();
+ break;
+ case SyscallSandboxPolicy::NET_OPEN_CONNECTION: // Thread: opencon
+ seccomp_policy_builder.AllowFileSystem();
+ seccomp_policy_builder.AllowNetwork();
+ break;
+ case SyscallSandboxPolicy::SCHEDULER: // Thread: scheduler
+ seccomp_policy_builder.AllowFileSystem();
+ break;
+ case SyscallSandboxPolicy::TOR_CONTROL: // Thread: torcontrol
+ seccomp_policy_builder.AllowFileSystem();
+ seccomp_policy_builder.AllowNetwork();
+ break;
+ case SyscallSandboxPolicy::TX_INDEX: // Thread: txindex
+ seccomp_policy_builder.AllowFileSystem();
+ break;
+ case SyscallSandboxPolicy::VALIDATION_SCRIPT_CHECK: // Thread: scriptch.<N>
+ break;
+ case SyscallSandboxPolicy::SHUTOFF: // Thread: main thread (state: shutoff)
+ seccomp_policy_builder.AllowFileSystem();
+ break;
+ }
+
+ const SyscallSandboxAction default_action = g_syscall_sandbox_log_violation_before_terminating ? SyscallSandboxAction::INVOKE_SIGNAL_HANDLER : SyscallSandboxAction::KILL_PROCESS;
+ std::vector<sock_filter> filter = seccomp_policy_builder.BuildFilter(default_action);
+ const sock_fprog prog = {
+ .len = static_cast<uint16_t>(filter.size()),
+ .filter = filter.data(),
+ };
+ // Do not allow abilities to be regained after being dropped.
+ //
+ // PR_SET_NO_NEW_PRIVS documentation: <https://www.kernel.org/doc/html/latest/userspace-api/no_new_privs.html>
+ if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) {
+ throw std::runtime_error("Syscall sandbox enforcement failed: prctl(PR_SET_NO_NEW_PRIVS)");
+ }
+ // Install seccomp-bpf syscall filter.
+ //
+ // PR_SET_SECCOMP documentation: <https://www.kernel.org/doc/html/latest/userspace-api/seccomp_filter.html>
+ if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) != 0) {
+ throw std::runtime_error("Syscall sandbox enforcement failed: prctl(PR_SET_SECCOMP)");
+ }
+
+ const std::string thread_name = !util::ThreadGetInternalName().empty() ? util::ThreadGetInternalName() : "*unnamed*";
+ LogPrint(BCLog::UTIL, "Syscall filter installed for thread \"%s\"\n", thread_name);
+#endif // defined(USE_SYSCALL_SANDBOX)
+}
diff --git a/src/util/syscall_sandbox.h b/src/util/syscall_sandbox.h
new file mode 100644
index 0000000000..0a0c964f94
--- /dev/null
+++ b/src/util/syscall_sandbox.h
@@ -0,0 +1,57 @@
+// Copyright (c) 2020 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_UTIL_SYSCALL_SANDBOX_H
+#define BITCOIN_UTIL_SYSCALL_SANDBOX_H
+
+enum class SyscallSandboxPolicy {
+ // 1. Initialization
+ INITIALIZATION,
+ INITIALIZATION_DNS_SEED,
+ INITIALIZATION_LOAD_BLOCKS,
+ INITIALIZATION_MAP_PORT,
+
+ // 2. Steady state (non-initialization, non-shutdown)
+ MESSAGE_HANDLER,
+ NET,
+ NET_ADD_CONNECTION,
+ NET_HTTP_SERVER,
+ NET_HTTP_SERVER_WORKER,
+ NET_OPEN_CONNECTION,
+ SCHEDULER,
+ TOR_CONTROL,
+ TX_INDEX,
+ VALIDATION_SCRIPT_CHECK,
+
+ // 3. Shutdown
+ SHUTOFF,
+};
+
+//! Force the current thread (and threads created from the current thread) into a restricted-service
+//! operating mode where only a subset of all syscalls are available.
+//!
+//! Subsequent calls to this function can reduce the abilities further, but abilities can never be
+//! regained.
+//!
+//! This function is a no-op unless SetupSyscallSandbox(...) has been called.
+//!
+//! SetupSyscallSandbox(...) is called during bitcoind initialization if Bitcoin Core was compiled
+//! with seccomp-bpf support (--with-seccomp) *and* the parameter -sandbox=<mode> was passed to
+//! bitcoind.
+//!
+//! This experimental feature is available under Linux x86_64 only.
+void SetSyscallSandboxPolicy(SyscallSandboxPolicy syscall_policy);
+
+#if defined(USE_SYSCALL_SANDBOX)
+//! Setup and enable the experimental syscall sandbox for the running process.
+//!
+//! SetSyscallSandboxPolicy(SyscallSandboxPolicy::INITIALIZATION) is called as part of
+//! SetupSyscallSandbox(...).
+[[nodiscard]] bool SetupSyscallSandbox(bool log_syscall_violation_before_terminating);
+
+//! Invoke a disallowed syscall. Use for testing purposes.
+void TestDisallowedSandboxCall();
+#endif // defined(USE_SYSCALL_SANDBOX)
+
+#endif // BITCOIN_UTIL_SYSCALL_SANDBOX_H
diff --git a/src/util/system.cpp b/src/util/system.cpp
index 4e16a83c87..79c08816fa 100644
--- a/src/util/system.cpp
+++ b/src/util/system.cpp
@@ -158,16 +158,14 @@ std::streampos GetFileSize(const char* path, std::streamsize max) {
/**
* Interpret a string argument as a boolean.
*
- * The definition of atoi() requires that non-numeric string values like "foo",
- * return 0. This means that if a user unintentionally supplies a non-integer
- * argument here, the return value is always false. This means that -foo=false
- * does what the user probably expects, but -foo=true is well defined but does
- * not do what they probably expected.
+ * The definition of LocaleIndependentAtoi<int>() requires that non-numeric string values
+ * like "foo", return 0. This means that if a user unintentionally supplies a
+ * non-integer argument here, the return value is always false. This means that
+ * -foo=false does what the user probably expects, but -foo=true is well defined
+ * but does not do what they probably expected.
*
- * The return value of atoi() is undefined when given input not representable as
- * an int. On most systems this means string value between "-2147483648" and
- * "2147483647" are well defined (this method will return true). Setting
- * -txindex=2147483648 on most systems, however, is probably undefined.
+ * The return value of LocaleIndependentAtoi<int>(...) is zero when given input not
+ * representable as an int.
*
* For a more extensive discussion of this topic (and a wide range of opinions
* on the Right Way to change this code), see PR12713.
@@ -176,7 +174,7 @@ static bool InterpretBool(const std::string& strValue)
{
if (strValue.empty())
return true;
- return (atoi(strValue) != 0);
+ return (LocaleIndependentAtoi<int>(strValue) != 0);
}
static std::string SettingName(const std::string& arg)
@@ -591,10 +589,10 @@ std::string ArgsManager::GetArg(const std::string& strArg, const std::string& st
return value.isNull() ? strDefault : value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str();
}
-int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault) const
+int64_t ArgsManager::GetIntArg(const std::string& strArg, int64_t nDefault) const
{
const util::SettingsValue value = GetSetting(strArg);
- return value.isNull() ? nDefault : value.isFalse() ? 0 : value.isTrue() ? 1 : value.isNum() ? value.get_int64() : atoi64(value.get_str());
+ return value.isNull() ? nDefault : value.isFalse() ? 0 : value.isTrue() ? 1 : value.isNum() ? value.get_int64() : LocaleIndependentAtoi<int64_t>(value.get_str());
}
bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
@@ -1306,7 +1304,7 @@ void SetupEnvironment()
#endif
// On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
// may be invalid, in which case the "C.UTF-8" locale is used as fallback.
-#if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
+#if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
try {
std::locale(""); // Raises a runtime error if current locale is invalid
} catch (const std::runtime_error&) {
diff --git a/src/util/system.h b/src/util/system.h
index 3c1399629c..2e217f6f90 100644
--- a/src/util/system.h
+++ b/src/util/system.h
@@ -327,7 +327,7 @@ protected:
* @param nDefault (e.g. 1)
* @return command-line argument (0 if invalid number) or default value
*/
- int64_t GetArg(const std::string& strArg, int64_t nDefault) const;
+ int64_t GetIntArg(const std::string& strArg, int64_t nDefault) const;
/**
* Return boolean argument or default value
diff --git a/src/util/types.h b/src/util/types.h
new file mode 100644
index 0000000000..0047b00026
--- /dev/null
+++ b/src/util/types.h
@@ -0,0 +1,11 @@
+// Copyright (c) 2021 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_UTIL_TYPES_H
+#define BITCOIN_UTIL_TYPES_H
+
+template <class>
+inline constexpr bool ALWAYS_FALSE{false};
+
+#endif // BITCOIN_UTIL_TYPES_H
diff --git a/src/validation.cpp b/src/validation.cpp
index 753b824167..14dcd2c24b 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -9,6 +9,7 @@
#include <chain.h>
#include <chainparams.h>
#include <checkqueue.h>
+#include <consensus/amount.h>
#include <consensus/consensus.h>
#include <consensus/merkle.h>
#include <consensus/tx_check.h>
@@ -24,6 +25,7 @@
#include <node/blockstorage.h>
#include <node/coinstats.h>
#include <node/ui_interface.h>
+#include <node/utxo_snapshot.h>
#include <policy/policy.h>
#include <policy/rbf.h>
#include <policy/settings.h>
@@ -192,7 +194,7 @@ bool CheckFinalTx(const CBlockIndex* active_chain_tip, const CTransaction &tx, i
// CheckFinalTx() uses active_chain_tip.Height()+1 to evaluate
// nLockTime because when IsFinalTx() is called within
- // CBlock::AcceptBlock(), the height of the block *being*
+ // AcceptBlock(), the height of the block *being*
// evaluated is what is used. Thus if we want to know if a
// transaction can be part of the *next* block, we need to call
// IsFinalTx() with one more than active_chain_tip.Height().
@@ -372,8 +374,8 @@ void CChainState::MaybeUpdateMempoolForReorg(
LimitMempoolSize(
*m_mempool,
this->CoinsTip(),
- gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000,
- std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
+ gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000,
+ std::chrono::hours{gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
}
/**
@@ -415,7 +417,7 @@ static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, TxValidationS
}
// Call CheckInputScripts() to cache signature and script validity against current tip consensus rules.
- return CheckInputScripts(tx, state, view, flags, /* cacheSigStore = */ true, /* cacheFullSciptStore = */ true, txdata);
+ return CheckInputScripts(tx, state, view, flags, /* cacheSigStore= */ true, /* cacheFullScriptStore= */ true, txdata);
}
namespace {
@@ -424,10 +426,10 @@ class MemPoolAccept
{
public:
explicit MemPoolAccept(CTxMemPool& mempool, CChainState& active_chainstate) : m_pool(mempool), m_view(&m_dummy), m_viewmempool(&active_chainstate.CoinsTip(), m_pool), m_active_chainstate(active_chainstate),
- m_limit_ancestors(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT)),
- m_limit_ancestor_size(gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000),
- m_limit_descendants(gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT)),
- m_limit_descendant_size(gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000) {
+ m_limit_ancestors(gArgs.GetIntArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT)),
+ m_limit_ancestor_size(gArgs.GetIntArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000),
+ m_limit_descendants(gArgs.GetIntArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT)),
+ m_limit_descendant_size(gArgs.GetIntArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000) {
}
// We put the arguments we're handed into a struct, so we can pass them
@@ -472,7 +474,6 @@ private:
std::unique_ptr<CTxMemPoolEntry> m_entry;
std::list<CTransactionRef> m_replaced_transactions;
- bool m_replacement_transaction;
CAmount m_base_fees;
CAmount m_modified_fees;
/** Total modified fees of all transactions being replaced. */
@@ -509,7 +510,7 @@ private:
// Compare a package's feerate against minimum allowed.
bool CheckFeeRate(size_t package_size, CAmount package_fee, TxValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs)
{
- CAmount mempoolRejectFee = m_pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(package_size);
+ CAmount mempoolRejectFee = m_pool.GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(package_size);
if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) {
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool min fee not met", strprintf("%d < %d", package_fee, mempoolRejectFee));
}
@@ -554,7 +555,6 @@ bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
CTxMemPool::setEntries& allConflicting = ws.m_all_conflicting;
CTxMemPool::setEntries& setAncestors = ws.m_ancestors;
std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
- bool& fReplacementTransaction = ws.m_replacement_transaction;
CAmount& nModifiedFees = ws.m_modified_fees;
CAmount& nConflictingFees = ws.m_conflicting_fees;
size_t& nConflictingSize = ws.m_conflicting_size;
@@ -770,117 +770,44 @@ bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
// that we have the set of all ancestors we can detect this
// pathological case by making sure setConflicts and setAncestors don't
// intersect.
- for (CTxMemPool::txiter ancestorIt : setAncestors)
- {
- const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
- if (setConflicts.count(hashAncestor))
- {
- return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-spends-conflicting-tx",
- strprintf("%s spends conflicting transaction %s",
- hash.ToString(),
- hashAncestor.ToString()));
- }
+ if (const auto err_string{EntriesAndTxidsDisjoint(setAncestors, setConflicts, hash)}) {
+ // We classify this as a consensus error because a transaction depending on something it
+ // conflicts with would be inconsistent.
+ return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-spends-conflicting-tx", *err_string);
}
- // If we don't hold the lock allConflicting might be incomplete; the
- // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
- // mempool consistency for us.
- fReplacementTransaction = setConflicts.size();
- if (fReplacementTransaction)
- {
- std::string err_string;
+ if (!setConflicts.empty()) {
CFeeRate newFeeRate(nModifiedFees, nSize);
- for (const auto& mi : setIterConflicting) {
- // Don't allow the replacement to reduce the feerate of the
- // mempool.
- //
- // We usually don't want to accept replacements with lower
- // feerates than what they replaced as that would lower the
- // feerate of the next block. Requiring that the feerate always
- // be increased is also an easy-to-reason about way to prevent
- // DoS attacks via replacements.
- //
- // We only consider the feerates of transactions being directly
- // replaced, not their indirect descendants. While that does
- // mean high feerate children are ignored when deciding whether
- // or not to replace, we do require the replacement to pay more
- // overall fees too, mitigating most cases.
- CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
- if (newFeeRate <= oldFeeRate)
- {
- return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee",
- strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
- hash.ToString(),
- newFeeRate.ToString(),
- oldFeeRate.ToString()));
- }
+ // It's possible that the replacement pays more fees than its direct conflicts but not more
+ // than all conflicts (i.e. the direct conflicts have high-fee descendants). However, if the
+ // replacement doesn't pay more fees than its direct conflicts, then we can be sure it's not
+ // more economically rational to mine. Before we go digging through the mempool for all
+ // transactions that would need to be removed (direct conflicts and all descendants), check
+ // that the replacement transaction pays more than its direct conflicts.
+ if (const auto err_string{PaysMoreThanConflicts(setIterConflicting, newFeeRate, hash)}) {
+ return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee", *err_string);
}
- // Calculate all conflicting entries and enforce Rule #5.
- if (!GetEntriesForConflicts(tx, m_pool, setIterConflicting, allConflicting, err_string)) {
- return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too many potential replacements", err_string);
+ // Calculate all conflicting entries and enforce BIP125 Rule #5.
+ if (const auto err_string{GetEntriesForConflicts(tx, m_pool, setIterConflicting, allConflicting)}) {
+ return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY,
+ "too many potential replacements", *err_string);
+ }
+ // Enforce BIP125 Rule #2.
+ if (const auto err_string{HasNoNewUnconfirmed(tx, m_pool, setIterConflicting)}) {
+ return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY,
+ "replacement-adds-unconfirmed", *err_string);
}
- // Check if it's economically rational to mine this transaction rather
- // than the ones it replaces.
+ // Check if it's economically rational to mine this transaction rather than the ones it
+ // replaces and pays for its own relay fees. Enforce BIP125 Rules #3 and #4.
for (CTxMemPool::txiter it : allConflicting) {
nConflictingFees += it->GetModifiedFee();
nConflictingSize += it->GetTxSize();
}
-
- std::set<uint256> setConflictsParents;
- for (const auto& mi : setIterConflicting) {
- for (const CTxIn &txin : mi->GetTx().vin)
- {
- setConflictsParents.insert(txin.prevout.hash);
- }
- }
-
- for (unsigned int j = 0; j < tx.vin.size(); j++)
- {
- // We don't want to accept replacements that require low
- // feerate junk to be mined first. Ideally we'd keep track of
- // the ancestor feerates and make the decision based on that,
- // but for now requiring all new inputs to be confirmed works.
- //
- // Note that if you relax this to make RBF a little more useful,
- // this may break the CalculateMempoolAncestors RBF relaxation,
- // above. See the comment above the first CalculateMempoolAncestors
- // call for more info.
- if (!setConflictsParents.count(tx.vin[j].prevout.hash))
- {
- // Rather than check the UTXO set - potentially expensive -
- // it's cheaper to just check if the new input refers to a
- // tx that's in the mempool.
- if (m_pool.exists(tx.vin[j].prevout.hash)) {
- return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "replacement-adds-unconfirmed",
- strprintf("replacement %s adds unconfirmed input, idx %d",
- hash.ToString(), j));
- }
- }
- }
-
- // The replacement must pay greater fees than the transactions it
- // replaces - if we did the bandwidth used by those conflicting
- // transactions would not be paid for.
- if (nModifiedFees < nConflictingFees)
- {
- return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee",
- strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
- hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
- }
-
- // Finally in addition to paying more fees than the conflicts the
- // new transaction must pay for its own bandwidth.
- CAmount nDeltaFees = nModifiedFees - nConflictingFees;
- if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
- {
- return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee",
- strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
- hash.ToString(),
- FormatMoney(nDeltaFees),
- FormatMoney(::incrementalRelayFee.GetFee(nSize))));
+ if (const auto err_string{PaysForRBF(nConflictingFees, nModifiedFees, nSize, ::incrementalRelayFee, hash)}) {
+ return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee", *err_string);
}
}
return true;
@@ -955,7 +882,6 @@ bool MemPoolAccept::Finalize(const ATMPArgs& args, Workspace& ws)
const CAmount& nModifiedFees = ws.m_modified_fees;
const CAmount& nConflictingFees = ws.m_conflicting_fees;
const size_t& nConflictingSize = ws.m_conflicting_size;
- const bool fReplacementTransaction = ws.m_replacement_transaction;
std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
// Remove conflicting transactions from the mempool
@@ -971,18 +897,17 @@ bool MemPoolAccept::Finalize(const ATMPArgs& args, Workspace& ws)
m_pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
// This transaction should only count for fee estimation if:
- // - it isn't a BIP 125 replacement transaction (may not be widely supported)
// - it's not being re-added during a reorg which bypasses typical mempool fee limits
// - the node is not behind
// - the transaction is not dependent on any other transactions in the mempool
- bool validForFeeEstimation = !fReplacementTransaction && !bypass_limits && IsCurrentForFeeEstimation(m_active_chainstate) && m_pool.HasNoInputsOf(tx);
+ bool validForFeeEstimation = !bypass_limits && IsCurrentForFeeEstimation(m_active_chainstate) && m_pool.HasNoInputsOf(tx);
// Store transaction in memory
m_pool.addUnchecked(*entry, setAncestors, validForFeeEstimation);
// trim mempool and check if tx was trimmed
if (!bypass_limits) {
- LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip(), gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
+ LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip(), gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, std::chrono::hours{gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
if (!m_pool.exists(hash))
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
}
@@ -1166,10 +1091,15 @@ void CoinsViews::InitCache()
m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
}
-CChainState::CChainState(CTxMemPool* mempool, BlockManager& blockman, std::optional<uint256> from_snapshot_blockhash)
+CChainState::CChainState(
+ CTxMemPool* mempool,
+ BlockManager& blockman,
+ ChainstateManager& chainman,
+ std::optional<uint256> from_snapshot_blockhash)
: m_mempool(mempool),
m_params(::Params()),
m_blockman(blockman),
+ m_chainman(chainman),
m_from_snapshot_blockhash(from_snapshot_blockhash) {}
void CChainState::InitCoinsDB(
@@ -1339,7 +1269,7 @@ void InitScriptExecutionCache() {
g_scriptExecutionCacheHasher.Write(nonce.begin(), 32);
// nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
// setup_bytes creates the minimum possible cache (2 elements).
- size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
+ size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetIntArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
size_t nElems = g_scriptExecutionCache.setup_bytes(nMaxCacheSize);
LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
(nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
@@ -1643,7 +1573,6 @@ static int64_t nTimeForks = 0;
static int64_t nTimeVerify = 0;
static int64_t nTimeConnect = 0;
static int64_t nTimeIndex = 0;
-static int64_t nTimeCallbacks = 0;
static int64_t nTimeTotal = 0;
static int64_t nBlocksTotal = 0;
@@ -1948,9 +1877,6 @@ bool CChainState::ConnectBlock(const CBlock& block, BlockValidationState& state,
int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
- int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
- LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
-
TRACE7(validation, block_connected,
block.GetHash().ToString().c_str(),
pindex->nHeight,
@@ -1968,7 +1894,7 @@ CoinsCacheSizeState CChainState::GetCoinsCacheSizeState()
{
return this->GetCoinsCacheSizeState(
m_coinstip_cache_size_bytes,
- gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
+ gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
}
CoinsCacheSizeState CChainState::GetCoinsCacheSizeState(
@@ -2165,8 +2091,42 @@ static void AppendWarning(bilingual_str& res, const bilingual_str& warn)
res += warn;
}
+static void UpdateTipLog(
+ const CCoinsViewCache& coins_tip,
+ const CBlockIndex* tip,
+ const CChainParams& params,
+ const std::string& func_name,
+ const std::string& prefix,
+ const std::string& warning_messages) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
+{
+
+ AssertLockHeld(::cs_main);
+ LogPrintf("%s%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)%s\n",
+ prefix, func_name,
+ tip->GetBlockHash().ToString(), tip->nHeight, tip->nVersion,
+ log(tip->nChainWork.getdouble()) / log(2.0), (unsigned long)tip->nChainTx,
+ FormatISO8601DateTime(tip->GetBlockTime()),
+ GuessVerificationProgress(params.TxData(), tip),
+ coins_tip.DynamicMemoryUsage() * (1.0 / (1 << 20)),
+ coins_tip.GetCacheSize(),
+ !warning_messages.empty() ? strprintf(" warning='%s'", warning_messages) : "");
+}
+
void CChainState::UpdateTip(const CBlockIndex* pindexNew)
{
+ const auto& coins_tip = this->CoinsTip();
+
+ // The remainder of the function isn't relevant if we are not acting on
+ // the active chainstate, so return if need be.
+ if (this != &m_chainman.ActiveChainstate()) {
+ // Only log every so often so that we don't bury log messages at the tip.
+ constexpr int BACKGROUND_LOG_INTERVAL = 2000;
+ if (pindexNew->nHeight % BACKGROUND_LOG_INTERVAL == 0) {
+ UpdateTipLog(coins_tip, pindexNew, m_params, __func__, "[background validation] ", "");
+ }
+ return;
+ }
+
// New best block
if (m_mempool) {
m_mempool->AddTransactionsUpdated(1);
@@ -2194,12 +2154,7 @@ void CChainState::UpdateTip(const CBlockIndex* pindexNew)
}
}
}
- LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)%s\n", __func__,
- pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, pindexNew->nVersion,
- log(pindexNew->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
- FormatISO8601DateTime(pindexNew->GetBlockTime()),
- GuessVerificationProgress(m_params.TxData(), pindexNew), this->CoinsTip().DynamicMemoryUsage() * (1.0 / (1<<20)), this->CoinsTip().GetCacheSize(),
- !warning_messages.empty() ? strprintf(" warning='%s'", warning_messages.original) : "");
+ UpdateTipLog(coins_tip, pindexNew, m_params, __func__, "", warning_messages.original);
}
/** Disconnect m_chain's tip.
@@ -2593,7 +2548,7 @@ bool CChainState::ActivateBestChain(BlockValidationState& state, std::shared_ptr
CBlockIndex *pindexMostWork = nullptr;
CBlockIndex *pindexNewTip = nullptr;
- int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
+ int nStopAtHeight = gArgs.GetIntArg("-stopatheight", DEFAULT_STOPATHEIGHT);
do {
// Block until the validation queue drains. This should largely
// never happen in normal operation, however may happen during
@@ -3696,7 +3651,9 @@ bool BlockManager::LoadBlockIndex(
pindex->nStatus |= BLOCK_FAILED_CHILD;
setDirtyBlockIndex.insert(pindex);
}
- if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->HaveTxsDownloaded() || pindex->pprev == nullptr)) {
+ if (pindex->IsAssumedValid() ||
+ (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) &&
+ (pindex->HaveTxsDownloaded() || pindex->pprev == nullptr))) {
block_index_candidates.insert(pindex);
}
if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
@@ -3779,7 +3736,7 @@ bool BlockManager::LoadBlockIndexDB(std::set<CBlockIndex*, CBlockIndexWorkCompar
void CChainState::LoadMempool(const ArgsManager& args)
{
if (!m_mempool) return;
- if (args.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
+ if (args.GetBoolArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
::LoadMempool(*m_mempool, *this);
}
m_mempool->SetIsLoaded(!ShutdownRequested());
@@ -4275,12 +4232,33 @@ void CChainState::CheckBlockIndex()
while (pindex != nullptr) {
nNodes++;
if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
- if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
+ // Assumed-valid index entries will not have data since we haven't downloaded the
+ // full block yet.
+ if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA) && !pindex->IsAssumedValid()) {
+ pindexFirstMissing = pindex;
+ }
if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
- if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
- if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
- if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
+
+ if (pindex->pprev != nullptr && !pindex->IsAssumedValid()) {
+ // Skip validity flag checks for BLOCK_ASSUMED_VALID index entries, since these
+ // *_VALID_MASK flags will not be present for index entries we are temporarily assuming
+ // valid.
+ if (pindexFirstNotTransactionsValid == nullptr &&
+ (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) {
+ pindexFirstNotTransactionsValid = pindex;
+ }
+
+ if (pindexFirstNotChainValid == nullptr &&
+ (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) {
+ pindexFirstNotChainValid = pindex;
+ }
+
+ if (pindexFirstNotScriptsValid == nullptr &&
+ (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) {
+ pindexFirstNotScriptsValid = pindex;
+ }
+ }
// Begin: actual consistency checks.
if (pindex->pprev == nullptr) {
@@ -4291,7 +4269,9 @@ void CChainState::CheckBlockIndex()
if (!pindex->HaveTxsDownloaded()) assert(pindex->nSequenceId <= 0); // nSequenceId can't be set positive for blocks that aren't linked (negative is used for preciousblock)
// VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
// HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
- if (!fHavePruned) {
+ // Unless these indexes are assumed valid and pending block download on a
+ // background chainstate.
+ if (!fHavePruned && !pindex->IsAssumedValid()) {
// If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
assert(pindexFirstMissing == pindexFirstNeverProcessed);
@@ -4300,7 +4280,16 @@ void CChainState::CheckBlockIndex()
if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
}
if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
- assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
+ if (pindex->IsAssumedValid()) {
+ // Assumed-valid blocks should have some nTx value.
+ assert(pindex->nTx > 0);
+ // Assumed-valid blocks should connect to the main chain.
+ assert((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE);
+ } else {
+ // Otherwise there should only be an nTx value if we have
+ // actually seen a block's transactions.
+ assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
+ }
// All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to HaveTxsDownloaded().
assert((pindexFirstNeverProcessed == nullptr) == pindex->HaveTxsDownloaded());
assert((pindexFirstNotTransactionsValid == nullptr) == pindex->HaveTxsDownloaded());
@@ -4317,11 +4306,17 @@ void CChainState::CheckBlockIndex()
}
if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && pindexFirstNeverProcessed == nullptr) {
if (pindexFirstInvalid == nullptr) {
+ const bool is_active = this == &m_chainman.ActiveChainstate();
+
// If this block sorts at least as good as the current tip and
// is valid and we have all data for its parents, it must be in
// setBlockIndexCandidates. m_chain.Tip() must also be there
// even if some data has been pruned.
- if (pindexFirstMissing == nullptr || pindex == m_chain.Tip()) {
+ //
+ // Don't perform this check for the background chainstate since
+ // its setBlockIndexCandidates shouldn't have some entries (i.e. those past the
+ // snapshot block) which do exist in the block index for the active chainstate.
+ if (is_active && (pindexFirstMissing == nullptr || pindex == m_chain.Tip())) {
assert(setBlockIndexCandidates.count(pindex));
}
// If some parent is missing, then it could be that this block was in
@@ -4459,7 +4454,7 @@ static const uint64_t MEMPOOL_DUMP_VERSION = 1;
bool LoadMempool(CTxMemPool& pool, CChainState& active_chainstate, FopenFn mockable_fopen_function)
{
const CChainParams& chainparams = Params();
- int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
+ int64_t nExpiryTimeout = gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
FILE* filestr{mockable_fopen_function(gArgs.GetDataDirNet() / "mempool.dat", "rb")};
CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
if (file.IsNull()) {
@@ -4656,7 +4651,7 @@ CChainState& ChainstateManager::InitializeChainstate(
if (to_modify) {
throw std::logic_error("should not be overwriting a chainstate");
}
- to_modify.reset(new CChainState(mempool, m_blockman, snapshot_blockhash));
+ to_modify.reset(new CChainState(mempool, m_blockman, *this, snapshot_blockhash));
// Snapshot chainstates and initial IBD chaintates always become active.
if (is_snapshot || (!is_snapshot && !m_active_chainstate)) {
@@ -4725,8 +4720,9 @@ bool ChainstateManager::ActivateSnapshot(
static_cast<size_t>(current_coinsdb_cache_size * IBD_CACHE_PERC));
}
- auto snapshot_chainstate = WITH_LOCK(::cs_main, return std::make_unique<CChainState>(
- /* mempool */ nullptr, m_blockman, base_blockhash));
+ auto snapshot_chainstate = WITH_LOCK(::cs_main,
+ return std::make_unique<CChainState>(
+ /* mempool */ nullptr, m_blockman, *this, base_blockhash));
{
LOCK(::cs_main);
@@ -4929,11 +4925,25 @@ bool ChainstateManager::PopulateAndValidateSnapshot(
// Fake nChainTx so that GuessVerificationProgress reports accurately
index->nChainTx = index->pprev ? index->pprev->nChainTx + index->nTx : 1;
+ // Mark unvalidated block index entries beneath the snapshot base block as assumed-valid.
+ if (!index->IsValid(BLOCK_VALID_SCRIPTS)) {
+ // This flag will be removed once the block is fully validated by a
+ // background chainstate.
+ index->nStatus |= BLOCK_ASSUMED_VALID;
+ }
+
// Fake BLOCK_OPT_WITNESS so that CChainState::NeedsRedownload()
// won't ask to rewind the entire assumed-valid chain on startup.
if (index->pprev && DeploymentActiveAt(*index, ::Params().GetConsensus(), Consensus::DEPLOYMENT_SEGWIT)) {
index->nStatus |= BLOCK_OPT_WITNESS;
}
+
+ setDirtyBlockIndex.insert(index);
+ // Changes to the block index will be flushed to disk after this call
+ // returns in `ActivateSnapshot()`, when `MaybeRebalanceCaches()` is
+ // called, since we've added a snapshot chainstate and therefore will
+ // have to downsize the IBD chainstate, which will result in a call to
+ // `FlushStateToDisk(ALWAYS)`.
}
assert(index);
@@ -4958,22 +4968,6 @@ bool ChainstateManager::IsSnapshotActive() const
return m_snapshot_chainstate && m_active_chainstate == m_snapshot_chainstate.get();
}
-CChainState& ChainstateManager::ValidatedChainstate() const
-{
- LOCK(::cs_main);
- if (m_snapshot_chainstate && IsSnapshotValidated()) {
- return *m_snapshot_chainstate.get();
- }
- assert(m_ibd_chainstate);
- return *m_ibd_chainstate.get();
-}
-
-bool ChainstateManager::IsBackgroundIBD(CChainState* chainstate) const
-{
- LOCK(::cs_main);
- return (m_snapshot_chainstate && chainstate == m_ibd_chainstate.get());
-}
-
void ChainstateManager::Unload()
{
for (CChainState* chainstate : this->GetAll()) {
diff --git a/src/validation.h b/src/validation.h
index d4fcac1d48..b10050f931 100644
--- a/src/validation.h
+++ b/src/validation.h
@@ -10,21 +10,18 @@
#include <config/bitcoin-config.h>
#endif
-#include <amount.h>
+#include <arith_uint256.h>
#include <attributes.h>
-#include <coins.h>
-#include <consensus/validation.h>
-#include <crypto/common.h> // for ReadLE64
+#include <chain.h>
+#include <consensus/amount.h>
#include <fs.h>
-#include <node/utxo_snapshot.h>
#include <policy/feerate.h>
#include <policy/packages.h>
-#include <protocol.h> // For CMessageHeader::MessageStartChars
#include <script/script_error.h>
#include <sync.h>
-#include <txmempool.h> // For CTxMemPool::cs
#include <txdb.h>
-#include <serialize.h>
+#include <txmempool.h> // For CTxMemPool::cs
+#include <uint256.h>
#include <util/check.h>
#include <util/hasher.h>
#include <util/translation.h>
@@ -41,19 +38,13 @@
#include <vector>
class CChainState;
-class BlockValidationState;
-class CBlockIndex;
class CBlockTreeDB;
-class CBlockUndo;
class CChainParams;
struct CCheckpointData;
-class CInv;
-class CConnman;
-class CScriptCheck;
class CTxMemPool;
class ChainstateManager;
+class SnapshotMetadata;
struct ChainTxData;
-
struct DisconnectedBlockTransactions;
struct PrecomputedTransactionData;
struct LockPoints;
@@ -109,6 +100,7 @@ extern RecursiveMutex cs_main;
typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
extern Mutex g_best_block_mutex;
extern std::condition_variable g_best_block_cv;
+/** Used to notify getblocktemplate RPC of new tips. */
extern uint256 g_best_block;
/** Whether there are dedicated script-checking threads running.
* False indicates all script checking is done on the main threadMessageHandler thread.
@@ -593,9 +585,15 @@ public:
//! CChainState instances.
BlockManager& m_blockman;
+ //! The chainstate manager that owns this chainstate. The reference is
+ //! necessary so that this instance can check whether it is the active
+ //! chainstate within deeply nested method calls.
+ ChainstateManager& m_chainman;
+
explicit CChainState(
CTxMemPool* mempool,
BlockManager& blockman,
+ ChainstateManager& chainman,
std::optional<uint256> from_snapshot_blockhash = std::nullopt);
/**
@@ -632,9 +630,10 @@ public:
const std::optional<uint256> m_from_snapshot_blockhash;
/**
- * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
- * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
- * missing the data for the block.
+ * The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for
+ * itself and all ancestors) *or* BLOCK_ASSUMED_VALID (if using background
+ * chainstates) and as good as our current tip or better. Entries may be failed,
+ * though, and pruning nodes may be missing the data for the block.
*/
std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
@@ -846,12 +845,6 @@ private:
* *Background IBD chainstate*: an IBD chainstate for which the
* IBD process is happening in the background while use of the
* active (snapshot) chainstate allows the rest of the system to function.
- *
- * *Validated chainstate*: the most-work chainstate which has been validated
- * locally via initial block download. This will be the snapshot chainstate
- * if a snapshot was loaded and all blocks up to the snapshot starting point
- * have been downloaded and validated (via background validation), otherwise
- * it will be the IBD chainstate.
*/
class ChainstateManager
{
@@ -970,19 +963,6 @@ public:
//! Is there a snapshot in use and has it been fully validated?
bool IsSnapshotValidated() const { return m_snapshot_validated; }
- //! @returns true if this chainstate is being used to validate an active
- //! snapshot in the background.
- bool IsBackgroundIBD(CChainState* chainstate) const;
-
- //! Return the most-work chainstate that has been fully validated.
- //!
- //! During background validation of a snapshot, this is the IBD chain. After
- //! background validation has completed, this is the snapshot chain.
- CChainState& ValidatedChainstate() const;
-
- CChain& ValidatedChain() const { return ValidatedChainstate().m_chain; }
- CBlockIndex* ValidatedTip() const { return ValidatedChain().Tip(); }
-
/**
* Process an incoming block. This only returns after the best known valid
* block is made active. Note that it does not, however, guarantee that the
diff --git a/src/wallet/bdb.cpp b/src/wallet/bdb.cpp
index 1dc23374e3..2eb4d3106c 100644
--- a/src/wallet/bdb.cpp
+++ b/src/wallet/bdb.cpp
@@ -375,7 +375,7 @@ void BerkeleyBatch::Flush()
nMinutes = 1;
if (env) { // env is nullptr for dummy databases (i.e. in tests). Don't actually flush if env is nullptr so we don't segfault
- env->dbenv->txn_checkpoint(nMinutes ? gArgs.GetArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0);
+ env->dbenv->txn_checkpoint(nMinutes ? gArgs.GetIntArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0);
}
}
diff --git a/src/wallet/coincontrol.h b/src/wallet/coincontrol.h
index 85cbec76b7..edd81e590f 100644
--- a/src/wallet/coincontrol.h
+++ b/src/wallet/coincontrol.h
@@ -9,9 +9,14 @@
#include <policy/feerate.h>
#include <policy/fees.h>
#include <primitives/transaction.h>
+#include <script/keyorigin.h>
+#include <script/signingprovider.h>
#include <script/standard.h>
#include <optional>
+#include <algorithm>
+#include <map>
+#include <set>
const int DEFAULT_MIN_DEPTH = 0;
const int DEFAULT_MAX_DEPTH = 9999999;
@@ -53,6 +58,8 @@ public:
int m_min_depth = DEFAULT_MIN_DEPTH;
//! Maximum chain depth value for coin availability
int m_max_depth = DEFAULT_MAX_DEPTH;
+ //! SigningProvider that has pubkeys and scripts to do spend size estimation for external inputs
+ FlatSigningProvider m_external_provider;
CCoinControl();
@@ -66,11 +73,32 @@ public:
return (setSelected.count(output) > 0);
}
+ bool IsExternalSelected(const COutPoint& output) const
+ {
+ return (m_external_txouts.count(output) > 0);
+ }
+
+ bool GetExternalOutput(const COutPoint& outpoint, CTxOut& txout) const
+ {
+ const auto ext_it = m_external_txouts.find(outpoint);
+ if (ext_it == m_external_txouts.end()) {
+ return false;
+ }
+ txout = ext_it->second;
+ return true;
+ }
+
void Select(const COutPoint& output)
{
setSelected.insert(output);
}
+ void SelectExternal(const COutPoint& outpoint, const CTxOut& txout)
+ {
+ setSelected.insert(outpoint);
+ m_external_txouts.emplace(outpoint, txout);
+ }
+
void UnSelect(const COutPoint& output)
{
setSelected.erase(output);
@@ -88,6 +116,7 @@ public:
private:
std::set<COutPoint> setSelected;
+ std::map<COutPoint, CTxOut> m_external_txouts;
};
#endif // BITCOIN_WALLET_COINCONTROL_H
diff --git a/src/wallet/coinselection.cpp b/src/wallet/coinselection.cpp
index 1699424657..e1ca3fb379 100644
--- a/src/wallet/coinselection.cpp
+++ b/src/wallet/coinselection.cpp
@@ -4,10 +4,13 @@
#include <wallet/coinselection.h>
+#include <consensus/amount.h>
#include <policy/feerate.h>
+#include <util/check.h>
#include <util/system.h>
#include <util/moneystr.h>
+#include <numeric>
#include <optional>
// Descending order comparator
@@ -168,6 +171,30 @@ bool SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& selectio
return true;
}
+std::optional<std::pair<std::set<CInputCoin>, CAmount>> SelectCoinsSRD(const std::vector<OutputGroup>& utxo_pool, CAmount target_value)
+{
+ std::set<CInputCoin> out_set;
+ CAmount value_ret = 0;
+
+ std::vector<size_t> indexes;
+ indexes.resize(utxo_pool.size());
+ std::iota(indexes.begin(), indexes.end(), 0);
+ Shuffle(indexes.begin(), indexes.end(), FastRandomContext());
+
+ CAmount selected_eff_value = 0;
+ for (const size_t i : indexes) {
+ const OutputGroup& group = utxo_pool.at(i);
+ Assume(group.GetSelectionAmount() > 0);
+ selected_eff_value += group.GetSelectionAmount();
+ value_ret += group.m_value;
+ util::insert(out_set, group.m_outputs);
+ if (selected_eff_value >= target_value) {
+ return std::make_pair(out_set, value_ret);
+ }
+ }
+ return std::nullopt;
+}
+
static void ApproximateBestSubset(const std::vector<OutputGroup>& groups, const CAmount& nTotalLower, const CAmount& nTargetValue,
std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
{
@@ -279,13 +306,13 @@ bool KnapsackSolver(const CAmount& nTargetValue, std::vector<OutputGroup>& group
}
if (LogAcceptCategory(BCLog::SELECTCOINS)) {
- LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: "); /* Continued */
+ std::string log_message{"Coin selection best subset: "};
for (unsigned int i = 0; i < applicable_groups.size(); i++) {
if (vfBest[i]) {
- LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(applicable_groups[i].m_value)); /* Continued */
+ log_message += strprintf("%s ", FormatMoney(applicable_groups[i].m_value));
}
}
- LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
+ LogPrint(BCLog::SELECTCOINS, "%stotal %s\n", log_message, FormatMoney(nBest));
}
}
diff --git a/src/wallet/coinselection.h b/src/wallet/coinselection.h
index 35617d455b..e7d467660f 100644
--- a/src/wallet/coinselection.h
+++ b/src/wallet/coinselection.h
@@ -5,11 +5,13 @@
#ifndef BITCOIN_WALLET_COINSELECTION_H
#define BITCOIN_WALLET_COINSELECTION_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <policy/feerate.h>
#include <primitives/transaction.h>
#include <random.h>
+#include <optional>
+
//! target minimum change amount
static constexpr CAmount MIN_CHANGE{COIN / 100};
//! final minimum change amount after paying for fees
@@ -35,6 +37,18 @@ public:
m_input_bytes = input_bytes;
}
+ CInputCoin(const COutPoint& outpoint_in, const CTxOut& txout_in)
+ {
+ outpoint = outpoint_in;
+ txout = txout_in;
+ effective_value = txout.nValue;
+ }
+
+ CInputCoin(const COutPoint& outpoint_in, const CTxOut& txout_in, int input_bytes) : CInputCoin(outpoint_in, txout_in)
+ {
+ m_input_bytes = input_bytes;
+ }
+
COutPoint outpoint;
CTxOut txout;
CAmount effective_value;
@@ -174,7 +188,9 @@ struct OutputGroup
* change_cost = effective_feerate * change_output_size + long_term_feerate * change_spend_size
*
* @param[in] inputs The selected inputs
- * @param[in] change_cost The cost of creating change and spending it in the future. Only used if there is change. Must be 0 if there is no change.
+ * @param[in] change_cost The cost of creating change and spending it in the future.
+ * Only used if there is change, in which case it must be positive.
+ * Must be 0 if there is no change.
* @param[in] target The amount targeted by the coin selection algorithm.
* @param[in] use_effective_value Whether to use the input's effective value (when true) or the real value (when false).
* @return The waste
@@ -183,6 +199,15 @@ struct OutputGroup
bool SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& selection_target, const CAmount& cost_of_change, std::set<CInputCoin>& out_set, CAmount& value_ret);
+/** Select coins by Single Random Draw. OutputGroups are selected randomly from the eligible
+ * outputs until the target is satisfied
+ *
+ * @param[in] utxo_pool The positive effective value OutputGroups eligible for selection
+ * @param[in] target_value The target value to select for
+ * @returns If successful, a pair of set of outputs and total selected value, otherwise, std::nullopt
+ */
+std::optional<std::pair<std::set<CInputCoin>, CAmount>> SelectCoinsSRD(const std::vector<OutputGroup>& utxo_pool, CAmount target_value);
+
// Original coin selection algorithm as a fallback
bool KnapsackSolver(const CAmount& nTargetValue, std::vector<OutputGroup>& groups, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet);
diff --git a/src/wallet/fees.h b/src/wallet/fees.h
index 434f211dc2..d6d625d9c1 100644
--- a/src/wallet/fees.h
+++ b/src/wallet/fees.h
@@ -6,7 +6,7 @@
#ifndef BITCOIN_WALLET_FEES_H
#define BITCOIN_WALLET_FEES_H
-#include <amount.h>
+#include <consensus/amount.h>
class CCoinControl;
class CFeeRate;
diff --git a/src/wallet/init.cpp b/src/wallet/init.cpp
index bb5f0cceff..59a59f9794 100644
--- a/src/wallet/init.cpp
+++ b/src/wallet/init.cpp
@@ -5,6 +5,7 @@
#include <init.h>
#include <interfaces/chain.h>
+#include <interfaces/init.h>
#include <interfaces/wallet.h>
#include <net.h>
#include <node/context.h>
@@ -61,7 +62,6 @@ void WalletInit::AddWalletOptions(ArgsManager& argsman) const
CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
argsman.AddArg("-paytxfee=<amt>", strprintf("Fee rate (in %s/kvB) to add to transactions you send (default: %s)",
CURRENCY_UNIT, FormatMoney(CFeeRate{DEFAULT_PAY_TX_FEE}.GetFeePerK())), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
- argsman.AddArg("-rescan", "Rescan the block chain for missing wallet transactions on startup", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
#ifdef ENABLE_EXTERNAL_SIGNER
argsman.AddArg("-signer=<cmd>", "External signing tool, see doc/external-signer.md", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
#endif
@@ -130,7 +130,7 @@ void WalletInit::Construct(NodeContext& node) const
LogPrintf("Wallet disabled!\n");
return;
}
- auto wallet_client = interfaces::MakeWalletClient(*node.chain, args);
+ auto wallet_client = node.init->makeWalletClient(*node.chain);
node.wallet_client = wallet_client.get();
node.chain_clients.emplace_back(std::move(wallet_client));
}
diff --git a/src/wallet/interfaces.cpp b/src/wallet/interfaces.cpp
index 9a8c1e3c02..7d0cdb6934 100644
--- a/src/wallet/interfaces.cpp
+++ b/src/wallet/interfaces.cpp
@@ -4,7 +4,7 @@
#include <interfaces/wallet.h>
-#include <amount.h>
+#include <consensus/amount.h>
#include <interfaces/chain.h>
#include <interfaces/handler.h>
#include <policy/fees.h>
@@ -214,15 +214,17 @@ public:
LOCK(m_wallet->cs_wallet);
return m_wallet->DisplayAddress(dest);
}
- void lockCoin(const COutPoint& output) override
+ bool lockCoin(const COutPoint& output, const bool write_to_db) override
{
LOCK(m_wallet->cs_wallet);
- return m_wallet->LockCoin(output);
+ std::unique_ptr<WalletBatch> batch = write_to_db ? std::make_unique<WalletBatch>(m_wallet->GetDatabase()) : nullptr;
+ return m_wallet->LockCoin(output, batch.get());
}
- void unlockCoin(const COutPoint& output) override
+ bool unlockCoin(const COutPoint& output) override
{
LOCK(m_wallet->cs_wallet);
- return m_wallet->UnlockCoin(output);
+ std::unique_ptr<WalletBatch> batch = std::make_unique<WalletBatch>(m_wallet->GetDatabase());
+ return m_wallet->UnlockCoin(output, batch.get());
}
bool isLockedCoin(const COutPoint& output) override
{
diff --git a/src/wallet/load.cpp b/src/wallet/load.cpp
index a994976394..1b841026b8 100644
--- a/src/wallet/load.cpp
+++ b/src/wallet/load.cpp
@@ -165,7 +165,7 @@ void UnloadWallets(WalletContext& context)
auto wallet = wallets.back();
wallets.pop_back();
std::vector<bilingual_str> warnings;
- RemoveWallet(context, wallet, /* load_on_startup= */ std::nullopt, warnings);
+ RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt, warnings);
UnloadWallet(std::move(wallet));
}
}
diff --git a/src/wallet/receive.cpp b/src/wallet/receive.cpp
index 98706dcdf8..2fb274b55f 100644
--- a/src/wallet/receive.cpp
+++ b/src/wallet/receive.cpp
@@ -2,6 +2,7 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#include <consensus/amount.h>
#include <consensus/consensus.h>
#include <wallet/receive.h>
#include <wallet/transaction.h>
diff --git a/src/wallet/receive.h b/src/wallet/receive.h
index b4b311636b..f659955fc6 100644
--- a/src/wallet/receive.h
+++ b/src/wallet/receive.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_WALLET_RECEIVE_H
#define BITCOIN_WALLET_RECEIVE_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <wallet/ismine.h>
#include <wallet/transaction.h>
#include <wallet/wallet.h>
diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp
index 72c60c8fe2..4d7fb2d38c 100644
--- a/src/wallet/rpcdump.cpp
+++ b/src/wallet/rpcdump.cpp
@@ -1439,7 +1439,7 @@ RPCHelpMan importmulti()
"and coins using this key may not appear in the wallet. This error could be "
"caused by pruning or data corruption (see bitcoind log for details) and could "
"be dealt with by downloading and rescanning the relevant blocks (see -reindex "
- "and -rescan options).",
+ "option and rescanblockchain RPC).",
GetImportTimestamp(request, now), scannedTime - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW)));
response.push_back(std::move(result));
}
@@ -1488,7 +1488,7 @@ static UniValue ProcessDescriptorImport(CWallet& wallet, const UniValue& data, c
} else {
warnings.push_back("Range not given, using default keypool range");
range_start = 0;
- range_end = gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE);
+ range_end = gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE);
}
next_index = range_start;
@@ -1744,7 +1744,7 @@ RPCHelpMan importdescriptors()
"and coins using this desc may not appear in the wallet. This error could be "
"caused by pruning or data corruption (see bitcoind log for details) and could "
"be dealt with by downloading and rescanning the relevant blocks (see -reindex "
- "and -rescan options).",
+ "option and rescanblockchain RPC).",
GetImportTimestamp(request, now), scanned_time - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW)));
response.push_back(std::move(result));
}
diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp
index ff9e10c5ad..8b481bc29c 100644
--- a/src/wallet/rpcwallet.cpp
+++ b/src/wallet/rpcwallet.cpp
@@ -3,7 +3,7 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <amount.h>
+#include <consensus/amount.h>
#include <core_io.h>
#include <interfaces/chain.h>
#include <key_io.h>
@@ -43,6 +43,7 @@
#include <univalue.h>
+#include <map>
using interfaces::FoundBlock;
@@ -472,7 +473,7 @@ static RPCHelpMan sendtoaddress()
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::STR_HEX, "txid", "The transaction id."},
- {RPCResult::Type::STR, "fee reason", "The transaction fee reason."}
+ {RPCResult::Type::STR, "fee_reason", "The transaction fee reason."}
},
},
},
@@ -899,7 +900,7 @@ static RPCHelpMan sendmany()
{
{RPCResult::Type::STR_HEX, "txid", "The transaction id for the send. Only 1 transaction is created regardless of\n"
"the number of addresses."},
- {RPCResult::Type::STR, "fee reason", "The transaction fee reason."}
+ {RPCResult::Type::STR, "fee_reason", "The transaction fee reason."}
},
},
},
@@ -1213,7 +1214,7 @@ static RPCHelpMan listreceivedbyaddress()
{
{RPCResult::Type::OBJ, "", "",
{
- {RPCResult::Type::BOOL, "involvesWatchonly", "Only returns true if imported addresses were involved in transaction"},
+ {RPCResult::Type::BOOL, "involvesWatchonly", /* optional */ true, "Only returns true if imported addresses were involved in transaction"},
{RPCResult::Type::STR, "address", "The receiving address"},
{RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " received by the address"},
{RPCResult::Type::NUM, "confirmations", "The number of confirmations of the most recent transaction included"},
@@ -1261,7 +1262,7 @@ static RPCHelpMan listreceivedbylabel()
{
{RPCResult::Type::OBJ, "", "",
{
- {RPCResult::Type::BOOL, "involvesWatchonly", "Only returns true if imported addresses were involved in transaction"},
+ {RPCResult::Type::BOOL, "involvesWatchonly", /* optional */ true, "Only returns true if imported addresses were involved in transaction"},
{RPCResult::Type::STR_AMOUNT, "amount", "The total amount received by addresses with this label"},
{RPCResult::Type::NUM, "confirmations", "The number of confirmations of the most recent transaction included"},
{RPCResult::Type::STR, "label", "The label of the receiving address. The default label is \"\""},
@@ -1388,20 +1389,24 @@ static const std::vector<RPCResult> TransactionDescriptionString()
{
return{{RPCResult::Type::NUM, "confirmations", "The number of confirmations for the transaction. Negative confirmations means the\n"
"transaction conflicted that many blocks ago."},
- {RPCResult::Type::BOOL, "generated", "Only present if transaction only input is a coinbase one."},
- {RPCResult::Type::BOOL, "trusted", "Only present if we consider transaction to be trusted and so safe to spend from."},
- {RPCResult::Type::STR_HEX, "blockhash", "The block hash containing the transaction."},
- {RPCResult::Type::NUM, "blockheight", "The block height containing the transaction."},
- {RPCResult::Type::NUM, "blockindex", "The index of the transaction in the block that includes it."},
- {RPCResult::Type::NUM_TIME, "blocktime", "The block time expressed in " + UNIX_EPOCH_TIME + "."},
+ {RPCResult::Type::BOOL, "generated", /* optional */ true, "Only present if transaction only input is a coinbase one."},
+ {RPCResult::Type::BOOL, "trusted", /* optional */ true, "Only present if we consider transaction to be trusted and so safe to spend from."},
+ {RPCResult::Type::STR_HEX, "blockhash", /* optional */ true, "The block hash containing the transaction."},
+ {RPCResult::Type::NUM, "blockheight", /* optional */ true, "The block height containing the transaction."},
+ {RPCResult::Type::NUM, "blockindex", /* optional */ true, "The index of the transaction in the block that includes it."},
+ {RPCResult::Type::NUM_TIME, "blocktime", /* optional */ true, "The block time expressed in " + UNIX_EPOCH_TIME + "."},
{RPCResult::Type::STR_HEX, "txid", "The transaction id."},
{RPCResult::Type::ARR, "walletconflicts", "Conflicting transaction ids.",
{
{RPCResult::Type::STR_HEX, "txid", "The transaction id."},
}},
+ {RPCResult::Type::STR_HEX, "replaced_by_txid", /* optional */ true, "The txid if this tx was replaced."},
+ {RPCResult::Type::STR_HEX, "replaces_txid", /* optional */ true, "The txid if the tx replaces one."},
+ {RPCResult::Type::STR, "comment", /* optional */ true, ""},
+ {RPCResult::Type::STR, "to", /* optional */ true, "If a comment to is associated with the transaction."},
{RPCResult::Type::NUM_TIME, "time", "The transaction time expressed in " + UNIX_EPOCH_TIME + "."},
{RPCResult::Type::NUM_TIME, "timereceived", "The time received expressed in " + UNIX_EPOCH_TIME + "."},
- {RPCResult::Type::STR, "comment", "If a comment is associated with the transaction, only present if not empty."},
+ {RPCResult::Type::STR, "comment", /* optional */ true, "If a comment is associated with the transaction, only present if not empty."},
{RPCResult::Type::STR, "bip125-replaceable", "(\"yes|no|unknown\") Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
"may be unknown for unconfirmed transactions not in the mempool"}};
}
@@ -1423,7 +1428,7 @@ static RPCHelpMan listtransactions()
{
{RPCResult::Type::OBJ, "", "", Cat(Cat<std::vector<RPCResult>>(
{
- {RPCResult::Type::BOOL, "involvesWatchonly", "Only returns true if imported addresses were involved in transaction."},
+ {RPCResult::Type::BOOL, "involvesWatchonly", /* optional */ true, "Only returns true if imported addresses were involved in transaction."},
{RPCResult::Type::STR, "address", "The bitcoin address of the transaction."},
{RPCResult::Type::STR, "category", "The transaction category.\n"
"\"send\" Transactions sent.\n"
@@ -1433,14 +1438,14 @@ static RPCHelpMan listtransactions()
"\"orphan\" Orphaned coinbase transactions received."},
{RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and is positive\n"
"for all other categories"},
- {RPCResult::Type::STR, "label", "A comment for the address/transaction, if any"},
+ {RPCResult::Type::STR, "label", /* optional */ true, "A comment for the address/transaction, if any"},
{RPCResult::Type::NUM, "vout", "the vout value"},
- {RPCResult::Type::STR_AMOUNT, "fee", "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the\n"
+ {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true, "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the\n"
"'send' category of transactions."},
},
TransactionDescriptionString()),
{
- {RPCResult::Type::BOOL, "abandoned", "'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n"
+ {RPCResult::Type::BOOL, "abandoned", /* optional */ true, "'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n"
"'send' category of transactions."},
})},
}
@@ -1537,7 +1542,7 @@ static RPCHelpMan listsinceblock()
{
{RPCResult::Type::OBJ, "", "", Cat(Cat<std::vector<RPCResult>>(
{
- {RPCResult::Type::BOOL, "involvesWatchonly", "Only returns true if imported addresses were involved in transaction."},
+ {RPCResult::Type::BOOL, "involvesWatchonly", /* optional */ true, "Only returns true if imported addresses were involved in transaction."},
{RPCResult::Type::STR, "address", "The bitcoin address of the transaction."},
{RPCResult::Type::STR, "category", "The transaction category.\n"
"\"send\" Transactions sent.\n"
@@ -1548,18 +1553,17 @@ static RPCHelpMan listsinceblock()
{RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and is positive\n"
"for all other categories"},
{RPCResult::Type::NUM, "vout", "the vout value"},
- {RPCResult::Type::STR_AMOUNT, "fee", "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the\n"
+ {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true, "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the\n"
"'send' category of transactions."},
},
TransactionDescriptionString()),
{
- {RPCResult::Type::BOOL, "abandoned", "'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n"
+ {RPCResult::Type::BOOL, "abandoned", /* optional */ true, "'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n"
"'send' category of transactions."},
- {RPCResult::Type::STR, "label", "A comment for the address/transaction, if any"},
- {RPCResult::Type::STR, "to", "If a comment to is associated with the transaction."},
+ {RPCResult::Type::STR, "label", /* optional */ true, "A comment for the address/transaction, if any"},
})},
}},
- {RPCResult::Type::ARR, "removed", "<structure is the same as \"transactions\" above, only present if include_removed=true>\n"
+ {RPCResult::Type::ARR, "removed", /* optional */ true, "<structure is the same as \"transactions\" above, only present if include_removed=true>\n"
"Note: transactions that were re-added in the active chain will appear as-is in this array, and may thus have a positive confirmation count."
, {{RPCResult::Type::ELISION, "", ""},}},
{RPCResult::Type::STR_HEX, "lastblock", "The hash of the block (target_confirmations-1) from the best block on the main chain, or the genesis hash if the referenced block does not exist yet. This is typically used to feed back into listsinceblock the next time you call it. So you would generally use a target_confirmations of say 6, so you will be continually re-notified of transactions until they've reached 6 confirmations plus any new ones"},
@@ -1672,7 +1676,7 @@ static RPCHelpMan gettransaction()
RPCResult::Type::OBJ, "", "", Cat(Cat<std::vector<RPCResult>>(
{
{RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT},
- {RPCResult::Type::STR_AMOUNT, "fee", "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the\n"
+ {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true, "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the\n"
"'send' category of transactions."},
},
TransactionDescriptionString()),
@@ -1681,8 +1685,8 @@ static RPCHelpMan gettransaction()
{
{RPCResult::Type::OBJ, "", "",
{
- {RPCResult::Type::BOOL, "involvesWatchonly", "Only returns true if imported addresses were involved in transaction."},
- {RPCResult::Type::STR, "address", "The bitcoin address involved in the transaction."},
+ {RPCResult::Type::BOOL, "involvesWatchonly", /* optional */ true, "Only returns true if imported addresses were involved in transaction."},
+ {RPCResult::Type::STR, "address", /* optional */ true, "The bitcoin address involved in the transaction."},
{RPCResult::Type::STR, "category", "The transaction category.\n"
"\"send\" Transactions sent.\n"
"\"receive\" Non-coinbase transactions received.\n"
@@ -1690,16 +1694,16 @@ static RPCHelpMan gettransaction()
"\"immature\" Coinbase transactions received with 100 or fewer confirmations.\n"
"\"orphan\" Orphaned coinbase transactions received."},
{RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT},
- {RPCResult::Type::STR, "label", "A comment for the address/transaction, if any"},
+ {RPCResult::Type::STR, "label", /* optional */ true, "A comment for the address/transaction, if any"},
{RPCResult::Type::NUM, "vout", "the vout value"},
- {RPCResult::Type::STR_AMOUNT, "fee", "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
+ {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true, "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
"'send' category of transactions."},
- {RPCResult::Type::BOOL, "abandoned", "'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n"
+ {RPCResult::Type::BOOL, "abandoned", /* optional */ true, "'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n"
"'send' category of transactions."},
}},
}},
{RPCResult::Type::STR_HEX, "hex", "Raw data for transaction"},
- {RPCResult::Type::OBJ, "decoded", "Optional, the decoded transaction (only present when `verbose` is passed)",
+ {RPCResult::Type::OBJ, "decoded", /* optional */ true, "The decoded transaction (only present when `verbose` is passed)",
{
{RPCResult::Type::ELISION, "", "Equivalent to the RPC decoderawtransaction method, or the RPC getrawtransaction method when `verbose` is passed."},
}},
@@ -1759,7 +1763,7 @@ static RPCHelpMan gettransaction()
if (verbose) {
UniValue decoded(UniValue::VOBJ);
- TxToUniv(*wtx.tx, uint256(), pwallet->chain().rpcEnableDeprecated("addresses"), decoded, false);
+ TxToUniv(*wtx.tx, uint256(), decoded, false);
entry.pushKV("decoded", decoded);
}
@@ -2137,8 +2141,9 @@ static RPCHelpMan lockunspent()
"If no transaction outputs are specified when unlocking then all current locked transaction outputs are unlocked.\n"
"A locked transaction output will not be chosen by automatic coin selection, when spending bitcoins.\n"
"Manually selected coins are automatically unlocked.\n"
- "Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n"
- "is always cleared (by virtue of process exit) when a node stops or fails.\n"
+ "Locks are stored in memory only, unless persistent=true, in which case they will be written to the\n"
+ "wallet database and loaded on node start. Unwritten (persistent=false) locks are always cleared\n"
+ "(by virtue of process exit) when a node stops or fails. Unlocking will clear both persistent and not.\n"
"Also see the listunspent call\n",
{
{"unlock", RPCArg::Type::BOOL, RPCArg::Optional::NO, "Whether to unlock (true) or lock (false) the specified transactions"},
@@ -2152,6 +2157,7 @@ static RPCHelpMan lockunspent()
},
},
},
+ {"persistent", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether to write/erase this lock in the wallet database, or keep the change in memory only. Ignored for unlocking."},
},
RPCResult{
RPCResult::Type::BOOL, "", "Whether the command was successful or not"
@@ -2165,6 +2171,8 @@ static RPCHelpMan lockunspent()
+ HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n"
+ HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
+ "\nLock the transaction persistently in the wallet database\n"
+ + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\" true") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"")
},
@@ -2183,9 +2191,13 @@ static RPCHelpMan lockunspent()
bool fUnlock = request.params[0].get_bool();
+ const bool persistent{request.params[2].isNull() ? false : request.params[2].get_bool()};
+
if (request.params[1].isNull()) {
- if (fUnlock)
- pwallet->UnlockAllCoins();
+ if (fUnlock) {
+ if (!pwallet->UnlockAllCoins())
+ throw JSONRPCError(RPC_WALLET_ERROR, "Unlocking coins failed");
+ }
return true;
}
@@ -2236,17 +2248,24 @@ static RPCHelpMan lockunspent()
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected locked output");
}
- if (!fUnlock && is_locked) {
+ if (!fUnlock && is_locked && !persistent) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, output already locked");
}
outputs.push_back(outpt);
}
+ std::unique_ptr<WalletBatch> batch = nullptr;
+ // Unlock is always persistent
+ if (fUnlock || persistent) batch = std::make_unique<WalletBatch>(pwallet->GetDatabase());
+
// Atomically set (un)locked status for the outputs.
for (const COutPoint& outpt : outputs) {
- if (fUnlock) pwallet->UnlockCoin(outpt);
- else pwallet->LockCoin(outpt);
+ if (fUnlock) {
+ if (!pwallet->UnlockCoin(outpt, batch.get())) throw JSONRPCError(RPC_WALLET_ERROR, "Unlocking coin failed");
+ } else {
+ if (!pwallet->LockCoin(outpt, batch.get())) throw JSONRPCError(RPC_WALLET_ERROR, "Locking coin failed");
+ }
}
return true;
@@ -2362,9 +2381,9 @@ static RPCHelpMan getbalances()
{RPCResult::Type::STR_AMOUNT, "trusted", "trusted balance (outputs created by the wallet or confirmed outputs)"},
{RPCResult::Type::STR_AMOUNT, "untrusted_pending", "untrusted pending balance (outputs created by others that are in the mempool)"},
{RPCResult::Type::STR_AMOUNT, "immature", "balance from immature coinbase outputs"},
- {RPCResult::Type::STR_AMOUNT, "used", "(only present if avoid_reuse is set) balance from coins sent to addresses that were previously spent from (potentially privacy violating)"},
+ {RPCResult::Type::STR_AMOUNT, "used", /* optional */ true, "(only present if avoid_reuse is set) balance from coins sent to addresses that were previously spent from (potentially privacy violating)"},
}},
- {RPCResult::Type::OBJ, "watchonly", "watchonly balances (not present if wallet does not watch anything)",
+ {RPCResult::Type::OBJ, "watchonly", /* optional */ true, "watchonly balances (not present if wallet does not watch anything)",
{
{RPCResult::Type::STR_AMOUNT, "trusted", "trusted balance (outputs created by the wallet or confirmed outputs)"},
{RPCResult::Type::STR_AMOUNT, "untrusted_pending", "untrusted pending balance (outputs created by others that are in the mempool)"},
@@ -2431,9 +2450,9 @@ static RPCHelpMan getwalletinfo()
{RPCResult::Type::STR_AMOUNT, "unconfirmed_balance", "DEPRECATED. Identical to getbalances().mine.untrusted_pending"},
{RPCResult::Type::STR_AMOUNT, "immature_balance", "DEPRECATED. Identical to getbalances().mine.immature"},
{RPCResult::Type::NUM, "txcount", "the total number of transactions in the wallet"},
- {RPCResult::Type::NUM_TIME, "keypoololdest", "the " + UNIX_EPOCH_TIME + " of the oldest pre-generated key in the key pool. Legacy wallets only."},
+ {RPCResult::Type::NUM_TIME, "keypoololdest", /* optional */ true, "the " + UNIX_EPOCH_TIME + " of the oldest pre-generated key in the key pool. Legacy wallets only."},
{RPCResult::Type::NUM, "keypoolsize", "how many new keys are pre-generated (only counts external keys)"},
- {RPCResult::Type::NUM, "keypoolsize_hd_internal", "how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)"},
+ {RPCResult::Type::NUM, "keypoolsize_hd_internal", /* optional */ true, "how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)"},
{RPCResult::Type::NUM_TIME, "unlocked_until", /* optional */ true, "the " + UNIX_EPOCH_TIME + " until which the wallet is unlocked for transfers, or 0 if the wallet is locked (only present for passphrase-encrypted wallets)"},
{RPCResult::Type::STR_AMOUNT, "paytxfee", "the transaction fee configuration, set in " + CURRENCY_UNIT + "/kvB"},
{RPCResult::Type::STR_HEX, "hdseedid", /* optional */ true, "the Hash160 of the HD seed (only present when HD is enabled)"},
@@ -2614,7 +2633,7 @@ static RPCHelpMan loadwallet()
return RPCHelpMan{"loadwallet",
"\nLoads a wallet from a wallet file or directory."
"\nNote that all wallet command-line options used when starting bitcoind will be"
- "\napplied to the new wallet (eg -rescan, etc).\n",
+ "\napplied to the new wallet.\n",
{
{"filename", RPCArg::Type::STR, RPCArg::Optional::NO, "The wallet directory or .dat file."},
{"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED_NAMED_ARG, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."},
@@ -2955,17 +2974,20 @@ static RPCHelpMan listunspent()
{
{RPCResult::Type::STR_HEX, "txid", "the transaction id"},
{RPCResult::Type::NUM, "vout", "the vout value"},
- {RPCResult::Type::STR, "address", "the bitcoin address"},
- {RPCResult::Type::STR, "label", "The associated label, or \"\" for the default label"},
+ {RPCResult::Type::STR, "address", /* optional */ true, "the bitcoin address"},
+ {RPCResult::Type::STR, "label", /* optional */ true, "The associated label, or \"\" for the default label"},
{RPCResult::Type::STR, "scriptPubKey", "the script key"},
{RPCResult::Type::STR_AMOUNT, "amount", "the transaction output amount in " + CURRENCY_UNIT},
{RPCResult::Type::NUM, "confirmations", "The number of confirmations"},
- {RPCResult::Type::STR_HEX, "redeemScript", "The redeemScript if scriptPubKey is P2SH"},
- {RPCResult::Type::STR, "witnessScript", "witnessScript if the scriptPubKey is P2WSH or P2SH-P2WSH"},
+ {RPCResult::Type::NUM, "ancestorcount", /* optional */ true, "The number of in-mempool ancestor transactions, including this one (if transaction is in the mempool)"},
+ {RPCResult::Type::NUM, "ancestorsize", /* optional */ true, "The virtual transaction size of in-mempool ancestors, including this one (if transaction is in the mempool)"},
+ {RPCResult::Type::STR_AMOUNT, "ancestorfees", /* optional */ true, "The total fees of in-mempool ancestors (including this one) with fee deltas used for mining priority in " + CURRENCY_ATOM + " (if transaction is in the mempool)"},
+ {RPCResult::Type::STR_HEX, "redeemScript", /* optional */ true, "The redeemScript if scriptPubKey is P2SH"},
+ {RPCResult::Type::STR, "witnessScript", /* optional */ true, "witnessScript if the scriptPubKey is P2WSH or P2SH-P2WSH"},
{RPCResult::Type::BOOL, "spendable", "Whether we have the private keys to spend this output"},
{RPCResult::Type::BOOL, "solvable", "Whether we know how to spend this output, ignoring the lack of keys"},
- {RPCResult::Type::BOOL, "reused", "(only present if avoid_reuse is set) Whether this output is reused/dirty (sent to an address that was previously spent from)"},
- {RPCResult::Type::STR, "desc", "(only when solvable) A descriptor for spending this output"},
+ {RPCResult::Type::BOOL, "reused", /* optional */ true, "(only present if avoid_reuse is set) Whether this output is reused/dirty (sent to an address that was previously spent from)"},
+ {RPCResult::Type::STR, "desc", /* optional */ true, "(only when solvable) A descriptor for spending this output"},
{RPCResult::Type::BOOL, "safe", "Whether this output is considered safe to spend. Unconfirmed transactions\n"
"from outside keys and unconfirmed replacement transactions are considered unsafe\n"
"and are not eligible for spending by fundrawtransaction and sendtoaddress."},
@@ -3126,6 +3148,16 @@ static RPCHelpMan listunspent()
entry.pushKV("scriptPubKey", HexStr(scriptPubKey));
entry.pushKV("amount", ValueFromAmount(out.tx->tx->vout[out.i].nValue));
entry.pushKV("confirmations", out.nDepth);
+ if (!out.nDepth) {
+ size_t ancestor_count, descendant_count, ancestor_size;
+ CAmount ancestor_fees;
+ pwallet->chain().getTransactionAncestry(out.tx->GetHash(), ancestor_count, descendant_count, &ancestor_size, &ancestor_fees);
+ if (ancestor_count) {
+ entry.pushKV("ancestorcount", uint64_t(ancestor_count));
+ entry.pushKV("ancestorsize", uint64_t(ancestor_size));
+ entry.pushKV("ancestorfees", uint64_t(ancestor_fees));
+ }
+ }
entry.pushKV("spendable", out.fSpendable);
entry.pushKV("solvable", out.fSolvable);
if (out.fSolvable) {
@@ -3145,6 +3177,34 @@ static RPCHelpMan listunspent()
};
}
+// Only includes key documentation where the key is snake_case in all RPC methods. MixedCase keys can be added later.
+static std::vector<RPCArg> FundTxDoc()
+{
+ return {
+ {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
+ {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, std::string() + "The fee estimate mode, must be one of (case insensitive):\n"
+ " \"" + FeeModes("\"\n\"") + "\""},
+ {"replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Marks this transaction as BIP125 replaceable.\n"
+ "Allows this transaction to be replaced by a transaction with higher fees"},
+ {"solving_data", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED_NAMED_ARG, "Keys and scripts needed for producing a final transaction with a dummy signature.\n"
+ "Used for fee estimation during coin selection.",
+ {
+ {"pubkeys", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Public keys involved in this transaction.",
+ {
+ {"pubkey", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A public key"},
+ }},
+ {"scripts", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Scripts involved in this transaction.",
+ {
+ {"script", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A script"},
+ }},
+ {"descriptors", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Descriptors that provide solving data for this transaction.",
+ {
+ {"descriptor", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A descriptor"},
+ }},
+ }},
+ };
+}
+
void FundTransaction(CWallet& wallet, CMutableTransaction& tx, CAmount& fee_out, int& change_position, const UniValue& options, CCoinControl& coinControl, bool override_min_fee)
{
// Make sure the results are valid at least up to the most recent block
@@ -3182,6 +3242,7 @@ void FundTransaction(CWallet& wallet, CMutableTransaction& tx, CAmount& fee_out,
{"fee_rate", UniValueType()}, // will be checked by AmountFromValue() in SetFeeEstimateMode()
{"feeRate", UniValueType()}, // will be checked by AmountFromValue() below
{"psbt", UniValueType(UniValue::VBOOL)},
+ {"solving_data", UniValueType(UniValue::VOBJ)},
{"subtractFeeFromOutputs", UniValueType(UniValue::VARR)},
{"subtract_fee_from_outputs", UniValueType(UniValue::VARR)},
{"replaceable", UniValueType(UniValue::VBOOL)},
@@ -3258,6 +3319,54 @@ void FundTransaction(CWallet& wallet, CMutableTransaction& tx, CAmount& fee_out,
coinControl.fAllowWatchOnly = ParseIncludeWatchonly(NullUniValue, wallet);
}
+ if (options.exists("solving_data")) {
+ const UniValue solving_data = options["solving_data"].get_obj();
+ if (solving_data.exists("pubkeys")) {
+ for (const UniValue& pk_univ : solving_data["pubkeys"].get_array().getValues()) {
+ const std::string& pk_str = pk_univ.get_str();
+ if (!IsHex(pk_str)) {
+ throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' is not hex", pk_str));
+ }
+ const std::vector<unsigned char> data(ParseHex(pk_str));
+ const CPubKey pubkey(data.begin(), data.end());
+ if (!pubkey.IsFullyValid()) {
+ throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' is not a valid public key", pk_str));
+ }
+ coinControl.m_external_provider.pubkeys.emplace(pubkey.GetID(), pubkey);
+ // Add witness script for pubkeys
+ const CScript wit_script = GetScriptForDestination(WitnessV0KeyHash(pubkey));
+ coinControl.m_external_provider.scripts.emplace(CScriptID(wit_script), wit_script);
+ }
+ }
+
+ if (solving_data.exists("scripts")) {
+ for (const UniValue& script_univ : solving_data["scripts"].get_array().getValues()) {
+ const std::string& script_str = script_univ.get_str();
+ if (!IsHex(script_str)) {
+ throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' is not hex", script_str));
+ }
+ std::vector<unsigned char> script_data(ParseHex(script_str));
+ const CScript script(script_data.begin(), script_data.end());
+ coinControl.m_external_provider.scripts.emplace(CScriptID(script), script);
+ }
+ }
+
+ if (solving_data.exists("descriptors")) {
+ for (const UniValue& desc_univ : solving_data["descriptors"].get_array().getValues()) {
+ const std::string& desc_str = desc_univ.get_str();
+ FlatSigningProvider desc_out;
+ std::string error;
+ std::vector<CScript> scripts_temp;
+ std::unique_ptr<Descriptor> desc = Parse(desc_str, desc_out, error, true);
+ if (!desc) {
+ throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unable to parse descriptor '%s': %s", desc_str, error));
+ }
+ desc->Expand(0, desc_out, scripts_temp, desc_out);
+ coinControl.m_external_provider = Merge(coinControl.m_external_provider, desc_out);
+ }
+ }
+ }
+
if (tx.vout.size() == 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output");
@@ -3275,6 +3384,19 @@ void FundTransaction(CWallet& wallet, CMutableTransaction& tx, CAmount& fee_out,
setSubtractFeeFromOutputs.insert(pos);
}
+ // Fetch specified UTXOs from the UTXO set to get the scriptPubKeys and values of the outputs being selected
+ // and to match with the given solving_data. Only used for non-wallet outputs.
+ std::map<COutPoint, Coin> coins;
+ for (const CTxIn& txin : tx.vin) {
+ coins[txin.prevout]; // Create empty map entry keyed by prevout.
+ }
+ wallet.chain().findCoins(coins);
+ for (const auto& coin : coins) {
+ if (!coin.second.out.IsNull()) {
+ coinControl.SelectExternal(coin.first, coin.second.out);
+ }
+ }
+
bilingual_str error;
if (!FundTransaction(wallet, tx, fee_out, change_position, error, lockUnspents, setSubtractFeeFromOutputs, coinControl)) {
@@ -3290,8 +3412,9 @@ static RPCHelpMan fundrawtransaction()
"No existing outputs will be modified unless \"subtractFeeFromOutputs\" is specified.\n"
"Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n"
"The inputs added will not be signed, use signrawtransactionwithkey\n"
- " or signrawtransactionwithwallet for that.\n"
- "Note that all existing inputs must have their previous output transaction be in the wallet.\n"
+ "or signrawtransactionwithwallet for that.\n"
+ "All existing inputs must either have their previous output transaction be in the wallet\n"
+ "or be in the UTXO set. Solving data must be provided for non-wallet inputs.\n"
"Note that all inputs selected must be of standard form and P2SH scripts must be\n"
"in the wallet using importaddress or addmultisigaddress (to calculate fees).\n"
"You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n"
@@ -3299,6 +3422,7 @@ static RPCHelpMan fundrawtransaction()
{
{"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex string of the raw transaction"},
{"options", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED_NAMED_ARG, "for backward compatibility: passing in a true instead of an object will result in {\"includeWatching\":true}",
+ Cat<std::vector<RPCArg>>(
{
{"add_inputs", RPCArg::Type::BOOL, RPCArg::Default{true}, "For a transaction with existing inputs, automatically include more if they are not enough."},
{"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include inputs that are not safe to spend (unconfirmed transactions from outside keys and unconfirmed replacement transactions).\n"
@@ -3321,12 +3445,8 @@ static RPCHelpMan fundrawtransaction()
{"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
},
},
- {"replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Marks this transaction as BIP125 replaceable.\n"
- "Allows this transaction to be replaced by a transaction with higher fees"},
- {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
- {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, std::string() + "The fee estimate mode, must be one of (case insensitive):\n"
- " \"" + FeeModes("\"\n\"") + "\""},
},
+ FundTxDoc()),
"options"},
{"iswitness", RPCArg::Type::BOOL, RPCArg::DefaultHint{"depends on heuristic tests"}, "Whether the transaction hex is a serialized witness transaction.\n"
"If iswitness is not present, heuristic tests will be used in decoding.\n"
@@ -3429,6 +3549,10 @@ RPCHelpMan signrawtransactionwithwallet()
{
{RPCResult::Type::STR_HEX, "txid", "The hash of the referenced, previous transaction"},
{RPCResult::Type::NUM, "vout", "The index of the output to spent and used as input"},
+ {RPCResult::Type::ARR, "witness", "",
+ {
+ {RPCResult::Type::STR_HEX, "witness", ""},
+ }},
{RPCResult::Type::STR_HEX, "scriptSig", "The hex-encoded signature script"},
{RPCResult::Type::NUM, "sequence", "Script sequence number"},
{RPCResult::Type::STR, "error", "Verification or signing error related to the input"},
@@ -3764,7 +3888,6 @@ public:
obj.pushKV("embedded", std::move(subobj));
} else if (which_type == TxoutType::MULTISIG) {
// Also report some information on multisig scripts (which do not have a corresponding address).
- // TODO: abstract out the common functionality between this logic and ExtractDestinations.
obj.pushKV("sigsrequired", solutions_data[0][0]);
UniValue pubkeys(UniValue::VARR);
for (size_t i = 1; i < solutions_data.size() - 1; ++i) {
@@ -4132,6 +4255,7 @@ static RPCHelpMan send()
" \"" + FeeModes("\"\n\"") + "\""},
{"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
{"options", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED_NAMED_ARG, "",
+ Cat<std::vector<RPCArg>>(
{
{"add_inputs", RPCArg::Type::BOOL, RPCArg::Default{false}, "If inputs are specified, automatically include more if they are not enough."},
{"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include inputs that are not safe to spend (unconfirmed transactions from outside keys and unconfirmed replacement transactions).\n"
@@ -4141,9 +4265,6 @@ static RPCHelpMan send()
{"change_address", RPCArg::Type::STR_HEX, RPCArg::DefaultHint{"pool address"}, "The bitcoin address to receive the change"},
{"change_position", RPCArg::Type::NUM, RPCArg::DefaultHint{"random"}, "The index of the change output"},
{"change_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -changetype"}, "The output type to use. Only valid if change_address is not specified. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
- {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
- {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, std::string() + "The fee estimate mode, must be one of (case insensitive):\n"
- " \"" + FeeModes("\"\n\"") + "\""},
{"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
{"include_watching", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Also select inputs which are watch only.\n"
"Only solvable inputs can be used. Watch-only destinations are solvable if the public key and/or output script was imported,\n"
@@ -4166,18 +4287,17 @@ static RPCHelpMan send()
{"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
},
},
- {"replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Marks this transaction as BIP125 replaceable.\n"
- "Allows this transaction to be replaced by a transaction with higher fees"},
},
+ FundTxDoc()),
"options"},
},
RPCResult{
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
- {RPCResult::Type::STR_HEX, "txid", "The transaction id for the send. Only 1 transaction is created regardless of the number of addresses."},
- {RPCResult::Type::STR_HEX, "hex", "If add_to_wallet is false, the hex-encoded raw transaction with signature(s)"},
- {RPCResult::Type::STR, "psbt", "If more signatures are needed, or if add_to_wallet is false, the base64-encoded (partially) signed transaction"}
+ {RPCResult::Type::STR_HEX, "txid", /* optional */ true, "The transaction id for the send. Only 1 transaction is created regardless of the number of addresses."},
+ {RPCResult::Type::STR_HEX, "hex", /* optional */ true, "If add_to_wallet is false, the hex-encoded raw transaction with signature(s)"},
+ {RPCResult::Type::STR, "psbt", /* optional */ true, "If more signatures are needed, or if add_to_wallet is false, the base64-encoded (partially) signed transaction"}
}
},
RPCExamples{""
@@ -4385,7 +4505,7 @@ static RPCHelpMan walletprocesspsbt()
HELP_REQUIRING_PASSPHRASE,
{
{"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction base64 string"},
- {"sign", RPCArg::Type::BOOL, RPCArg::Default{true}, "Also sign the transaction when updating"},
+ {"sign", RPCArg::Type::BOOL, RPCArg::Default{true}, "Also sign the transaction when updating (requires wallet to be unlocked)"},
{"sighashtype", RPCArg::Type::STR, RPCArg::Default{"DEFAULT"}, "The signature hash type to sign with if not specified by the PSBT. Must be one of\n"
" \"DEFAULT\"\n"
" \"ALL\"\n"
@@ -4432,6 +4552,9 @@ static RPCHelpMan walletprocesspsbt()
bool sign = request.params[1].isNull() ? true : request.params[1].get_bool();
bool bip32derivs = request.params[3].isNull() ? true : request.params[3].get_bool();
bool complete = true;
+
+ if (sign) EnsureWalletIsUnlocked(*pwallet);
+
const TransactionError err{wallet.FillPSBT(psbtx, complete, nHashType, sign, bip32derivs)};
if (err != TransactionError::OK) {
throw JSONRPCTransactionError(err);
@@ -4452,7 +4575,9 @@ static RPCHelpMan walletcreatefundedpsbt()
{
return RPCHelpMan{"walletcreatefundedpsbt",
"\nCreates and funds a transaction in the Partially Signed Transaction format.\n"
- "Implements the Creator and Updater roles.\n",
+ "Implements the Creator and Updater roles.\n"
+ "All existing inputs must either have their previous output transaction be in the wallet\n"
+ "or be in the UTXO set. Solving data must be provided for non-wallet inputs.\n",
{
{"inputs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "Leave empty to add inputs automatically. See add_inputs option.",
{
@@ -4484,6 +4609,7 @@ static RPCHelpMan walletcreatefundedpsbt()
},
{"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"},
{"options", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED_NAMED_ARG, "",
+ Cat<std::vector<RPCArg>>(
{
{"add_inputs", RPCArg::Type::BOOL, RPCArg::Default{false}, "If inputs are specified, automatically include more if they are not enough."},
{"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include inputs that are not safe to spend (unconfirmed transactions from outside keys and unconfirmed replacement transactions).\n"
@@ -4504,12 +4630,8 @@ static RPCHelpMan walletcreatefundedpsbt()
{"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
},
},
- {"replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Marks this transaction as BIP125 replaceable.\n"
- "Allows this transaction to be replaced by a transaction with higher fees"},
- {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
- {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, std::string() + "The fee estimate mode, must be one of (case insensitive):\n"
- " \"" + FeeModes("\"\n\"") + "\""},
},
+ FundTxDoc()),
"options"},
{"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true}, "Include BIP 32 derivation paths for public keys if we know them"},
},
@@ -4650,10 +4772,11 @@ static RPCHelpMan upgradewallet()
#ifdef ENABLE_EXTERNAL_SIGNER
static RPCHelpMan walletdisplayaddress()
{
- return RPCHelpMan{"walletdisplayaddress",
+ return RPCHelpMan{
+ "walletdisplayaddress",
"Display address on an external signer for verification.",
{
- {"address", RPCArg::Type::STR, RPCArg::Optional::NO, /* default_val */ "", "bitcoin address to display"},
+ {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "bitcoin address to display"},
},
RPCResult{
RPCResult::Type::OBJ,"","",
diff --git a/src/wallet/salvage.cpp b/src/wallet/salvage.cpp
index ea045eb6d8..4151099c1f 100644
--- a/src/wallet/salvage.cpp
+++ b/src/wallet/salvage.cpp
@@ -45,7 +45,7 @@ bool RecoverDatabaseFile(const fs::path& file_path, bilingual_str& error, std::v
// Call Salvage with fAggressive=true to
// get as much data as possible.
// Rewrite salvaged data to fresh wallet file
- // Set -rescan so any missing transactions will be
+ // Rescan so any missing transactions will be
// found.
int64_t now = GetTime();
std::string newFilename = strprintf("%s.%d.bak", filename, now);
diff --git a/src/wallet/scriptpubkeyman.cpp b/src/wallet/scriptpubkeyman.cpp
index fe41f9b8cc..fdfb36bb0a 100644
--- a/src/wallet/scriptpubkeyman.cpp
+++ b/src/wallet/scriptpubkeyman.cpp
@@ -331,7 +331,7 @@ bool LegacyScriptPubKeyMan::TopUpInactiveHDChain(const CKeyID seed_id, int64_t i
CHDChain& chain = it->second;
// Top up key pool
- int64_t target_size = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1);
+ int64_t target_size = std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1);
// "size" of the keypools. Not really the size, actually the difference between index and the chain counter
// Since chain counter is 1 based and index is 0 based, one of them needs to be offset by 1.
@@ -1259,7 +1259,7 @@ bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize)
if (kpSize > 0)
nTargetSize = kpSize;
else
- nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
+ nTargetSize = std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
// count amount of available keys (internal, external)
// make sure the keypool of external and internal keys fits the user selected target (-keypool)
@@ -1764,7 +1764,7 @@ bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
if (size > 0) {
target_size = size;
} else {
- target_size = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1);
+ target_size = std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1);
}
// Calculate the new range_end
diff --git a/src/wallet/spend.cpp b/src/wallet/spend.cpp
index 4a7a268982..5470177440 100644
--- a/src/wallet/spend.cpp
+++ b/src/wallet/spend.cpp
@@ -2,9 +2,11 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#include <consensus/amount.h>
#include <consensus/validation.h>
#include <interfaces/chain.h>
#include <policy/policy.h>
+#include <script/signingprovider.h>
#include <util/check.h>
#include <util/fees.h>
#include <util/moneystr.h>
@@ -31,21 +33,27 @@ std::string COutput::ToString() const
return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
}
-int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* wallet, bool use_max_sig)
+int CalculateMaximumSignedInputSize(const CTxOut& txout, const SigningProvider* provider, bool use_max_sig)
{
CMutableTransaction txn;
txn.vin.push_back(CTxIn(COutPoint()));
- if (!wallet->DummySignInput(txn.vin[0], txout, use_max_sig)) {
+ if (!provider || !DummySignInput(*provider, txn.vin[0], txout, use_max_sig)) {
return -1;
}
return GetVirtualTransactionInputSize(txn.vin[0]);
}
+int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* wallet, bool use_max_sig)
+{
+ const std::unique_ptr<SigningProvider> provider = wallet->GetSolvingProvider(txout.scriptPubKey);
+ return CalculateMaximumSignedInputSize(txout, provider.get(), use_max_sig);
+}
+
// txouts needs to be in the order of tx.vin
-TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, bool use_max_sig)
+TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, const CCoinControl* coin_control)
{
CMutableTransaction txNew(tx);
- if (!wallet->DummySignTx(txNew, txouts, use_max_sig)) {
+ if (!wallet->DummySignTx(txNew, txouts, coin_control)) {
return TxSize{-1, -1};
}
CTransaction ctx(txNew);
@@ -54,19 +62,27 @@ TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *walle
return TxSize{vsize, weight};
}
-TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig)
+TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const CCoinControl* coin_control)
{
std::vector<CTxOut> txouts;
+ // Look up the inputs. The inputs are either in the wallet, or in coin_control.
for (const CTxIn& input : tx.vin) {
const auto mi = wallet->mapWallet.find(input.prevout.hash);
// Can not estimate size without knowing the input details
- if (mi == wallet->mapWallet.end()) {
+ if (mi != wallet->mapWallet.end()) {
+ assert(input.prevout.n < mi->second.tx->vout.size());
+ txouts.emplace_back(mi->second.tx->vout.at(input.prevout.n));
+ } else if (coin_control) {
+ CTxOut txout;
+ if (!coin_control->GetExternalOutput(input.prevout, txout)) {
+ return TxSize{-1, -1};
+ }
+ txouts.emplace_back(txout);
+ } else {
return TxSize{-1, -1};
}
- assert(input.prevout.n < mi->second.tx->vout.size());
- txouts.emplace_back(mi->second.tx->vout[input.prevout.n]);
}
- return CalculateMaximumSignedTxSize(tx, wallet, txouts, use_max_sig);
+ return CalculateMaximumSignedTxSize(tx, wallet, txouts, coin_control);
}
void AvailableCoins(const CWallet& wallet, std::vector<COutput>& vCoins, const CCoinControl* coinControl, const CAmount& nMinimumAmount, const CAmount& nMaximumAmount, const CAmount& nMinimumSumAmount, const uint64_t nMaximumCount)
@@ -387,6 +403,15 @@ bool AttemptSelection(const CWallet& wallet, const CAmount& nTargetValue, const
results.emplace_back(std::make_tuple(waste, std::move(knapsack_coins), knapsack_value));
}
+ // We include the minimum final change for SRD as we do want to avoid making really small change.
+ // KnapsackSolver does not need this because it includes MIN_CHANGE internally.
+ const CAmount srd_target = nTargetValue + coin_selection_params.m_change_fee + MIN_FINAL_CHANGE;
+ auto srd_result = SelectCoinsSRD(positive_groups, srd_target);
+ if (srd_result != std::nullopt) {
+ const auto waste = GetSelectionWaste(srd_result->first, coin_selection_params.m_cost_of_change, srd_target, !coin_selection_params.m_subtract_fee_outputs);
+ results.emplace_back(std::make_tuple(waste, std::move(srd_result->first), srd_result->second));
+ }
+
if (results.size() == 0) {
// No solution found
return false;
@@ -426,32 +451,40 @@ bool SelectCoins(const CWallet& wallet, const std::vector<COutput>& vAvailableCo
std::vector<COutPoint> vPresetInputs;
coin_control.ListSelected(vPresetInputs);
- for (const COutPoint& outpoint : vPresetInputs)
- {
+ for (const COutPoint& outpoint : vPresetInputs) {
+ int input_bytes = -1;
+ CTxOut txout;
std::map<uint256, CWalletTx>::const_iterator it = wallet.mapWallet.find(outpoint.hash);
- if (it != wallet.mapWallet.end())
- {
+ if (it != wallet.mapWallet.end()) {
const CWalletTx& wtx = it->second;
// Clearly invalid input, fail
if (wtx.tx->vout.size() <= outpoint.n) {
return false;
}
- // Just to calculate the marginal byte size
- CInputCoin coin(wtx.tx, outpoint.n, GetTxSpendSize(wallet, wtx, outpoint.n, false));
- nValueFromPresetInputs += coin.txout.nValue;
- if (coin.m_input_bytes <= 0) {
- return false; // Not solvable, can't estimate size for fee
- }
- coin.effective_value = coin.txout.nValue - coin_selection_params.m_effective_feerate.GetFee(coin.m_input_bytes);
- if (coin_selection_params.m_subtract_fee_outputs) {
- value_to_select -= coin.txout.nValue;
- } else {
- value_to_select -= coin.effective_value;
+ input_bytes = GetTxSpendSize(wallet, wtx, outpoint.n, false);
+ txout = wtx.tx->vout.at(outpoint.n);
+ }
+ if (input_bytes == -1) {
+ // The input is external. We either did not find the tx in mapWallet, or we did but couldn't compute the input size with wallet data
+ if (!coin_control.GetExternalOutput(outpoint, txout)) {
+ // Not ours, and we don't have solving data.
+ return false;
}
- setPresetCoins.insert(coin);
+ input_bytes = CalculateMaximumSignedInputSize(txout, &coin_control.m_external_provider, /* use_max_sig */ true);
+ }
+
+ CInputCoin coin(outpoint, txout, input_bytes);
+ nValueFromPresetInputs += coin.txout.nValue;
+ if (coin.m_input_bytes == -1) {
+ return false; // Not solvable, can't estimate size for fee
+ }
+ coin.effective_value = coin.txout.nValue - coin_selection_params.m_effective_feerate.GetFee(coin.m_input_bytes);
+ if (coin_selection_params.m_subtract_fee_outputs) {
+ value_to_select -= coin.txout.nValue;
} else {
- return false; // TODO: Allow non-wallet inputs
+ value_to_select -= coin.effective_value;
}
+ setPresetCoins.insert(coin);
}
// remove preset inputs from vCoins so that Coin Selection doesn't pick them.
@@ -779,10 +812,10 @@ static bool CreateTransactionInternal(
}
// Calculate the transaction fee
- TxSize tx_sizes = CalculateMaximumSignedTxSize(CTransaction(txNew), &wallet, coin_control.fAllowWatchOnly);
+ TxSize tx_sizes = CalculateMaximumSignedTxSize(CTransaction(txNew), &wallet, &coin_control);
int nBytes = tx_sizes.vsize;
- if (nBytes < 0) {
- error = _("Signing transaction failed");
+ if (nBytes == -1) {
+ error = _("Missing solving data for estimating transaction size");
return false;
}
nFeeRet = coin_selection_params.m_effective_feerate.GetFee(nBytes);
@@ -804,7 +837,7 @@ static bool CreateTransactionInternal(
txNew.vout.erase(change_position);
// Because we have dropped this change, the tx size and required fee will be different, so let's recalculate those
- tx_sizes = CalculateMaximumSignedTxSize(CTransaction(txNew), &wallet, coin_control.fAllowWatchOnly);
+ tx_sizes = CalculateMaximumSignedTxSize(CTransaction(txNew), &wallet, &coin_control);
nBytes = tx_sizes.vsize;
fee_needed = coin_selection_params.m_effective_feerate.GetFee(nBytes);
}
diff --git a/src/wallet/spend.h b/src/wallet/spend.h
index e39f134dc3..7467dd9fa3 100644
--- a/src/wallet/spend.h
+++ b/src/wallet/spend.h
@@ -5,6 +5,7 @@
#ifndef BITCOIN_WALLET_SPEND_H
#define BITCOIN_WALLET_SPEND_H
+#include <consensus/amount.h>
#include <wallet/coinselection.h>
#include <wallet/transaction.h>
#include <wallet/wallet.h>
@@ -66,6 +67,7 @@ public:
//Get the marginal bytes of spending the specified output
int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* pwallet, bool use_max_sig = false);
+int CalculateMaximumSignedInputSize(const CTxOut& txout, const SigningProvider* pwallet, bool use_max_sig = false);
struct TxSize {
int64_t vsize{-1};
@@ -76,8 +78,8 @@ struct TxSize {
* Use DummySignatureCreator, which inserts 71 byte signatures everywhere.
* NOTE: this requires that all inputs must be in mapWallet (eg the tx should
* be AllInputsMine). */
-TxSize CalculateMaximumSignedTxSize(const CTransaction& tx, const CWallet* wallet, const std::vector<CTxOut>& txouts, bool use_max_sig = false);
-TxSize CalculateMaximumSignedTxSize(const CTransaction& tx, const CWallet* wallet, bool use_max_sig = false) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet);
+TxSize CalculateMaximumSignedTxSize(const CTransaction& tx, const CWallet* wallet, const std::vector<CTxOut>& txouts, const CCoinControl* coin_control = nullptr);
+TxSize CalculateMaximumSignedTxSize(const CTransaction& tx, const CWallet* wallet, const CCoinControl* coin_control = nullptr) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet);
/**
* populate vCoins with vector of available COutputs.
diff --git a/src/wallet/sqlite.cpp b/src/wallet/sqlite.cpp
index 2e60aca017..815d17967c 100644
--- a/src/wallet/sqlite.cpp
+++ b/src/wallet/sqlite.cpp
@@ -212,6 +212,10 @@ void SQLiteDatabase::Open()
if (ret != SQLITE_OK) {
throw std::runtime_error(strprintf("SQLiteDatabase: Failed to open database: %s\n", sqlite3_errstr(ret)));
}
+ ret = sqlite3_extended_result_codes(m_db, 1);
+ if (ret != SQLITE_OK) {
+ throw std::runtime_error(strprintf("SQLiteDatabase: Failed to enable extended result codes: %s\n", sqlite3_errstr(ret)));
+ }
}
if (sqlite3_db_readonly(m_db, "main") != 0) {
diff --git a/src/wallet/test/coinselector_tests.cpp b/src/wallet/test/coinselector_tests.cpp
index f901679efc..f80c4637b8 100644
--- a/src/wallet/test/coinselector_tests.cpp
+++ b/src/wallet/test/coinselector_tests.cpp
@@ -2,7 +2,7 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <amount.h>
+#include <consensus/amount.h>
#include <node/context.h>
#include <primitives/transaction.h>
#include <random.h>
@@ -40,7 +40,7 @@ CoinEligibilityFilter filter_standard_extra(6, 6, 0);
CoinSelectionParams coin_selection_params(/* change_output_size= */ 0,
/* change_spend_size= */ 0, /* effective_feerate= */ CFeeRate(0),
/* long_term_feerate= */ CFeeRate(0), /* discard_feerate= */ CFeeRate(0),
- /* tx_no_inputs_size= */ 0, /* avoid_partial= */ false);
+ /* tx_noinputs_size= */ 0, /* avoid_partial= */ false);
static void add_coin(const CAmount& nValue, int nInput, std::vector<CInputCoin>& set)
{
@@ -287,7 +287,7 @@ BOOST_AUTO_TEST_CASE(bnb_search_test)
CoinSelectionParams coin_selection_params_bnb(/* change_output_size= */ 0,
/* change_spend_size= */ 0, /* effective_feerate= */ CFeeRate(3000),
/* long_term_feerate= */ CFeeRate(1000), /* discard_feerate= */ CFeeRate(1000),
- /* tx_no_inputs_size= */ 0, /* avoid_partial= */ false);
+ /* tx_noinputs_size= */ 0, /* avoid_partial= */ false);
CoinSet setCoinsRet;
CAmount nValueRet;
empty_wallet();
@@ -654,7 +654,7 @@ BOOST_AUTO_TEST_CASE(SelectCoins_test)
CoinSelectionParams cs_params(/* change_output_size= */ 34,
/* change_spend_size= */ 148, /* effective_feerate= */ CFeeRate(0),
/* long_term_feerate= */ CFeeRate(0), /* discard_feerate= */ CFeeRate(0),
- /* tx_no_inputs_size= */ 0, /* avoid_partial= */ false);
+ /* tx_noinputs_size= */ 0, /* avoid_partial= */ false);
CoinSet out_set;
CAmount out_value = 0;
CCoinControl cc;
@@ -724,12 +724,25 @@ BOOST_AUTO_TEST_CASE(waste_test)
BOOST_CHECK_LT(waste_nochange2, waste_nochange1);
selection.clear();
- // 0 Waste only when fee == long term fee, no change, and no excess
+ // No Waste when fee == long_term_fee, no change, and no excess
add_coin(1 * COIN, 1, selection, fee, fee);
add_coin(2 * COIN, 2, selection, fee, fee);
- const CAmount exact_target = in_amt - 2 * fee;
- BOOST_CHECK_EQUAL(0, GetSelectionWaste(selection, 0, exact_target));
+ const CAmount exact_target{in_amt - fee * 2};
+ BOOST_CHECK_EQUAL(0, GetSelectionWaste(selection, /* change_cost */ 0, exact_target));
+ selection.clear();
+ // No Waste when (fee - long_term_fee) == (-cost_of_change), and no excess
+ const CAmount new_change_cost{fee_diff * 2};
+ add_coin(1 * COIN, 1, selection, fee, fee + fee_diff);
+ add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
+ BOOST_CHECK_EQUAL(0, GetSelectionWaste(selection, new_change_cost, target));
+ selection.clear();
+
+ // No Waste when (fee - long_term_fee) == (-excess), no change cost
+ const CAmount new_target{in_amt - fee * 2 - fee_diff * 2};
+ add_coin(1 * COIN, 1, selection, fee, fee + fee_diff);
+ add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
+ BOOST_CHECK_EQUAL(0, GetSelectionWaste(selection, /* change cost */ 0, new_target));
}
BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/wallet/test/spend_tests.cpp b/src/wallet/test/spend_tests.cpp
index e779b2450f..becef70729 100644
--- a/src/wallet/test/spend_tests.cpp
+++ b/src/wallet/test/spend_tests.cpp
@@ -2,6 +2,7 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#include <consensus/amount.h>
#include <policy/fees.h>
#include <validation.h>
#include <wallet/coincontrol.h>
diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp
index 12a22f458a..9938380369 100644
--- a/src/wallet/test/wallet_tests.cpp
+++ b/src/wallet/test/wallet_tests.cpp
@@ -232,10 +232,10 @@ BOOST_FIXTURE_TEST_CASE(importmulti_rescan, TestChain100Setup)
"seconds of key creation, and could contain transactions pertaining to the key. As a result, "
"transactions and coins using this key may not appear in the wallet. This error could be caused "
"by pruning or data corruption (see bitcoind log for details) and could be dealt with by "
- "downloading and rescanning the relevant blocks (see -reindex and -rescan "
- "options).\"}},{\"success\":true}]",
+ "downloading and rescanning the relevant blocks (see -reindex option and rescanblockchain "
+ "RPC).\"}},{\"success\":true}]",
0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
- RemoveWallet(context, wallet, /* load_on_startup= */ std::nullopt);
+ RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
}
}
@@ -280,7 +280,7 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup)
request.params.push_back(backup_file);
::dumpwallet().HandleRequest(request);
- RemoveWallet(context, wallet, /* load_on_startup= */ std::nullopt);
+ RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
}
// Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
@@ -299,7 +299,7 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup)
AddWallet(context, wallet);
wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
::importwallet().HandleRequest(request);
- RemoveWallet(context, wallet, /* load_on_startup= */ std::nullopt);
+ RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U);
BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U);
diff --git a/src/wallet/transaction.h b/src/wallet/transaction.h
index 094221adf2..6fc1bd1eed 100644
--- a/src/wallet/transaction.h
+++ b/src/wallet/transaction.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_WALLET_TRANSACTION_H
#define BITCOIN_WALLET_TRANSACTION_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <primitives/transaction.h>
#include <serialize.h>
#include <wallet/ismine.h>
@@ -19,25 +19,6 @@
typedef std::map<std::string, std::string> mapValue_t;
-
-static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
-{
- if (!mapValue.count("n"))
- {
- nOrderPos = -1; // TODO: calculate elsewhere
- return;
- }
- nOrderPos = atoi64(mapValue["n"]);
-}
-
-
-static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
-{
- if (nOrderPos == -1)
- return;
- mapValue["n"] = ToString(nOrderPos);
-}
-
/** Legacy class used for deserializing vtxPrev for backwards compatibility.
* vtxPrev was removed in commit 93a18a3650292afbb441a47d1fa1b94aeb0164e3,
* but old wallet.dat files may still contain vtxPrev vectors of CMerkleTxs.
@@ -192,7 +173,9 @@ public:
mapValue_t mapValueCopy = mapValue;
mapValueCopy["fromaccount"] = "";
- WriteOrderPos(nOrderPos, mapValueCopy);
+ if (nOrderPos != -1) {
+ mapValueCopy["n"] = ToString(nOrderPos);
+ }
if (nTimeSmart) {
mapValueCopy["timesmart"] = strprintf("%u", nTimeSmart);
}
@@ -232,8 +215,10 @@ public:
setConfirmed();
}
- ReadOrderPos(nOrderPos, mapValue);
- nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
+ const auto it_op = mapValue.find("n");
+ nOrderPos = (it_op != mapValue.end()) ? LocaleIndependentAtoi<int64_t>(it_op->second) : -1;
+ const auto it_ts = mapValue.find("timesmart");
+ nTimeSmart = (it_ts != mapValue.end()) ? static_cast<unsigned int>(LocaleIndependentAtoi<int64_t>(it_ts->second)) : 0;
mapValue.erase("fromaccount");
mapValue.erase("spent");
diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
index 70349b2455..abfe9d7dba 100644
--- a/src/wallet/wallet.cpp
+++ b/src/wallet/wallet.cpp
@@ -6,6 +6,7 @@
#include <wallet/wallet.h>
#include <chain.h>
+#include <consensus/amount.h>
#include <consensus/consensus.h>
#include <consensus/validation.h>
#include <external_signer.h>
@@ -589,11 +590,16 @@ bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
return false;
}
-void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
+void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid, WalletBatch* batch)
{
mapTxSpends.insert(std::make_pair(outpoint, wtxid));
- setLockedCoins.erase(outpoint);
+ if (batch) {
+ UnlockCoin(outpoint, batch);
+ } else {
+ WalletBatch temp_batch(GetDatabase());
+ UnlockCoin(outpoint, &temp_batch);
+ }
std::pair<TxSpends::iterator, TxSpends::iterator> range;
range = mapTxSpends.equal_range(outpoint);
@@ -601,7 +607,7 @@ void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
}
-void CWallet::AddToSpends(const uint256& wtxid)
+void CWallet::AddToSpends(const uint256& wtxid, WalletBatch* batch)
{
auto it = mapWallet.find(wtxid);
assert(it != mapWallet.end());
@@ -610,7 +616,7 @@ void CWallet::AddToSpends(const uint256& wtxid)
return;
for (const CTxIn& txin : thisTx.tx->vin)
- AddToSpends(txin.prevout, wtxid);
+ AddToSpends(txin.prevout, wtxid, batch);
}
bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
@@ -879,7 +885,7 @@ bool CWallet::IsSpentKey(const uint256& hash, unsigned int n) const
return false;
}
-CWalletTx* CWallet::AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation& confirm, const UpdateWalletTxFn& update_wtx, bool fFlushOnClose)
+CWalletTx* CWallet::AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation& confirm, const UpdateWalletTxFn& update_wtx, bool fFlushOnClose, bool rescanning_old_block)
{
LOCK(cs_wallet);
@@ -909,8 +915,8 @@ CWalletTx* CWallet::AddToWallet(CTransactionRef tx, const CWalletTx::Confirmatio
wtx.nTimeReceived = chain().getAdjustedTime();
wtx.nOrderPos = IncOrderPosNext(&batch);
wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
- wtx.nTimeSmart = ComputeTimeSmart(wtx);
- AddToSpends(hash);
+ wtx.nTimeSmart = ComputeTimeSmart(wtx, rescanning_old_block);
+ AddToSpends(hash, &batch);
}
if (!fInsertedNew)
@@ -1026,7 +1032,7 @@ bool CWallet::LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx
return true;
}
-bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, CWalletTx::Confirmation confirm, bool fUpdate)
+bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, CWalletTx::Confirmation confirm, bool fUpdate, bool rescanning_old_block)
{
const CTransaction& tx = *ptx;
{
@@ -1064,7 +1070,7 @@ bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, CWalletTx::Co
// Block disconnection override an abandoned tx as unconfirmed
// which means user may have to call abandontransaction again
- return AddToWallet(MakeTransactionRef(tx), confirm, /* update_wtx= */ nullptr, /* fFlushOnClose= */ false);
+ return AddToWallet(MakeTransactionRef(tx), confirm, /* update_wtx= */ nullptr, /* fFlushOnClose= */ false, rescanning_old_block);
}
}
return false;
@@ -1193,9 +1199,9 @@ void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, c
}
}
-void CWallet::SyncTransaction(const CTransactionRef& ptx, CWalletTx::Confirmation confirm, bool update_tx)
+void CWallet::SyncTransaction(const CTransactionRef& ptx, CWalletTx::Confirmation confirm, bool update_tx, bool rescanning_old_block)
{
- if (!AddToWalletIfInvolvingMe(ptx, confirm, update_tx))
+ if (!AddToWalletIfInvolvingMe(ptx, confirm, update_tx, rescanning_old_block))
return; // Not one of ours
// If a transaction changes 'conflicted' state, that changes the balance
@@ -1443,19 +1449,13 @@ bool CWallet::AddWalletFlags(uint64_t flags)
// Helper for producing a max-sized low-S low-R signature (eg 71 bytes)
// or a max-sized low-S signature (e.g. 72 bytes) if use_max_sig is true
-bool CWallet::DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig) const
+bool DummySignInput(const SigningProvider& provider, CTxIn &tx_in, const CTxOut &txout, bool use_max_sig)
{
// Fill in dummy signatures for fee calculation.
const CScript& scriptPubKey = txout.scriptPubKey;
SignatureData sigdata;
- std::unique_ptr<SigningProvider> provider = GetSolvingProvider(scriptPubKey);
- if (!provider) {
- // We don't know about this scriptpbuKey;
- return false;
- }
-
- if (!ProduceSignature(*provider, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, scriptPubKey, sigdata)) {
+ if (!ProduceSignature(provider, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, scriptPubKey, sigdata)) {
return false;
}
UpdateInput(tx_in, sigdata);
@@ -1463,14 +1463,21 @@ bool CWallet::DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig
}
// Helper for producing a bunch of max-sized low-S low-R signatures (eg 71 bytes)
-bool CWallet::DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig) const
+bool CWallet::DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, const CCoinControl* coin_control) const
{
// Fill in dummy signatures for fee calculation.
int nIn = 0;
for (const auto& txout : txouts)
{
- if (!DummySignInput(txNew.vin[nIn], txout, use_max_sig)) {
- return false;
+ CTxIn& txin = txNew.vin[nIn];
+ // Use max sig if watch only inputs were used or if this particular input is an external input
+ // to ensure a sufficient fee is attained for the requested feerate.
+ const bool use_max_sig = coin_control && (coin_control->fAllowWatchOnly || coin_control->IsExternalSelected(txin.prevout));
+ const std::unique_ptr<SigningProvider> provider = GetSolvingProvider(txout.scriptPubKey);
+ if (!provider || !DummySignInput(*provider, txin, txout, use_max_sig)) {
+ if (!coin_control || !DummySignInput(coin_control->m_external_provider, txin, txout, use_max_sig)) {
+ return false;
+ }
}
nIn++;
@@ -1595,7 +1602,7 @@ CWallet::ScanResult CWallet::ScanForWalletTransactions(const uint256& start_bloc
WalletLogPrintf("Rescan started from block %s...\n", start_block.ToString());
fAbortRescan = false;
- ShowProgress(strprintf("%s " + _("Rescanning…").translated, GetDisplayName()), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
+ ShowProgress(strprintf("%s " + _("Rescanning…").translated, GetDisplayName()), 0); // show rescan progress in GUI as dialog or on splashscreen, if rescan required on startup (e.g. due to corruption)
uint256 tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
uint256 end_hash = tip_hash;
if (max_height) chain().findAncestorByHeight(tip_hash, *max_height, FoundBlock().hash(end_hash));
@@ -1638,7 +1645,7 @@ CWallet::ScanResult CWallet::ScanForWalletTransactions(const uint256& start_bloc
break;
}
for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
- SyncTransaction(block.vtx[posInBlock], {CWalletTx::Status::CONFIRMED, block_height, block_hash, (int)posInBlock}, fUpdate);
+ SyncTransaction(block.vtx[posInBlock], {CWalletTx::Status::CONFIRMED, block_height, block_hash, (int)posInBlock}, fUpdate, /* rescanning_old_block */ true);
}
// scan succeeded, record block as most recent successfully scanned
result.last_scanned_block = block_hash;
@@ -2002,10 +2009,7 @@ DBErrors CWallet::LoadWallet()
assert(m_internal_spk_managers.empty());
}
- if (nLoadWalletRet != DBErrors::LOAD_OK)
- return nLoadWalletRet;
-
- return DBErrors::LOAD_OK;
+ return nLoadWalletRet;
}
DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
@@ -2260,22 +2264,36 @@ bool CWallet::DisplayAddress(const CTxDestination& dest)
return signer_spk_man->DisplayAddress(scriptPubKey, signer);
}
-void CWallet::LockCoin(const COutPoint& output)
+bool CWallet::LockCoin(const COutPoint& output, WalletBatch* batch)
{
AssertLockHeld(cs_wallet);
setLockedCoins.insert(output);
+ if (batch) {
+ return batch->WriteLockedUTXO(output);
+ }
+ return true;
}
-void CWallet::UnlockCoin(const COutPoint& output)
+bool CWallet::UnlockCoin(const COutPoint& output, WalletBatch* batch)
{
AssertLockHeld(cs_wallet);
- setLockedCoins.erase(output);
+ bool was_locked = setLockedCoins.erase(output);
+ if (batch && was_locked) {
+ return batch->EraseLockedUTXO(output);
+ }
+ return true;
}
-void CWallet::UnlockAllCoins()
+bool CWallet::UnlockAllCoins()
{
AssertLockHeld(cs_wallet);
+ bool success = true;
+ WalletBatch batch(GetDatabase());
+ for (auto it = setLockedCoins.begin(); it != setLockedCoins.end(); ++it) {
+ success &= batch.EraseLockedUTXO(*it);
+ }
setLockedCoins.clear();
+ return success;
}
bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
@@ -2365,6 +2383,8 @@ void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const {
* - If sending a transaction, assign its timestamp to the current time.
* - If receiving a transaction outside a block, assign its timestamp to the
* current time.
+ * - If receiving a transaction during a rescanning process, assign all its
+ * (not already known) transactions' timestamps to the block time.
* - If receiving a block with a future timestamp, assign all its (not already
* known) transactions' timestamps to the current time.
* - If receiving a block with a past timestamp, before the most recent known
@@ -2379,38 +2399,43 @@ void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const {
* https://bitcointalk.org/?topic=54527, or
* https://github.com/bitcoin/bitcoin/pull/1393.
*/
-unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
+unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const
{
unsigned int nTimeSmart = wtx.nTimeReceived;
if (!wtx.isUnconfirmed() && !wtx.isAbandoned()) {
int64_t blocktime;
- if (chain().findBlock(wtx.m_confirm.hashBlock, FoundBlock().time(blocktime))) {
- int64_t latestNow = wtx.nTimeReceived;
- int64_t latestEntry = 0;
-
- // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
- int64_t latestTolerated = latestNow + 300;
- const TxItems& txOrdered = wtxOrdered;
- for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
- CWalletTx* const pwtx = it->second;
- if (pwtx == &wtx) {
- continue;
- }
- int64_t nSmartTime;
- nSmartTime = pwtx->nTimeSmart;
- if (!nSmartTime) {
- nSmartTime = pwtx->nTimeReceived;
- }
- if (nSmartTime <= latestTolerated) {
- latestEntry = nSmartTime;
- if (nSmartTime > latestNow) {
- latestNow = nSmartTime;
+ int64_t block_max_time;
+ if (chain().findBlock(wtx.m_confirm.hashBlock, FoundBlock().time(blocktime).maxTime(block_max_time))) {
+ if (rescanning_old_block) {
+ nTimeSmart = block_max_time;
+ } else {
+ int64_t latestNow = wtx.nTimeReceived;
+ int64_t latestEntry = 0;
+
+ // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
+ int64_t latestTolerated = latestNow + 300;
+ const TxItems& txOrdered = wtxOrdered;
+ for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
+ CWalletTx* const pwtx = it->second;
+ if (pwtx == &wtx) {
+ continue;
+ }
+ int64_t nSmartTime;
+ nSmartTime = pwtx->nTimeSmart;
+ if (!nSmartTime) {
+ nSmartTime = pwtx->nTimeReceived;
+ }
+ if (nSmartTime <= latestTolerated) {
+ latestEntry = nSmartTime;
+ if (nSmartTime > latestNow) {
+ latestNow = nSmartTime;
+ }
+ break;
}
- break;
}
- }
- nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
+ nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
+ }
} else {
WalletLogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.m_confirm.hashBlock.ToString());
}
@@ -2516,6 +2541,7 @@ std::shared_ptr<CWallet> CWallet::Create(WalletContext& context, const std::stri
// TODO: Can't use std::make_shared because we need a custom deleter but
// should be possible to use std::allocate_shared.
std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), ReleaseWallet);
+ bool rescan_required = false;
DBErrors nLoadWalletRet = walletInstance->LoadWallet();
if (nLoadWalletRet != DBErrors::LOAD_OK) {
if (nLoadWalletRet == DBErrors::CORRUPT) {
@@ -2536,6 +2562,10 @@ std::shared_ptr<CWallet> CWallet::Create(WalletContext& context, const std::stri
{
error = strprintf(_("Wallet needed to be rewritten: restart %s to complete"), PACKAGE_NAME);
return nullptr;
+ } else if (nLoadWalletRet == DBErrors::NEED_RESCAN) {
+ warnings.push_back(strprintf(_("Error reading %s! Transaction data may be missing or incorrect."
+ " Rescanning wallet."), walletFile));
+ rescan_required = true;
}
else {
error = strprintf(_("Error loading %s"), walletFile);
@@ -2716,7 +2746,7 @@ std::shared_ptr<CWallet> CWallet::Create(WalletContext& context, const std::stri
_("The wallet will avoid paying less than the minimum relay fee."));
}
- walletInstance->m_confirm_target = args.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
+ walletInstance->m_confirm_target = args.GetIntArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
walletInstance->m_spend_zero_conf_change = args.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
walletInstance->m_signal_rbf = args.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
@@ -2727,7 +2757,7 @@ std::shared_ptr<CWallet> CWallet::Create(WalletContext& context, const std::stri
LOCK(walletInstance->cs_wallet);
- if (chain && !AttachChain(walletInstance, *chain, error, warnings)) {
+ if (chain && !AttachChain(walletInstance, *chain, rescan_required, error, warnings)) {
return nullptr;
}
@@ -2749,7 +2779,7 @@ std::shared_ptr<CWallet> CWallet::Create(WalletContext& context, const std::stri
return walletInstance;
}
-bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interfaces::Chain& chain, bilingual_str& error, std::vector<bilingual_str>& warnings)
+bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interfaces::Chain& chain, const bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings)
{
LOCK(walletInstance->cs_wallet);
// allow setting the chain if it hasn't been set already but prevent changing it
@@ -2766,8 +2796,9 @@ bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interf
// interface.
walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
+ // If rescan_required = true, rescan_height remains equal to 0
int rescan_height = 0;
- if (!gArgs.GetBoolArg("-rescan", false))
+ if (!rescan_required)
{
WalletBatch batch(walletInstance->GetDatabase());
CBlockLocator locator;
diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h
index 2dc9eff712..767b24adbb 100644
--- a/src/wallet/wallet.h
+++ b/src/wallet/wallet.h
@@ -6,7 +6,7 @@
#ifndef BITCOIN_WALLET_WALLET_H
#define BITCOIN_WALLET_WALLET_H
-#include <amount.h>
+#include <consensus/amount.h>
#include <interfaces/chain.h>
#include <interfaces/handler.h>
#include <outputtype.h>
@@ -256,8 +256,8 @@ private:
*/
typedef std::multimap<COutPoint, uint256> TxSpends;
TxSpends mapTxSpends GUARDED_BY(cs_wallet);
- void AddToSpends(const COutPoint& outpoint, const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
- void AddToSpends(const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
+ void AddToSpends(const COutPoint& outpoint, const uint256& wtxid, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
+ void AddToSpends(const uint256& wtxid, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
/**
* Add a transaction to the wallet, or update it. pIndex and posInBlock should
@@ -271,8 +271,11 @@ private:
* abandoned is an indication that it is not safe to be considered abandoned.
* Abandoned state should probably be more carefully tracked via different
* posInBlock signals or by checking mempool presence when necessary.
+ *
+ * Should be called with rescanning_old_block set to true, if the transaction is
+ * not discovered in real time, but during a rescan of old blocks.
*/
- bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool fUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
+ bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool fUpdate, bool rescanning_old_block) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
/** Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
void MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx);
@@ -284,7 +287,7 @@ private:
/* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected/ScanForWalletTransactions.
* Should be called with non-zero block_hash and posInBlock if this is for a transaction that is included in a block. */
- void SyncTransaction(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool update_tx = true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
+ void SyncTransaction(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool update_tx = true, bool rescanning_old_block = false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
/** WalletFlags set on this wallet. */
std::atomic<uint64_t> m_wallet_flags{0};
@@ -334,7 +337,7 @@ private:
* block locator and m_last_block_processed, and registering for
* notifications about new blocks and transactions.
*/
- static bool AttachChain(const std::shared_ptr<CWallet>& wallet, interfaces::Chain& chain, bilingual_str& error, std::vector<bilingual_str>& warnings);
+ static bool AttachChain(const std::shared_ptr<CWallet>& wallet, interfaces::Chain& chain, const bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings);
public:
/**
@@ -449,9 +452,9 @@ public:
bool DisplayAddress(const CTxDestination& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
- void LockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
- void UnlockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
- void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
+ bool LockCoin(const COutPoint& output, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
+ bool UnlockCoin(const COutPoint& output, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
+ bool UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
/*
@@ -484,7 +487,7 @@ public:
bool EncryptWallet(const SecureString& strWalletPassphrase);
void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
- unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
+ unsigned int ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const;
/**
* Increment the next transaction order id
@@ -503,7 +506,7 @@ public:
//! @return true if wtx is changed and needs to be saved to disk, otherwise false
using UpdateWalletTxFn = std::function<bool(CWalletTx& wtx, bool new_tx)>;
- CWalletTx* AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation& confirm, const UpdateWalletTxFn& update_wtx=nullptr, bool fFlushOnClose=true);
+ CWalletTx* AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation& confirm, const UpdateWalletTxFn& update_wtx=nullptr, bool fFlushOnClose=true, bool rescanning_old_block = false);
bool LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
void transactionAddedToMempool(const CTransactionRef& tx, uint64_t mempool_sequence) override;
void blockConnected(const CBlock& block, int height) override;
@@ -573,14 +576,13 @@ public:
/** Pass this transaction to node for mempool insertion and relay to peers if flag set to true */
bool SubmitTxMemoryPoolAndRelay(const CWalletTx& wtx, std::string& err_string, bool relay) const;
- bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts, bool use_max_sig = false) const
+ bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts, const CCoinControl* coin_control = nullptr) const
{
std::vector<CTxOut> v_txouts(txouts.size());
std::copy(txouts.begin(), txouts.end(), v_txouts.begin());
- return DummySignTx(txNew, v_txouts, use_max_sig);
+ return DummySignTx(txNew, v_txouts, coin_control);
}
- bool DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig = false) const;
- bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig = false) const;
+ bool DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, const CCoinControl* coin_control = nullptr) const;
bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
@@ -925,4 +927,6 @@ bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
//! Remove wallet name from persistent configuration so it will not be loaded on startup.
bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
+bool DummySignInput(const SigningProvider& provider, CTxIn &tx_in, const CTxOut &txout, bool use_max_sig);
+
#endif // BITCOIN_WALLET_WALLET_H
diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp
index 03464cd2c8..8ff09a0878 100644
--- a/src/wallet/walletdb.cpp
+++ b/src/wallet/walletdb.cpp
@@ -40,6 +40,7 @@ const std::string FLAGS{"flags"};
const std::string HDCHAIN{"hdchain"};
const std::string KEYMETA{"keymeta"};
const std::string KEY{"key"};
+const std::string LOCKED_UTXO{"lockedutxo"};
const std::string MASTER_KEY{"mkey"};
const std::string MINVERSION{"minversion"};
const std::string NAME{"name"};
@@ -284,6 +285,16 @@ bool WalletBatch::WriteDescriptorCacheItems(const uint256& desc_id, const Descri
return true;
}
+bool WalletBatch::WriteLockedUTXO(const COutPoint& output)
+{
+ return WriteIC(std::make_pair(DBKeys::LOCKED_UTXO, std::make_pair(output.hash, output.n)), uint8_t{'1'});
+}
+
+bool WalletBatch::EraseLockedUTXO(const COutPoint& output)
+{
+ return EraseIC(std::make_pair(DBKeys::LOCKED_UTXO, std::make_pair(output.hash, output.n)));
+}
+
class CWalletScanState {
public:
unsigned int nKeys{0};
@@ -300,6 +311,7 @@ public:
std::map<std::pair<uint256, CKeyID>, CKey> m_descriptor_keys;
std::map<std::pair<uint256, CKeyID>, std::pair<CPubKey, std::vector<unsigned char>>> m_descriptor_crypt_keys;
std::map<uint160, CHDChain> m_hd_chains;
+ bool tx_corrupt{false};
CWalletScanState() {
}
@@ -334,7 +346,13 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
// LoadToWallet call below creates a new CWalletTx that fill_wtx
// callback fills with transaction metadata.
auto fill_wtx = [&](CWalletTx& wtx, bool new_tx) {
- assert(new_tx);
+ if(!new_tx) {
+ // There's some corruption here since the tx we just tried to load was already in the wallet.
+ // We don't consider this type of corruption critical, and can fix it by removing tx data and
+ // rescanning.
+ wss.tx_corrupt = true;
+ return false;
+ }
ssValue >> wtx;
if (wtx.GetHash() != hash)
return false;
@@ -701,6 +719,12 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
wss.m_descriptor_crypt_keys.insert(std::make_pair(std::make_pair(desc_id, pubkey.GetID()), std::make_pair(pubkey, privkey)));
wss.fIsEncrypted = true;
+ } else if (strType == DBKeys::LOCKED_UTXO) {
+ uint256 hash;
+ uint32_t n;
+ ssKey >> hash;
+ ssKey >> n;
+ pwallet->LockCoin(COutPoint(hash, n));
} else if (strType != DBKeys::BESTBLOCK && strType != DBKeys::BESTBLOCK_NOMERKLE &&
strType != DBKeys::MINVERSION && strType != DBKeys::ACENTRY &&
strType != DBKeys::VERSION && strType != DBKeys::SETTINGS &&
@@ -738,6 +762,7 @@ DBErrors WalletBatch::LoadWallet(CWallet* pwallet)
{
CWalletScanState wss;
bool fNoncriticalErrors = false;
+ bool rescan_required = false;
DBErrors result = DBErrors::LOAD_OK;
LOCK(pwallet->cs_wallet);
@@ -801,12 +826,17 @@ DBErrors WalletBatch::LoadWallet(CWallet* pwallet)
} else if (strType == DBKeys::FLAGS) {
// reading the wallet flags can only fail if unknown flags are present
result = DBErrors::TOO_NEW;
+ } else if (wss.tx_corrupt) {
+ pwallet->WalletLogPrintf("Error: Corrupt transaction found. This can be fixed by removing transactions from wallet and rescanning.\n");
+ // Set tx_corrupt back to false so that the error is only printed once (per corrupt tx)
+ wss.tx_corrupt = false;
+ result = DBErrors::CORRUPT;
} else {
// Leave other errors alone, if we try to fix them we might make things worse.
fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
if (strType == DBKeys::TX)
// Rescan if there is a bad transaction record:
- gArgs.SoftSetBoolArg("-rescan", true);
+ rescan_required = true;
}
}
if (!strErr.empty())
@@ -842,8 +872,11 @@ DBErrors WalletBatch::LoadWallet(CWallet* pwallet)
((DescriptorScriptPubKeyMan*)spk_man)->AddCryptedKey(desc_key_pair.first.second, desc_key_pair.second.first, desc_key_pair.second.second);
}
- if (fNoncriticalErrors && result == DBErrors::LOAD_OK)
+ if (rescan_required && result == DBErrors::LOAD_OK) {
+ result = DBErrors::NEED_RESCAN;
+ } else if (fNoncriticalErrors && result == DBErrors::LOAD_OK) {
result = DBErrors::NONCRITICAL_ERROR;
+ }
// Any wallet corruption at all: skip any rewriting or
// upgrading, we don't want to make it worse.
diff --git a/src/wallet/walletdb.h b/src/wallet/walletdb.h
index 25c2ec5909..9c752623b3 100644
--- a/src/wallet/walletdb.h
+++ b/src/wallet/walletdb.h
@@ -6,7 +6,6 @@
#ifndef BITCOIN_WALLET_WALLETDB_H
#define BITCOIN_WALLET_WALLETDB_H
-#include <amount.h>
#include <script/sign.h>
#include <wallet/db.h>
#include <wallet/walletutil.h>
@@ -48,7 +47,8 @@ enum class DBErrors
NONCRITICAL_ERROR,
TOO_NEW,
LOAD_FAIL,
- NEED_REWRITE
+ NEED_REWRITE,
+ NEED_RESCAN
};
namespace DBKeys {
@@ -65,6 +65,7 @@ extern const std::string FLAGS;
extern const std::string HDCHAIN;
extern const std::string KEY;
extern const std::string KEYMETA;
+extern const std::string LOCKED_UTXO;
extern const std::string MASTER_KEY;
extern const std::string MINVERSION;
extern const std::string NAME;
@@ -250,6 +251,9 @@ public:
bool WriteDescriptorLastHardenedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index);
bool WriteDescriptorCacheItems(const uint256& desc_id, const DescriptorCache& cache);
+ bool WriteLockedUTXO(const COutPoint& output);
+ bool EraseLockedUTXO(const COutPoint& output);
+
/// Write destination data key,value tuple to database
bool WriteDestData(const std::string &address, const std::string &key, const std::string &value);
/// Erase destination data tuple from wallet database
diff --git a/src/wallet/wallettool.cpp b/src/wallet/wallettool.cpp
index 50b6c9d29f..e3cb5cee5d 100644
--- a/src/wallet/wallettool.cpp
+++ b/src/wallet/wallettool.cpp
@@ -76,6 +76,10 @@ static std::shared_ptr<CWallet> MakeWallet(const std::string& name, const fs::pa
} else if (load_wallet_ret == DBErrors::NEED_REWRITE) {
tfm::format(std::cerr, "Wallet needed to be rewritten: restart %s to complete", PACKAGE_NAME);
return nullptr;
+ } else if (load_wallet_ret == DBErrors::NEED_RESCAN) {
+ tfm::format(std::cerr, "Error reading %s! Some transaction data might be missing or"
+ " incorrect. Wallet requires a rescan.",
+ name);
} else {
tfm::format(std::cerr, "Error loading %s", name);
return nullptr;
diff --git a/src/zmq/zmqnotificationinterface.cpp b/src/zmq/zmqnotificationinterface.cpp
index 86f47d71f3..a53de34db4 100644
--- a/src/zmq/zmqnotificationinterface.cpp
+++ b/src/zmq/zmqnotificationinterface.cpp
@@ -47,7 +47,7 @@ CZMQNotificationInterface* CZMQNotificationInterface::Create()
std::unique_ptr<CZMQAbstractNotifier> notifier = factory();
notifier->SetType(entry.first);
notifier->SetAddress(address);
- notifier->SetOutboundMessageHighWaterMark(static_cast<int>(gArgs.GetArg(arg + "hwm", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM)));
+ notifier->SetOutboundMessageHighWaterMark(static_cast<int>(gArgs.GetIntArg(arg + "hwm", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM)));
notifiers.push_back(std::move(notifier));
}
}
diff --git a/src/zmq/zmqpublishnotifier.cpp b/src/zmq/zmqpublishnotifier.cpp
index 6ae866cc07..56f4c98317 100644
--- a/src/zmq/zmqpublishnotifier.cpp
+++ b/src/zmq/zmqpublishnotifier.cpp
@@ -6,6 +6,7 @@
#include <chain.h>
#include <chainparams.h>
+#include <netbase.h>
#include <node/blockstorage.h>
#include <rpc/server.h>
#include <streams.h>
@@ -73,6 +74,20 @@ static int zmq_send_multipart(void *sock, const void* data, size_t size, ...)
return 0;
}
+static bool IsZMQAddressIPV6(const std::string &zmq_address)
+{
+ const std::string tcp_prefix = "tcp://";
+ const size_t tcp_index = zmq_address.rfind(tcp_prefix);
+ const size_t colon_index = zmq_address.rfind(":");
+ if (tcp_index == 0 && colon_index != std::string::npos) {
+ const std::string ip = zmq_address.substr(tcp_prefix.length(), colon_index - tcp_prefix.length());
+ CNetAddr addr;
+ LookupHost(ip, addr, false);
+ if (addr.IsIPv6()) return true;
+ }
+ return false;
+}
+
bool CZMQAbstractPublishNotifier::Initialize(void *pcontext)
{
assert(!psocket);
@@ -107,6 +122,15 @@ bool CZMQAbstractPublishNotifier::Initialize(void *pcontext)
return false;
}
+ // On some systems (e.g. OpenBSD) the ZMQ_IPV6 must not be enabled, if the address to bind isn't IPv6
+ const int enable_ipv6 { IsZMQAddressIPV6(address) ? 1 : 0};
+ rc = zmq_setsockopt(psocket, ZMQ_IPV6, &enable_ipv6, sizeof(enable_ipv6));
+ if (rc != 0) {
+ zmqError("Failed to set ZMQ_IPV6");
+ zmq_close(psocket);
+ return false;
+ }
+
rc = zmq_bind(psocket, address.c_str());
if (rc != 0)
{
diff --git a/test/README.md b/test/README.md
index 412d5ae106..acd68d8d8f 100644
--- a/test/README.md
+++ b/test/README.md
@@ -26,13 +26,20 @@ See [/doc/fuzzing.md](/doc/fuzzing.md)
### Functional tests
-#### Dependencies
+#### Dependencies and prerequisites
The ZMQ functional test requires a python ZMQ library. To install it:
- on Unix, run `sudo apt-get install python3-zmq`
- on mac OS, run `pip3 install pyzmq`
+
+On Windows the `PYTHONUTF8` environment variable must be set to 1:
+
+```cmd
+set PYTHONUTF8=1
+```
+
#### Running the tests
Individual tests can be run by directly calling the test script, e.g.:
diff --git a/test/config.ini.in b/test/config.ini.in
index db80bba6f1..8bcba1b39c 100644
--- a/test/config.ini.in
+++ b/test/config.ini.in
@@ -24,3 +24,4 @@ RPCAUTH=@abs_top_srcdir@/share/rpcauth/rpcauth.py
@ENABLE_FUZZ_TRUE@ENABLE_FUZZ=true
@ENABLE_ZMQ_TRUE@ENABLE_ZMQ=true
@ENABLE_EXTERNAL_SIGNER_TRUE@ENABLE_EXTERNAL_SIGNER=true
+@ENABLE_SYSCALL_SANDBOX_TRUE@ENABLE_SYSCALL_SANDBOX=true
diff --git a/test/functional/README.md b/test/functional/README.md
index d830ba0334..926810cf03 100644
--- a/test/functional/README.md
+++ b/test/functional/README.md
@@ -188,5 +188,5 @@ perf report -i /path/to/datadir/send-big-msgs.perf.data.xxxx --stdio | c++filt |
#### See also:
- [Installing perf](https://askubuntu.com/q/50145)
-- [Perf examples](http://www.brendangregg.com/perf.html)
+- [Perf examples](https://www.brendangregg.com/perf.html)
- [Hotspot](https://github.com/KDAB/hotspot): a GUI for perf output analysis
diff --git a/test/functional/example_test.py b/test/functional/example_test.py
index a0eb213a78..d6fc2d580f 100755
--- a/test/functional/example_test.py
+++ b/test/functional/example_test.py
@@ -141,7 +141,7 @@ class ExampleTest(BitcoinTestFramework):
peer_messaging = self.nodes[0].add_p2p_connection(BaseNode())
# Generating a block on one of the nodes will get us out of IBD
- blocks = [int(self.nodes[0].generate(nblocks=1)[0], 16)]
+ blocks = [int(self.generate(self.nodes[0], nblocks=1)[0], 16)]
self.sync_all(self.nodes[0:2])
# Notice above how we called an RPC by calling a method with the same
diff --git a/test/functional/feature_abortnode.py b/test/functional/feature_abortnode.py
index 8abfdef3a1..e3cb7725bd 100755
--- a/test/functional/feature_abortnode.py
+++ b/test/functional/feature_abortnode.py
@@ -26,7 +26,7 @@ class AbortNodeTest(BitcoinTestFramework):
# We'll connect the nodes later
def run_test(self):
- self.nodes[0].generate(3)
+ self.generate(self.nodes[0], 3)
datadir = get_datadir_path(self.options.tmpdir, 0)
# Deleting the undo file will result in reorg failure
@@ -34,10 +34,10 @@ class AbortNodeTest(BitcoinTestFramework):
# Connecting to a node with a more work chain will trigger a reorg
# attempt.
- self.nodes[1].generate(3)
+ self.generate(self.nodes[1], 3)
with self.nodes[0].assert_debug_log(["Failed to disconnect block"]):
self.connect_nodes(0, 1)
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
# Check that node0 aborted
self.log.info("Waiting for crash")
diff --git a/test/functional/feature_addrman.py b/test/functional/feature_addrman.py
index 8ccff340f0..93d50c1369 100755
--- a/test/functional/feature_addrman.py
+++ b/test/functional/feature_addrman.py
@@ -5,30 +5,41 @@
"""Test addrman functionality"""
import os
+import re
import struct
from test_framework.messages import ser_uint256, hash256
from test_framework.p2p import MAGIC_BYTES
from test_framework.test_framework import BitcoinTestFramework
+from test_framework.test_node import ErrorMatch
from test_framework.util import assert_equal
-def serialize_addrman(*, format=1, lowest_compatible=3):
+def serialize_addrman(
+ *,
+ format=1,
+ lowest_compatible=3,
+ net_magic="regtest",
+ bucket_key=1,
+ len_new=None,
+ len_tried=None,
+ mock_checksum=None,
+):
new = []
tried = []
INCOMPATIBILITY_BASE = 32
- r = MAGIC_BYTES["regtest"]
+ r = MAGIC_BYTES[net_magic]
r += struct.pack("B", format)
r += struct.pack("B", INCOMPATIBILITY_BASE + lowest_compatible)
- r += ser_uint256(1)
- r += struct.pack("i", len(new))
- r += struct.pack("i", len(tried))
+ r += ser_uint256(bucket_key)
+ r += struct.pack("i", len_new or len(new))
+ r += struct.pack("i", len_tried or len(tried))
ADDRMAN_NEW_BUCKET_COUNT = 1 << 10
r += struct.pack("i", ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30))
for _ in range(ADDRMAN_NEW_BUCKET_COUNT):
r += struct.pack("i", 0)
checksum = hash256(r)
- r += checksum
+ r += mock_checksum or checksum
return r
@@ -43,6 +54,12 @@ class AddrmanTest(BitcoinTestFramework):
def run_test(self):
peers_dat = os.path.join(self.nodes[0].datadir, self.chain, "peers.dat")
+ init_error = lambda reason: (
+ f"Error: Invalid or corrupt peers.dat \\({reason}\\). If you believe this "
+ f"is a bug, please report it to {self.config['environment']['PACKAGE_BUGREPORT']}. "
+ f'As a workaround, you can move the file \\("{re.escape(peers_dat)}"\\) out of the way \\(rename, '
+ "move, or delete\\) to have a new one created on the next start."
+ )
self.log.info("Check that mocked addrman is valid")
self.stop_node(0)
@@ -54,30 +71,69 @@ class AddrmanTest(BitcoinTestFramework):
self.log.info("Check that addrman from future cannot be read")
self.stop_node(0)
write_addrman(peers_dat, lowest_compatible=111)
- with self.nodes[0].assert_debug_log([
- f'ERROR: DeserializeDB: Deserialize or I/O error - Unsupported format of addrman database: 1. It is compatible with formats >=111, but the maximum supported by this version of {self.config["environment"]["PACKAGE_NAME"]} is 3.',
- "Recreating peers.dat",
- ]):
- self.start_node(0)
- assert_equal(self.nodes[0].getnodeaddresses(), [])
+ self.nodes[0].assert_start_raises_init_error(
+ expected_msg=init_error(
+ "Unsupported format of addrman database: 1. It is compatible with "
+ "formats >=111, but the maximum supported by this version of "
+ f"{self.config['environment']['PACKAGE_NAME']} is 3.: (.+)"
+ ),
+ match=ErrorMatch.FULL_REGEX,
+ )
- self.log.info("Check that corrupt addrman cannot be read")
+ self.log.info("Check that corrupt addrman cannot be read (EOF)")
self.stop_node(0)
with open(peers_dat, "wb") as f:
f.write(serialize_addrman()[:-1])
- with self.nodes[0].assert_debug_log([
- "ERROR: DeserializeDB: Deserialize or I/O error - CAutoFile::read: end of file",
- "Recreating peers.dat",
- ]):
- self.start_node(0)
- assert_equal(self.nodes[0].getnodeaddresses(), [])
+ self.nodes[0].assert_start_raises_init_error(
+ expected_msg=init_error("CAutoFile::read: end of file.*"),
+ match=ErrorMatch.FULL_REGEX,
+ )
+
+ self.log.info("Check that corrupt addrman cannot be read (magic)")
+ self.stop_node(0)
+ write_addrman(peers_dat, net_magic="signet")
+ self.nodes[0].assert_start_raises_init_error(
+ expected_msg=init_error("Invalid network magic number"),
+ match=ErrorMatch.FULL_REGEX,
+ )
+
+ self.log.info("Check that corrupt addrman cannot be read (checksum)")
+ self.stop_node(0)
+ write_addrman(peers_dat, mock_checksum=b"ab" * 32)
+ self.nodes[0].assert_start_raises_init_error(
+ expected_msg=init_error("Checksum mismatch, data corrupted"),
+ match=ErrorMatch.FULL_REGEX,
+ )
+
+ self.log.info("Check that corrupt addrman cannot be read (len_tried)")
+ self.stop_node(0)
+ write_addrman(peers_dat, len_tried=-1)
+ self.nodes[0].assert_start_raises_init_error(
+ expected_msg=init_error("Corrupt AddrMan serialization: nTried=-1, should be in \\[0, 16384\\]:.*"),
+ match=ErrorMatch.FULL_REGEX,
+ )
+
+ self.log.info("Check that corrupt addrman cannot be read (len_new)")
+ self.stop_node(0)
+ write_addrman(peers_dat, len_new=-1)
+ self.nodes[0].assert_start_raises_init_error(
+ expected_msg=init_error("Corrupt AddrMan serialization: nNew=-1, should be in \\[0, 65536\\]:.*"),
+ match=ErrorMatch.FULL_REGEX,
+ )
+
+ self.log.info("Check that corrupt addrman cannot be read (failed check)")
+ self.stop_node(0)
+ write_addrman(peers_dat, bucket_key=0)
+ self.nodes[0].assert_start_raises_init_error(
+ expected_msg=init_error("Corrupt data. Consistency check failed with code -16: .*"),
+ match=ErrorMatch.FULL_REGEX,
+ )
self.log.info("Check that missing addrman is recreated")
self.stop_node(0)
os.remove(peers_dat)
with self.nodes[0].assert_debug_log([
- f"Missing or invalid file {peers_dat}",
- "Recreating peers.dat",
+ f'Creating peers.dat because the file was not found ("{peers_dat}")',
]):
self.start_node(0)
assert_equal(self.nodes[0].getnodeaddresses(), [])
diff --git a/test/functional/feature_asmap.py b/test/functional/feature_asmap.py
index 704dd6126b..debd87962f 100755
--- a/test/functional/feature_asmap.py
+++ b/test/functional/feature_asmap.py
@@ -14,9 +14,11 @@ Verify node behaviour and debug log when launching bitcoind in these cases:
4. `bitcoind -asmap/-asmap=` with no file specified, using the default asmap
-5. `bitcoind -asmap` with no file specified and a missing default asmap file
+5. `bitcoind -asmap` restart with an addrman containing new and tried entries
-6. `bitcoind -asmap` with an empty (unparsable) default asmap file
+6. `bitcoind -asmap` with no file specified and a missing default asmap file
+
+7. `bitcoind -asmap` with an empty (unparsable) default asmap file
The tests are order-independent.
@@ -37,6 +39,12 @@ def expected_messages(filename):
class AsmapTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
+ self.extra_args = [["-checkaddrman=1"]] # Do addrman checks on all operations.
+
+ def fill_addrman(self, node_id):
+ """Add 1 tried address to the addrman, followed by 1 new address."""
+ for addr, tried in [[0, True], [1, False]]:
+ self.nodes[node_id].addpeeraddress(address=f"101.{addr}.0.0", tried=tried, port=8333)
def test_without_asmap_arg(self):
self.log.info('Test bitcoind with no -asmap arg passed')
@@ -72,6 +80,22 @@ class AsmapTest(BitcoinTestFramework):
self.start_node(0, [arg])
os.remove(self.default_asmap)
+ def test_asmap_interaction_with_addrman_containing_entries(self):
+ self.log.info("Test bitcoind -asmap restart with addrman containing new and tried entries")
+ self.stop_node(0)
+ shutil.copyfile(self.asmap_raw, self.default_asmap)
+ self.start_node(0, ["-asmap", "-checkaddrman=1"])
+ self.fill_addrman(node_id=0)
+ self.restart_node(0, ["-asmap", "-checkaddrman=1"])
+ with self.node.assert_debug_log(
+ expected_msgs=[
+ "Addrman checks started: new 1, tried 1, total 2",
+ "Addrman checks completed successfully",
+ ]
+ ):
+ self.node.getnodeaddresses() # getnodeaddresses re-runs the addrman checks
+ os.remove(self.default_asmap)
+
def test_default_asmap_with_missing_file(self):
self.log.info('Test bitcoind -asmap with missing default map file')
self.stop_node(0)
@@ -97,6 +121,7 @@ class AsmapTest(BitcoinTestFramework):
self.test_asmap_with_absolute_path()
self.test_asmap_with_relative_path()
self.test_default_asmap()
+ self.test_asmap_interaction_with_addrman_containing_entries()
self.test_default_asmap_with_missing_file()
self.test_empty_asmap()
diff --git a/test/functional/feature_backwards_compatibility.py b/test/functional/feature_backwards_compatibility.py
index 978080703e..e65525a023 100755
--- a/test/functional/feature_backwards_compatibility.py
+++ b/test/functional/feature_backwards_compatibility.py
@@ -64,7 +64,7 @@ class BackwardsCompatibilityTest(BitcoinTestFramework):
self.import_deterministic_coinbase_privkeys()
def run_test(self):
- self.nodes[0].generatetoaddress(COINBASE_MATURITY + 1, self.nodes[0].getnewaddress())
+ self.generatetoaddress(self.nodes[0], COINBASE_MATURITY + 1, self.nodes[0].getnewaddress())
self.sync_blocks()
@@ -92,7 +92,7 @@ class BackwardsCompatibilityTest(BitcoinTestFramework):
address = wallet.getnewaddress()
self.nodes[0].sendtoaddress(address, 10)
self.sync_mempools()
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
# Create a conflicting transaction using RBF
return_address = self.nodes[0].getnewaddress()
@@ -100,7 +100,7 @@ class BackwardsCompatibilityTest(BitcoinTestFramework):
tx2_id = self.nodes[1].bumpfee(tx1_id)["txid"]
# Confirm the transaction
self.sync_mempools()
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
# Create another conflicting transaction using RBF
tx3_id = self.nodes[1].sendtoaddress(return_address, 1)
diff --git a/test/functional/feature_bip68_sequence.py b/test/functional/feature_bip68_sequence.py
index e44ce9b57d..99ac1b5884 100755
--- a/test/functional/feature_bip68_sequence.py
+++ b/test/functional/feature_bip68_sequence.py
@@ -24,7 +24,6 @@ from test_framework.util import (
assert_equal,
assert_greater_than,
assert_raises_rpc_error,
- satoshi_round,
softfork_active,
)
from test_framework.script_util import DUMMY_P2WPKH_SCRIPT
@@ -42,10 +41,13 @@ class BIP68Test(BitcoinTestFramework):
self.num_nodes = 2
self.extra_args = [
[
+ '-testactivationheight=csv@432',
"-acceptnonstdtxn=1",
- "-peertimeout=9999", # bump because mocktime might cause a disconnect otherwise
],
- ["-acceptnonstdtxn=0"],
+ [
+ '-testactivationheight=csv@432',
+ "-acceptnonstdtxn=0",
+ ],
]
def skip_test_if_missing_module(self):
@@ -55,7 +57,7 @@ class BIP68Test(BitcoinTestFramework):
self.relayfee = self.nodes[0].getnetworkinfo()["relayfee"]
# Generate some coins
- self.nodes[0].generate(110)
+ self.generate(self.nodes[0], 110)
self.log.info("Running test disable flag")
self.test_disable_flag()
@@ -91,7 +93,7 @@ class BIP68Test(BitcoinTestFramework):
utxo = utxos[0]
tx1 = CTransaction()
- value = int(satoshi_round(utxo["amount"] - self.relayfee)*COIN)
+ value = int((utxo["amount"] - self.relayfee) * COIN)
# Check that the disable flag disables relative locktime.
# If sequence locks were used, this would require 1 block for the
@@ -143,7 +145,7 @@ class BIP68Test(BitcoinTestFramework):
for i in range(num_outputs):
outputs[addresses[i]] = random.randint(1, 20)*0.01
self.nodes[0].sendmany("", outputs)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
utxos = self.nodes[0].listunspent()
@@ -273,7 +275,7 @@ class BIP68Test(BitcoinTestFramework):
cur_time = int(time.time())
for _ in range(10):
self.nodes[0].setmocktime(cur_time + 600)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
cur_time += 600
assert tx2.hash in self.nodes[0].getrawmempool()
@@ -288,7 +290,7 @@ class BIP68Test(BitcoinTestFramework):
self.nodes[0].setmocktime(cur_time+600)
# Save block template now to use for the reorg later
tmpl = self.nodes[0].getblocktemplate(NORMAL_GBT_REQUEST_PARAMS)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
assert tx2.hash not in self.nodes[0].getrawmempool()
# Now that tx2 is not in the mempool, a sequence locked spend should
@@ -296,7 +298,7 @@ class BIP68Test(BitcoinTestFramework):
tx3 = test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False)
assert tx3.hash in self.nodes[0].getrawmempool()
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
assert tx3.hash not in self.nodes[0].getrawmempool()
# One more test, this time using height locks
@@ -349,7 +351,7 @@ class BIP68Test(BitcoinTestFramework):
# Reset the chain and get rid of the mocktimed-blocks
self.nodes[0].setmocktime(0)
self.nodes[0].invalidateblock(self.nodes[0].getblockhash(cur_height+1))
- self.nodes[0].generate(10)
+ self.generate(self.nodes[0], 10)
# Make sure that BIP68 isn't being used to validate blocks prior to
# activation height. If more blocks are mined prior to this test
@@ -403,9 +405,9 @@ class BIP68Test(BitcoinTestFramework):
min_activation_height = 432
height = self.nodes[0].getblockcount()
assert_greater_than(min_activation_height - height, 2)
- self.nodes[0].generate(min_activation_height - height - 2)
+ self.generate(self.nodes[0], min_activation_height - height - 2)
assert not softfork_active(self.nodes[0], 'csv')
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
assert softfork_active(self.nodes[0], 'csv')
self.sync_blocks()
diff --git a/test/functional/feature_block.py b/test/functional/feature_block.py
index 777787ed32..b06ea8542b 100755
--- a/test/functional/feature_block.py
+++ b/test/functional/feature_block.py
@@ -82,7 +82,10 @@ class FullBlockTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
- self.extra_args = [['-acceptnonstdtxn=1']] # This is a consensus block test, we don't care about tx policy
+ self.extra_args = [[
+ '-acceptnonstdtxn=1', # This is a consensus block test, we don't care about tx policy
+ '-testactivationheight=bip34@2',
+ ]]
def run_test(self):
node = self.nodes[0] # convenience reference to the node
diff --git a/test/functional/feature_blockfilterindex_prune.py b/test/functional/feature_blockfilterindex_prune.py
index 28d8f2fbbc..b740f2cc27 100755
--- a/test/functional/feature_blockfilterindex_prune.py
+++ b/test/functional/feature_blockfilterindex_prune.py
@@ -25,9 +25,9 @@ class FeatureBlockfilterindexPruneTest(BitcoinTestFramework):
self.sync_index(height=200)
assert_greater_than(len(self.nodes[0].getblockfilter(self.nodes[0].getbestblockhash())['filter']), 0)
# Mine two batches of blocks to avoid hitting NODE_NETWORK_LIMITED_MIN_BLOCKS disconnection
- self.nodes[0].generate(250)
+ self.generate(self.nodes[0], 250)
self.sync_all()
- self.nodes[0].generate(250)
+ self.generate(self.nodes[0], 250)
self.sync_all()
self.sync_index(height=700)
@@ -46,7 +46,7 @@ class FeatureBlockfilterindexPruneTest(BitcoinTestFramework):
self.log.info("make sure accessing the blockfilters throws an error")
assert_raises_rpc_error(-1, "Index is not enabled for filtertype basic", self.nodes[0].getblockfilter, self.nodes[0].getblockhash(2))
- self.nodes[0].generate(1000)
+ self.generate(self.nodes[0], 1000)
self.log.info("prune below the blockfilterindexes best block while blockfilters are disabled")
pruneheight_new = self.nodes[0].pruneblockchain(1000)
diff --git a/test/functional/feature_blocksdir.py b/test/functional/feature_blocksdir.py
index d3276e64ee..28e6d6cdf9 100755
--- a/test/functional/feature_blocksdir.py
+++ b/test/functional/feature_blocksdir.py
@@ -29,7 +29,7 @@ class BlocksdirTest(BitcoinTestFramework):
self.log.info("Starting with existing blocksdir ...")
self.start_node(0, [f"-blocksdir={blocksdir_path}"])
self.log.info("mining blocks..")
- self.nodes[0].generatetoaddress(10, self.nodes[0].get_deterministic_priv_key().address)
+ self.generatetoaddress(self.nodes[0], 10, self.nodes[0].get_deterministic_priv_key().address)
assert os.path.isfile(os.path.join(blocksdir_path, self.chain, "blocks", "blk00000.dat"))
assert os.path.isdir(os.path.join(self.nodes[0].datadir, self.chain, "blocks", "index"))
diff --git a/test/functional/feature_cltv.py b/test/functional/feature_cltv.py
index 3438027db6..3dc858f5d2 100755
--- a/test/functional/feature_cltv.py
+++ b/test/functional/feature_cltv.py
@@ -8,7 +8,6 @@ Test that the CHECKLOCKTIMEVERIFY soft-fork activates.
"""
from test_framework.blocktools import (
- CLTV_HEIGHT,
create_block,
create_coinbase,
)
@@ -76,10 +75,14 @@ def cltv_validate(tx, height):
cltv_modify_tx(tx, prepend_scriptsig=scheme[0], nsequence=scheme[1], nlocktime=scheme[2])
+CLTV_HEIGHT = 111
+
+
class BIP65Test(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.extra_args = [[
+ f'-testactivationheight=cltv@{CLTV_HEIGHT}',
'-whitelist=noban@127.0.0.1',
'-par=1', # Use only one script thread to get the exact reject reason for testing
'-acceptnonstdtxn=1', # cltv_invalidate is nonstandard
@@ -102,8 +105,8 @@ class BIP65Test(BitcoinTestFramework):
self.test_cltv_info(is_active=False)
self.log.info("Mining %d blocks", CLTV_HEIGHT - 2)
- wallet.generate(10)
- self.nodes[0].generate(CLTV_HEIGHT - 2 - 10)
+ self.generate(wallet, 10)
+ self.generate(self.nodes[0], CLTV_HEIGHT - 2 - 10)
assert_equal(self.nodes[0].getblockcount(), CLTV_HEIGHT - 2)
self.log.info("Test that invalid-according-to-CLTV transactions can still appear in a block")
diff --git a/test/functional/feature_coinstatsindex.py b/test/functional/feature_coinstatsindex.py
index 71d522a245..c592d7bd69 100755
--- a/test/functional/feature_coinstatsindex.py
+++ b/test/functional/feature_coinstatsindex.py
@@ -67,10 +67,10 @@ class CoinStatsIndexTest(BitcoinTestFramework):
index_hash_options = ['none', 'muhash']
# Generate a normal transaction and mine it
- node.generate(COINBASE_MATURITY + 1)
+ self.generate(node, COINBASE_MATURITY + 1)
address = self.nodes[0].get_deterministic_priv_key().address
node.sendtoaddress(address=address, amount=10, subtractfeefromamount=True)
- node.generate(1)
+ self.generate(node, 1)
self.sync_blocks(timeout=120)
@@ -92,7 +92,7 @@ class CoinStatsIndexTest(BitcoinTestFramework):
self.log.info("Test that gettxoutsetinfo() can get fetch data on specific heights with index")
# Generate a new tip
- node.generate(5)
+ self.generate(node, 5)
for hash_option in index_hash_options:
# Fetch old stats by height
@@ -164,27 +164,27 @@ class CoinStatsIndexTest(BitcoinTestFramework):
# Generate and send another tx with an OP_RETURN output (which is unspendable)
tx2 = CTransaction()
tx2.vin.append(CTxIn(COutPoint(int(tx1_txid, 16), n), b''))
- tx2.vout.append(CTxOut(int(20.99 * COIN), CScript([OP_RETURN] + [OP_FALSE]*30)))
+ tx2.vout.append(CTxOut(int(Decimal('20.99') * COIN), CScript([OP_RETURN] + [OP_FALSE]*30)))
tx2_hex = self.nodes[0].signrawtransactionwithwallet(tx2.serialize().hex())['hex']
self.nodes[0].sendrawtransaction(tx2_hex)
# Include both txs in a block
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
for hash_option in index_hash_options:
# Check all amounts were registered correctly
res6 = index_node.gettxoutsetinfo(hash_option, 108)
- assert_equal(res6['total_unspendable_amount'], Decimal('70.98999999'))
+ assert_equal(res6['total_unspendable_amount'], Decimal('70.99000000'))
assert_equal(res6['block_info'], {
- 'unspendable': Decimal('20.98999999'),
+ 'unspendable': Decimal('20.99000000'),
'prevout_spent': 111,
'new_outputs_ex_coinbase': Decimal('89.99993620'),
- 'coinbase': Decimal('50.01006381'),
+ 'coinbase': Decimal('50.01006380'),
'unspendables': {
'genesis_block': 0,
'bip30': 0,
- 'scripts': Decimal('20.98999999'),
+ 'scripts': Decimal('20.99000000'),
'unclaimed_rewards': 0
}
})
@@ -206,7 +206,7 @@ class CoinStatsIndexTest(BitcoinTestFramework):
for hash_option in index_hash_options:
res7 = index_node.gettxoutsetinfo(hash_option, 109)
- assert_equal(res7['total_unspendable_amount'], Decimal('80.98999999'))
+ assert_equal(res7['total_unspendable_amount'], Decimal('80.99000000'))
assert_equal(res7['block_info'], {
'unspendable': 10,
'prevout_spent': 0,
@@ -228,7 +228,7 @@ class CoinStatsIndexTest(BitcoinTestFramework):
res9 = index_node.gettxoutsetinfo('muhash')
assert_equal(res8, res9)
- index_node.generate(1)
+ self.generate(index_node, 1)
res10 = index_node.gettxoutsetinfo('muhash')
assert(res8['txouts'] < res10['txouts'])
@@ -247,14 +247,14 @@ class CoinStatsIndexTest(BitcoinTestFramework):
# Generate two block, let the index catch up, then invalidate the blocks
index_node = self.nodes[1]
- reorg_blocks = index_node.generatetoaddress(2, index_node.getnewaddress())
+ reorg_blocks = self.generatetoaddress(index_node, 2, index_node.getnewaddress())
reorg_block = reorg_blocks[1]
res_invalid = index_node.gettxoutsetinfo('muhash')
index_node.invalidateblock(reorg_blocks[0])
assert_equal(index_node.gettxoutsetinfo('muhash')['height'], 110)
# Add two new blocks
- block = index_node.generate(2)[1]
+ block = self.generate(index_node, 2)[1]
res = index_node.gettxoutsetinfo(hash_type='muhash', hash_or_height=None, use_index=False)
# Test that the result of the reorged block is not returned for its old block height
@@ -270,7 +270,7 @@ class CoinStatsIndexTest(BitcoinTestFramework):
# Add another block, so we don't depend on reconsiderblock remembering which
# blocks were touched by invalidateblock
- index_node.generate(1)
+ self.generate(index_node, 1)
self.sync_all()
# Ensure that removing and re-adding blocks yields consistent results
diff --git a/test/functional/feature_config_args.py b/test/functional/feature_config_args.py
index 0daa0ba3d8..3d9d8b7441 100755
--- a/test/functional/feature_config_args.py
+++ b/test/functional/feature_config_args.py
@@ -164,11 +164,14 @@ class ConfArgsTest(BitcoinTestFramework):
# fixed seeds
assert not os.path.exists(os.path.join(default_data_dir, "peers.dat"))
start = int(time.time())
- with self.nodes[0].assert_debug_log(expected_msgs=[
- "Loaded 0 addresses from peers.dat",
- "0 addresses found from DNS seeds",
- "opencon thread start", # Ensure ThreadOpenConnections::start time is properly set
- ]):
+ with self.nodes[0].assert_debug_log(
+ expected_msgs=[
+ "Loaded 0 addresses from peers.dat",
+ "0 addresses found from DNS seeds",
+ "opencon thread start", # Ensure ThreadOpenConnections::start time is properly set
+ ],
+ timeout=10,
+ ):
self.start_node(0, extra_args=['-dnsseed=1', '-fixedseeds=1', f'-mocktime={start}'])
with self.nodes[0].assert_debug_log(expected_msgs=[
"Adding fixed seeds as 60 seconds have passed and addrman is empty",
@@ -206,11 +209,14 @@ class ConfArgsTest(BitcoinTestFramework):
# We expect the node will allow 60 seconds prior to using fixed seeds
assert not os.path.exists(os.path.join(default_data_dir, "peers.dat"))
start = int(time.time())
- with self.nodes[0].assert_debug_log(expected_msgs=[
- "Loaded 0 addresses from peers.dat",
- "DNS seeding disabled",
- "opencon thread start", # Ensure ThreadOpenConnections::start time is properly set
- ]):
+ with self.nodes[0].assert_debug_log(
+ expected_msgs=[
+ "Loaded 0 addresses from peers.dat",
+ "DNS seeding disabled",
+ "opencon thread start", # Ensure ThreadOpenConnections::start time is properly set
+ ],
+ timeout=10,
+ ):
self.start_node(0, extra_args=['-dnsseed=0', '-fixedseeds=1', '-addnode=fakenodeaddr', f'-mocktime={start}'])
with self.nodes[0].assert_debug_log(expected_msgs=[
"Adding fixed seeds as 60 seconds have passed and addrman is empty",
diff --git a/test/functional/feature_csv_activation.py b/test/functional/feature_csv_activation.py
index bc0050d47a..5255b13bd1 100755
--- a/test/functional/feature_csv_activation.py
+++ b/test/functional/feature_csv_activation.py
@@ -41,7 +41,6 @@ from itertools import product
import time
from test_framework.blocktools import (
- CSV_ACTIVATION_HEIGHT,
create_block,
create_coinbase,
)
@@ -69,6 +68,7 @@ SEQ_RANDOM_HIGH_BIT = 1 << 25
SEQ_TYPE_FLAG = 1 << 22
SEQ_RANDOM_LOW_BIT = 1 << 18
+
def relative_locktime(sdf, srhb, stf, srlb):
"""Returns a locktime with certain bits set."""
@@ -83,16 +83,21 @@ def relative_locktime(sdf, srhb, stf, srlb):
locktime |= SEQ_RANDOM_LOW_BIT
return locktime
+
def all_rlt_txs(txs):
return [tx['tx'] for tx in txs]
+CSV_ACTIVATION_HEIGHT = 432
+
+
class BIP68_112_113Test(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
self.extra_args = [[
'-whitelist=noban@127.0.0.1',
+ f'-testactivationheight=csv@{CSV_ACTIVATION_HEIGHT}',
'-par=1', # Use only one script thread to get the exact reject reason for testing
]]
self.supports_cli = False
@@ -143,13 +148,13 @@ class BIP68_112_113Test(BitcoinTestFramework):
for i, (sdf, srhb, stf, srlb) in enumerate(product(*[[True, False]] * 4)):
locktime = relative_locktime(sdf, srhb, stf, srlb)
tx = self.create_self_transfer_from_utxo(bip112inputs[i])
- if (varyOP_CSV): # if varying OP_CSV, nSequence is fixed
+ if varyOP_CSV: # if varying OP_CSV, nSequence is fixed
tx.vin[0].nSequence = BASE_RELATIVE_LOCKTIME + locktime_delta
else: # vary nSequence instead, OP_CSV is fixed
tx.vin[0].nSequence = locktime + locktime_delta
tx.nVersion = txversion
self.miniwallet.sign_tx(tx)
- if (varyOP_CSV):
+ if varyOP_CSV:
tx.vin[0].scriptSig = CScript([locktime, OP_CHECKSEQUENCEVERIFY, OP_DROP] + list(CScript(tx.vin[0].scriptSig)))
else:
tx.vin[0].scriptSig = CScript([BASE_RELATIVE_LOCKTIME, OP_CHECKSEQUENCEVERIFY, OP_DROP] + list(CScript(tx.vin[0].scriptSig)))
@@ -189,7 +194,7 @@ class BIP68_112_113Test(BitcoinTestFramework):
self.log.info("Generate blocks in the past for coinbase outputs.")
long_past_time = int(time.time()) - 600 * 1000 # enough to build up to 1000 blocks 10 minutes apart without worrying about getting into the future
self.nodes[0].setmocktime(long_past_time - 100) # enough so that the generated blocks will still all be before long_past_time
- self.coinbase_blocks = self.miniwallet.generate(COINBASE_BLOCK_COUNT) # blocks generated for inputs
+ self.coinbase_blocks = self.generate(self.miniwallet, COINBASE_BLOCK_COUNT) # blocks generated for inputs
self.nodes[0].setmocktime(0) # set time back to present so yielded blocks aren't in the future as we advance last_block_time
self.tipheight = COINBASE_BLOCK_COUNT # height of the next block to build
self.last_block_time = long_past_time
@@ -197,7 +202,7 @@ class BIP68_112_113Test(BitcoinTestFramework):
# Activation height is hardcoded
# We advance to block height five below BIP112 activation for the following tests
- test_blocks = self.generate_blocks(CSV_ACTIVATION_HEIGHT-5 - COINBASE_BLOCK_COUNT)
+ test_blocks = self.generate_blocks(CSV_ACTIVATION_HEIGHT - 5 - COINBASE_BLOCK_COUNT)
self.send_blocks(test_blocks)
assert not softfork_active(self.nodes[0], 'csv')
@@ -235,7 +240,7 @@ class BIP68_112_113Test(BitcoinTestFramework):
bip113input = self.send_generic_input_tx(self.coinbase_blocks)
self.nodes[0].setmocktime(self.last_block_time + 600)
- inputblockhash = self.nodes[0].generate(1)[0] # 1 block generated for inputs to be in chain at height 431
+ inputblockhash = self.generate(self.nodes[0], 1)[0] # 1 block generated for inputs to be in chain at height 431
self.nodes[0].setmocktime(0)
self.tip = int(inputblockhash, 16)
self.tipheight += 1
@@ -482,5 +487,6 @@ class BIP68_112_113Test(BitcoinTestFramework):
self.send_blocks([self.create_test_block(time_txs)])
self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash())
+
if __name__ == '__main__':
BIP68_112_113Test().main()
diff --git a/test/functional/feature_dersig.py b/test/functional/feature_dersig.py
index fd46385cd4..28aff1f2f9 100755
--- a/test/functional/feature_dersig.py
+++ b/test/functional/feature_dersig.py
@@ -8,7 +8,6 @@ Test the DERSIG soft-fork activation on regtest.
"""
from test_framework.blocktools import (
- DERSIG_HEIGHT,
create_block,
create_coinbase,
)
@@ -42,10 +41,14 @@ def unDERify(tx):
tx.vin[0].scriptSig = CScript(newscript)
+DERSIG_HEIGHT = 102
+
+
class BIP66Test(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.extra_args = [[
+ f'-testactivationheight=dersig@{DERSIG_HEIGHT}',
'-whitelist=noban@127.0.0.1',
'-par=1', # Use only one script thread to get the exact log msg for testing
]]
@@ -72,7 +75,7 @@ class BIP66Test(BitcoinTestFramework):
self.test_dersig_info(is_active=False)
self.log.info("Mining %d blocks", DERSIG_HEIGHT - 2)
- self.coinbase_txids = [self.nodes[0].getblock(b)['tx'][0] for b in self.miniwallet.generate(DERSIG_HEIGHT - 2)]
+ self.coinbase_txids = [self.nodes[0].getblock(b)['tx'][0] for b in self.generate(self.miniwallet, DERSIG_HEIGHT - 2)]
self.log.info("Test that a transaction with non-DER signature can still appear in a block")
@@ -83,7 +86,6 @@ class BIP66Test(BitcoinTestFramework):
tip = self.nodes[0].getbestblockhash()
block_time = self.nodes[0].getblockheader(tip)['mediantime'] + 1
block = create_block(int(tip, 16), create_coinbase(DERSIG_HEIGHT - 1), block_time)
- block.nVersion = 2
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
@@ -110,7 +112,7 @@ class BIP66Test(BitcoinTestFramework):
peer.sync_with_ping()
self.log.info("Test that transactions with non-DER signatures cannot appear in a block")
- block.nVersion = 3
+ block.nVersion = 4
spendtx = self.create_tx(self.coinbase_txids[1])
unDERify(spendtx)
@@ -139,7 +141,7 @@ class BIP66Test(BitcoinTestFramework):
assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)
peer.sync_with_ping()
- self.log.info("Test that a version 3 block with a DERSIG-compliant transaction is accepted")
+ self.log.info("Test that a block with a DERSIG-compliant transaction is accepted")
block.vtx[1] = self.create_tx(self.coinbase_txids[1])
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
diff --git a/test/functional/feature_fee_estimation.py b/test/functional/feature_fee_estimation.py
index a8f3e12e07..ac00db8ff0 100755
--- a/test/functional/feature_fee_estimation.py
+++ b/test/functional/feature_fee_estimation.py
@@ -4,6 +4,7 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test fee estimation code."""
from decimal import Decimal
+import os
import random
from test_framework.messages import (
@@ -132,9 +133,13 @@ def check_smart_estimates(node, fees_seen):
delta = 1.0e-6 # account for rounding error
last_feerate = float(max(fees_seen))
all_smart_estimates = [node.estimatesmartfee(i) for i in range(1, 26)]
+ mempoolMinFee = node.getmempoolinfo()['mempoolminfee']
+ minRelaytxFee = node.getmempoolinfo()['minrelaytxfee']
for i, e in enumerate(all_smart_estimates): # estimate is for i+1
feerate = float(e["feerate"])
assert_greater_than(feerate, 0)
+ assert_greater_than_or_equal(feerate, float(mempoolMinFee))
+ assert_greater_than_or_equal(feerate, float(minRelaytxFee))
if feerate + delta < min(fees_seen) or feerate - delta > max(fees_seen):
raise AssertionError(f"Estimated fee ({feerate}) out of range ({min(fees_seen)},{max(fees_seen)})")
@@ -151,6 +156,21 @@ def check_estimates(node, fees_seen):
check_raw_estimates(node, fees_seen)
check_smart_estimates(node, fees_seen)
+
+def send_tx(node, utxo, feerate):
+ """Broadcast a 1in-1out transaction with a specific input and feerate (sat/vb)."""
+ overhead, op, scriptsig, nseq, value, spk = 10, 36, 5, 4, 8, 24
+ tx_size = overhead + op + scriptsig + nseq + value + spk
+ fee = tx_size * feerate
+
+ tx = CTransaction()
+ tx.vin = [CTxIn(COutPoint(int(utxo["txid"], 16), utxo["vout"]), SCRIPT_SIG[utxo["vout"]])]
+ tx.vout = [CTxOut(int(utxo["amount"] * COIN) - fee, P2SH_1)]
+ txid = node.sendrawtransaction(tx.serialize().hex())
+
+ return txid
+
+
class EstimateFeeTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 3
@@ -197,7 +217,7 @@ class EstimateFeeTest(BitcoinTestFramework):
tx_kbytes = (len(txhex) // 2) / 1000.0
self.fees_per_kb.append(float(fee) / tx_kbytes)
self.sync_mempools(wait=.1)
- mined = mining_node.getblock(mining_node.generate(1)[0], True)["tx"]
+ mined = mining_node.getblock(self.generate(mining_node, 1)[0], True)["tx"]
self.sync_blocks(wait=.1)
# update which txouts are confirmed
newmem = []
@@ -208,20 +228,16 @@ class EstimateFeeTest(BitcoinTestFramework):
newmem.append(utx)
self.memutxo = newmem
- def run_test(self):
- self.log.info("This test is time consuming, please be patient")
- self.log.info("Splitting inputs so we can generate tx's")
-
- # Start node0
- self.start_node(0)
+ def initial_split(self, node):
+ """Split two coinbase UTxOs into many small coins"""
self.txouts = []
self.txouts2 = []
# Split a coinbase into two transaction puzzle outputs
- split_inputs(self.nodes[0], self.nodes[0].listunspent(0), self.txouts, True)
+ split_inputs(node, node.listunspent(0), self.txouts, True)
# Mine
- while len(self.nodes[0].getrawmempool()) > 0:
- self.nodes[0].generate(1)
+ while len(node.getrawmempool()) > 0:
+ self.generate(node, 1)
# Repeatedly split those 2 outputs, doubling twice for each rep
# Use txouts to monitor the available utxo, since these won't be tracked in wallet
@@ -229,27 +245,19 @@ class EstimateFeeTest(BitcoinTestFramework):
while reps < 5:
# Double txouts to txouts2
while len(self.txouts) > 0:
- split_inputs(self.nodes[0], self.txouts, self.txouts2)
- while len(self.nodes[0].getrawmempool()) > 0:
- self.nodes[0].generate(1)
+ split_inputs(node, self.txouts, self.txouts2)
+ while len(node.getrawmempool()) > 0:
+ self.generate(node, 1)
# Double txouts2 to txouts
while len(self.txouts2) > 0:
- split_inputs(self.nodes[0], self.txouts2, self.txouts)
- while len(self.nodes[0].getrawmempool()) > 0:
- self.nodes[0].generate(1)
+ split_inputs(node, self.txouts2, self.txouts)
+ while len(node.getrawmempool()) > 0:
+ self.generate(node, 1)
reps += 1
- self.log.info("Finished splitting")
-
- # Now we can connect the other nodes, didn't want to connect them earlier
- # so the estimates would not be affected by the splitting transactions
- self.start_node(1)
- self.start_node(2)
- self.connect_nodes(1, 0)
- self.connect_nodes(0, 2)
- self.connect_nodes(2, 1)
-
- self.sync_all()
+ def sanity_check_estimates_range(self):
+ """Populate estimation buckets, assert estimates are in a sane range and
+ are strictly increasing as the target decreases."""
self.fees_per_kb = []
self.memutxo = []
self.confutxo = self.txouts # Start with the set of confirmed txouts after splitting
@@ -269,12 +277,107 @@ class EstimateFeeTest(BitcoinTestFramework):
# Finish by mining a normal-sized block:
while len(self.nodes[1].getrawmempool()) > 0:
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
self.sync_blocks(self.nodes[0:3], wait=.1)
self.log.info("Final estimates after emptying mempools")
check_estimates(self.nodes[1], self.fees_per_kb)
+ def test_feerate_mempoolminfee(self):
+ high_val = 3*self.nodes[1].estimatesmartfee(1)['feerate']
+ self.restart_node(1, extra_args=[f'-minrelaytxfee={high_val}'])
+ check_estimates(self.nodes[1], self.fees_per_kb)
+ self.restart_node(1)
+
+ def sanity_check_rbf_estimates(self, utxos):
+ """During 5 blocks, broadcast low fee transactions. Only 10% of them get
+ confirmed and the remaining ones get RBF'd with a high fee transaction at
+ the next block.
+ The block policy estimator should return the high feerate.
+ """
+ # The broadcaster and block producer
+ node = self.nodes[0]
+ miner = self.nodes[1]
+ # In sat/vb
+ low_feerate = 1
+ high_feerate = 10
+ # Cache the utxos of which to replace the spender after it failed to get
+ # confirmed
+ utxos_to_respend = []
+ txids_to_replace = []
+
+ assert len(utxos) >= 250
+ for _ in range(5):
+ # Broadcast 45 low fee transactions that will need to be RBF'd
+ for _ in range(45):
+ u = utxos.pop(0)
+ txid = send_tx(node, u, low_feerate)
+ utxos_to_respend.append(u)
+ txids_to_replace.append(txid)
+ # Broadcast 5 low fee transaction which don't need to
+ for _ in range(5):
+ send_tx(node, utxos.pop(0), low_feerate)
+ # Mine the transactions on another node
+ self.sync_mempools(wait=.1, nodes=[node, miner])
+ for txid in txids_to_replace:
+ miner.prioritisetransaction(txid=txid, fee_delta=-COIN)
+ self.generate(miner, 1)
+ self.sync_blocks(wait=.1, nodes=[node, miner])
+ # RBF the low-fee transactions
+ while True:
+ try:
+ u = utxos_to_respend.pop(0)
+ send_tx(node, u, high_feerate)
+ except IndexError:
+ break
+
+ # Mine the last replacement txs
+ self.sync_mempools(wait=.1, nodes=[node, miner])
+ self.generate(miner, 1)
+ self.sync_blocks(wait=.1, nodes=[node, miner])
+
+ # Only 10% of the transactions were really confirmed with a low feerate,
+ # the rest needed to be RBF'd. We must return the 90% conf rate feerate.
+ high_feerate_kvb = Decimal(high_feerate) / COIN * 10**3
+ est_feerate = node.estimatesmartfee(2)["feerate"]
+ assert est_feerate == high_feerate_kvb
+
+ def run_test(self):
+ self.log.info("This test is time consuming, please be patient")
+ self.log.info("Splitting inputs so we can generate tx's")
+
+ # Split two coinbases into many small utxos
+ self.start_node(0)
+ self.initial_split(self.nodes[0])
+ self.log.info("Finished splitting")
+
+ # Now we can connect the other nodes, didn't want to connect them earlier
+ # so the estimates would not be affected by the splitting transactions
+ self.start_node(1)
+ self.start_node(2)
+ self.connect_nodes(1, 0)
+ self.connect_nodes(0, 2)
+ self.connect_nodes(2, 1)
+ self.sync_all()
+
+ self.log.info("Testing estimates with single transactions.")
+ self.sanity_check_estimates_range()
+
+ # check that the effective feerate is greater than or equal to the mempoolminfee even for high mempoolminfee
+ self.log.info("Test fee rate estimation after restarting node with high MempoolMinFee")
+ self.test_feerate_mempoolminfee()
+
+ self.log.info("Restarting node with fresh estimation")
+ self.stop_node(0)
+ fee_dat = os.path.join(self.nodes[0].datadir, self.chain, "fee_estimates.dat")
+ os.remove(fee_dat)
+ self.start_node(0)
+ self.connect_nodes(0, 1)
+ self.connect_nodes(0, 2)
+
+ self.log.info("Testing estimates with RBF.")
+ self.sanity_check_rbf_estimates(self.confutxo + self.memutxo)
+
self.log.info("Testing that fee estimation is disabled in blocksonly.")
self.restart_node(0, ["-blocksonly"])
assert_raises_rpc_error(-32603, "Fee estimation disabled",
diff --git a/test/functional/feature_loadblock.py b/test/functional/feature_loadblock.py
index e5db6de085..13e6a8d6d7 100755
--- a/test/functional/feature_loadblock.py
+++ b/test/functional/feature_loadblock.py
@@ -29,7 +29,7 @@ class LoadblockTest(BitcoinTestFramework):
def run_test(self):
self.nodes[1].setnetworkactive(state=False)
- self.nodes[0].generate(COINBASE_MATURITY)
+ self.generate(self.nodes[0], COINBASE_MATURITY)
# Parsing the url of our node to get settings for config file
data_dir = self.nodes[0].datadir
diff --git a/test/functional/feature_maxuploadtarget.py b/test/functional/feature_maxuploadtarget.py
index bd615997cb..ac4d40638e 100755
--- a/test/functional/feature_maxuploadtarget.py
+++ b/test/functional/feature_maxuploadtarget.py
@@ -38,7 +38,6 @@ class MaxUploadTest(BitcoinTestFramework):
self.extra_args = [[
"-maxuploadtarget=800",
"-acceptnonstdtxn=1",
- "-peertimeout=9999", # bump because mocktime might cause a disconnect otherwise
]]
self.supports_cli = False
@@ -56,7 +55,7 @@ class MaxUploadTest(BitcoinTestFramework):
self.nodes[0].setmocktime(old_time)
# Generate some old blocks
- self.nodes[0].generate(130)
+ self.generate(self.nodes[0], 130)
# p2p_conns[0] will only request old blocks
# p2p_conns[1] will only request new blocks
diff --git a/test/functional/feature_minchainwork.py b/test/functional/feature_minchainwork.py
index 3950690cf0..11cb4aa3cb 100755
--- a/test/functional/feature_minchainwork.py
+++ b/test/functional/feature_minchainwork.py
@@ -51,7 +51,7 @@ class MinimumChainWorkTest(BitcoinTestFramework):
num_blocks_to_generate = int((self.node_min_work[1] - starting_chain_work) / REGTEST_WORK_PER_BLOCK)
self.log.info(f"Generating {num_blocks_to_generate} blocks on node0")
- hashes = self.nodes[0].generatetoaddress(num_blocks_to_generate,
+ hashes = self.generatetoaddress(self.nodes[0], num_blocks_to_generate,
self.nodes[0].get_deterministic_priv_key().address)
self.log.info(f"Node0 current chain work: {self.nodes[0].getblockheader(hashes[-1])['chainwork']}")
@@ -73,7 +73,7 @@ class MinimumChainWorkTest(BitcoinTestFramework):
assert_equal(self.nodes[2].getblockcount(), starting_blockcount)
self.log.info("Generating one more block")
- self.nodes[0].generatetoaddress(1, self.nodes[0].get_deterministic_priv_key().address)
+ self.generatetoaddress(self.nodes[0], 1, self.nodes[0].get_deterministic_priv_key().address)
self.log.info("Verifying nodes are all synced")
diff --git a/test/functional/feature_notifications.py b/test/functional/feature_notifications.py
index 3f8fe9ccd5..2a507c75c4 100755
--- a/test/functional/feature_notifications.py
+++ b/test/functional/feature_notifications.py
@@ -27,6 +27,9 @@ class NotificationsTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
+ # The experimental syscall sandbox feature (-sandbox) is not compatible with -alertnotify,
+ # -blocknotify or -walletnotify (which all invoke execve).
+ self.disable_syscall_sandbox = True
def setup_network(self):
self.wallet = ''.join(chr(i) for i in range(FILE_CHAR_START, FILE_CHAR_END) if chr(i) not in FILE_CHARS_DISALLOWED)
@@ -42,7 +45,6 @@ class NotificationsTest(BitcoinTestFramework):
f"-alertnotify=echo > {os.path.join(self.alertnotify_dir, '%s')}",
f"-blocknotify=echo > {os.path.join(self.blocknotify_dir, '%s')}",
], [
- "-rescan",
f"-walletnotify=echo %h_%b > {os.path.join(self.walletnotify_dir, notify_outputname('%w', '%s'))}",
]]
self.wallet_names = [self.default_wallet_name, self.wallet]
@@ -76,7 +78,7 @@ class NotificationsTest(BitcoinTestFramework):
self.log.info("test -blocknotify")
block_count = 10
- blocks = self.nodes[1].generatetoaddress(block_count, self.nodes[1].getnewaddress() if self.is_wallet_compiled() else ADDRESS_BCRT1_UNSPENDABLE)
+ blocks = self.generatetoaddress(self.nodes[1], block_count, self.nodes[1].getnewaddress() if self.is_wallet_compiled() else ADDRESS_BCRT1_UNSPENDABLE)
# wait at most 10 seconds for expected number of files before reading the content
self.wait_until(lambda: len(os.listdir(self.blocknotify_dir)) == block_count, timeout=10)
@@ -91,16 +93,15 @@ class NotificationsTest(BitcoinTestFramework):
# directory content should equal the generated transaction hashes
tx_details = list(map(lambda t: (t['txid'], t['blockheight'], t['blockhash']), self.nodes[1].listtransactions("*", block_count)))
- self.stop_node(1)
self.expect_wallet_notify(tx_details)
self.log.info("test -walletnotify after rescan")
- # restart node to rescan to force wallet notifications
- self.start_node(1)
- self.connect_nodes(0, 1)
-
+ # rescan to force wallet notifications
+ self.nodes[1].rescanblockchain()
self.wait_until(lambda: len(os.listdir(self.walletnotify_dir)) == block_count, timeout=10)
+ self.connect_nodes(0, 1)
+
# directory content should equal the generated transaction hashes
tx_details = list(map(lambda t: (t['txid'], t['blockheight'], t['blockhash']), self.nodes[1].listtransactions("*", block_count)))
self.expect_wallet_notify(tx_details)
@@ -110,7 +111,7 @@ class NotificationsTest(BitcoinTestFramework):
# triggered by node 1
self.log.info("test -walletnotify with conflicting transactions")
self.nodes[0].rescanblockchain()
- self.nodes[0].generatetoaddress(100, ADDRESS_BCRT1_UNSPENDABLE)
+ self.generatetoaddress(self.nodes[0], 100, ADDRESS_BCRT1_UNSPENDABLE)
self.sync_blocks()
# Generate transaction on node 0, sync mempools, and check for
@@ -131,7 +132,7 @@ class NotificationsTest(BitcoinTestFramework):
# Add bump1 transaction to new block, checking for a notification
# and the correct number of confirmations.
- blockhash1 = self.nodes[0].generatetoaddress(1, ADDRESS_BCRT1_UNSPENDABLE)[0]
+ blockhash1 = self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_UNSPENDABLE)[0]
blockheight1 = self.nodes[0].getblockcount()
self.sync_blocks()
self.expect_wallet_notify([(bump1, blockheight1, blockhash1)])
@@ -148,7 +149,7 @@ class NotificationsTest(BitcoinTestFramework):
# about newly confirmed bump2 and newly conflicted tx2.
self.disconnect_nodes(0, 1)
bump2 = self.nodes[0].bumpfee(tx2)["txid"]
- blockhash2 = self.nodes[0].generatetoaddress(1, ADDRESS_BCRT1_UNSPENDABLE)[0]
+ blockhash2 = self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_UNSPENDABLE)[0]
blockheight2 = self.nodes[0].getblockcount()
assert_equal(self.nodes[0].gettransaction(bump2)["confirmations"], 1)
assert_equal(tx2 in self.nodes[1].getrawmempool(), True)
diff --git a/test/functional/feature_nulldummy.py b/test/functional/feature_nulldummy.py
index 678e103e5f..217a38050d 100755
--- a/test/functional/feature_nulldummy.py
+++ b/test/functional/feature_nulldummy.py
@@ -52,7 +52,7 @@ class NULLDUMMYTest(BitcoinTestFramework):
# This script tests NULLDUMMY activation, which is part of the 'segwit' deployment, so we go through
# normal segwit activation here (and don't use the default always-on behaviour).
self.extra_args = [[
- f'-segwitheight={COINBASE_MATURITY + 5}',
+ f'-testactivationheight=segwit@{COINBASE_MATURITY + 5}',
'-addresstype=legacy',
'-par=1', # Use only one script thread to get the exact reject reason for testing
]]
@@ -74,11 +74,11 @@ class NULLDUMMYTest(BitcoinTestFramework):
wmulti.importaddress(self.ms_address)
wmulti.importaddress(self.wit_ms_address)
- self.coinbase_blocks = self.nodes[0].generate(2) # block height = 2
+ self.coinbase_blocks = self.generate(self.nodes[0], 2) # block height = 2
coinbase_txid = []
for i in self.coinbase_blocks:
coinbase_txid.append(self.nodes[0].getblock(i)['tx'][0])
- self.nodes[0].generate(COINBASE_MATURITY) # block height = COINBASE_MATURITY + 2
+ self.generate(self.nodes[0], COINBASE_MATURITY) # block height = COINBASE_MATURITY + 2
self.lastblockhash = self.nodes[0].getbestblockhash()
self.lastblockheight = COINBASE_MATURITY + 2
self.lastblocktime = int(time.time()) + self.lastblockheight
diff --git a/test/functional/feature_presegwit_node_upgrade.py b/test/functional/feature_presegwit_node_upgrade.py
index 0428588da3..aac42d4dbf 100755
--- a/test/functional/feature_presegwit_node_upgrade.py
+++ b/test/functional/feature_presegwit_node_upgrade.py
@@ -9,12 +9,14 @@ from test_framework.util import (
assert_equal,
softfork_active,
)
+import os
+
class SegwitUpgradeTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
- self.extra_args = [["-segwitheight=10"]]
+ self.extra_args = [["-testactivationheight=segwit@10"]]
def run_test(self):
"""A pre-segwit node with insufficiently validated blocks needs to redownload blocks"""
@@ -28,18 +30,21 @@ class SegwitUpgradeTest(BitcoinTestFramework):
assert not softfork_active(node, "segwit")
# Generate 8 blocks without witness data
- node.generate(8)
+ self.generate(node, 8)
assert_equal(node.getblockcount(), 8)
self.stop_node(0)
# Restarting the node (with segwit activation height set to 5) should result in a shutdown
# because the blockchain consists of 3 insufficiently validated blocks per segwit consensus rules.
node.assert_start_raises_init_error(
- extra_args=["-segwitheight=5"],
- expected_msg=": Witness data for blocks after height 5 requires validation. Please restart with -reindex..\nPlease restart with -reindex or -reindex-chainstate to recover.")
+ extra_args=["-testactivationheight=segwit@5"],
+ expected_msg=": Witness data for blocks after height 5 requires "
+ f"validation. Please restart with -reindex..{os.linesep}"
+ "Please restart with -reindex or -reindex-chainstate to recover.",
+ )
# As directed, the user restarts the node with -reindex
- self.start_node(0, extra_args=["-reindex", "-segwitheight=5"])
+ self.start_node(0, extra_args=["-reindex", "-testactivationheight=segwit@5"])
# With the segwit consensus rules, the node is able to validate only up to block 4
assert_equal(node.getblockcount(), 4)
diff --git a/test/functional/feature_pruning.py b/test/functional/feature_pruning.py
index 2f0868e733..c2463d0bcc 100755
--- a/test/functional/feature_pruning.py
+++ b/test/functional/feature_pruning.py
@@ -118,9 +118,9 @@ class PruneTest(BitcoinTestFramework):
def create_big_chain(self):
# Start by creating some coinbases we can spend later
- self.nodes[1].generate(200)
+ self.generate(self.nodes[1], 200)
self.sync_blocks(self.nodes[0:2])
- self.nodes[0].generate(150)
+ self.generate(self.nodes[0], 150)
# Then mine enough full blocks to create more than 550MiB of data
mine_large_blocks(self.nodes[0], 645)
@@ -211,7 +211,7 @@ class PruneTest(BitcoinTestFramework):
self.disconnect_nodes(1, 2)
self.log.info("Generating new longer chain of 300 more blocks")
- self.nodes[1].generate(300)
+ self.generate(self.nodes[1], 300)
self.log.info("Reconnect nodes")
self.connect_nodes(0, 1)
@@ -263,7 +263,7 @@ class PruneTest(BitcoinTestFramework):
self.nodes[0].invalidateblock(curchainhash)
assert_equal(self.nodes[0].getblockcount(), self.mainchainheight)
assert_equal(self.nodes[0].getbestblockhash(), self.mainchainhash2)
- goalbesthash = self.nodes[0].generate(blocks_to_mine)[-1]
+ goalbesthash = self.generate(self.nodes[0], blocks_to_mine)[-1]
goalbestheight = first_reorg_height + 1
self.log.info("Verify node 2 reorged back to the main chain, some blocks of which it had to redownload")
@@ -306,7 +306,7 @@ class PruneTest(BitcoinTestFramework):
assert_equal(block1_details["nTx"], len(block1_details["tx"]))
# mine 6 blocks so we are at height 1001 (i.e., above PruneAfterHeight)
- node.generate(6)
+ self.generate(node, 6)
assert_equal(node.getblockchaininfo()["blocks"], 1001)
# Pruned block should still know the number of transactions
@@ -337,7 +337,7 @@ class PruneTest(BitcoinTestFramework):
assert has_block(2), "blk00002.dat is still there, should be pruned by now"
# advance the tip so blk00002.dat and blk00003.dat can be pruned (the last 288 blocks should now be in blk00004.dat)
- node.generate(288)
+ self.generate(node, 288)
prune(1000)
assert not has_block(2), "blk00002.dat is still there, should be pruned by now"
assert not has_block(3), "blk00003.dat is still there, should be pruned by now"
diff --git a/test/functional/feature_rbf.py b/test/functional/feature_rbf.py
index cb7556feb4..4eaaf46454 100755
--- a/test/functional/feature_rbf.py
+++ b/test/functional/feature_rbf.py
@@ -7,7 +7,6 @@
from copy import deepcopy
from decimal import Decimal
-from test_framework.blocktools import COINBASE_MATURITY
from test_framework.messages import (
BIP125_SEQUENCE_NUMBER,
COIN,
@@ -18,9 +17,16 @@ from test_framework.messages import (
)
from test_framework.script import CScript, OP_DROP
from test_framework.test_framework import BitcoinTestFramework
-from test_framework.util import assert_equal, assert_raises_rpc_error, satoshi_round
-from test_framework.script_util import DUMMY_P2WPKH_SCRIPT, DUMMY_2_P2WPKH_SCRIPT
+from test_framework.util import (
+ assert_equal,
+ assert_raises_rpc_error,
+)
+from test_framework.script_util import (
+ DUMMY_P2WPKH_SCRIPT,
+ DUMMY_2_P2WPKH_SCRIPT,
+)
from test_framework.wallet import MiniWallet
+from test_framework.address import ADDRESS_BCRT1_UNSPENDABLE
MAX_REPLACEMENT_LIMIT = 100
class ReplaceByFeeTest(BitcoinTestFramework):
@@ -38,15 +44,12 @@ class ReplaceByFeeTest(BitcoinTestFramework):
]
self.supports_cli = False
- def skip_test_if_missing_module(self):
- self.skip_if_no_wallet()
-
def run_test(self):
self.wallet = MiniWallet(self.nodes[0])
# the pre-mined test framework chain contains coinbase outputs to the
# MiniWallet's default address ADDRESS_BCRT1_P2WSH_OP_TRUE in blocks
# 76-100 (see method BitcoinTestFramework._initialize_chain())
- self.wallet.scan_blocks(start=76, num=2)
+ self.wallet.rescan_utxos()
self.log.info("Running test simple doublespend...")
self.test_simple_doublespend()
@@ -89,29 +92,10 @@ class ReplaceByFeeTest(BitcoinTestFramework):
def make_utxo(self, node, amount, confirmed=True, scriptPubKey=DUMMY_P2WPKH_SCRIPT):
"""Create a txout with a given amount and scriptPubKey
- Mines coins as needed.
-
confirmed - txouts created will be confirmed in the blockchain;
unconfirmed otherwise.
"""
- fee = 1 * COIN
- while node.getbalance() < satoshi_round((amount + fee) / COIN):
- self.generate(node, COINBASE_MATURITY)
-
- new_addr = node.getnewaddress()
- txid = node.sendtoaddress(new_addr, satoshi_round((amount + fee) / COIN))
- tx1 = node.getrawtransaction(txid, 1)
- txid = int(txid, 16)
- i, _ = next(filter(lambda vout: new_addr == vout[1]['scriptPubKey']['address'], enumerate(tx1['vout'])))
-
- tx2 = CTransaction()
- tx2.vin = [CTxIn(COutPoint(txid, i))]
- tx2.vout = [CTxOut(amount, scriptPubKey)]
- tx2.rehash()
-
- signed_tx = node.signrawtransactionwithwallet(tx2.serialize().hex())
-
- txid = node.sendrawtransaction(signed_tx['hex'], 0)
+ txid, n = self.wallet.send_to(from_node=node, scriptPubKey=scriptPubKey, amount=amount)
# If requested, ensure txouts are confirmed.
if confirmed:
@@ -124,7 +108,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
assert new_size < mempool_size
mempool_size = new_size
- return COutPoint(int(txid, 16), 0)
+ return COutPoint(int(txid, 16), n)
def test_simple_doublespend(self):
"""Simple doublespend"""
@@ -161,14 +145,14 @@ class ReplaceByFeeTest(BitcoinTestFramework):
def test_doublespend_chain(self):
"""Doublespend of a long chain"""
- initial_nValue = 50 * COIN
+ initial_nValue = 5 * COIN
tx0_outpoint = self.make_utxo(self.nodes[0], initial_nValue)
prevout = tx0_outpoint
remaining_value = initial_nValue
chain_txids = []
- while remaining_value > 10 * COIN:
- remaining_value -= 1 * COIN
+ while remaining_value > 1 * COIN:
+ remaining_value -= int(0.1 * COIN)
tx = CTransaction()
tx.vin = [CTxIn(prevout, nSequence=0)]
tx.vout = [CTxOut(remaining_value, CScript([1, OP_DROP] * 15 + [1]))]
@@ -178,10 +162,10 @@ class ReplaceByFeeTest(BitcoinTestFramework):
prevout = COutPoint(int(txid, 16), 0)
# Whether the double-spend is allowed is evaluated by including all
- # child fees - 40 BTC - so this attempt is rejected.
+ # child fees - 4 BTC - so this attempt is rejected.
dbl_tx = CTransaction()
dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]
- dbl_tx.vout = [CTxOut(initial_nValue - 30 * COIN, DUMMY_P2WPKH_SCRIPT)]
+ dbl_tx.vout = [CTxOut(initial_nValue - 3 * COIN, DUMMY_P2WPKH_SCRIPT)]
dbl_tx_hex = dbl_tx.serialize().hex()
# This will raise an exception due to insufficient fee
@@ -190,7 +174,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
# Accepted with sufficient fee
dbl_tx = CTransaction()
dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]
- dbl_tx.vout = [CTxOut(1 * COIN, DUMMY_P2WPKH_SCRIPT)]
+ dbl_tx.vout = [CTxOut(int(0.1 * COIN), DUMMY_P2WPKH_SCRIPT)]
dbl_tx_hex = dbl_tx.serialize().hex()
self.nodes[0].sendrawtransaction(dbl_tx_hex, 0)
@@ -201,10 +185,10 @@ class ReplaceByFeeTest(BitcoinTestFramework):
def test_doublespend_tree(self):
"""Doublespend of a big tree of transactions"""
- initial_nValue = 50 * COIN
+ initial_nValue = 5 * COIN
tx0_outpoint = self.make_utxo(self.nodes[0], initial_nValue)
- def branch(prevout, initial_value, max_txs, tree_width=5, fee=0.0001 * COIN, _total_txs=None):
+ def branch(prevout, initial_value, max_txs, tree_width=5, fee=0.00001 * COIN, _total_txs=None):
if _total_txs is None:
_total_txs = [0]
if _total_txs[0] >= max_txs:
@@ -235,7 +219,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
_total_txs=_total_txs):
yield x
- fee = int(0.0001 * COIN)
+ fee = int(0.00001 * COIN)
n = MAX_REPLACEMENT_LIMIT
tree_txs = list(branch(tx0_outpoint, initial_nValue, n, fee=fee))
assert_equal(len(tree_txs), n)
@@ -248,10 +232,10 @@ class ReplaceByFeeTest(BitcoinTestFramework):
# This will raise an exception due to insufficient fee
assert_raises_rpc_error(-26, "insufficient fee", self.nodes[0].sendrawtransaction, dbl_tx_hex, 0)
- # 1 BTC fee is enough
+ # 0.1 BTC fee is enough
dbl_tx = CTransaction()
dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]
- dbl_tx.vout = [CTxOut(initial_nValue - fee * n - 1 * COIN, DUMMY_P2WPKH_SCRIPT)]
+ dbl_tx.vout = [CTxOut(initial_nValue - fee * n - int(0.1 * COIN), DUMMY_P2WPKH_SCRIPT)]
dbl_tx_hex = dbl_tx.serialize().hex()
self.nodes[0].sendrawtransaction(dbl_tx_hex, 0)
@@ -264,7 +248,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
# Try again, but with more total transactions than the "max txs
# double-spent at once" anti-DoS limit.
for n in (MAX_REPLACEMENT_LIMIT + 1, MAX_REPLACEMENT_LIMIT * 2):
- fee = int(0.0001 * COIN)
+ fee = int(0.00001 * COIN)
tx0_outpoint = self.make_utxo(self.nodes[0], initial_nValue)
tree_txs = list(branch(tx0_outpoint, initial_nValue, n, fee=fee))
assert_equal(len(tree_txs), n)
@@ -544,9 +528,9 @@ class ReplaceByFeeTest(BitcoinTestFramework):
assert tx2b_txid in self.nodes[0].getrawmempool()
def test_rpc(self):
- us0 = self.nodes[0].listunspent()[0]
+ us0 = self.wallet.get_utxo()
ins = [us0]
- outs = {self.nodes[0].getnewaddress(): Decimal(1.0000000)}
+ outs = {ADDRESS_BCRT1_UNSPENDABLE: Decimal(1.0000000)}
rawtx0 = self.nodes[0].createrawtransaction(ins, outs, 0, True)
rawtx1 = self.nodes[0].createrawtransaction(ins, outs, 0, False)
json0 = self.nodes[0].decoderawtransaction(rawtx0)
@@ -554,14 +538,16 @@ class ReplaceByFeeTest(BitcoinTestFramework):
assert_equal(json0["vin"][0]["sequence"], 4294967293)
assert_equal(json1["vin"][0]["sequence"], 4294967295)
- rawtx2 = self.nodes[0].createrawtransaction([], outs)
- frawtx2a = self.nodes[0].fundrawtransaction(rawtx2, {"replaceable": True})
- frawtx2b = self.nodes[0].fundrawtransaction(rawtx2, {"replaceable": False})
+ if self.is_wallet_compiled():
+ self.init_wallet(0)
+ rawtx2 = self.nodes[0].createrawtransaction([], outs)
+ frawtx2a = self.nodes[0].fundrawtransaction(rawtx2, {"replaceable": True})
+ frawtx2b = self.nodes[0].fundrawtransaction(rawtx2, {"replaceable": False})
- json0 = self.nodes[0].decoderawtransaction(frawtx2a['hex'])
- json1 = self.nodes[0].decoderawtransaction(frawtx2b['hex'])
- assert_equal(json0["vin"][0]["sequence"], 4294967293)
- assert_equal(json1["vin"][0]["sequence"], 4294967294)
+ json0 = self.nodes[0].decoderawtransaction(frawtx2a['hex'])
+ json1 = self.nodes[0].decoderawtransaction(frawtx2b['hex'])
+ assert_equal(json0["vin"][0]["sequence"], 4294967293)
+ assert_equal(json1["vin"][0]["sequence"], 4294967294)
def test_no_inherited_signaling(self):
confirmed_utxo = self.wallet.get_utxo()
diff --git a/test/functional/feature_reindex.py b/test/functional/feature_reindex.py
index 68585b7475..f0435b21b2 100755
--- a/test/functional/feature_reindex.py
+++ b/test/functional/feature_reindex.py
@@ -19,7 +19,7 @@ class ReindexTest(BitcoinTestFramework):
self.num_nodes = 1
def reindex(self, justchainstate=False):
- self.nodes[0].generatetoaddress(3, self.nodes[0].get_deterministic_priv_key().address)
+ self.generatetoaddress(self.nodes[0], 3, self.nodes[0].get_deterministic_priv_key().address)
blockcount = self.nodes[0].getblockcount()
self.stop_nodes()
extra_args = [["-reindex-chainstate" if justchainstate else "-reindex"]]
diff --git a/test/functional/feature_segwit.py b/test/functional/feature_segwit.py
index 6f1cecce58..2f9ab34e99 100755
--- a/test/functional/feature_segwit.py
+++ b/test/functional/feature_segwit.py
@@ -31,11 +31,11 @@ from test_framework.script import (
OP_1,
OP_2,
OP_CHECKMULTISIG,
- OP_CHECKSIG,
OP_DROP,
OP_TRUE,
)
from test_framework.script_util import (
+ key_to_p2pk_script,
key_to_p2pkh_script,
key_to_p2wpkh_script,
script_to_p2sh_script,
@@ -44,6 +44,7 @@ from test_framework.script_util import (
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
+ assert_greater_than_or_equal,
assert_is_hex_string,
assert_raises_rpc_error,
try_rpc,
@@ -54,12 +55,14 @@ NODE_2 = 2
P2WPKH = 0
P2WSH = 1
+
def getutxo(txid):
utxo = {}
utxo["vout"] = 0
utxo["txid"] = txid
return utxo
+
def find_spendable_utxo(node, min_value):
for utxo in node.listunspent(query_options={'minimumAmount': min_value}):
if utxo['spendable']:
@@ -67,7 +70,9 @@ def find_spendable_utxo(node, min_value):
raise AssertionError(f"Unspent output equal or higher than {min_value} not found")
-txs_mined = {} # txindex from txid to blockhash
+
+txs_mined = {} # txindex from txid to blockhash
+
class SegWitTest(BitcoinTestFramework):
def set_test_params(self):
@@ -78,18 +83,18 @@ class SegWitTest(BitcoinTestFramework):
[
"-acceptnonstdtxn=1",
"-rpcserialversion=0",
- "-segwitheight=432",
+ "-testactivationheight=segwit@432",
"-addresstype=legacy",
],
[
"-acceptnonstdtxn=1",
"-rpcserialversion=1",
- "-segwitheight=432",
+ "-testactivationheight=segwit@432",
"-addresstype=legacy",
],
[
"-acceptnonstdtxn=1",
- "-segwitheight=432",
+ "-testactivationheight=segwit@432",
"-addresstype=legacy",
],
]
@@ -105,13 +110,13 @@ class SegWitTest(BitcoinTestFramework):
def success_mine(self, node, txid, sign, redeem_script=""):
send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
- block = node.generate(1)
+ block = self.generate(node, 1)
assert_equal(len(node.getblock(block[0])["tx"]), 2)
self.sync_blocks()
def skip_mine(self, node, txid, sign, redeem_script=""):
send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
- block = node.generate(1)
+ block = self.generate(node, 1)
assert_equal(len(node.getblock(block[0])["tx"]), 1)
self.sync_blocks()
@@ -119,23 +124,23 @@ class SegWitTest(BitcoinTestFramework):
assert_raises_rpc_error(-26, error_msg, send_to_witness, use_p2wsh=1, node=node, utxo=getutxo(txid), pubkey=self.pubkey[0], encode_p2sh=False, amount=Decimal("49.998"), sign=sign, insert_redeem_script=redeem_script)
def run_test(self):
- self.nodes[0].generate(161) # block 161
+ self.generate(self.nodes[0], 161) # block 161
self.log.info("Verify sigops are counted in GBT with pre-BIP141 rules before the fork")
txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
tmpl = self.nodes[0].getblocktemplate({'rules': ['segwit']})
- assert tmpl['sizelimit'] == 1000000
+ assert_equal(tmpl['sizelimit'], 1000000)
assert 'weightlimit' not in tmpl
- assert tmpl['sigoplimit'] == 20000
- assert tmpl['transactions'][0]['hash'] == txid
- assert tmpl['transactions'][0]['sigops'] == 2
+ assert_equal(tmpl['sigoplimit'], 20000)
+ assert_equal(tmpl['transactions'][0]['hash'], txid)
+ assert_equal(tmpl['transactions'][0]['sigops'], 2)
assert '!segwit' not in tmpl['rules']
- self.nodes[0].generate(1) # block 162
+ self.generate(self.nodes[0], 1) # block 162
balance_presetup = self.nodes[0].getbalance()
self.pubkey = []
- p2sh_ids = [] # p2sh_ids[NODE][TYPE] is an array of txids that spend to P2WPKH (TYPE=0) or P2WSH (TYPE=1) scripts to an address for NODE embedded in p2sh
- wit_ids = [] # wit_ids[NODE][TYPE] is an array of txids that spend to P2WPKH (TYPE=0) or P2WSH (TYPE=1) scripts to an address for NODE via bare witness
+ p2sh_ids = [] # p2sh_ids[NODE][TYPE] is an array of txids that spend to P2WPKH (TYPE=0) or P2WSH (TYPE=1) scripts to an address for NODE embedded in p2sh
+ wit_ids = [] # wit_ids[NODE][TYPE] is an array of txids that spend to P2WPKH (TYPE=0) or P2WSH (TYPE=1) scripts to an address for NODE via bare witness
for i in range(3):
newaddress = self.nodes[i].getnewaddress()
self.pubkey.append(self.nodes[i].getaddressinfo(newaddress)["pubkey"])
@@ -156,7 +161,7 @@ class SegWitTest(BitcoinTestFramework):
wit_ids[n][v].append(send_to_witness(v, self.nodes[0], find_spendable_utxo(self.nodes[0], 50), self.pubkey[n], False, Decimal("49.999")))
p2sh_ids[n][v].append(send_to_witness(v, self.nodes[0], find_spendable_utxo(self.nodes[0], 50), self.pubkey[n], True, Decimal("49.999")))
- self.nodes[0].generate(1) # block 163
+ self.generate(self.nodes[0], 1) # block 163
self.sync_blocks()
# Make sure all nodes recognize the transactions as theirs
@@ -164,7 +169,7 @@ class SegWitTest(BitcoinTestFramework):
assert_equal(self.nodes[1].getbalance(), 20 * Decimal("49.999"))
assert_equal(self.nodes[2].getbalance(), 20 * Decimal("49.999"))
- self.nodes[0].generate(260) # block 423
+ self.generate(self.nodes[0], 260) # block 423
self.sync_blocks()
self.log.info("Verify witness txs are skipped for mining before the fork")
@@ -177,11 +182,11 @@ class SegWitTest(BitcoinTestFramework):
self.fail_accept(self.nodes[2], "mandatory-script-verify-flag-failed (Operation not valid with the current stack size)", p2sh_ids[NODE_2][P2WPKH][1], sign=False)
self.fail_accept(self.nodes[2], "mandatory-script-verify-flag-failed (Operation not valid with the current stack size)", p2sh_ids[NODE_2][P2WSH][1], sign=False)
- self.nodes[2].generate(4) # blocks 428-431
+ self.generate(self.nodes[2], 4) # blocks 428-431
self.log.info("Verify previous witness txs skipped for mining can now be mined")
assert_equal(len(self.nodes[2].getrawmempool()), 4)
- blockhash = self.nodes[2].generate(1)[0] # block 432 (first block with new rules; 432 = 144 * 3)
+ blockhash = self.generate(self.nodes[2], 1)[0] # block 432 (first block with new rules; 432 = 144 * 3)
self.sync_blocks()
assert_equal(len(self.nodes[2].getrawmempool()), 0)
segwit_tx_list = self.nodes[2].getblock(blockhash)["tx"]
@@ -215,7 +220,7 @@ class SegWitTest(BitcoinTestFramework):
witnesses = coinbase_tx["decoded"]["vin"][0]["txinwitness"]
assert_equal(len(witnesses), 1)
assert_is_hex_string(witnesses[0])
- assert_equal(witnesses[0], '00'*32)
+ assert_equal(witnesses[0], '00' * 32)
self.log.info("Verify witness txs without witness data are invalid after the fork")
self.fail_accept(self.nodes[2], 'non-mandatory-script-verify-flag (Witness program hash mismatch)', wit_ids[NODE_2][P2WPKH][2], sign=False)
@@ -231,15 +236,17 @@ class SegWitTest(BitcoinTestFramework):
self.log.info("Verify sigops are counted in GBT with BIP141 rules after the fork")
txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
+ raw_tx = self.nodes[0].getrawtransaction(txid, True)
tmpl = self.nodes[0].getblocktemplate({'rules': ['segwit']})
- assert tmpl['sizelimit'] >= 3999577 # actual maximum size is lower due to minimum mandatory non-witness data
- assert tmpl['weightlimit'] == 4000000
- assert tmpl['sigoplimit'] == 80000
- assert tmpl['transactions'][0]['txid'] == txid
- assert tmpl['transactions'][0]['sigops'] == 8
+ assert_greater_than_or_equal(tmpl['sizelimit'], 3999577) # actual maximum size is lower due to minimum mandatory non-witness data
+ assert_equal(tmpl['weightlimit'], 4000000)
+ assert_equal(tmpl['sigoplimit'], 80000)
+ assert_equal(tmpl['transactions'][0]['txid'], txid)
+ expected_sigops = 9 if 'txinwitness' in raw_tx["vin"][0] else 8
+ assert_equal(tmpl['transactions'][0]['sigops'], expected_sigops)
assert '!segwit' in tmpl['rules']
- self.nodes[0].generate(1) # Mine a block to clear the gbt cache
+ self.generate(self.nodes[0], 1) # Mine a block to clear the gbt cache
self.log.info("Non-segwit miners are able to use GBT response after activation.")
# Create a 3-tx chain: tx1 (non-segwit input, paying to a segwit output) ->
@@ -302,7 +309,7 @@ class SegWitTest(BitcoinTestFramework):
assert_equal(self.nodes[0].getmempoolentry(txid3)["weight"], tx.get_weight())
# Mine a block to clear the gbt cache again.
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.log.info("Verify behaviour of importaddress and listunspent")
@@ -356,7 +363,7 @@ class SegWitTest(BitcoinTestFramework):
for i in compressed_spendable_address:
v = self.nodes[0].getaddressinfo(i)
- if (v['isscript']):
+ if v['isscript']:
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
# p2sh multisig with compressed keys should always be spendable
spendable_anytime.extend([p2sh])
@@ -375,7 +382,7 @@ class SegWitTest(BitcoinTestFramework):
for i in uncompressed_spendable_address:
v = self.nodes[0].getaddressinfo(i)
- if (v['isscript']):
+ if v['isscript']:
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
# p2sh multisig with uncompressed keys should always be spendable
spendable_anytime.extend([p2sh])
@@ -394,7 +401,7 @@ class SegWitTest(BitcoinTestFramework):
for i in compressed_solvable_address:
v = self.nodes[0].getaddressinfo(i)
- if (v['isscript']):
+ if v['isscript']:
# Multisig without private is not seen after addmultisigaddress, but seen after importaddress
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
solvable_after_importaddress.extend([bare, p2sh, p2wsh, p2sh_p2wsh])
@@ -407,7 +414,7 @@ class SegWitTest(BitcoinTestFramework):
for i in uncompressed_solvable_address:
v = self.nodes[0].getaddressinfo(i)
- if (v['isscript']):
+ if v['isscript']:
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
# Base uncompressed multisig without private is not seen after addmultisigaddress, but seen after importaddress
solvable_after_importaddress.extend([bare, p2sh])
@@ -446,13 +453,13 @@ class SegWitTest(BitcoinTestFramework):
importlist = []
for i in compressed_spendable_address + uncompressed_spendable_address + compressed_solvable_address + uncompressed_solvable_address:
v = self.nodes[0].getaddressinfo(i)
- if (v['isscript']):
+ if v['isscript']:
bare = bytes.fromhex(v['hex'])
importlist.append(bare.hex())
importlist.append(script_to_p2wsh_script(bare).hex())
else:
pubkey = bytes.fromhex(v['pubkey'])
- p2pk = CScript([pubkey, OP_CHECKSIG])
+ p2pk = key_to_p2pk_script(pubkey)
p2pkh = key_to_p2pkh_script(pubkey)
importlist.append(p2pk.hex())
importlist.append(p2pkh.hex())
@@ -509,7 +516,7 @@ class SegWitTest(BitcoinTestFramework):
for i in compressed_spendable_address:
v = self.nodes[0].getaddressinfo(i)
- if (v['isscript']):
+ if v['isscript']:
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
premature_witaddress.append(script_to_p2sh(p2wsh))
else:
@@ -519,7 +526,7 @@ class SegWitTest(BitcoinTestFramework):
for i in uncompressed_spendable_address + uncompressed_solvable_address:
v = self.nodes[0].getaddressinfo(i)
- if (v['isscript']):
+ if v['isscript']:
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
# P2WSH and P2SH(P2WSH) multisig with uncompressed keys are never seen
unseen_anytime.extend([p2wsh, p2sh_p2wsh])
@@ -530,7 +537,7 @@ class SegWitTest(BitcoinTestFramework):
for i in compressed_solvable_address:
v = self.nodes[0].getaddressinfo(i)
- if (v['isscript']):
+ if v['isscript']:
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
premature_witaddress.append(script_to_p2sh(p2wsh))
else:
@@ -592,18 +599,18 @@ class SegWitTest(BitcoinTestFramework):
tx.rehash()
signresults = self.nodes[0].signrawtransactionwithwallet(tx.serialize_without_witness().hex())['hex']
txid = self.nodes[0].sendrawtransaction(hexstring=signresults, maxfeerate=0)
- txs_mined[txid] = self.nodes[0].generate(1)[0]
+ txs_mined[txid] = self.generate(self.nodes[0], 1)[0]
self.sync_blocks()
watchcount = 0
spendcount = 0
for i in self.nodes[0].listunspent():
- if (i['txid'] == txid):
+ if i['txid'] == txid:
watchcount += 1
if i['spendable']:
spendcount += 1
- if (ismine == 2):
+ if ismine == 2:
assert_equal(spendcount, len(script_list))
- elif (ismine == 1):
+ elif ismine == 1:
assert_equal(watchcount, len(script_list))
assert_equal(spendcount, 0)
else:
@@ -615,13 +622,13 @@ class SegWitTest(BitcoinTestFramework):
p2sh = CScript(bytes.fromhex(v['scriptPubKey']))
p2wsh = script_to_p2wsh_script(bare)
p2sh_p2wsh = script_to_p2sh_script(p2wsh)
- return([bare, p2sh, p2wsh, p2sh_p2wsh])
+ return [bare, p2sh, p2wsh, p2sh_p2wsh]
def p2pkh_address_to_script(self, v):
pubkey = bytes.fromhex(v['pubkey'])
p2wpkh = key_to_p2wpkh_script(pubkey)
p2sh_p2wpkh = script_to_p2sh_script(p2wpkh)
- p2pk = CScript([pubkey, OP_CHECKSIG])
+ p2pk = key_to_p2pk_script(pubkey)
p2pkh = CScript(bytes.fromhex(v['scriptPubKey']))
p2sh_p2pk = script_to_p2sh_script(p2pk)
p2sh_p2pkh = script_to_p2sh_script(p2pkh)
@@ -642,7 +649,7 @@ class SegWitTest(BitcoinTestFramework):
tx.rehash()
signresults = self.nodes[0].signrawtransactionwithwallet(tx.serialize_without_witness().hex())['hex']
self.nodes[0].sendrawtransaction(hexstring=signresults, maxfeerate=0)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
diff --git a/test/functional/feature_signet.py b/test/functional/feature_signet.py
index 96c581dede..94138b0e6d 100755
--- a/test/functional/feature_signet.py
+++ b/test/functional/feature_signet.py
@@ -51,7 +51,7 @@ class SignetBasicTest(BitcoinTestFramework):
assert_equal(mining_info['networkhashps'], Decimal('0'))
assert_equal(mining_info['pooledtx'], 0)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.log.info("pregenerated signet blocks check")
diff --git a/test/functional/feature_syscall_sandbox.py b/test/functional/feature_syscall_sandbox.py
new file mode 100755
index 0000000000..caf7f1e7fc
--- /dev/null
+++ b/test/functional/feature_syscall_sandbox.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python3
+# Copyright (c) 2021 The Bitcoin Core developers
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+"""Test bitcoind aborts if a disallowed syscall is used when compiled with the syscall sandbox."""
+
+from test_framework.test_framework import BitcoinTestFramework, SkipTest
+
+
+class SyscallSandboxTest(BitcoinTestFramework):
+ def set_test_params(self):
+ self.num_nodes = 1
+
+ def skip_test_if_missing_module(self):
+ if not self.is_syscall_sandbox_compiled():
+ raise SkipTest("bitcoind has not been built with syscall sandbox enabled.")
+ if self.options.nosandbox:
+ raise SkipTest("--nosandbox passed to test runner.")
+
+ def run_test(self):
+ disallowed_syscall_terminated_bitcoind = False
+ expected_log_entry = 'ERROR: The syscall "getgroups" (syscall number 115) is not allowed by the syscall sandbox'
+ with self.nodes[0].assert_debug_log([expected_log_entry]):
+ self.log.info("Invoking disallowed syscall")
+ try:
+ self.nodes[0].invokedisallowedsyscall()
+ except ConnectionError:
+ disallowed_syscall_terminated_bitcoind = True
+ assert disallowed_syscall_terminated_bitcoind
+ self.nodes = []
+
+
+if __name__ == "__main__":
+ SyscallSandboxTest().main()
diff --git a/test/functional/feature_taproot.py b/test/functional/feature_taproot.py
index f27ab2057c..50a25ee1ef 100755
--- a/test/functional/feature_taproot.py
+++ b/test/functional/feature_taproot.py
@@ -76,6 +76,7 @@ from test_framework.script import (
taproot_construct,
)
from test_framework.script_util import (
+ key_to_p2pk_script,
key_to_p2wpkh_script,
keyhash_to_p2pkh_script,
script_to_p2sh_script,
@@ -1109,7 +1110,7 @@ def spenders_taproot_active():
for witv0 in [False, True]:
for hashtype in VALID_SIGHASHES_ECDSA + [random.randrange(0x04, 0x80), random.randrange(0x84, 0x100)]:
standard = (hashtype in VALID_SIGHASHES_ECDSA) and (compressed or not witv0)
- add_spender(spenders, "legacy/pk-wrongkey", hashtype=hashtype, p2sh=p2sh, witv0=witv0, standard=standard, script=CScript([pubkey1, OP_CHECKSIG]), **SINGLE_SIG, key=eckey1, failure={"key": eckey2}, sigops_weight=4-3*witv0, **ERR_NO_SUCCESS)
+ add_spender(spenders, "legacy/pk-wrongkey", hashtype=hashtype, p2sh=p2sh, witv0=witv0, standard=standard, script=key_to_p2pk_script(pubkey1), **SINGLE_SIG, key=eckey1, failure={"key": eckey2}, sigops_weight=4-3*witv0, **ERR_NO_SUCCESS)
add_spender(spenders, "legacy/pkh-sighashflip", hashtype=hashtype, p2sh=p2sh, witv0=witv0, standard=standard, pkh=pubkey1, key=eckey1, **SIGHASH_BITFLIP, sigops_weight=4-3*witv0, **ERR_NO_SUCCESS)
# Verify that OP_CHECKSIGADD wasn't accidentally added to pre-taproot validation logic.
@@ -1461,7 +1462,7 @@ class TaprootTest(BitcoinTestFramework):
def run_test(self):
# Post-taproot activation tests go first (pre-taproot tests' blocks are invalid post-taproot).
self.log.info("Post-activation tests...")
- self.nodes[1].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[1], COINBASE_MATURITY + 1)
self.test_spenders(self.nodes[1], spenders_taproot_active(), input_counts=[1, 2, 2, 2, 2, 3])
# Re-connect nodes in case they have been disconnected
diff --git a/test/functional/feature_utxo_set_hash.py b/test/functional/feature_utxo_set_hash.py
index afc0bdb8c5..b1b4703d37 100755
--- a/test/functional/feature_utxo_set_hash.py
+++ b/test/functional/feature_utxo_set_hash.py
@@ -31,13 +31,13 @@ class UTXOSetHashTest(BitcoinTestFramework):
# Generate 100 blocks and remove the first since we plan to spend its
# coinbase
- block_hashes = wallet.generate(1) + node.generate(99)
+ block_hashes = self.generate(wallet, 1) + self.generate(node, 99)
blocks = list(map(lambda block: from_hex(CBlock(), node.getblock(block, False)), block_hashes))
blocks.pop(0)
# Create a spending transaction and mine a block which includes it
txid = wallet.send_self_transfer(from_node=node)['txid']
- tx_block = node.generateblock(output=wallet.get_address(), transactions=[txid])
+ tx_block = self.generateblock(node, output=wallet.get_address(), transactions=[txid])
blocks.append(from_hex(CBlock(), node.getblock(tx_block['hash'], False)))
# Serialize the outputs that should be in the UTXO set and add them to
diff --git a/test/functional/feature_versionbits_warning.py b/test/functional/feature_versionbits_warning.py
index a7ec5c48e3..d74ef5e088 100755
--- a/test/functional/feature_versionbits_warning.py
+++ b/test/functional/feature_versionbits_warning.py
@@ -28,6 +28,9 @@ class VersionBitsWarningTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
+ # The experimental syscall sandbox feature (-sandbox) is not compatible with -alertnotify
+ # (which invokes execve).
+ self.disable_syscall_sandbox = True
def setup_network(self):
self.alert_filename = os.path.join(self.options.tmpdir, "alert.txt")
@@ -65,12 +68,12 @@ class VersionBitsWarningTest(BitcoinTestFramework):
node_deterministic_address = node.get_deterministic_priv_key().address
# Mine one period worth of blocks
- node.generatetoaddress(VB_PERIOD, node_deterministic_address)
+ self.generatetoaddress(node, VB_PERIOD, node_deterministic_address)
self.log.info("Check that there is no warning if previous VB_BLOCKS have <VB_THRESHOLD blocks with unknown versionbits version.")
# Build one period of blocks with < VB_THRESHOLD blocks signaling some unknown bit
self.send_blocks_with_version(peer, VB_THRESHOLD - 1, VB_UNKNOWN_VERSION)
- node.generatetoaddress(VB_PERIOD - VB_THRESHOLD + 1, node_deterministic_address)
+ self.generatetoaddress(node, VB_PERIOD - VB_THRESHOLD + 1, node_deterministic_address)
# Check that we're not getting any versionbit-related errors in get*info()
assert not VB_PATTERN.match(node.getmininginfo()["warnings"])
@@ -78,21 +81,21 @@ class VersionBitsWarningTest(BitcoinTestFramework):
# Build one period of blocks with VB_THRESHOLD blocks signaling some unknown bit
self.send_blocks_with_version(peer, VB_THRESHOLD, VB_UNKNOWN_VERSION)
- node.generatetoaddress(VB_PERIOD - VB_THRESHOLD, node_deterministic_address)
+ self.generatetoaddress(node, VB_PERIOD - VB_THRESHOLD, node_deterministic_address)
self.log.info("Check that there is a warning if previous VB_BLOCKS have >=VB_THRESHOLD blocks with unknown versionbits version.")
# Mine a period worth of expected blocks so the generic block-version warning
# is cleared. This will move the versionbit state to ACTIVE.
- node.generatetoaddress(VB_PERIOD, node_deterministic_address)
+ self.generatetoaddress(node, VB_PERIOD, node_deterministic_address)
# Stop-start the node. This is required because bitcoind will only warn once about unknown versions or unknown rules activating.
self.restart_node(0)
# Generating one block guarantees that we'll get out of IBD
- node.generatetoaddress(1, node_deterministic_address)
+ self.generatetoaddress(node, 1, node_deterministic_address)
self.wait_until(lambda: not node.getblockchaininfo()['initialblockdownload'])
# Generating one more block will be enough to generate an error.
- node.generatetoaddress(1, node_deterministic_address)
+ self.generatetoaddress(node, 1, node_deterministic_address)
# Check that get*info() shows the versionbits unknown rules warning
assert WARN_UNKNOWN_RULES_ACTIVE in node.getmininginfo()["warnings"]
assert WARN_UNKNOWN_RULES_ACTIVE in node.getnetworkinfo()["warnings"]
diff --git a/test/functional/interface_bitcoin_cli.py b/test/functional/interface_bitcoin_cli.py
index 4b5363ec49..c28186cde7 100755
--- a/test/functional/interface_bitcoin_cli.py
+++ b/test/functional/interface_bitcoin_cli.py
@@ -57,7 +57,7 @@ def cli_get_info_string_to_dict(cli_get_info_string):
if key == 'Wallet' and value == '""':
# Set default wallet("") to empty string
value = ''
- if key == "Proxy" and value == "N/A":
+ if key == "Proxies" and value == "n/a":
# Set N/A to empty string to represent no proxy
value = ''
cli_get_info[key.strip()] = value.strip()
@@ -77,7 +77,7 @@ class TestBitcoinCli(BitcoinTestFramework):
def run_test(self):
"""Main test logic"""
- self.nodes[0].generate(BLOCKS)
+ self.generate(self.nodes[0], BLOCKS)
self.log.info("Compare responses from getblockchaininfo RPC and `bitcoin-cli getblockchaininfo`")
cli_response = self.nodes[0].cli.getblockchaininfo()
@@ -127,10 +127,17 @@ class TestBitcoinCli(BitcoinTestFramework):
assert_equal(int(cli_get_info['Time offset (s)']), network_info['timeoffset'])
expected_network_info = f"in {network_info['connections_in']}, out {network_info['connections_out']}, total {network_info['connections']}"
assert_equal(cli_get_info["Network"], expected_network_info)
- assert_equal(cli_get_info['Proxy'], network_info['networks'][0]['proxy'])
+ assert_equal(cli_get_info['Proxies'], network_info['networks'][0]['proxy'])
assert_equal(Decimal(cli_get_info['Difficulty']), blockchain_info['difficulty'])
assert_equal(cli_get_info['Chain'], blockchain_info['chain'])
+ self.log.info("Test -getinfo and bitcoin-cli return all proxies")
+ self.restart_node(0, extra_args=["-proxy=127.0.0.1:9050", "-i2psam=127.0.0.1:7656"])
+ network_info = self.nodes[0].getnetworkinfo()
+ cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli()
+ cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
+ assert_equal(cli_get_info["Proxies"], "127.0.0.1:9050 (ipv4, ipv6, onion), 127.0.0.1:7656 (i2p)")
+
if self.is_wallet_compiled():
self.log.info("Test -getinfo and bitcoin-cli getwalletinfo return expected wallet info")
assert_equal(Decimal(cli_get_info['Balance']), BALANCE)
@@ -158,7 +165,7 @@ class TestBitcoinCli(BitcoinTestFramework):
w1.sendtoaddress(w3.getnewaddress(), amounts[2])
# Mine a block to confirm; adds a block reward (50 BTC) to the default wallet.
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.log.info("Test -getinfo with multiple wallets and -rpcwallet returns specified wallet balance")
for i in range(len(wallets)):
@@ -291,7 +298,7 @@ class TestBitcoinCli(BitcoinTestFramework):
assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate', 1, 2, 3).echo)
else:
self.log.info("*** Wallet not compiled; cli getwalletinfo and -getinfo wallet tests skipped")
- self.nodes[0].generate(25) # maintain block parity with the wallet_compiled conditional branch
+ self.generate(self.nodes[0], 25) # maintain block parity with the wallet_compiled conditional branch
self.log.info("Test -version with node stopped")
self.stop_node(0)
diff --git a/test/functional/interface_rest.py b/test/functional/interface_rest.py
index 47c95f5673..e0716fc54a 100755
--- a/test/functional/interface_rest.py
+++ b/test/functional/interface_rest.py
@@ -80,9 +80,9 @@ class RESTTest (BitcoinTestFramework):
# Random address so node1's balance doesn't increase
not_related_address = "2MxqoHEdNQTyYeX1mHcbrrpzgojbosTpCvJ"
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
- self.nodes[1].generatetoaddress(100, not_related_address)
+ self.generatetoaddress(self.nodes[1], 100, not_related_address)
self.sync_all()
assert_equal(self.nodes[0].getbalance(), 50)
@@ -107,7 +107,7 @@ class RESTTest (BitcoinTestFramework):
self.log.info("Query an unspent TXO using the /getutxos URI")
- self.nodes[1].generatetoaddress(1, not_related_address)
+ self.generatetoaddress(self.nodes[1], 1, not_related_address)
self.sync_all()
bb_hash = self.nodes[0].getbestblockhash()
@@ -182,7 +182,7 @@ class RESTTest (BitcoinTestFramework):
json_obj = self.test_rest_request(f"/getutxos/checkmempool/{spent[0]}-{spent[1]}")
assert_equal(len(json_obj['utxos']), 0)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
json_obj = self.test_rest_request(f"/getutxos/{spending[0]}-{spending[1]}")
@@ -203,7 +203,7 @@ class RESTTest (BitcoinTestFramework):
long_uri = '/'.join([f'{txid}-{n_}' for n_ in range(15)])
self.test_rest_request(f"/getutxos/checkmempool/{long_uri}", http_method='POST', status=200)
- self.nodes[0].generate(1) # generate block to not affect upcoming tests
+ self.generate(self.nodes[0], 1) # generate block to not affect upcoming tests
self.sync_all()
self.log.info("Test the /block, /blockhashbyheight and /headers URIs")
@@ -274,7 +274,7 @@ class RESTTest (BitcoinTestFramework):
assert_equal(json_obj[0][key], rpc_block_json[key])
# See if we can get 5 headers in one response
- self.nodes[1].generate(5)
+ self.generate(self.nodes[1], 5)
self.sync_all()
json_obj = self.test_rest_request(f"/headers/5/{bb_hash}")
assert_equal(len(json_obj), 5) # now we should have 5 header objects
@@ -302,7 +302,7 @@ class RESTTest (BitcoinTestFramework):
assert_equal(json_obj[tx]['depends'], txs[i - 1:i])
# Now mine the transactions
- newblockhash = self.nodes[1].generate(1)
+ newblockhash = self.generate(self.nodes[1], 1)
self.sync_all()
# Check if the 3 tx show up in the new block
diff --git a/test/functional/interface_zmq.py b/test/functional/interface_zmq.py
index 6686f77a44..5a11a62ec4 100755
--- a/test/functional/interface_zmq.py
+++ b/test/functional/interface_zmq.py
@@ -24,6 +24,7 @@ from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
)
+from test_framework.netutil import test_ipv6_local
from io import BytesIO
from time import sleep
@@ -119,6 +120,7 @@ class ZMQTest (BitcoinTestFramework):
self.test_mempool_sync()
self.test_reorg()
self.test_multiple_interfaces()
+ self.test_ipv6()
finally:
# Destroy the ZMQ context.
self.log.debug("Destroying ZMQ context")
@@ -126,10 +128,12 @@ class ZMQTest (BitcoinTestFramework):
# Restart node with the specified zmq notifications enabled, subscribe to
# all of them and return the corresponding ZMQSubscriber objects.
- def setup_zmq_test(self, services, *, recv_timeout=60, sync_blocks=True):
+ def setup_zmq_test(self, services, *, recv_timeout=60, sync_blocks=True, ipv6=False):
subscribers = []
for topic, address in services:
socket = self.ctx.socket(zmq.SUB)
+ if ipv6:
+ socket.setsockopt(zmq.IPV6, 1)
subscribers.append(ZMQSubscriber(socket, topic.encode()))
self.restart_node(0, [f"-zmqpub{topic}={address}" for topic, address in services] +
@@ -185,7 +189,7 @@ class ZMQTest (BitcoinTestFramework):
num_blocks = 5
self.log.info(f"Generate {num_blocks} blocks (and {num_blocks} coinbase txes)")
- genhashes = self.nodes[0].generatetoaddress(num_blocks, ADDRESS_BCRT1_UNSPENDABLE)
+ genhashes = self.generatetoaddress(self.nodes[0], num_blocks, ADDRESS_BCRT1_UNSPENDABLE)
self.sync_all()
@@ -226,7 +230,7 @@ class ZMQTest (BitcoinTestFramework):
# Mining the block with this tx should result in second notification
# after coinbase tx notification
- self.nodes[0].generatetoaddress(1, ADDRESS_BCRT1_UNSPENDABLE)
+ self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_UNSPENDABLE)
hashtx.receive()
txid = hashtx.receive()
assert_equal(payment_txid, txid.hex())
@@ -257,14 +261,14 @@ class ZMQTest (BitcoinTestFramework):
# Generate 1 block in nodes[0] with 1 mempool tx and receive all notifications
payment_txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1.0)
- disconnect_block = self.nodes[0].generatetoaddress(1, ADDRESS_BCRT1_UNSPENDABLE)[0]
+ disconnect_block = self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_UNSPENDABLE)[0]
disconnect_cb = self.nodes[0].getblock(disconnect_block)["tx"][0]
assert_equal(self.nodes[0].getbestblockhash(), hashblock.receive().hex())
assert_equal(hashtx.receive().hex(), payment_txid)
assert_equal(hashtx.receive().hex(), disconnect_cb)
# Generate 2 blocks in nodes[1] to a different address to ensure split
- connect_blocks = self.nodes[1].generatetoaddress(2, ADDRESS_BCRT1_P2WSH_OP_TRUE)
+ connect_blocks = self.generatetoaddress(self.nodes[1], 2, ADDRESS_BCRT1_P2WSH_OP_TRUE)
# nodes[0] will reorg chain after connecting back nodes[1]
self.connect_nodes(0, 1)
@@ -308,13 +312,13 @@ class ZMQTest (BitcoinTestFramework):
seq_num = 1
# Generate 1 block in nodes[0] and receive all notifications
- dc_block = self.nodes[0].generatetoaddress(1, ADDRESS_BCRT1_UNSPENDABLE)[0]
+ dc_block = self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_UNSPENDABLE)[0]
# Note: We are not notified of any block transactions, coinbase or mined
assert_equal((self.nodes[0].getbestblockhash(), "C", None), seq.receive_sequence())
# Generate 2 blocks in nodes[1] to a different address to ensure a chain split
- self.nodes[1].generatetoaddress(2, ADDRESS_BCRT1_P2WSH_OP_TRUE)
+ self.generatetoaddress(self.nodes[1], 2, ADDRESS_BCRT1_P2WSH_OP_TRUE)
# nodes[0] will reorg chain after connecting back nodes[1]
self.connect_nodes(0, 1)
@@ -349,7 +353,7 @@ class ZMQTest (BitcoinTestFramework):
# though the mempool sequence number does go up by the number of transactions
# removed from the mempool by the block mining it.
mempool_size = len(self.nodes[0].getrawmempool())
- c_block = self.nodes[0].generatetoaddress(1, ADDRESS_BCRT1_UNSPENDABLE)[0]
+ c_block = self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_UNSPENDABLE)[0]
self.sync_all()
# Make sure the number of mined transactions matches the number of txs out of mempool
mempool_size_delta = mempool_size - len(self.nodes[0].getrawmempool())
@@ -389,7 +393,7 @@ class ZMQTest (BitcoinTestFramework):
# Other things may happen but aren't wallet-deterministic so we don't test for them currently
self.nodes[0].reconsiderblock(best_hash)
- self.nodes[1].generatetoaddress(1, ADDRESS_BCRT1_UNSPENDABLE)
+ self.generatetoaddress(self.nodes[1], 1, ADDRESS_BCRT1_UNSPENDABLE)
self.sync_all()
self.log.info("Evict mempool transaction by block conflict")
@@ -441,7 +445,7 @@ class ZMQTest (BitcoinTestFramework):
# Last tx
assert_equal((orig_txid_2, "A", mempool_seq), seq.receive_sequence())
mempool_seq += 1
- self.nodes[0].generatetoaddress(1, ADDRESS_BCRT1_UNSPENDABLE)
+ self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_UNSPENDABLE)
self.sync_all() # want to make sure we didn't break "consensus" for other tests
def test_mempool_sync(self):
@@ -493,7 +497,7 @@ class ZMQTest (BitcoinTestFramework):
txids.append(self.nodes[0].sendtoaddress(address=self.nodes[0].getnewaddress(), amount=0.1, replaceable=True))
self.nodes[0].bumpfee(txids[-1])
self.sync_all()
- self.nodes[0].generatetoaddress(1, ADDRESS_BCRT1_UNSPENDABLE)
+ self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_UNSPENDABLE)
final_txid = self.nodes[0].sendtoaddress(address=self.nodes[0].getnewaddress(), amount=0.1, replaceable=True)
# 3) Consume ZMQ backlog until we get to "now" for the mempool snapshot
@@ -549,7 +553,7 @@ class ZMQTest (BitcoinTestFramework):
# 5) If you miss a zmq/mempool sequence number, go back to step (2)
- self.nodes[0].generatetoaddress(1, ADDRESS_BCRT1_UNSPENDABLE)
+ self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_UNSPENDABLE)
def test_multiple_interfaces(self):
# Set up two subscribers with different addresses
@@ -562,11 +566,28 @@ class ZMQTest (BitcoinTestFramework):
], sync_blocks=False)
# Generate 1 block in nodes[0] and receive all notifications
- self.nodes[0].generatetoaddress(1, ADDRESS_BCRT1_UNSPENDABLE)
+ self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_UNSPENDABLE)
# Should receive the same block hash on both subscribers
assert_equal(self.nodes[0].getbestblockhash(), subscribers[0].receive().hex())
assert_equal(self.nodes[0].getbestblockhash(), subscribers[1].receive().hex())
+ def test_ipv6(self):
+ if not test_ipv6_local():
+ self.log.info("Skipping IPv6 test, because IPv6 is not supported.")
+ return
+ self.log.info("Testing IPv6")
+ # Set up subscriber using IPv6 loopback address
+ subscribers = self.setup_zmq_test([
+ ("hashblock", "tcp://[::1]:28332")
+ ], ipv6=True)
+
+ # Generate 1 block in nodes[0]
+ self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_UNSPENDABLE)
+
+ # Should receive the same block hash
+ assert_equal(self.nodes[0].getbestblockhash(), subscribers[0].receive().hex())
+
+
if __name__ == '__main__':
ZMQTest().main()
diff --git a/test/functional/mempool_accept.py b/test/functional/mempool_accept.py
index 97d29ff197..2ee440bcb7 100755
--- a/test/functional/mempool_accept.py
+++ b/test/functional/mempool_accept.py
@@ -78,7 +78,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
outputs=[{node.getnewaddress(): 0.3}, {node.getnewaddress(): 49}],
))['hex']
txid_in_block = node.sendrawtransaction(hexstring=raw_tx_in_block, maxfeerate=0)
- node.generate(1)
+ self.generate(node, 1)
self.mempool_size = 0
self.check_mempool_result(
result_expected=[{'txid': txid_in_block, 'allowed': False, 'reject-reason': 'txn-already-known'}],
@@ -172,7 +172,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
outputs=[{node.getnewaddress(): 0.1}]
))['hex']
txid_spend_both = node.sendrawtransaction(hexstring=raw_tx_spend_both, maxfeerate=0)
- node.generate(1)
+ self.generate(node, 1)
self.mempool_size = 0
# Now see if we can add the coins back to the utxo set by sending the exact txs again
self.check_mempool_result(
diff --git a/test/functional/mempool_accept_wtxid.py b/test/functional/mempool_accept_wtxid.py
index 82752f2d70..4767d6db22 100755
--- a/test/functional/mempool_accept_wtxid.py
+++ b/test/functional/mempool_accept_wtxid.py
@@ -44,7 +44,7 @@ class MempoolWtxidTest(BitcoinTestFramework):
self.log.info('Start with empty mempool and 101 blocks')
# The last 100 coinbase transactions are premature
- blockhash = node.generate(101)[0]
+ blockhash = self.generate(node, 101)[0]
txid = node.getblock(blockhash=blockhash, verbosity=2)["tx"][0]["txid"]
assert_equal(node.getmempoolinfo()['size'], 0)
@@ -62,7 +62,7 @@ class MempoolWtxidTest(BitcoinTestFramework):
privkeys = [node.get_deterministic_priv_key().key]
raw_parent = node.signrawtransactionwithkey(hexstring=parent.serialize().hex(), privkeys=privkeys)['hex']
parent_txid = node.sendrawtransaction(hexstring=raw_parent, maxfeerate=0)
- node.generate(1)
+ self.generate(node, 1)
peer_wtxid_relay = node.add_p2p_connection(P2PTxInvStore())
diff --git a/test/functional/mempool_compatibility.py b/test/functional/mempool_compatibility.py
index 9a50647a01..a9f09b1cf8 100755
--- a/test/functional/mempool_compatibility.py
+++ b/test/functional/mempool_compatibility.py
@@ -38,8 +38,8 @@ class MempoolCompatibilityTest(BitcoinTestFramework):
old_node, new_node = self.nodes
new_wallet = MiniWallet(new_node)
- new_wallet.generate(1)
- new_node.generate(COINBASE_MATURITY)
+ self.generate(new_wallet, 1)
+ self.generate(new_node, COINBASE_MATURITY)
# Sync the nodes to ensure old_node has the block that contains the coinbase that new_wallet will spend.
# Otherwise, because coinbases are only valid in a block and not as loose txns, if the nodes aren't synced
# unbroadcasted_tx won't pass old_node's `MemPoolAccept::PreChecks`.
diff --git a/test/functional/mempool_expiry.py b/test/functional/mempool_expiry.py
index 7d1bfef333..942f79e8b0 100755
--- a/test/functional/mempool_expiry.py
+++ b/test/functional/mempool_expiry.py
@@ -36,8 +36,8 @@ class MempoolExpiryTest(BitcoinTestFramework):
self.wallet = MiniWallet(node)
# Add enough mature utxos to the wallet so that all txs spend confirmed coins.
- self.wallet.generate(4)
- node.generate(COINBASE_MATURITY)
+ self.generate(self.wallet, 4)
+ self.generate(node, COINBASE_MATURITY)
# Send a parent transaction that will expire.
parent_txid = self.wallet.send_self_transfer(from_node=node)['txid']
diff --git a/test/functional/mempool_limit.py b/test/functional/mempool_limit.py
index 1b1ac23024..c82dbb3f3d 100755
--- a/test/functional/mempool_limit.py
+++ b/test/functional/mempool_limit.py
@@ -6,8 +6,11 @@
from decimal import Decimal
+from test_framework.blocktools import COINBASE_MATURITY
from test_framework.test_framework import BitcoinTestFramework
-from test_framework.util import assert_equal, assert_greater_than, assert_raises_rpc_error, create_confirmed_utxos, create_lots_of_big_transactions, gen_return_txouts
+from test_framework.util import assert_equal, assert_greater_than, assert_raises_rpc_error, gen_return_txouts
+from test_framework.wallet import MiniWallet
+
class MempoolLimitTest(BitcoinTestFramework):
def set_test_params(self):
@@ -20,55 +23,59 @@ class MempoolLimitTest(BitcoinTestFramework):
]]
self.supports_cli = False
- def skip_test_if_missing_module(self):
- self.skip_if_no_wallet()
+ def send_large_txs(self, node, miniwallet, txouts, fee_rate, tx_batch_size):
+ for _ in range(tx_batch_size):
+ tx = miniwallet.create_self_transfer(from_node=node, fee_rate=fee_rate)['tx']
+ for txout in txouts:
+ tx.vout.append(txout)
+ miniwallet.sendrawtransaction(from_node=node, tx_hex=tx.serialize().hex())
def run_test(self):
txouts = gen_return_txouts()
- relayfee = self.nodes[0].getnetworkinfo()['relayfee']
+ node=self.nodes[0]
+ miniwallet = MiniWallet(node)
+ relayfee = node.getnetworkinfo()['relayfee']
+
+ self.log.info('Check that mempoolminfee is minrelaytxfee')
+ assert_equal(node.getmempoolinfo()['minrelaytxfee'], Decimal('0.00001000'))
+ assert_equal(node.getmempoolinfo()['mempoolminfee'], Decimal('0.00001000'))
- self.log.info('Check that mempoolminfee is minrelytxfee')
- assert_equal(self.nodes[0].getmempoolinfo()['minrelaytxfee'], Decimal('0.00001000'))
- assert_equal(self.nodes[0].getmempoolinfo()['mempoolminfee'], Decimal('0.00001000'))
+ tx_batch_size = 25
+ num_of_batches = 3
+ # Generate UTXOs to flood the mempool
+ # 1 to create a tx initially that will be evicted from the mempool later
+ # 3 batches of multiple transactions with a fee rate much higher than the previous UTXO
+ # And 1 more to verify that this tx does not get added to the mempool with a fee rate less than the mempoolminfee
+ self.generate(miniwallet, 1 + (num_of_batches * tx_batch_size) + 1)
- txids = []
- utxos = create_confirmed_utxos(self, relayfee, self.nodes[0], 91)
+ # Mine 99 blocks so that the UTXOs are allowed to be spent
+ self.generate(node, COINBASE_MATURITY - 1)
self.log.info('Create a mempool tx that will be evicted')
- us0 = utxos.pop()
- inputs = [{ "txid" : us0["txid"], "vout" : us0["vout"]}]
- outputs = {self.nodes[0].getnewaddress() : 0.0001}
- tx = self.nodes[0].createrawtransaction(inputs, outputs)
- self.nodes[0].settxfee(relayfee) # specifically fund this tx with low fee
- txF = self.nodes[0].fundrawtransaction(tx)
- self.nodes[0].settxfee(0) # return to automatic fee selection
- txFS = self.nodes[0].signrawtransactionwithwallet(txF['hex'])
- txid = self.nodes[0].sendrawtransaction(txFS['hex'])
-
- relayfee = self.nodes[0].getnetworkinfo()['relayfee']
- base_fee = relayfee*100
- for i in range (3):
- txids.append([])
- txids[i] = create_lots_of_big_transactions(self.nodes[0], txouts, utxos[30*i:30*i+30], 30, (i+1)*base_fee)
+ tx_to_be_evicted_id = miniwallet.send_self_transfer(from_node=node, fee_rate=relayfee)["txid"]
+
+ # Increase the tx fee rate massively to give the subsequent transactions a higher priority in the mempool
+ base_fee = relayfee * 1000
+
+ self.log.info("Fill up the mempool with txs with higher fee rate")
+ for batch_of_txid in range(num_of_batches):
+ fee_rate=(batch_of_txid + 1) * base_fee
+ self.send_large_txs(node, miniwallet, txouts, fee_rate, tx_batch_size)
self.log.info('The tx should be evicted by now')
- assert txid not in self.nodes[0].getrawmempool()
- txdata = self.nodes[0].gettransaction(txid)
- assert txdata['confirmations'] == 0 #confirmation should still be 0
+ # The number of transactions created should be greater than the ones present in the mempool
+ assert_greater_than(tx_batch_size * num_of_batches, len(node.getrawmempool()))
+ # Initial tx created should not be present in the mempool anymore as it had a lower fee rate
+ assert tx_to_be_evicted_id not in node.getrawmempool()
- self.log.info('Check that mempoolminfee is larger than minrelytxfee')
- assert_equal(self.nodes[0].getmempoolinfo()['minrelaytxfee'], Decimal('0.00001000'))
- assert_greater_than(self.nodes[0].getmempoolinfo()['mempoolminfee'], Decimal('0.00001000'))
+ self.log.info('Check that mempoolminfee is larger than minrelaytxfee')
+ assert_equal(node.getmempoolinfo()['minrelaytxfee'], Decimal('0.00001000'))
+ assert_greater_than(node.getmempoolinfo()['mempoolminfee'], Decimal('0.00001000'))
+ # Deliberately try to create a tx with a fee less than the minimum mempool fee to assert that it does not get added to the mempool
self.log.info('Create a mempool tx that will not pass mempoolminfee')
- us0 = utxos.pop()
- inputs = [{ "txid" : us0["txid"], "vout" : us0["vout"]}]
- outputs = {self.nodes[0].getnewaddress() : 0.0001}
- tx = self.nodes[0].createrawtransaction(inputs, outputs)
- # specifically fund this tx with a fee < mempoolminfee, >= than minrelaytxfee
- txF = self.nodes[0].fundrawtransaction(tx, {'feeRate': relayfee})
- txFS = self.nodes[0].signrawtransactionwithwallet(txF['hex'])
- assert_raises_rpc_error(-26, "mempool min fee not met", self.nodes[0].sendrawtransaction, txFS['hex'])
+ assert_raises_rpc_error(-26, "mempool min fee not met", miniwallet.send_self_transfer, from_node=node, fee_rate=relayfee, mempool_valid=False)
+
if __name__ == '__main__':
MempoolLimitTest().main()
diff --git a/test/functional/mempool_package_limits.py b/test/functional/mempool_package_limits.py
index a54c1d0457..2217628858 100755
--- a/test/functional/mempool_package_limits.py
+++ b/test/functional/mempool_package_limits.py
@@ -26,6 +26,7 @@ from test_framework.wallet import (
bulk_transaction,
create_child_with_parents,
make_chain,
+ DEFAULT_FEE,
)
class MempoolPackageLimitsTest(BitcoinTestFramework):
@@ -40,7 +41,7 @@ class MempoolPackageLimitsTest(BitcoinTestFramework):
self.address = node.get_deterministic_priv_key().address
self.coins = []
# The last 100 coinbase transactions are premature
- for b in node.generatetoaddress(200, self.address)[:100]:
+ for b in self.generatetoaddress(node, 200, self.address)[:100]:
coinbase = node.getblock(blockhash=b, verbosity=2)["tx"][0]
self.coins.append({
"txid": coinbase["txid"],
@@ -50,6 +51,7 @@ class MempoolPackageLimitsTest(BitcoinTestFramework):
self.test_chain_limits()
self.test_desc_count_limits()
+ self.test_desc_count_limits_2()
self.test_anc_count_limits()
self.test_anc_count_limits_2()
self.test_anc_count_limits_bushy()
@@ -83,7 +85,7 @@ class MempoolPackageLimitsTest(BitcoinTestFramework):
assert_equal(txres["package-error"], "package-mempool-limits")
# Clear mempool and check that the package passes now
- node.generate(1)
+ self.generate(node, 1)
assert all([res["allowed"] for res in node.testmempoolaccept(rawtxs=chain_hex)])
def test_chain_limits(self):
@@ -174,6 +176,74 @@ class MempoolPackageLimitsTest(BitcoinTestFramework):
assert_equal(txres["package-error"], "package-mempool-limits")
# Clear mempool and check that the package passes now
+ self.generate(node, 1)
+ assert all([res["allowed"] for res in node.testmempoolaccept(rawtxs=package_hex)])
+
+ def test_desc_count_limits_2(self):
+ """Create a Package with 24 transaction in mempool and 2 transaction in package:
+ M1
+ ^ ^
+ M2 ^
+ . ^
+ . ^
+ . ^
+ M24 ^
+ ^
+ P1
+ ^
+ P2
+ P1 has M1 as a mempool ancestor, P2 has no in-mempool ancestors, but when
+ combined P2 has M1 as an ancestor and M1 exceeds descendant_limits(23 in-mempool
+ descendants + 2 in-package descendants, a total of 26 including itself).
+ """
+
+ node = self.nodes[0]
+ package_hex = []
+ # M1
+ first_coin_a = self.coins.pop()
+ parent_value = (first_coin_a["amount"] - DEFAULT_FEE) / 2 # Deduct reasonable fee and make 2 outputs
+ inputs = [{"txid": first_coin_a["txid"], "vout": 0}]
+ outputs = [{self.address : parent_value}, {ADDRESS_BCRT1_P2WSH_OP_TRUE : parent_value}]
+ rawtx = node.createrawtransaction(inputs, outputs)
+
+ parent_signed = node.signrawtransactionwithkey(hexstring=rawtx, privkeys=self.privkeys)
+ assert parent_signed["complete"]
+ parent_tx = tx_from_hex(parent_signed["hex"])
+ parent_txid = parent_tx.rehash()
+ node.sendrawtransaction(parent_signed["hex"])
+
+ # Chain M2...M24
+ spk = parent_tx.vout[0].scriptPubKey.hex()
+ value = parent_value
+ txid = parent_txid
+ for i in range(23): # M2...M24
+ (tx, txhex, value, spk) = make_chain(node, self.address, self.privkeys, txid, value, 0, spk)
+ txid = tx.rehash()
+ node.sendrawtransaction(txhex)
+
+ # P1
+ value_p1 = (parent_value - DEFAULT_FEE)
+ rawtx_p1 = node.createrawtransaction([{"txid": parent_txid, "vout": 1}], [{self.address : value_p1}])
+ tx_child_p1 = tx_from_hex(rawtx_p1)
+ tx_child_p1.wit.vtxinwit = [CTxInWitness()]
+ tx_child_p1.wit.vtxinwit[0].scriptWitness.stack = [CScript([OP_TRUE])]
+ tx_child_p1_hex = tx_child_p1.serialize().hex()
+ txid_child_p1 = tx_child_p1.rehash()
+ package_hex.append(tx_child_p1_hex)
+ tx_child_p1_spk = tx_child_p1.vout[0].scriptPubKey.hex()
+
+ # P2
+ (_, tx_child_p2_hex, _, _) = make_chain(node, self.address, self.privkeys, txid_child_p1, value_p1, 0, tx_child_p1_spk)
+ package_hex.append(tx_child_p2_hex)
+
+ assert_equal(24, node.getmempoolinfo()["size"])
+ assert_equal(2, len(package_hex))
+ testres = node.testmempoolaccept(rawtxs=package_hex)
+ assert_equal(len(testres), len(package_hex))
+ for txres in testres:
+ assert_equal(txres["package-error"], "package-mempool-limits")
+
+ # Clear mempool and check that the package passes now
node.generate(1)
assert all([res["allowed"] for res in node.testmempoolaccept(rawtxs=package_hex)])
@@ -230,7 +300,7 @@ class MempoolPackageLimitsTest(BitcoinTestFramework):
assert_equal(txres["package-error"], "package-mempool-limits")
# Clear mempool and check that the package passes now
- node.generate(1)
+ self.generate(node, 1)
assert all([res["allowed"] for res in node.testmempoolaccept(rawtxs=package_hex)])
def test_anc_count_limits_2(self):
@@ -288,7 +358,7 @@ class MempoolPackageLimitsTest(BitcoinTestFramework):
assert_equal(txres["package-error"], "package-mempool-limits")
# Clear mempool and check that the package passes now
- node.generate(1)
+ self.generate(node, 1)
assert all([res["allowed"] for res in node.testmempoolaccept(rawtxs=[pc_hex, pd_hex])])
def test_anc_count_limits_bushy(self):
@@ -338,7 +408,7 @@ class MempoolPackageLimitsTest(BitcoinTestFramework):
assert_equal(txres["package-error"], "package-mempool-limits")
# Clear mempool and check that the package passes now
- node.generate(1)
+ self.generate(node, 1)
assert all([res["allowed"] for res in node.testmempoolaccept(rawtxs=package_hex)])
def test_anc_size_limits(self):
@@ -397,7 +467,7 @@ class MempoolPackageLimitsTest(BitcoinTestFramework):
assert_equal(txres["package-error"], "package-mempool-limits")
# Clear mempool and check that the package passes now
- node.generate(1)
+ self.generate(node, 1)
assert all([res["allowed"] for res in node.testmempoolaccept(rawtxs=[pc_hex, pd_hex])])
def test_desc_size_limits(self):
@@ -468,7 +538,7 @@ class MempoolPackageLimitsTest(BitcoinTestFramework):
assert_equal(txres["package-error"], "package-mempool-limits")
# Clear mempool and check that the package passes now
- node.generate(1)
+ self.generate(node, 1)
assert all([res["allowed"] for res in node.testmempoolaccept(rawtxs=package_hex)])
if __name__ == "__main__":
diff --git a/test/functional/mempool_package_onemore.py b/test/functional/mempool_package_onemore.py
index 3ee50f5a8a..69c21f32bc 100755
--- a/test/functional/mempool_package_onemore.py
+++ b/test/functional/mempool_package_onemore.py
@@ -30,7 +30,7 @@ class MempoolPackagesTest(BitcoinTestFramework):
def run_test(self):
# Mine some blocks and have them mature.
- self.nodes[0].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[0], COINBASE_MATURITY + 1)
utxo = self.nodes[0].listunspent(10)
txid = utxo[0]['txid']
vout = utxo[0]['vout']
diff --git a/test/functional/mempool_packages.py b/test/functional/mempool_packages.py
index 173d1d7493..3943bba489 100755
--- a/test/functional/mempool_packages.py
+++ b/test/functional/mempool_packages.py
@@ -14,7 +14,6 @@ from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
chain_transaction,
- satoshi_round,
)
# default limits
@@ -46,17 +45,22 @@ class MempoolPackagesTest(BitcoinTestFramework):
def run_test(self):
# Mine some blocks and have them mature.
peer_inv_store = self.nodes[0].add_p2p_connection(P2PTxInvStore()) # keep track of invs
- self.nodes[0].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[0], COINBASE_MATURITY + 1)
utxo = self.nodes[0].listunspent(10)
txid = utxo[0]['txid']
vout = utxo[0]['vout']
value = utxo[0]['amount']
+ assert 'ancestorcount' not in utxo[0]
+ assert 'ancestorsize' not in utxo[0]
+ assert 'ancestorfees' not in utxo[0]
fee = Decimal("0.0001")
# MAX_ANCESTORS transactions off a confirmed tx should be fine
chain = []
witness_chain = []
- for _ in range(MAX_ANCESTORS):
+ ancestor_vsize = 0
+ ancestor_fees = Decimal(0)
+ for i in range(MAX_ANCESTORS):
(txid, sent_value) = chain_transaction(self.nodes[0], [txid], [0], value, fee, 1)
value = sent_value
chain.append(txid)
@@ -65,6 +69,15 @@ class MempoolPackagesTest(BitcoinTestFramework):
witnesstx = self.nodes[0].decoderawtransaction(fulltx, True)
witness_chain.append(witnesstx['hash'])
+ # Check that listunspent ancestor{count, size, fees} yield the correct results
+ wallet_unspent = self.nodes[0].listunspent(minconf=0)
+ this_unspent = next(utxo_info for utxo_info in wallet_unspent if utxo_info['txid'] == txid)
+ assert_equal(this_unspent['ancestorcount'], i + 1)
+ ancestor_vsize += self.nodes[0].getrawtransaction(txid=txid, verbose=True)['vsize']
+ assert_equal(this_unspent['ancestorsize'], ancestor_vsize)
+ ancestor_fees -= self.nodes[0].gettransaction(txid=txid)['fee']
+ assert_equal(this_unspent['ancestorfees'], ancestor_fees * COIN)
+
# Wait until mempool transactions have passed initial broadcast (sent inv and received getdata)
# Otherwise, getrawmempool may be inconsistent with getmempoolentry if unbroadcast changes in between
peer_inv_store.wait_for_broadcast(witness_chain)
@@ -77,9 +90,9 @@ class MempoolPackagesTest(BitcoinTestFramework):
descendant_fees = 0
descendant_vsize = 0
- ancestor_vsize = sum([mempool[tx]['vsize'] for tx in mempool])
+ assert_equal(ancestor_vsize, sum([mempool[tx]['vsize'] for tx in mempool]))
ancestor_count = MAX_ANCESTORS
- ancestor_fees = sum([mempool[tx]['fee'] for tx in mempool])
+ assert_equal(ancestor_fees, sum([mempool[tx]['fee'] for tx in mempool]))
descendants = []
ancestors = list(chain)
@@ -179,7 +192,7 @@ class MempoolPackagesTest(BitcoinTestFramework):
# Check that prioritising a tx before it's added to the mempool works
# First clear the mempool by mining a block.
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
assert_equal(len(self.nodes[0].getrawmempool()), 0)
# Prioritise a transaction that has been mined, then add it back to the
@@ -195,10 +208,10 @@ class MempoolPackagesTest(BitcoinTestFramework):
entry = self.nodes[0].getmempoolentry(x)
descendant_fees += entry['fee']
if (x == chain[-1]):
- assert_equal(entry['modifiedfee'], entry['fee']+satoshi_round(0.00002))
- assert_equal(entry['fees']['modified'], entry['fee']+satoshi_round(0.00002))
+ assert_equal(entry['modifiedfee'], entry['fee'] + Decimal("0.00002"))
+ assert_equal(entry['fees']['modified'], entry['fee'] + Decimal("0.00002"))
assert_equal(entry['descendantfees'], descendant_fees * COIN + 2000)
- assert_equal(entry['fees']['descendant'], descendant_fees+satoshi_round(0.00002))
+ assert_equal(entry['fees']['descendant'], descendant_fees + Decimal("0.00002"))
# Check that node1's mempool is as expected (-> custom ancestor limit)
mempool0 = self.nodes[0].getrawmempool(False)
@@ -270,7 +283,7 @@ class MempoolPackagesTest(BitcoinTestFramework):
# Test reorg handling
# First, the basics:
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
self.nodes[1].invalidateblock(self.nodes[0].getbestblockhash())
self.nodes[1].reconsiderblock(self.nodes[0].getbestblockhash())
@@ -294,7 +307,7 @@ class MempoolPackagesTest(BitcoinTestFramework):
value = utxo[0]['amount']
vout = utxo[0]['vout']
- send_value = satoshi_round((value - fee)/2)
+ send_value = (value - fee) / 2
inputs = [ {'txid' : txid, 'vout' : vout} ]
outputs = {}
for _ in range(2):
@@ -317,7 +330,7 @@ class MempoolPackagesTest(BitcoinTestFramework):
value = sent_value
# Mine these in a block
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# Now generate tx8, with a big fee
diff --git a/test/functional/mempool_persist.py b/test/functional/mempool_persist.py
index 752b925b92..71a132dca3 100755
--- a/test/functional/mempool_persist.py
+++ b/test/functional/mempool_persist.py
@@ -46,6 +46,7 @@ from test_framework.util import (
assert_greater_than_or_equal,
assert_raises_rpc_error,
)
+from test_framework.wallet import MiniWallet
class MempoolPersistTest(BitcoinTestFramework):
@@ -53,15 +54,26 @@ class MempoolPersistTest(BitcoinTestFramework):
self.num_nodes = 3
self.extra_args = [[], ["-persistmempool=0"], []]
- def skip_test_if_missing_module(self):
- self.skip_if_no_wallet()
-
def run_test(self):
+ self.mini_wallet = MiniWallet(self.nodes[2])
+ self.mini_wallet.rescan_utxos()
+ if self.is_sqlite_compiled():
+ self.nodes[2].createwallet(
+ wallet_name="watch",
+ descriptors=True,
+ disable_private_keys=True,
+ load_on_startup=False,
+ )
+ wallet_watch = self.nodes[2].get_wallet_rpc("watch")
+ assert_equal([{'success': True}], wallet_watch.importdescriptors([{'desc': self.mini_wallet.get_descriptor(), 'timestamp': 0}]))
+
self.log.debug("Send 5 transactions from node2 (to its own address)")
tx_creation_time_lower = int(time.time())
for _ in range(5):
- last_txid = self.nodes[2].sendtoaddress(self.nodes[2].getnewaddress(), Decimal("10"))
- node2_balance = self.nodes[2].getbalance()
+ last_txid = self.mini_wallet.send_self_transfer(from_node=self.nodes[2])["txid"]
+ if self.is_sqlite_compiled():
+ self.nodes[2].syncwithvalidationinterfacequeue() # Flush mempool to wallet
+ node2_balance = wallet_watch.getbalance()
self.sync_all()
tx_creation_time_higher = int(time.time())
@@ -82,16 +94,16 @@ class MempoolPersistTest(BitcoinTestFramework):
assert_equal(total_fee_old, self.nodes[0].getmempoolinfo()['total_fee'])
assert_equal(total_fee_old, sum(v['fees']['base'] for k, v in self.nodes[0].getrawmempool(verbose=True).items()))
- tx_creation_time = self.nodes[0].getmempoolentry(txid=last_txid)['time']
+ last_entry = self.nodes[0].getmempoolentry(txid=last_txid)
+ tx_creation_time = last_entry['time']
assert_greater_than_or_equal(tx_creation_time, tx_creation_time_lower)
assert_greater_than_or_equal(tx_creation_time_higher, tx_creation_time)
# disconnect nodes & make a txn that remains in the unbroadcast set.
self.disconnect_nodes(0, 1)
- assert(len(self.nodes[0].getpeerinfo()) == 0)
- assert(len(self.nodes[0].p2ps) == 0)
- self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), Decimal("12"))
- self.connect_nodes(0, 2)
+ assert_equal(len(self.nodes[0].getpeerinfo()), 0)
+ assert_equal(len(self.nodes[0].p2ps), 0)
+ self.mini_wallet.send_self_transfer(from_node=self.nodes[0])
self.log.debug("Stop-start the nodes. Verify that node0 has the transactions in its mempool and node1 does not. Verify that node2 calculates its balance correctly after loading wallet transactions.")
self.stop_nodes()
@@ -111,17 +123,19 @@ class MempoolPersistTest(BitcoinTestFramework):
fees = self.nodes[0].getmempoolentry(txid=last_txid)['fees']
assert_equal(fees['base'] + Decimal('0.00001000'), fees['modified'])
- self.log.debug('Verify time is loaded correctly')
- assert_equal(tx_creation_time, self.nodes[0].getmempoolentry(txid=last_txid)['time'])
+ self.log.debug('Verify all fields are loaded correctly')
+ assert_equal(last_entry, self.nodes[0].getmempoolentry(txid=last_txid))
# Verify accounting of mempool transactions after restart is correct
- self.nodes[2].syncwithvalidationinterfacequeue() # Flush mempool to wallet
- assert_equal(node2_balance, self.nodes[2].getbalance())
+ if self.is_sqlite_compiled():
+ self.nodes[2].loadwallet("watch")
+ wallet_watch = self.nodes[2].get_wallet_rpc("watch")
+ self.nodes[2].syncwithvalidationinterfacequeue() # Flush mempool to wallet
+ assert_equal(node2_balance, wallet_watch.getbalance())
- # start node0 with wallet disabled so wallet transactions don't get resubmitted
self.log.debug("Stop-start node0 with -persistmempool=0. Verify that it doesn't load its mempool.dat file.")
self.stop_nodes()
- self.start_node(0, extra_args=["-persistmempool=0", "-disablewallet"])
+ self.start_node(0, extra_args=["-persistmempool=0"])
assert self.nodes[0].getmempoolinfo()["loaded"]
assert_equal(len(self.nodes[0].getrawmempool()), 0)
@@ -141,7 +155,7 @@ class MempoolPersistTest(BitcoinTestFramework):
self.log.debug("Stop nodes, make node1 use mempool.dat from node0. Verify it has 6 transactions")
os.rename(mempooldat0, mempooldat1)
self.stop_nodes()
- self.start_node(1, extra_args=[])
+ self.start_node(1, extra_args=["-persistmempool"])
assert self.nodes[1].getmempoolinfo()["loaded"]
assert_equal(len(self.nodes[1].getrawmempool()), 6)
@@ -160,22 +174,22 @@ class MempoolPersistTest(BitcoinTestFramework):
self.start_node(0)
# clear out mempool
- node0.generate(1)
+ self.generate(node0, 1)
# ensure node0 doesn't have any connections
# make a transaction that will remain in the unbroadcast set
- assert(len(node0.getpeerinfo()) == 0)
- assert(len(node0.p2ps) == 0)
- node0.sendtoaddress(self.nodes[1].getnewaddress(), Decimal("12"))
+ assert_equal(len(node0.getpeerinfo()), 0)
+ assert_equal(len(node0.p2ps), 0)
+ self.mini_wallet.send_self_transfer(from_node=node0)
# shutdown, then startup with wallet disabled
- self.stop_nodes()
- self.start_node(0, extra_args=["-disablewallet"])
+ self.restart_node(0, extra_args=["-disablewallet"])
# check that txn gets broadcast due to unbroadcast logic
conn = node0.add_p2p_connection(P2PTxInvStore())
- node0.mockscheduler(16*60) # 15 min + 1 for buffer
+ node0.mockscheduler(16 * 60) # 15 min + 1 for buffer
self.wait_until(lambda: len(conn.get_invs()) == 1)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
MempoolPersistTest().main()
diff --git a/test/functional/mempool_reorg.py b/test/functional/mempool_reorg.py
index b5086e1df1..260b41ef12 100755
--- a/test/functional/mempool_reorg.py
+++ b/test/functional/mempool_reorg.py
@@ -31,7 +31,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
self.log.info("Add 4 coinbase utxos to the miniwallet")
# Block 76 contains the first spendable coinbase txs.
first_block = 76
- wallet.scan_blocks(start=first_block, num=4)
+ wallet.rescan_utxos()
# Three scenarios for re-orging coinbase spends in the memory pool:
# 1. Direct coinbase spend : spend_1
@@ -65,7 +65,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
wallet.sendrawtransaction(from_node=self.nodes[0], tx_hex=spend_2['hex'])
wallet.sendrawtransaction(from_node=self.nodes[0], tx_hex=spend_3['hex'])
self.log.info("Generate a block")
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.log.info("Check that time-locked transaction is still too immature to spend")
assert_raises_rpc_error(-26, 'non-final', self.nodes[0].sendrawtransaction, timelock_tx)
@@ -78,7 +78,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
self.log.info("Broadcast and mine spend_3_1")
spend_3_1_id = self.nodes[0].sendrawtransaction(spend_3_1['hex'])
self.log.info("Generate a block")
- last_block = self.nodes[0].generate(1)
+ last_block = self.generate(self.nodes[0], 1)
# Sync blocks, so that peer 1 gets the block before timelock_tx
# Otherwise, peer 1 would put the timelock_tx in m_recent_rejects
self.sync_all()
diff --git a/test/functional/mempool_resurrect.py b/test/functional/mempool_resurrect.py
index 1b5ca7e15a..4fce07dad3 100755
--- a/test/functional/mempool_resurrect.py
+++ b/test/functional/mempool_resurrect.py
@@ -20,8 +20,8 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
wallet = MiniWallet(node)
# Add enough mature utxos to the wallet so that all txs spend confirmed coins
- wallet.generate(3)
- node.generate(COINBASE_MATURITY)
+ self.generate(wallet, 3)
+ self.generate(node, COINBASE_MATURITY)
# Spend block 1/2/3's coinbase transactions
# Mine a block
@@ -34,9 +34,9 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
# ... make sure all the transactions are confirmed again
blocks = []
spends1_ids = [wallet.send_self_transfer(from_node=node)['txid'] for _ in range(3)]
- blocks.extend(node.generate(1))
+ blocks.extend(self.generate(node, 1))
spends2_ids = [wallet.send_self_transfer(from_node=node)['txid'] for _ in range(3)]
- blocks.extend(node.generate(1))
+ blocks.extend(self.generate(node, 1))
spends_ids = set(spends1_ids + spends2_ids)
@@ -53,7 +53,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
assert_equal(set(node.getrawmempool()), spends_ids)
# Generate another block, they should all get mined
- blocks = node.generate(1)
+ blocks = self.generate(node, 1)
# mempool should be empty, all txns confirmed
assert_equal(set(node.getrawmempool()), set())
confirmed_txns = set(node.getblock(blocks[0])['tx'])
diff --git a/test/functional/mempool_spend_coinbase.py b/test/functional/mempool_spend_coinbase.py
index b900aa0b9c..4e1dd80ba7 100755
--- a/test/functional/mempool_spend_coinbase.py
+++ b/test/functional/mempool_spend_coinbase.py
@@ -28,14 +28,14 @@ class MempoolSpendCoinbaseTest(BitcoinTestFramework):
chain_height = 198
self.nodes[0].invalidateblock(self.nodes[0].getblockhash(chain_height + 1))
assert_equal(chain_height, self.nodes[0].getblockcount())
+ wallet.rescan_utxos()
# Coinbase at height chain_height-100+1 ok in mempool, should
# get mined. Coinbase at height chain_height-100+2 is
# too immature to spend.
- wallet.scan_blocks(start=chain_height - 100 + 1, num=1)
- utxo_mature = wallet.get_utxo()
- wallet.scan_blocks(start=chain_height - 100 + 2, num=1)
- utxo_immature = wallet.get_utxo()
+ coinbase_txid = lambda h: self.nodes[0].getblock(self.nodes[0].getblockhash(h))['tx'][0]
+ utxo_mature = wallet.get_utxo(txid=coinbase_txid(chain_height - 100 + 1))
+ utxo_immature = wallet.get_utxo(txid=coinbase_txid(chain_height - 100 + 2))
spend_mature_id = wallet.send_self_transfer(from_node=self.nodes[0], utxo_to_spend=utxo_mature)["txid"]
@@ -49,7 +49,7 @@ class MempoolSpendCoinbaseTest(BitcoinTestFramework):
assert_equal(self.nodes[0].getrawmempool(), [spend_mature_id])
# mine a block, mature one should get confirmed
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
assert_equal(set(self.nodes[0].getrawmempool()), set())
# ... and now previously immature can be spent:
diff --git a/test/functional/mempool_unbroadcast.py b/test/functional/mempool_unbroadcast.py
index d10b510c6a..4d6379fe86 100755
--- a/test/functional/mempool_unbroadcast.py
+++ b/test/functional/mempool_unbroadcast.py
@@ -109,7 +109,7 @@ class MempoolUnbroadcastTest(BitcoinTestFramework):
# a block
removal_reason = "Removed {} from set of unbroadcast txns before confirmation that txn was sent out".format(txhsh)
with node.assert_debug_log([removal_reason]):
- node.generate(1)
+ self.generate(node, 1)
if __name__ == "__main__":
MempoolUnbroadcastTest().main()
diff --git a/test/functional/mempool_updatefromblock.py b/test/functional/mempool_updatefromblock.py
index 4cd11e9d11..22f136d1a5 100755
--- a/test/functional/mempool_updatefromblock.py
+++ b/test/functional/mempool_updatefromblock.py
@@ -91,7 +91,7 @@ class MempoolUpdateFromBlockTest(BitcoinTestFramework):
if tx_count in n_tx_to_mine:
# The created transactions are mined into blocks by batches.
self.log.info('The batch of {} transactions has been accepted into the mempool.'.format(len(self.nodes[0].getrawmempool())))
- block_hash = self.nodes[0].generate(1)[0]
+ block_hash = self.generate(self.nodes[0], 1)[0]
if not first_block_hash:
first_block_hash = block_hash
assert_equal(len(self.nodes[0].getrawmempool()), 0)
diff --git a/test/functional/mining_basic.py b/test/functional/mining_basic.py
index 23711646a2..f141d201eb 100755
--- a/test/functional/mining_basic.py
+++ b/test/functional/mining_basic.py
@@ -58,7 +58,7 @@ class MiningTest(BitcoinTestFramework):
self.log.info('Create some old blocks')
for t in range(TIME_GENESIS_BLOCK, TIME_GENESIS_BLOCK + 200 * 600, 600):
self.nodes[0].setmocktime(t)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
mining_info = self.nodes[0].getmininginfo()
assert_equal(mining_info['blocks'], 200)
assert_equal(mining_info['currentblocktx'], 0)
@@ -109,7 +109,7 @@ class MiningTest(BitcoinTestFramework):
assert_equal(witness_commitment, script.hex())
# Mine a block to leave initial block download and clear the mempool
- node.generatetoaddress(1, node.get_deterministic_priv_key().address)
+ self.generatetoaddress(node, 1, node.get_deterministic_priv_key().address)
tmpl = node.getblocktemplate(NORMAL_GBT_REQUEST_PARAMS)
self.log.info("getblocktemplate: Test capability advertised")
assert 'proposal' in tmpl['capabilities']
@@ -271,7 +271,7 @@ class MiningTest(BitcoinTestFramework):
assert chain_tip(block.hash, status='active', branchlen=0) in node.getchaintips()
# Building a few blocks should give the same results
- node.generatetoaddress(10, node.get_deterministic_priv_key().address)
+ self.generatetoaddress(node, 10, node.get_deterministic_priv_key().address)
assert_raises_rpc_error(-25, 'time-too-old', lambda: node.submitheader(hexdata=CBlockHeader(bad_block_time).serialize().hex()))
assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=CBlockHeader(bad_block2).serialize().hex()))
node.submitheader(hexdata=CBlockHeader(block).serialize().hex())
diff --git a/test/functional/mining_getblocktemplate_longpoll.py b/test/functional/mining_getblocktemplate_longpoll.py
index 3003627778..0879fb9f2d 100755
--- a/test/functional/mining_getblocktemplate_longpoll.py
+++ b/test/functional/mining_getblocktemplate_longpoll.py
@@ -35,7 +35,7 @@ class GetBlockTemplateLPTest(BitcoinTestFramework):
def run_test(self):
self.log.info("Warning: this test will take about 70 seconds in the best case. Be patient.")
self.log.info("Test that longpollid doesn't change between successive getblocktemplate() invocations if nothing else happens")
- self.nodes[0].generate(10)
+ self.generate(self.nodes[0], 10)
template = self.nodes[0].getblocktemplate({'rules': ['segwit']})
longpollid = template['longpollid']
template2 = self.nodes[0].getblocktemplate({'rules': ['segwit']})
@@ -63,7 +63,7 @@ class GetBlockTemplateLPTest(BitcoinTestFramework):
assert not thr.is_alive()
# Add enough mature utxos to the wallets, so that all txs spend confirmed coins
- self.nodes[0].generate(COINBASE_MATURITY)
+ self.generate(self.nodes[0], COINBASE_MATURITY)
self.sync_blocks()
self.log.info("Test that introducing a new transaction into the mempool will terminate the longpoll")
diff --git a/test/functional/mining_prioritisetransaction.py b/test/functional/mining_prioritisetransaction.py
index d357e2ed47..da85ee54be 100755
--- a/test/functional/mining_prioritisetransaction.py
+++ b/test/functional/mining_prioritisetransaction.py
@@ -75,7 +75,7 @@ class PrioritiseTransactionTest(BitcoinTestFramework):
# also check that a different entry in the cheapest bucket is NOT mined
self.nodes[0].prioritisetransaction(txid=txids[0][0], fee_delta=int(3*base_fee*COIN))
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
mempool = self.nodes[0].getrawmempool()
self.log.info("Assert that prioritised transaction was mined")
@@ -105,7 +105,7 @@ class PrioritiseTransactionTest(BitcoinTestFramework):
# the other high fee transactions. Keep mining until our mempool has
# decreased by all the high fee size that we calculated above.
while (self.nodes[0].getmempoolinfo()['bytes'] > sizes[0] + sizes[1]):
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
# High fee transaction should not have been mined, but other high fee rate
# transactions should have been.
diff --git a/test/functional/p2p_addr_relay.py b/test/functional/p2p_addr_relay.py
index e93698b08e..15b90fa61f 100755
--- a/test/functional/p2p_addr_relay.py
+++ b/test/functional/p2p_addr_relay.py
@@ -6,22 +6,22 @@
Test addr relay
"""
+import random
+import time
+
from test_framework.messages import (
CAddress,
- NODE_NETWORK,
- NODE_WITNESS,
msg_addr,
msg_getaddr,
- msg_verack
+ msg_verack,
)
from test_framework.p2p import (
P2PInterface,
p2p_lock,
+ P2P_SERVICES,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_greater_than
-import random
-import time
class AddrReceiver(P2PInterface):
@@ -96,7 +96,7 @@ class AddrTest(BitcoinTestFramework):
for i in range(num):
addr = CAddress()
addr.time = self.mocktime + i
- addr.nServices = NODE_NETWORK | NODE_WITNESS
+ addr.nServices = P2P_SERVICES
addr.ip = f"123.123.123.{self.counter % 256}"
addr.port = 8333 + i
addrs.append(addr)
@@ -111,7 +111,7 @@ class AddrTest(BitcoinTestFramework):
for i in range(num):
addr = CAddress()
addr.time = self.mocktime + i
- addr.nServices = NODE_NETWORK | NODE_WITNESS
+ addr.nServices = P2P_SERVICES
addr.ip = f"{random.randrange(128,169)}.{random.randrange(1,255)}.{random.randrange(1,255)}.{random.randrange(1,255)}"
addr.port = 8333
addrs.append(addr)
diff --git a/test/functional/p2p_addrfetch.py b/test/functional/p2p_addrfetch.py
index 2a0f6432a9..25efd50040 100755
--- a/test/functional/p2p_addrfetch.py
+++ b/test/functional/p2p_addrfetch.py
@@ -8,14 +8,21 @@ Test p2p addr-fetch connections
import time
-from test_framework.messages import msg_addr, CAddress, NODE_NETWORK, NODE_WITNESS
-from test_framework.p2p import P2PInterface, p2p_lock
+from test_framework.messages import (
+ CAddress,
+ msg_addr,
+)
+from test_framework.p2p import (
+ P2PInterface,
+ p2p_lock,
+ P2P_SERVICES,
+)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
ADDR = CAddress()
ADDR.time = int(time.time())
-ADDR.nServices = NODE_NETWORK | NODE_WITNESS
+ADDR.nServices = P2P_SERVICES
ADDR.ip = "192.0.0.8"
ADDR.port = 18444
diff --git a/test/functional/p2p_addrv2_relay.py b/test/functional/p2p_addrv2_relay.py
index 32c1d42b1c..3833c58680 100755
--- a/test/functional/p2p_addrv2_relay.py
+++ b/test/functional/p2p_addrv2_relay.py
@@ -11,10 +11,11 @@ import time
from test_framework.messages import (
CAddress,
msg_addrv2,
- NODE_NETWORK,
- NODE_WITNESS,
)
-from test_framework.p2p import P2PInterface
+from test_framework.p2p import (
+ P2PInterface,
+ P2P_SERVICES,
+)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
@@ -24,7 +25,7 @@ ADDRS = []
for i in range(10):
addr = CAddress()
addr.time = int(time.time()) + i
- addr.nServices = NODE_NETWORK | NODE_WITNESS
+ addr.nServices = P2P_SERVICES
# Add one I2P address at an arbitrary position.
if i == 5:
addr.net = addr.NET_I2P
diff --git a/test/functional/p2p_blockfilters.py b/test/functional/p2p_blockfilters.py
index 63fc2a98d4..3a4fcc4549 100755
--- a/test/functional/p2p_blockfilters.py
+++ b/test/functional/p2p_blockfilters.py
@@ -56,17 +56,17 @@ class CompactFiltersTest(BitcoinTestFramework):
peer_1 = self.nodes[1].add_p2p_connection(FiltersClient())
# Nodes 0 & 1 share the same first 999 blocks in the chain.
- self.nodes[0].generate(999)
+ self.generate(self.nodes[0], 999)
self.sync_blocks(timeout=600)
# Stale blocks by disconnecting nodes 0 & 1, mining, then reconnecting
self.disconnect_nodes(0, 1)
- stale_block_hash = self.nodes[0].generate(1)[0]
+ stale_block_hash = self.generate(self.nodes[0], 1)[0]
self.nodes[0].syncwithvalidationinterfacequeue()
assert_equal(self.nodes[0].getblockcount(), 1000)
- self.nodes[1].generate(1001)
+ self.generate(self.nodes[1], 1001)
assert_equal(self.nodes[1].getblockcount(), 2000)
# Check that nodes have signalled NODE_COMPACT_FILTERS correctly.
diff --git a/test/functional/p2p_blocksonly.py b/test/functional/p2p_blocksonly.py
index 6409d4ea82..94ae758d46 100755
--- a/test/functional/p2p_blocksonly.py
+++ b/test/functional/p2p_blocksonly.py
@@ -6,8 +6,7 @@
import time
-from test_framework.blocktools import COINBASE_MATURITY
-from test_framework.messages import msg_tx
+from test_framework.messages import msg_tx, msg_inv, CInv, MSG_WTX
from test_framework.p2p import P2PInterface, P2PTxInvStore
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
@@ -16,15 +15,13 @@ from test_framework.wallet import MiniWallet
class P2PBlocksOnly(BitcoinTestFramework):
def set_test_params(self):
- self.setup_clean_chain = True
self.num_nodes = 1
self.extra_args = [["-blocksonly"]]
def run_test(self):
self.miniwallet = MiniWallet(self.nodes[0])
# Add enough mature utxos to the wallet, so that all txs spend confirmed coins
- self.miniwallet.generate(2)
- self.nodes[0].generate(COINBASE_MATURITY)
+ self.miniwallet.rescan_utxos()
self.blocksonly_mode_tests()
self.blocks_relay_conn_tests()
@@ -36,12 +33,19 @@ class P2PBlocksOnly(BitcoinTestFramework):
self.nodes[0].add_p2p_connection(P2PInterface())
tx, txid, wtxid, tx_hex = self.check_p2p_tx_violation()
+ self.log.info('Check that tx invs also violate the protocol')
+ self.nodes[0].add_p2p_connection(P2PInterface())
+ with self.nodes[0].assert_debug_log(['transaction (0000000000000000000000000000000000000000000000000000000000001234) inv sent in violation of protocol, disconnecting peer']):
+ self.nodes[0].p2ps[0].send_message(msg_inv([CInv(t=MSG_WTX, h=0x1234)]))
+ self.nodes[0].p2ps[0].wait_for_disconnect()
+ del self.nodes[0].p2ps[0]
+
self.log.info('Check that txs from rpc are not rejected and relayed to other peers')
tx_relay_peer = self.nodes[0].add_p2p_connection(P2PInterface())
assert_equal(self.nodes[0].getpeerinfo()[0]['relaytxes'], True)
assert_equal(self.nodes[0].testmempoolaccept([tx_hex])[0]['allowed'], True)
- with self.nodes[0].assert_debug_log(['received getdata for: wtx {} peer=1'.format(wtxid)]):
+ with self.nodes[0].assert_debug_log(['received getdata for: wtx {} peer'.format(wtxid)]):
self.nodes[0].sendrawtransaction(tx_hex)
tx_relay_peer.wait_for_tx(txid)
assert_equal(self.nodes[0].getmempoolinfo()['size'], 1)
@@ -73,7 +77,7 @@ class P2PBlocksOnly(BitcoinTestFramework):
self.log.info("Relay-permission peer's transaction is accepted and relayed")
self.nodes[0].disconnect_p2ps()
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
def blocks_relay_conn_tests(self):
self.log.info('Tests with node in normal mode with block-relay-only connections')
@@ -83,7 +87,7 @@ class P2PBlocksOnly(BitcoinTestFramework):
# Ensure we disconnect if a block-relay-only connection sends us a transaction
self.nodes[0].add_outbound_p2p_connection(P2PInterface(), p2p_idx=0, connection_type="block-relay-only")
assert_equal(self.nodes[0].getpeerinfo()[0]['relaytxes'], False)
- _, txid, _, tx_hex = self.check_p2p_tx_violation(index=2)
+ _, txid, _, tx_hex = self.check_p2p_tx_violation()
self.log.info("Check that txs from RPC are not sent to blockrelay connection")
conn = self.nodes[0].add_outbound_p2p_connection(P2PTxInvStore(), p2p_idx=1, connection_type="block-relay-only")
@@ -96,11 +100,9 @@ class P2PBlocksOnly(BitcoinTestFramework):
conn.sync_send_with_ping()
assert(int(txid, 16) not in conn.get_invs())
- def check_p2p_tx_violation(self, index=1):
+ def check_p2p_tx_violation(self):
self.log.info('Check that txs from P2P are rejected and result in disconnect')
- input_txid = self.nodes[0].getblock(self.nodes[0].getblockhash(index), 2)['tx'][0]['txid']
- utxo_to_spend = self.miniwallet.get_utxo(txid=input_txid)
- spendtx = self.miniwallet.create_self_transfer(from_node=self.nodes[0], utxo_to_spend=utxo_to_spend)
+ spendtx = self.miniwallet.create_self_transfer(from_node=self.nodes[0])
with self.nodes[0].assert_debug_log(['transaction sent in violation of protocol peer=0']):
self.nodes[0].p2ps[0].send_message(msg_tx(spendtx['tx']))
diff --git a/test/functional/p2p_compactblocks.py b/test/functional/p2p_compactblocks.py
index b4e662de2e..3f01d552b2 100755
--- a/test/functional/p2p_compactblocks.py
+++ b/test/functional/p2p_compactblocks.py
@@ -165,7 +165,7 @@ class CompactBlocksTest(BitcoinTestFramework):
block = self.build_block_on_tip(self.nodes[0])
self.segwit_node.send_and_ping(msg_no_witness_block(block))
assert int(self.nodes[0].getbestblockhash(), 16) == block.sha256
- self.nodes[0].generatetoaddress(COINBASE_MATURITY, self.nodes[0].getnewaddress(address_type="bech32"))
+ self.generatetoaddress(self.nodes[0], COINBASE_MATURITY, self.nodes[0].getnewaddress(address_type="bech32"))
total_value = block.vtx[0].vout[0].nValue
out_value = total_value // 10
@@ -212,7 +212,7 @@ class CompactBlocksTest(BitcoinTestFramework):
def check_announcement_of_new_block(node, peer, predicate):
peer.clear_block_announcement()
- block_hash = int(node.generate(1)[0], 16)
+ block_hash = int(self.generate(node, 1)[0], 16)
peer.wait_for_block_announcement(block_hash, timeout=30)
assert peer.block_announced
@@ -276,7 +276,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# This test actually causes bitcoind to (reasonably!) disconnect us, so do this last.
def test_invalid_cmpctblock_message(self):
- self.nodes[0].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[0], COINBASE_MATURITY + 1)
block = self.build_block_on_tip(self.nodes[0])
cmpct_block = P2PHeaderAndShortIDs()
@@ -294,7 +294,7 @@ class CompactBlocksTest(BitcoinTestFramework):
version = test_node.cmpct_version
node = self.nodes[0]
# Generate a bunch of transactions.
- node.generate(COINBASE_MATURITY + 1)
+ self.generate(node, COINBASE_MATURITY + 1)
num_transactions = 25
address = node.getnewaddress()
@@ -318,7 +318,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# Now mine a block, and look at the resulting compact block.
test_node.clear_block_announcement()
- block_hash = int(node.generate(1)[0], 16)
+ block_hash = int(self.generate(node, 1)[0], 16)
# Store the raw block in our internal format.
block = from_hex(CBlock(), node.getblock("%064x" % block_hash, False))
@@ -660,7 +660,7 @@ class CompactBlocksTest(BitcoinTestFramework):
new_blocks = []
for _ in range(MAX_CMPCTBLOCK_DEPTH + 1):
test_node.clear_block_announcement()
- new_blocks.append(node.generate(1)[0])
+ new_blocks.append(self.generate(node, 1)[0])
test_node.wait_until(test_node.received_block_announcement, timeout=30)
test_node.clear_block_announcement()
@@ -668,7 +668,7 @@ class CompactBlocksTest(BitcoinTestFramework):
test_node.wait_until(lambda: "cmpctblock" in test_node.last_message, timeout=30)
test_node.clear_block_announcement()
- node.generate(1)
+ self.generate(node, 1)
test_node.wait_until(test_node.received_block_announcement, timeout=30)
test_node.clear_block_announcement()
with p2p_lock:
@@ -844,7 +844,7 @@ class CompactBlocksTest(BitcoinTestFramework):
def run_test(self):
# Get the nodes out of IBD
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
# Setup the p2p connections
self.segwit_node = self.nodes[0].add_p2p_connection(TestP2PConn(cmpct_version=2))
diff --git a/test/functional/p2p_compactblocks_blocksonly.py b/test/functional/p2p_compactblocks_blocksonly.py
new file mode 100755
index 0000000000..5f01fa4dfe
--- /dev/null
+++ b/test/functional/p2p_compactblocks_blocksonly.py
@@ -0,0 +1,130 @@
+#!/usr/bin/env python3
+# Copyright (c) 2021-2021 The Bitcoin Core developers
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+"""Test that a node in blocksonly mode does not request compact blocks."""
+
+from test_framework.messages import (
+ MSG_BLOCK,
+ MSG_CMPCT_BLOCK,
+ MSG_WITNESS_FLAG,
+ CBlock,
+ CBlockHeader,
+ CInv,
+ from_hex,
+ msg_block,
+ msg_getdata,
+ msg_headers,
+ msg_sendcmpct,
+)
+from test_framework.p2p import P2PInterface
+from test_framework.test_framework import BitcoinTestFramework
+from test_framework.util import assert_equal
+
+
+class P2PCompactBlocksBlocksOnly(BitcoinTestFramework):
+ def set_test_params(self):
+ self.extra_args = [["-blocksonly"], [], [], []]
+ self.num_nodes = 4
+
+ def setup_network(self):
+ self.setup_nodes()
+ # Start network with everyone disconnected
+ self.sync_all()
+
+ def build_block_on_tip(self):
+ blockhash = self.generate(self.nodes[2], 1)[0]
+ block_hex = self.nodes[2].getblock(blockhash=blockhash, verbosity=0)
+ block = from_hex(CBlock(), block_hex)
+ block.rehash()
+ return block
+
+ def run_test(self):
+ # Nodes will only request hb compact blocks mode when they're out of IBD
+ for node in self.nodes:
+ assert not node.getblockchaininfo()['initialblockdownload']
+
+ p2p_conn_blocksonly = self.nodes[0].add_p2p_connection(P2PInterface())
+ p2p_conn_high_bw = self.nodes[1].add_p2p_connection(P2PInterface())
+ p2p_conn_low_bw = self.nodes[3].add_p2p_connection(P2PInterface())
+ for conn in [p2p_conn_blocksonly, p2p_conn_high_bw, p2p_conn_low_bw]:
+ assert_equal(conn.message_count['sendcmpct'], 2)
+ conn.send_and_ping(msg_sendcmpct(announce=False, version=2))
+
+ # Nodes:
+ # 0 -> blocksonly
+ # 1 -> high bandwidth
+ # 2 -> miner
+ # 3 -> low bandwidth
+ #
+ # Topology:
+ # p2p_conn_blocksonly ---> node0
+ # p2p_conn_high_bw ---> node1
+ # p2p_conn_low_bw ---> node3
+ # node2 (no connections)
+ #
+ # node2 produces blocks that are passed to the rest of the nodes
+ # through the respective p2p connections.
+
+ self.log.info("Test that -blocksonly nodes do not select peers for BIP152 high bandwidth mode")
+
+ block0 = self.build_block_on_tip()
+
+ # A -blocksonly node should not request BIP152 high bandwidth mode upon
+ # receiving a new valid block at the tip.
+ p2p_conn_blocksonly.send_and_ping(msg_block(block0))
+ assert_equal(int(self.nodes[0].getbestblockhash(), 16), block0.sha256)
+ assert_equal(p2p_conn_blocksonly.message_count['sendcmpct'], 2)
+ assert_equal(p2p_conn_blocksonly.last_message['sendcmpct'].announce, False)
+
+ # A normal node participating in transaction relay should request BIP152
+ # high bandwidth mode upon receiving a new valid block at the tip.
+ p2p_conn_high_bw.send_and_ping(msg_block(block0))
+ assert_equal(int(self.nodes[1].getbestblockhash(), 16), block0.sha256)
+ p2p_conn_high_bw.wait_until(lambda: p2p_conn_high_bw.message_count['sendcmpct'] == 3)
+ assert_equal(p2p_conn_high_bw.last_message['sendcmpct'].announce, True)
+
+ # Don't send a block from the p2p_conn_low_bw so the low bandwidth node
+ # doesn't select it for BIP152 high bandwidth relay.
+ self.nodes[3].submitblock(block0.serialize().hex())
+
+ self.log.info("Test that -blocksonly nodes send getdata(BLOCK) instead"
+ " of getdata(CMPCT) in BIP152 low bandwidth mode")
+
+ block1 = self.build_block_on_tip()
+
+ p2p_conn_blocksonly.send_message(msg_headers(headers=[CBlockHeader(block1)]))
+ p2p_conn_blocksonly.sync_send_with_ping()
+ assert_equal(p2p_conn_blocksonly.last_message['getdata'].inv, [CInv(MSG_BLOCK | MSG_WITNESS_FLAG, block1.sha256)])
+
+ p2p_conn_high_bw.send_message(msg_headers(headers=[CBlockHeader(block1)]))
+ p2p_conn_high_bw.sync_send_with_ping()
+ assert_equal(p2p_conn_high_bw.last_message['getdata'].inv, [CInv(MSG_CMPCT_BLOCK, block1.sha256)])
+
+ self.log.info("Test that getdata(CMPCT) is still sent on BIP152 low bandwidth connections"
+ " when no -blocksonly nodes are involved")
+
+ p2p_conn_low_bw.send_and_ping(msg_headers(headers=[CBlockHeader(block1)]))
+ p2p_conn_low_bw.sync_with_ping()
+ assert_equal(p2p_conn_low_bw.last_message['getdata'].inv, [CInv(MSG_CMPCT_BLOCK, block1.sha256)])
+
+ self.log.info("Test that -blocksonly nodes still serve compact blocks")
+
+ def test_for_cmpctblock(block):
+ if 'cmpctblock' not in p2p_conn_blocksonly.last_message:
+ return False
+ return p2p_conn_blocksonly.last_message['cmpctblock'].header_and_shortids.header.rehash() == block.sha256
+
+ p2p_conn_blocksonly.send_message(msg_getdata([CInv(MSG_CMPCT_BLOCK, block0.sha256)]))
+ p2p_conn_blocksonly.wait_until(lambda: test_for_cmpctblock(block0))
+
+ # Request BIP152 high bandwidth mode from the -blocksonly node.
+ p2p_conn_blocksonly.send_and_ping(msg_sendcmpct(announce=True, version=2))
+
+ block2 = self.build_block_on_tip()
+ self.nodes[0].submitblock(block1.serialize().hex())
+ self.nodes[0].submitblock(block2.serialize().hex())
+ p2p_conn_blocksonly.wait_until(lambda: test_for_cmpctblock(block2))
+
+if __name__ == '__main__':
+ P2PCompactBlocksBlocksOnly().main()
diff --git a/test/functional/p2p_compactblocks_hb.py b/test/functional/p2p_compactblocks_hb.py
index a3d30a6f04..72b3897b4f 100755
--- a/test/functional/p2p_compactblocks_hb.py
+++ b/test/functional/p2p_compactblocks_hb.py
@@ -30,7 +30,7 @@ class CompactBlocksConnectionTest(BitcoinTestFramework):
def relay_block_through(self, peer):
"""Relay a new block through peer peer, and return HB status between 1 and [2,3,4,5]."""
self.connect_nodes(peer, 0)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
self.disconnect_nodes(peer, 0)
status_to = [self.peer_info(1, i)['bip152_hb_to'] for i in range(2, 6)]
@@ -44,7 +44,7 @@ class CompactBlocksConnectionTest(BitcoinTestFramework):
# Connect everyone to node 0, and mine some blocks to get all nodes out of IBD.
for i in range(1, 6):
self.connect_nodes(i, 0)
- self.nodes[0].generate(2)
+ self.generate(self.nodes[0], 2)
self.sync_blocks()
for i in range(1, 6):
self.disconnect_nodes(i, 0)
diff --git a/test/functional/p2p_eviction.py b/test/functional/p2p_eviction.py
index 35bce7c69e..4ccc942164 100755
--- a/test/functional/p2p_eviction.py
+++ b/test/functional/p2p_eviction.py
@@ -53,7 +53,7 @@ class P2PEvict(BitcoinTestFramework):
protected_peers = set() # peers that we expect to be protected from eviction
current_peer = -1
node = self.nodes[0]
- node.generatetoaddress(COINBASE_MATURITY + 1, node.get_deterministic_priv_key().address)
+ self.generatetoaddress(node, COINBASE_MATURITY + 1, node.get_deterministic_priv_key().address)
self.log.info("Create 4 peers and protect them from eviction by sending us a block")
for _ in range(4):
diff --git a/test/functional/p2p_feefilter.py b/test/functional/p2p_feefilter.py
index 0175b9f6c0..60adc2c7fa 100755
--- a/test/functional/p2p_feefilter.py
+++ b/test/functional/p2p_feefilter.py
@@ -81,8 +81,8 @@ class FeeFilterTest(BitcoinTestFramework):
node0 = self.nodes[0]
miniwallet = MiniWallet(node1)
# Add enough mature utxos to the wallet, so that all txs spend confirmed coins
- miniwallet.generate(5)
- node1.generate(COINBASE_MATURITY)
+ self.generate(miniwallet, 5)
+ self.generate(node1, COINBASE_MATURITY)
conn = self.nodes[0].add_p2p_connection(TestP2PConn())
diff --git a/test/functional/p2p_filter.py b/test/functional/p2p_filter.py
index 359cfb9c34..0d8c298bea 100755
--- a/test/functional/p2p_filter.py
+++ b/test/functional/p2p_filter.py
@@ -8,6 +8,7 @@ Test BIP 37
from test_framework.messages import (
CInv,
+ COIN,
MAX_BLOOM_FILTER_SIZE,
MAX_BLOOM_HASH_FUNCS,
MSG_BLOCK,
@@ -28,11 +29,15 @@ from test_framework.p2p import (
)
from test_framework.script import MAX_SCRIPT_ELEMENT_SIZE
from test_framework.test_framework import BitcoinTestFramework
+from test_framework.wallet import (
+ MiniWallet,
+ random_p2wpkh,
+)
class P2PBloomFilter(P2PInterface):
# This is a P2SH watch-only wallet
- watch_script_pubkey = 'a914ffffffffffffffffffffffffffffffffffffffff87'
+ watch_script_pubkey = bytes.fromhex('a914ffffffffffffffffffffffffffffffffffffffff87')
# The initial filter (n=10, fp=0.000001) with just the above scriptPubKey added
watch_filter_init = msg_filterload(
data=
@@ -93,8 +98,9 @@ class FilterTest(BitcoinTestFramework):
'-whitelist=noban@127.0.0.1', # immediate tx relay
]]
- def skip_test_if_missing_module(self):
- self.skip_if_no_wallet()
+ def generatetoscriptpubkey(self, scriptpubkey):
+ """Helper to generate a single block to the given scriptPubKey."""
+ return self.generatetodescriptor(self.nodes[0], 1, f'raw({scriptpubkey.hex()})')[0]
def test_size_limits(self, filter_peer):
self.log.info('Check that too large filter is rejected')
@@ -130,8 +136,7 @@ class FilterTest(BitcoinTestFramework):
filter_peer = P2PBloomFilter()
self.log.debug("Create a tx relevant to the peer before connecting")
- filter_address = self.nodes[0].decodescript(filter_peer.watch_script_pubkey)['address']
- txid = self.nodes[0].sendtoaddress(filter_address, 90)
+ txid, _ = self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=filter_peer.watch_script_pubkey, amount=9 * COIN)
self.log.debug("Send a mempool msg after connecting and check that the tx is received")
self.nodes[0].add_p2p_connection(filter_peer)
@@ -142,59 +147,57 @@ class FilterTest(BitcoinTestFramework):
def test_frelay_false(self, filter_peer):
self.log.info("Check that a node with fRelay set to false does not receive invs until the filter is set")
filter_peer.tx_received = False
- filter_address = self.nodes[0].decodescript(filter_peer.watch_script_pubkey)['address']
- self.nodes[0].sendtoaddress(filter_address, 90)
+ self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=filter_peer.watch_script_pubkey, amount=9 * COIN)
# Sync to make sure the reason filter_peer doesn't receive the tx is not p2p delays
filter_peer.sync_with_ping()
assert not filter_peer.tx_received
# Clear the mempool so that this transaction does not impact subsequent tests
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
def test_filter(self, filter_peer):
# Set the bloomfilter using filterload
filter_peer.send_and_ping(filter_peer.watch_filter_init)
# If fRelay is not already True, sending filterload sets it to True
assert self.nodes[0].getpeerinfo()[0]['relaytxes']
- filter_address = self.nodes[0].decodescript(filter_peer.watch_script_pubkey)['address']
self.log.info('Check that we receive merkleblock and tx if the filter matches a tx in a block')
- block_hash = self.nodes[0].generatetoaddress(1, filter_address)[0]
+ block_hash = self.generatetoscriptpubkey(filter_peer.watch_script_pubkey)
txid = self.nodes[0].getblock(block_hash)['tx'][0]
filter_peer.wait_for_merkleblock(block_hash)
filter_peer.wait_for_tx(txid)
self.log.info('Check that we only receive a merkleblock if the filter does not match a tx in a block')
filter_peer.tx_received = False
- block_hash = self.nodes[0].generatetoaddress(1, self.nodes[0].getnewaddress())[0]
+ block_hash = self.generatetoscriptpubkey(random_p2wpkh())
filter_peer.wait_for_merkleblock(block_hash)
assert not filter_peer.tx_received
self.log.info('Check that we not receive a tx if the filter does not match a mempool tx')
filter_peer.merkleblock_received = False
filter_peer.tx_received = False
- self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 90)
+ self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=random_p2wpkh(), amount=7 * COIN)
filter_peer.sync_send_with_ping()
assert not filter_peer.merkleblock_received
assert not filter_peer.tx_received
self.log.info('Check that we receive a tx if the filter matches a mempool tx')
filter_peer.merkleblock_received = False
- txid = self.nodes[0].sendtoaddress(filter_address, 90)
+ txid, _ = self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=filter_peer.watch_script_pubkey, amount=9 * COIN)
filter_peer.wait_for_tx(txid)
assert not filter_peer.merkleblock_received
self.log.info('Check that after deleting filter all txs get relayed again')
filter_peer.send_and_ping(msg_filterclear())
for _ in range(5):
- txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 7)
+ txid, _ = self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=random_p2wpkh(), amount=7 * COIN)
filter_peer.wait_for_tx(txid)
self.log.info('Check that request for filtered blocks is ignored if no filter is set')
filter_peer.merkleblock_received = False
filter_peer.tx_received = False
with self.nodes[0].assert_debug_log(expected_msgs=['received getdata']):
- block_hash = self.nodes[0].generatetoaddress(1, self.nodes[0].getnewaddress())[0]
+ block_hash = self.generatetoscriptpubkey(random_p2wpkh())
filter_peer.wait_for_inv([CInv(MSG_BLOCK, int(block_hash, 16))])
filter_peer.sync_with_ping()
assert not filter_peer.merkleblock_received
@@ -210,6 +213,9 @@ class FilterTest(BitcoinTestFramework):
self.nodes[0].disconnect_p2ps()
def run_test(self):
+ self.wallet = MiniWallet(self.nodes[0])
+ self.wallet.rescan_utxos()
+
filter_peer = self.nodes[0].add_p2p_connection(P2PBloomFilter())
self.log.info('Test filter size limits')
self.test_size_limits(filter_peer)
diff --git a/test/functional/p2p_fingerprint.py b/test/functional/p2p_fingerprint.py
index 469d66a851..2962dc8085 100755
--- a/test/functional/p2p_fingerprint.py
+++ b/test/functional/p2p_fingerprint.py
@@ -69,7 +69,7 @@ class P2PFingerprintTest(BitcoinTestFramework):
self.nodes[0].setmocktime(int(time.time()) - 60 * 24 * 60 * 60)
# Generating a chain of 10 blocks
- block_hashes = self.nodes[0].generatetoaddress(10, self.nodes[0].get_deterministic_priv_key().address)
+ block_hashes = self.generatetoaddress(self.nodes[0], 10, self.nodes[0].get_deterministic_priv_key().address)
# Create longer chain starting 2 blocks before current tip
height = len(block_hashes) - 2
@@ -98,7 +98,7 @@ class P2PFingerprintTest(BitcoinTestFramework):
# Longest chain is extended so stale is much older than chain tip
self.nodes[0].setmocktime(0)
- block_hash = int(self.nodes[0].generatetoaddress(1, self.nodes[0].get_deterministic_priv_key().address)[-1], 16)
+ block_hash = int(self.generatetoaddress(self.nodes[0], 1, self.nodes[0].get_deterministic_priv_key().address)[-1], 16)
assert_equal(self.nodes[0].getblockcount(), 14)
node0.wait_for_block(block_hash, timeout=3)
diff --git a/test/functional/p2p_ibd_txrelay.py b/test/functional/p2p_ibd_txrelay.py
index c3e758b021..c35053d9d4 100755
--- a/test/functional/p2p_ibd_txrelay.py
+++ b/test/functional/p2p_ibd_txrelay.py
@@ -29,7 +29,7 @@ class P2PIBDTxRelayTest(BitcoinTestFramework):
self.wait_until(lambda: all(peer['minfeefilter'] == MAX_FEE_FILTER for peer in node.getpeerinfo()))
# Come out of IBD by generating a block
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
self.log.info("Check that nodes reset minfilter after coming out of IBD")
diff --git a/test/functional/p2p_invalid_block.py b/test/functional/p2p_invalid_block.py
index 91666d0f08..875ab52db4 100755
--- a/test/functional/p2p_invalid_block.py
+++ b/test/functional/p2p_invalid_block.py
@@ -51,7 +51,7 @@ class InvalidBlockRequestTest(BitcoinTestFramework):
peer.send_blocks_and_test([block1], node, success=True)
self.log.info("Mature the block.")
- node.generatetoaddress(100, node.get_deterministic_priv_key().address)
+ self.generatetoaddress(node, 100, node.get_deterministic_priv_key().address)
best_block = node.getblock(node.getbestblockhash())
tip = int(node.getbestblockhash(), 16)
diff --git a/test/functional/p2p_invalid_locator.py b/test/functional/p2p_invalid_locator.py
index f884cf90ff..a586b48d4c 100755
--- a/test/functional/p2p_invalid_locator.py
+++ b/test/functional/p2p_invalid_locator.py
@@ -16,7 +16,7 @@ class InvalidLocatorTest(BitcoinTestFramework):
def run_test(self):
node = self.nodes[0] # convenience reference to the node
- node.generatetoaddress(1, node.get_deterministic_priv_key().address) # Get node out of IBD
+ self.generatetoaddress(node, 1, node.get_deterministic_priv_key().address) # Get node out of IBD
self.log.info('Test max locator size')
block_count = node.getblockcount()
diff --git a/test/functional/p2p_invalid_tx.py b/test/functional/p2p_invalid_tx.py
index 8fef2d173f..0a3ae23f58 100755
--- a/test/functional/p2p_invalid_tx.py
+++ b/test/functional/p2p_invalid_tx.py
@@ -64,7 +64,7 @@ class InvalidTxRequestTest(BitcoinTestFramework):
node.p2ps[0].send_blocks_and_test([block], node, success=True)
self.log.info("Mature the block.")
- self.nodes[0].generatetoaddress(100, self.nodes[0].get_deterministic_priv_key().address)
+ self.generatetoaddress(self.nodes[0], 100, self.nodes[0].get_deterministic_priv_key().address)
# Iterate through a list of known invalid transaction types, ensuring each is
# rejected. Some are consensus invalid and some just violate policy.
diff --git a/test/functional/p2p_leak.py b/test/functional/p2p_leak.py
index f1538e8ac7..de58e07aad 100755
--- a/test/functional/p2p_leak.py
+++ b/test/functional/p2p_leak.py
@@ -133,7 +133,7 @@ class P2PLeakTest(BitcoinTestFramework):
pre_wtxidrelay_peer.wait_until(lambda: pre_wtxidrelay_peer.version_received)
# Mine a block and make sure that it's not sent to the connected peers
- self.nodes[0].generate(nblocks=1)
+ self.generate(self.nodes[0], nblocks=1)
# Give the node enough time to possibly leak out a message
time.sleep(PEER_TIMEOUT + 2)
diff --git a/test/functional/p2p_leak_tx.py b/test/functional/p2p_leak_tx.py
index 9a4ceb86ae..9b80e1b877 100755
--- a/test/functional/p2p_leak_tx.py
+++ b/test/functional/p2p_leak_tx.py
@@ -27,8 +27,8 @@ class P2PLeakTxTest(BitcoinTestFramework):
gen_node = self.nodes[0] # The block and tx generating node
miniwallet = MiniWallet(gen_node)
# Add enough mature utxos to the wallet, so that all txs spend confirmed coins
- miniwallet.generate(1)
- gen_node.generate(COINBASE_MATURITY)
+ self.generate(miniwallet, 1)
+ self.generate(gen_node, COINBASE_MATURITY)
inbound_peer = self.nodes[0].add_p2p_connection(P2PNode()) # An "attacking" inbound peer
diff --git a/test/functional/p2p_node_network_limited.py b/test/functional/p2p_node_network_limited.py
index 8d95f155c8..e491fe7e07 100755
--- a/test/functional/p2p_node_network_limited.py
+++ b/test/functional/p2p_node_network_limited.py
@@ -59,7 +59,7 @@ class NodeNetworkLimitedTest(BitcoinTestFramework):
self.log.info("Mine enough blocks to reach the NODE_NETWORK_LIMITED range.")
self.connect_nodes(0, 1)
- blocks = self.nodes[1].generatetoaddress(292, self.nodes[1].get_deterministic_priv_key().address)
+ blocks = self.generatetoaddress(self.nodes[1], 292, self.nodes[1].get_deterministic_priv_key().address)
self.sync_blocks([self.nodes[0], self.nodes[1]])
self.log.info("Make sure we can max retrieve block at tip-288.")
@@ -101,7 +101,7 @@ class NodeNetworkLimitedTest(BitcoinTestFramework):
self.disconnect_all()
# mine 10 blocks on node 0 (pruned node)
- self.nodes[0].generatetoaddress(10, self.nodes[0].get_deterministic_priv_key().address)
+ self.generatetoaddress(self.nodes[0], 10, self.nodes[0].get_deterministic_priv_key().address)
# connect node1 (non pruned) with node0 (pruned) and check if the can sync
self.connect_nodes(0, 1)
diff --git a/test/functional/p2p_permissions.py b/test/functional/p2p_permissions.py
index 8b285907c5..32f2ea14e1 100755
--- a/test/functional/p2p_permissions.py
+++ b/test/functional/p2p_permissions.py
@@ -93,7 +93,7 @@ class P2PPermissionsTests(BitcoinTestFramework):
self.nodes[1].assert_start_raises_init_error(["-whitebind=noban@127.0.0.1/10"], "Cannot resolve -whitebind address", match=ErrorMatch.PARTIAL_REGEX)
def check_tx_relay(self):
- block_op_true = self.nodes[0].getblock(self.nodes[0].generatetoaddress(100, ADDRESS_BCRT1_P2WSH_OP_TRUE)[0])
+ block_op_true = self.nodes[0].getblock(self.generatetoaddress(self.nodes[0], 100, ADDRESS_BCRT1_P2WSH_OP_TRUE)[0])
self.sync_all()
self.log.debug("Create a connection from a forcerelay peer that rebroadcasts raw txs")
diff --git a/test/functional/p2p_segwit.py b/test/functional/p2p_segwit.py
index e5093855ff..4e21d08e5c 100755
--- a/test/functional/p2p_segwit.py
+++ b/test/functional/p2p_segwit.py
@@ -43,6 +43,7 @@ from test_framework.messages import (
from test_framework.p2p import (
P2PInterface,
p2p_lock,
+ P2P_SERVICES,
)
from test_framework.script import (
CScript,
@@ -71,6 +72,7 @@ from test_framework.script import (
hash160,
)
from test_framework.script_util import (
+ key_to_p2pk_script,
key_to_p2wpkh_script,
keyhash_to_p2pkh_script,
script_to_p2sh_script,
@@ -83,10 +85,6 @@ from test_framework.util import (
assert_raises_rpc_error,
)
-# The versionbit bit used to signal activation of SegWit
-VB_WITNESS_BIT = 1
-VB_TOP_BITS = 0x20000000
-
MAX_SIGOP_COST = 80000
SEGWIT_HEIGHT = 120
@@ -196,8 +194,8 @@ class SegWitTest(BitcoinTestFramework):
self.num_nodes = 2
# This test tests SegWit both pre and post-activation, so use the normal BIP9 activation.
self.extra_args = [
- ["-acceptnonstdtxn=1", "-segwitheight={}".format(SEGWIT_HEIGHT), "-whitelist=noban@127.0.0.1"],
- ["-acceptnonstdtxn=0", "-segwitheight={}".format(SEGWIT_HEIGHT)],
+ ["-acceptnonstdtxn=1", f"-testactivationheight=segwit@{SEGWIT_HEIGHT}", "-whitelist=noban@127.0.0.1"],
+ ["-acceptnonstdtxn=0", f"-testactivationheight=segwit@{SEGWIT_HEIGHT}"],
]
self.supports_cli = False
@@ -206,13 +204,13 @@ class SegWitTest(BitcoinTestFramework):
# Helper functions
- def build_next_block(self, version=4):
+ def build_next_block(self):
"""Build a block on top of node0's tip."""
tip = self.nodes[0].getbestblockhash()
height = self.nodes[0].getblockcount() + 1
block_time = self.nodes[0].getblockheader(tip)["mediantime"] + 1
block = create_block(int(tip, 16), create_coinbase(height), block_time)
- block.nVersion = version
+ block.nVersion = 4
block.rehash()
return block
@@ -224,14 +222,14 @@ class SegWitTest(BitcoinTestFramework):
def run_test(self):
# Setup the p2p connections
- # self.test_node sets NODE_WITNESS|NODE_NETWORK
- self.test_node = self.nodes[0].add_p2p_connection(TestP2PConn(), services=NODE_NETWORK | NODE_WITNESS)
+ # self.test_node sets P2P_SERVICES, i.e. NODE_WITNESS | NODE_NETWORK
+ self.test_node = self.nodes[0].add_p2p_connection(TestP2PConn(), services=P2P_SERVICES)
# self.old_node sets only NODE_NETWORK
self.old_node = self.nodes[0].add_p2p_connection(TestP2PConn(), services=NODE_NETWORK)
# self.std_node is for testing node1 (fRequireStandard=true)
- self.std_node = self.nodes[1].add_p2p_connection(TestP2PConn(), services=NODE_NETWORK | NODE_WITNESS)
+ self.std_node = self.nodes[1].add_p2p_connection(TestP2PConn(), services=P2P_SERVICES)
# self.std_wtx_node is for testing node1 with wtxid relay
- self.std_wtx_node = self.nodes[1].add_p2p_connection(TestP2PConn(wtxidrelay=True), services=NODE_NETWORK | NODE_WITNESS)
+ self.std_wtx_node = self.nodes[1].add_p2p_connection(TestP2PConn(wtxidrelay=True), services=P2P_SERVICES)
assert self.test_node.nServices & NODE_WITNESS != 0
@@ -298,12 +296,12 @@ class SegWitTest(BitcoinTestFramework):
# Mine a block with an anyone-can-spend coinbase,
# let it mature, then try to spend it.
- block = self.build_next_block(version=1)
+ block = self.build_next_block()
block.solve()
self.test_node.send_and_ping(msg_no_witness_block(block)) # make sure the block was processed
txid = block.vtx[0].sha256
- self.nodes[0].generate(99) # let the block mature
+ self.generate(self.nodes[0], 99) # let the block mature
# Create a transaction that spends the coinbase
tx = CTransaction()
@@ -319,7 +317,7 @@ class SegWitTest(BitcoinTestFramework):
assert tx.hash in self.nodes[0].getrawmempool()
# Save this transaction for later
self.utxo.append(UTXO(tx.sha256, 0, 49 * 100000000))
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
@subtest # type: ignore
def test_unnecessary_witness_before_segwit_activation(self):
@@ -336,8 +334,8 @@ class SegWitTest(BitcoinTestFramework):
tx.rehash()
assert tx.sha256 != tx.calc_sha256(with_witness=True)
- # Construct a segwit-signaling block that includes the transaction.
- block = self.build_next_block(version=(VB_TOP_BITS | (1 << VB_WITNESS_BIT)))
+ # Construct a block that includes the transaction.
+ block = self.build_next_block()
self.update_witness_block_with_transactions(block, [tx])
# Sending witness data before activation is not allowed (anti-spam
# rule).
@@ -364,7 +362,7 @@ class SegWitTest(BitcoinTestFramework):
# test_node has set NODE_WITNESS, so all getdata requests should be for
# witness blocks.
# Test announcing a block via inv results in a getdata, and that
- # announcing a version 4 or random VB block with a header results in a getdata
+ # announcing a block with a header results in a getdata
block1 = self.build_next_block()
block1.solve()
@@ -372,19 +370,13 @@ class SegWitTest(BitcoinTestFramework):
assert self.test_node.last_message["getdata"].inv[0].type == blocktype
test_witness_block(self.nodes[0], self.test_node, block1, True)
- block2 = self.build_next_block(version=4)
+ block2 = self.build_next_block()
block2.solve()
self.test_node.announce_block_and_wait_for_getdata(block2, use_header=True)
assert self.test_node.last_message["getdata"].inv[0].type == blocktype
test_witness_block(self.nodes[0], self.test_node, block2, True)
- block3 = self.build_next_block(version=(VB_TOP_BITS | (1 << 15)))
- block3.solve()
- self.test_node.announce_block_and_wait_for_getdata(block3, use_header=True)
- assert self.test_node.last_message["getdata"].inv[0].type == blocktype
- test_witness_block(self.nodes[0], self.test_node, block3, True)
-
# Check that we can getdata for witness blocks or regular blocks,
# and the right thing happens.
if not self.segwit_active:
@@ -429,7 +421,7 @@ class SegWitTest(BitcoinTestFramework):
assert_equal(rpc_details["weight"], block.get_weight())
# Upgraded node should not ask for blocks from unupgraded
- block4 = self.build_next_block(version=4)
+ block4 = self.build_next_block()
block4.solve()
self.old_node.getdataset = set()
@@ -555,7 +547,7 @@ class SegWitTest(BitcoinTestFramework):
test_transaction_acceptance(self.nodes[0], self.test_node, tx, with_witness=False, accepted=True)
# Cleanup: mine the first transaction and update utxo
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
assert_equal(len(self.nodes[0].getrawmempool()), 0)
self.utxo.pop(0)
@@ -580,7 +572,7 @@ class SegWitTest(BitcoinTestFramework):
# Mine it on test_node to create the confirmed output.
test_transaction_acceptance(self.nodes[0], self.test_node, p2sh_tx, with_witness=True, accepted=True)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
# Now test standardness of v0 P2WSH outputs.
@@ -653,7 +645,7 @@ class SegWitTest(BitcoinTestFramework):
)
test_transaction_acceptance(self.nodes[0], self.test_node, tx3, with_witness=True, accepted=True)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
self.utxo.pop(0)
self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue))
@@ -664,9 +656,9 @@ class SegWitTest(BitcoinTestFramework):
"""Mine enough blocks to activate segwit."""
assert not softfork_active(self.nodes[0], 'segwit')
height = self.nodes[0].getblockcount()
- self.nodes[0].generate(SEGWIT_HEIGHT - height - 2)
+ self.generate(self.nodes[0], SEGWIT_HEIGHT - height - 2)
assert not softfork_active(self.nodes[0], 'segwit')
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
assert softfork_active(self.nodes[0], 'segwit')
self.segwit_active = True
@@ -1298,7 +1290,7 @@ class SegWitTest(BitcoinTestFramework):
assert vsize != raw_tx["size"]
# Cleanup: mine the transactions and update utxo for next test
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
assert_equal(len(self.nodes[0].getrawmempool()), 0)
self.utxo.pop(0)
@@ -1348,7 +1340,7 @@ class SegWitTest(BitcoinTestFramework):
self.utxo.pop(0)
temp_utxo.append(UTXO(tx.sha256, 0, tx.vout[0].nValue))
- self.nodes[0].generate(1) # Mine all the transactions
+ self.generate(self.nodes[0], 1) # Mine all the transactions
self.sync_blocks()
assert len(self.nodes[0].getrawmempool()) == 0
@@ -1419,14 +1411,14 @@ class SegWitTest(BitcoinTestFramework):
spend_tx.rehash()
# Now test a premature spend.
- self.nodes[0].generate(98)
+ self.generate(self.nodes[0], 98)
self.sync_blocks()
block2 = self.build_next_block()
self.update_witness_block_with_transactions(block2, [spend_tx])
test_witness_block(self.nodes[0], self.test_node, block2, accepted=False)
# Advancing one more block should allow the spend.
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
block2 = self.build_next_block()
self.update_witness_block_with_transactions(block2, [spend_tx])
test_witness_block(self.nodes[0], self.test_node, block2, accepted=True)
@@ -1464,7 +1456,7 @@ class SegWitTest(BitcoinTestFramework):
# Now try to spend it. Send it to a P2WSH output, which we'll
# use in the next test.
- witness_script = CScript([pubkey, CScriptOp(OP_CHECKSIG)])
+ witness_script = key_to_p2pk_script(pubkey)
script_wsh = script_to_p2wsh_script(witness_script)
tx2 = CTransaction()
@@ -1542,7 +1534,7 @@ class SegWitTest(BitcoinTestFramework):
key.generate()
pubkey = key.get_pubkey().get_bytes()
- witness_script = CScript([pubkey, CScriptOp(OP_CHECKSIG)])
+ witness_script = key_to_p2pk_script(pubkey)
script_pubkey = script_to_p2wsh_script(witness_script)
# First create a witness output for use in the tests.
@@ -1733,7 +1725,7 @@ class SegWitTest(BitcoinTestFramework):
tx.vout.append(CTxOut(self.utxo[0].nValue - 1000, script_pubkey))
tx.rehash()
test_transaction_acceptance(self.nodes[0], self.test_node, tx, False, True)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
# We'll add an unnecessary witness to this transaction that would cause
@@ -1762,7 +1754,7 @@ class SegWitTest(BitcoinTestFramework):
test_transaction_acceptance(self.nodes[0], self.test_node, tx2, False, True)
test_transaction_acceptance(self.nodes[0], self.test_node, tx3, False, True)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
# Update our utxo list; we spent the first entry.
@@ -1797,7 +1789,7 @@ class SegWitTest(BitcoinTestFramework):
txid = tx.sha256
test_transaction_acceptance(self.nodes[0], self.test_node, tx, with_witness=False, accepted=True)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
# Creating transactions for tests
@@ -1860,7 +1852,7 @@ class SegWitTest(BitcoinTestFramework):
test_transaction_acceptance(self.nodes[1], self.std_node, p2sh_txs[3], True, False, 'bad-witness-nonstandard')
test_transaction_acceptance(self.nodes[0], self.test_node, p2sh_txs[3], True, True)
- self.nodes[0].generate(1) # Mine and clean up the mempool of non-standard node
+ self.generate(self.nodes[0], 1) # Mine and clean up the mempool of non-standard node
# Valid but non-standard transactions in a block should be accepted by standard node
self.sync_blocks()
assert_equal(len(self.nodes[0].getrawmempool()), 0)
@@ -1998,7 +1990,7 @@ class SegWitTest(BitcoinTestFramework):
return serialize_with_bogus_witness(self.tx)
self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(address_type='bech32'), 5)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
unspent = next(u for u in self.nodes[0].listunspent() if u['spendable'] and u['address'].startswith('bcrt'))
raw = self.nodes[0].createrawtransaction([{"txid": unspent['txid'], "vout": unspent['vout']}], {self.nodes[0].getnewaddress(): 1})
@@ -2017,8 +2009,8 @@ class SegWitTest(BitcoinTestFramework):
@subtest # type: ignore
def test_wtxid_relay(self):
# Use brand new nodes to avoid contamination from earlier tests
- self.wtx_node = self.nodes[0].add_p2p_connection(TestP2PConn(wtxidrelay=True), services=NODE_NETWORK | NODE_WITNESS)
- self.tx_node = self.nodes[0].add_p2p_connection(TestP2PConn(wtxidrelay=False), services=NODE_NETWORK | NODE_WITNESS)
+ self.wtx_node = self.nodes[0].add_p2p_connection(TestP2PConn(wtxidrelay=True), services=P2P_SERVICES)
+ self.tx_node = self.nodes[0].add_p2p_connection(TestP2PConn(wtxidrelay=False), services=P2P_SERVICES)
# Check wtxidrelay feature negotiation message through connecting a new peer
def received_wtxidrelay():
diff --git a/test/functional/p2p_sendheaders.py b/test/functional/p2p_sendheaders.py
index 04e6ec4172..7bf1803780 100755
--- a/test/functional/p2p_sendheaders.py
+++ b/test/functional/p2p_sendheaders.py
@@ -205,7 +205,7 @@ class SendHeadersTest(BitcoinTestFramework):
# Clear out block announcements from each p2p listener
[x.clear_block_announcements() for x in self.nodes[0].p2ps]
- self.nodes[0].generatetoaddress(count, self.nodes[0].get_deterministic_priv_key().address)
+ self.generatetoaddress(self.nodes[0], count, self.nodes[0].get_deterministic_priv_key().address)
return int(self.nodes[0].getbestblockhash(), 16)
def mine_reorg(self, length):
@@ -216,7 +216,7 @@ class SendHeadersTest(BitcoinTestFramework):
return the list of block hashes newly mined."""
# make sure all invalidated blocks are node0's
- self.nodes[0].generatetoaddress(length, self.nodes[0].get_deterministic_priv_key().address)
+ self.generatetoaddress(self.nodes[0], length, self.nodes[0].get_deterministic_priv_key().address)
self.sync_blocks(self.nodes, wait=0.1)
for x in self.nodes[0].p2ps:
x.wait_for_block_announcement(int(self.nodes[0].getbestblockhash(), 16))
@@ -225,7 +225,7 @@ class SendHeadersTest(BitcoinTestFramework):
tip_height = self.nodes[1].getblockcount()
hash_to_invalidate = self.nodes[1].getblockhash(tip_height - (length - 1))
self.nodes[1].invalidateblock(hash_to_invalidate)
- all_hashes = self.nodes[1].generatetoaddress(length + 1, self.nodes[1].get_deterministic_priv_key().address) # Must be longer than the orig chain
+ all_hashes = self.generatetoaddress(self.nodes[1], length + 1, self.nodes[1].get_deterministic_priv_key().address) # Must be longer than the orig chain
self.sync_blocks(self.nodes, wait=0.1)
return [int(x, 16) for x in all_hashes]
@@ -240,7 +240,7 @@ class SendHeadersTest(BitcoinTestFramework):
self.test_nonnull_locators(test_node, inv_node)
def test_null_locators(self, test_node, inv_node):
- tip = self.nodes[0].getblockheader(self.nodes[0].generatetoaddress(1, self.nodes[0].get_deterministic_priv_key().address)[0])
+ tip = self.nodes[0].getblockheader(self.generatetoaddress(self.nodes[0], 1, self.nodes[0].get_deterministic_priv_key().address)[0])
tip_hash = int(tip["hash"], 16)
inv_node.check_last_inv_announcement(inv=[tip_hash])
diff --git a/test/functional/rpc_addresses_deprecation.py b/test/functional/rpc_addresses_deprecation.py
deleted file mode 100755
index 251cc85ae9..0000000000
--- a/test/functional/rpc_addresses_deprecation.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/env python3
-# Copyright (c) 2020 The Bitcoin Core developers
-# Distributed under the MIT software license, see the accompanying
-# file COPYING or http://www.opensource.org/licenses/mit-license.php.
-"""Test deprecation of reqSigs and addresses RPC fields."""
-
-from test_framework.messages import (
- tx_from_hex,
-)
-from test_framework.test_framework import BitcoinTestFramework
-from test_framework.util import (
- assert_equal,
-)
-
-
-class AddressesDeprecationTest(BitcoinTestFramework):
- def set_test_params(self):
- self.num_nodes = 2
- self.extra_args = [[], ["-deprecatedrpc=addresses"]]
-
- def skip_test_if_missing_module(self):
- self.skip_if_no_wallet()
-
- def run_test(self):
- self.test_addresses_deprecation()
-
- def test_addresses_deprecation(self):
- node = self.nodes[0]
- coin = node.listunspent().pop()
-
- inputs = [{'txid': coin['txid'], 'vout': coin['vout']}]
- outputs = {node.getnewaddress(): 0.99}
- raw = node.createrawtransaction(inputs, outputs)
- signed = node.signrawtransactionwithwallet(raw)['hex']
-
- # This transaction is derived from test/util/data/txcreatemultisig1.json
- tx = tx_from_hex(signed)
- tx.vout[0].scriptPubKey = bytes.fromhex("522102a5613bd857b7048924264d1e70e08fb2a7e6527d32b7ab1bb993ac59964ff39721021ac43c7ff740014c3b33737ede99c967e4764553d1b2b83db77c83b8715fa72d2102df2089105c77f266fa11a9d33f05c735234075f2e8780824c6b709415f9fb48553ae")
- tx_signed = node.signrawtransactionwithwallet(tx.serialize().hex())['hex']
- txid = node.sendrawtransaction(hexstring=tx_signed, maxfeerate=0)
-
- self.log.info("Test RPCResult scriptPubKey no longer returns the fields addresses or reqSigs by default")
- hash = node.generateblock(output=node.getnewaddress(), transactions=[txid])['hash']
- # Ensure both nodes have the newly generated block on disk.
- self.sync_blocks()
- script_pub_key = node.getblock(blockhash=hash, verbose=2)['tx'][-1]['vout'][0]['scriptPubKey']
- assert 'addresses' not in script_pub_key and 'reqSigs' not in script_pub_key
-
- self.log.info("Test RPCResult scriptPubKey returns the addresses field with -deprecatedrpc=addresses")
- script_pub_key = self.nodes[1].getblock(blockhash=hash, verbose=2)['tx'][-1]['vout'][0]['scriptPubKey']
- assert_equal(script_pub_key['addresses'], ['mvKDK6D54HU8wQumJBLHY95eq5iHFqXSBz', 'mv3rHCQSwKp2BLSuMHD8uCS32LW5xiNAA5', 'mirrsyhAQYzo5CwVhcaYJKwUJu1WJRCRJe'])
- assert_equal(script_pub_key['reqSigs'], 2)
-
-
-if __name__ == "__main__":
- AddressesDeprecationTest().main()
diff --git a/test/functional/rpc_blockchain.py b/test/functional/rpc_blockchain.py
index 2ee5c7ee0a..c3c6ade684 100755
--- a/test/functional/rpc_blockchain.py
+++ b/test/functional/rpc_blockchain.py
@@ -27,8 +27,6 @@ import subprocess
from test_framework.address import ADDRESS_BCRT1_P2WSH_OP_TRUE
from test_framework.blocktools import (
- CLTV_HEIGHT,
- DERSIG_HEIGHT,
create_block,
create_coinbase,
TIME_GENESIS_BLOCK,
@@ -84,7 +82,7 @@ class BlockchainTest(BitcoinTestFramework):
self.log.info(f"Generate {HEIGHT} blocks after the genesis block in ten-minute steps")
for t in range(TIME_GENESIS_BLOCK, TIME_RANGE_END, TIME_RANGE_STEP):
self.nodes[0].setmocktime(t)
- self.nodes[0].generatetoaddress(1, ADDRESS_BCRT1_P2WSH_OP_TRUE)
+ self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_P2WSH_OP_TRUE)
assert_equal(self.nodes[0].getblockchaininfo()['blocks'], HEIGHT)
def _test_getblockchaininfo(self):
@@ -129,7 +127,29 @@ class BlockchainTest(BitcoinTestFramework):
# should have exact keys
assert_equal(sorted(res.keys()), keys)
- self.restart_node(0, ['-stopatheight=207', '-prune=550'])
+ self.stop_node(0)
+ self.nodes[0].assert_start_raises_init_error(
+ extra_args=['-testactivationheight=name@2'],
+ expected_msg='Error: Invalid name (name@2) for -testactivationheight=name@height.',
+ )
+ self.nodes[0].assert_start_raises_init_error(
+ extra_args=['-testactivationheight=bip34@-2'],
+ expected_msg='Error: Invalid height value (bip34@-2) for -testactivationheight=name@height.',
+ )
+ self.nodes[0].assert_start_raises_init_error(
+ extra_args=['-testactivationheight='],
+ expected_msg='Error: Invalid format () for -testactivationheight=name@height.',
+ )
+ self.start_node(0, extra_args=[
+ '-stopatheight=207',
+ '-prune=550',
+ '-testactivationheight=bip34@2',
+ '-testactivationheight=dersig@3',
+ '-testactivationheight=cltv@4',
+ '-testactivationheight=csv@5',
+ '-testactivationheight=segwit@6',
+ ])
+
res = self.nodes[0].getblockchaininfo()
# result should have these additional pruning keys if prune=550
assert_equal(sorted(res.keys()), sorted(['pruneheight', 'automatic_pruning', 'prune_target_size'] + keys))
@@ -143,10 +163,10 @@ class BlockchainTest(BitcoinTestFramework):
assert_equal(res['softforks'], {
'bip34': {'type': 'buried', 'active': True, 'height': 2},
- 'bip66': {'type': 'buried', 'active': True, 'height': DERSIG_HEIGHT},
- 'bip65': {'type': 'buried', 'active': True, 'height': CLTV_HEIGHT},
- 'csv': {'type': 'buried', 'active': False, 'height': 432},
- 'segwit': {'type': 'buried', 'active': True, 'height': 0},
+ 'bip66': {'type': 'buried', 'active': True, 'height': 3},
+ 'bip65': {'type': 'buried', 'active': True, 'height': 4},
+ 'csv': {'type': 'buried', 'active': True, 'height': 5},
+ 'segwit': {'type': 'buried', 'active': True, 'height': 6},
'testdummy': {
'type': 'bip9',
'bip9': {
@@ -351,12 +371,12 @@ class BlockchainTest(BitcoinTestFramework):
def _test_stopatheight(self):
self.log.info("Test stopping at height")
assert_equal(self.nodes[0].getblockcount(), HEIGHT)
- self.nodes[0].generatetoaddress(6, ADDRESS_BCRT1_P2WSH_OP_TRUE)
+ self.generatetoaddress(self.nodes[0], 6, ADDRESS_BCRT1_P2WSH_OP_TRUE)
assert_equal(self.nodes[0].getblockcount(), HEIGHT + 6)
self.log.debug('Node should not stop at this height')
assert_raises(subprocess.TimeoutExpired, lambda: self.nodes[0].process.wait(timeout=3))
try:
- self.nodes[0].generatetoaddress(1, ADDRESS_BCRT1_P2WSH_OP_TRUE)
+ self.generatetoaddress(self.nodes[0], 1, ADDRESS_BCRT1_P2WSH_OP_TRUE)
except (ConnectionError, http.client.BadStatusLine):
pass # The node already shut down before response
self.log.debug('Node should stop at this height...')
@@ -406,13 +426,13 @@ class BlockchainTest(BitcoinTestFramework):
node = self.nodes[0]
miniwallet = MiniWallet(node)
- miniwallet.scan_blocks(num=5)
+ miniwallet.rescan_utxos()
fee_per_byte = Decimal('0.00000010')
fee_per_kb = 1000 * fee_per_byte
miniwallet.send_self_transfer(fee_rate=fee_per_kb, from_node=node)
- blockhash = node.generate(1)[0]
+ blockhash = self.generate(node, 1)[0]
self.log.info("Test getblock with verbosity 1 doesn't include fee")
block = node.getblock(blockhash, 1)
diff --git a/test/functional/rpc_createmultisig.py b/test/functional/rpc_createmultisig.py
index bb2e51c2f7..696438ccfe 100755
--- a/test/functional/rpc_createmultisig.py
+++ b/test/functional/rpc_createmultisig.py
@@ -45,7 +45,7 @@ class RpcCreateMultiSigTest(BitcoinTestFramework):
self.check_addmultisigaddress_errors()
self.log.info('Generating blocks ...')
- node0.generate(149)
+ self.generate(node0, 149)
self.sync_all()
self.moved = 0
@@ -116,7 +116,7 @@ class RpcCreateMultiSigTest(BitcoinTestFramework):
def checkbalances(self):
node0, node1, node2 = self.nodes
- node0.generate(COINBASE_MATURITY)
+ self.generate(node0, COINBASE_MATURITY)
self.sync_all()
bal0 = node0.getbalance()
@@ -179,7 +179,7 @@ class RpcCreateMultiSigTest(BitcoinTestFramework):
value = tx["vout"][vout]["value"]
prevtxs = [{"txid": txid, "vout": vout, "scriptPubKey": scriptPubKey, "redeemScript": mredeem, "amount": value}]
- node0.generate(1)
+ self.generate(node0, 1)
outval = value - decimal.Decimal("0.00001000")
rawtx = node2.createrawtransaction([{"txid": txid, "vout": vout}], [{self.final: outval}])
@@ -215,7 +215,7 @@ class RpcCreateMultiSigTest(BitcoinTestFramework):
self.moved += outval
tx = node0.sendrawtransaction(rawtx3["hex"], 0)
- blk = node0.generate(1)[0]
+ blk = self.generate(node0, 1)[0]
assert tx in node0.getblock(blk)["tx"]
txinfo = node0.getrawtransaction(tx, True, blk)
diff --git a/test/functional/rpc_deprecated.py b/test/functional/rpc_deprecated.py
index 1af79b9f7c..fdaed918a1 100755
--- a/test/functional/rpc_deprecated.py
+++ b/test/functional/rpc_deprecated.py
@@ -21,7 +21,7 @@ class DeprecatedRpcTest(BitcoinTestFramework):
# In run_test:
# self.log.info("Test generate RPC")
# assert_raises_rpc_error(-32, 'The wallet generate rpc method is deprecated', self.nodes[0].rpc.generate, 1)
- # self.nodes[1].generate(1)
+ # self.generate(self.nodes[1], 1)
self.log.info("No tested deprecated RPC methods")
diff --git a/test/functional/rpc_dumptxoutset.py b/test/functional/rpc_dumptxoutset.py
index 3efbdab013..89388df555 100755
--- a/test/functional/rpc_dumptxoutset.py
+++ b/test/functional/rpc_dumptxoutset.py
@@ -23,7 +23,7 @@ class DumptxoutsetTest(BitcoinTestFramework):
node = self.nodes[0]
mocktime = node.getblockheader(node.getblockhash(0))['time'] + 1
node.setmocktime(mocktime)
- node.generate(COINBASE_MATURITY)
+ self.generate(node, COINBASE_MATURITY)
FILENAME = 'txoutset.dat'
out = node.dumptxoutset(FILENAME)
diff --git a/test/functional/rpc_fundrawtransaction.py b/test/functional/rpc_fundrawtransaction.py
index 0ce58efbcf..b0e46c6ca7 100755
--- a/test/functional/rpc_fundrawtransaction.py
+++ b/test/functional/rpc_fundrawtransaction.py
@@ -8,6 +8,7 @@ from decimal import Decimal
from itertools import product
from test_framework.descriptors import descsum_create
+from test_framework.key import ECKey
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_approx,
@@ -19,6 +20,7 @@ from test_framework.util import (
count_bytes,
find_vout_for_address,
)
+from test_framework.wallet_util import bytes_to_wif
def get_unspent(listunspent, amount):
@@ -47,7 +49,40 @@ class RawTransactionsTest(BitcoinTestFramework):
self.connect_nodes(0, 2)
self.connect_nodes(0, 3)
+ def lock_outputs_type(self, wallet, outputtype):
+ """
+ Only allow UTXOs of the given type
+ """
+ if outputtype in ["legacy", "p2pkh", "pkh"]:
+ prefixes = ["pkh(", "sh(multi("]
+ elif outputtype in ["p2sh-segwit", "sh_wpkh"]:
+ prefixes = ["sh(wpkh(", "sh(wsh("]
+ elif outputtype in ["bech32", "wpkh"]:
+ prefixes = ["wpkh(", "wsh("]
+ else:
+ assert False, f"Unknown output type {outputtype}"
+
+ to_lock = []
+ for utxo in wallet.listunspent():
+ if "desc" in utxo:
+ for prefix in prefixes:
+ if utxo["desc"].startswith(prefix):
+ to_lock.append({"txid": utxo["txid"], "vout": utxo["vout"]})
+ wallet.lockunspent(False, to_lock)
+
+ def unlock_utxos(self, wallet):
+ """
+ Unlock all UTXOs except the watchonly one
+ """
+ to_keep = []
+ if self.watchonly_txid is not None and self.watchonly_vout is not None:
+ to_keep.append({"txid": self.watchonly_txid, "vout": self.watchonly_vout})
+ wallet.lockunspent(True)
+ wallet.lockunspent(False, to_keep)
+
def run_test(self):
+ self.watchonly_txid = None
+ self.watchonly_vout = None
self.log.info("Connect nodes, set fees, generate blocks, and sync")
self.min_relay_tx_fee = self.nodes[0].getnetworkinfo()['relayfee']
# This test is not meant to test fee estimation and we'd like
@@ -63,9 +98,9 @@ class RawTransactionsTest(BitcoinTestFramework):
# = 2 bytes * minRelayTxFeePerByte
self.fee_tolerance = 2 * self.min_relay_tx_fee / 1000
- self.nodes[2].generate(1)
+ self.generate(self.nodes[2], 1)
self.sync_all()
- self.nodes[0].generate(121)
+ self.generate(self.nodes[0], 121)
self.sync_all()
self.test_change_position()
@@ -99,6 +134,7 @@ class RawTransactionsTest(BitcoinTestFramework):
self.test_subtract_fee_with_presets()
self.test_transaction_too_large()
self.test_include_unsafe()
+ self.test_external_inputs()
self.test_22670()
def test_change_position(self):
@@ -126,7 +162,7 @@ class RawTransactionsTest(BitcoinTestFramework):
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.0)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 5.0)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
wwatch.unloadwallet()
@@ -373,6 +409,7 @@ class RawTransactionsTest(BitcoinTestFramework):
def test_fee_p2pkh(self):
"""Compare fee of a standard pubkeyhash transaction."""
self.log.info("Test fundrawtxn p2pkh fee")
+ self.lock_outputs_type(self.nodes[0], "p2pkh")
inputs = []
outputs = {self.nodes[1].getnewaddress():1.1}
rawtx = self.nodes[0].createrawtransaction(inputs, outputs)
@@ -386,9 +423,12 @@ class RawTransactionsTest(BitcoinTestFramework):
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert feeDelta >= 0 and feeDelta <= self.fee_tolerance
+ self.unlock_utxos(self.nodes[0])
+
def test_fee_p2pkh_multi_out(self):
"""Compare fee of a standard pubkeyhash transaction with multiple outputs."""
self.log.info("Test fundrawtxn p2pkh fee with multiple outputs")
+ self.lock_outputs_type(self.nodes[0], "p2pkh")
inputs = []
outputs = {
self.nodes[1].getnewaddress():1.1,
@@ -409,8 +449,11 @@ class RawTransactionsTest(BitcoinTestFramework):
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert feeDelta >= 0 and feeDelta <= self.fee_tolerance
+ self.unlock_utxos(self.nodes[0])
+
def test_fee_p2sh(self):
"""Compare fee of a 2-of-2 multisig p2sh transaction."""
+ self.lock_outputs_type(self.nodes[0], "p2pkh")
# Create 2-of-2 addr.
addr1 = self.nodes[1].getnewaddress()
addr2 = self.nodes[1].getnewaddress()
@@ -433,9 +476,12 @@ class RawTransactionsTest(BitcoinTestFramework):
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert feeDelta >= 0 and feeDelta <= self.fee_tolerance
+ self.unlock_utxos(self.nodes[0])
+
def test_fee_4of5(self):
"""Compare fee of a standard pubkeyhash transaction."""
self.log.info("Test fundrawtxn fee with 4-of-5 addresses")
+ self.lock_outputs_type(self.nodes[0], "p2pkh")
# Create 4-of-5 addr.
addr1 = self.nodes[1].getnewaddress()
@@ -474,6 +520,8 @@ class RawTransactionsTest(BitcoinTestFramework):
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert feeDelta >= 0 and feeDelta <= self.fee_tolerance
+ self.unlock_utxos(self.nodes[0])
+
def test_spend_2of2(self):
"""Spend a 2-of-2 multisig transaction over fundraw."""
self.log.info("Test fundpsbt spending 2-of-2 multisig")
@@ -500,7 +548,7 @@ class RawTransactionsTest(BitcoinTestFramework):
# Send 1.2 BTC to msig addr.
self.nodes[0].sendtoaddress(mSigObj, 1.2)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
oldBalance = self.nodes[1].getbalance()
@@ -511,7 +559,7 @@ class RawTransactionsTest(BitcoinTestFramework):
signed_psbt = w2.walletprocesspsbt(funded_psbt)
final_psbt = w2.finalizepsbt(signed_psbt['psbt'])
self.nodes[2].sendrawtransaction(final_psbt['hex'])
- self.nodes[2].generate(1)
+ self.generate(self.nodes[2], 1)
self.sync_all()
# Make sure funds are received at node1.
@@ -542,15 +590,18 @@ class RawTransactionsTest(BitcoinTestFramework):
# Drain the keypool.
self.nodes[1].getnewaddress()
self.nodes[1].getrawchangeaddress()
- inputs = []
- outputs = {self.nodes[0].getnewaddress():1.19999500}
+
+ # Choose 2 inputs
+ inputs = self.nodes[1].listunspent()[0:2]
+ value = sum(inp["amount"] for inp in inputs) - Decimal("0.00000500") # Pay a 500 sat fee
+ outputs = {self.nodes[0].getnewaddress():value}
rawtx = self.nodes[1].createrawtransaction(inputs, outputs)
# fund a transaction that does not require a new key for the change output
self.nodes[1].fundrawtransaction(rawtx)
# fund a transaction that requires a new key for the change output
# creating the key must be impossible because the wallet is locked
- outputs = {self.nodes[0].getnewaddress():1.1}
+ outputs = {self.nodes[0].getnewaddress():value - Decimal("0.1")}
rawtx = self.nodes[1].createrawtransaction(inputs, outputs)
assert_raises_rpc_error(-4, "Transaction needs a change address, but we can't generate it.", self.nodes[1].fundrawtransaction, rawtx)
@@ -572,7 +623,7 @@ class RawTransactionsTest(BitcoinTestFramework):
self.nodes[1].walletpassphrase("test", 600)
signedTx = self.nodes[1].signrawtransactionwithwallet(fundedTx['hex'])
self.nodes[1].sendrawtransaction(signedTx['hex'])
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
self.sync_all()
# Make sure funds are received at node1.
@@ -584,12 +635,12 @@ class RawTransactionsTest(BitcoinTestFramework):
# Empty node1, send some small coins from node0 to node1.
self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True)
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
self.sync_all()
for _ in range(20):
self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# Fund a tx with ~20 small inputs.
@@ -612,12 +663,12 @@ class RawTransactionsTest(BitcoinTestFramework):
# Again, empty node1, send some small coins from node0 to node1.
self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True)
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
self.sync_all()
for _ in range(20):
self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# Fund a tx with ~20 small inputs.
@@ -629,7 +680,7 @@ class RawTransactionsTest(BitcoinTestFramework):
fundedTx = self.nodes[1].fundrawtransaction(rawtx)
fundedAndSignedTx = self.nodes[1].signrawtransactionwithwallet(fundedTx['hex'])
self.nodes[1].sendrawtransaction(fundedAndSignedTx['hex'])
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
self.sync_all()
assert_equal(oldBalance+Decimal('50.19000000'), self.nodes[0].getbalance()) #0.19+block reward
@@ -707,7 +758,7 @@ class RawTransactionsTest(BitcoinTestFramework):
signedtx = self.nodes[0].signrawtransactionwithwallet(signedtx["hex"])
assert signedtx["complete"]
self.nodes[0].sendrawtransaction(signedtx["hex"])
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
wwatch.unloadwallet()
@@ -933,8 +984,59 @@ class RawTransactionsTest(BitcoinTestFramework):
for _ in range(1500):
outputs[recipient.getnewaddress()] = 0.1
wallet.sendmany("", outputs)
- self.nodes[0].generate(10)
+ self.generate(self.nodes[0], 10)
assert_raises_rpc_error(-4, "Transaction too large", recipient.fundrawtransaction, rawtx)
+ self.nodes[0].unloadwallet("large")
+
+ def test_external_inputs(self):
+ self.log.info("Test funding with external inputs")
+
+ eckey = ECKey()
+ eckey.generate()
+ privkey = bytes_to_wif(eckey.get_bytes())
+
+ self.nodes[2].createwallet("extfund")
+ wallet = self.nodes[2].get_wallet_rpc("extfund")
+
+ # Make a weird but signable script. sh(pkh()) descriptor accomplishes this
+ desc = descsum_create("sh(pkh({}))".format(privkey))
+ if self.options.descriptors:
+ res = self.nodes[0].importdescriptors([{"desc": desc, "timestamp": "now"}])
+ else:
+ res = self.nodes[0].importmulti([{"desc": desc, "timestamp": "now"}])
+ assert res[0]["success"]
+ addr = self.nodes[0].deriveaddresses(desc)[0]
+ addr_info = self.nodes[0].getaddressinfo(addr)
+
+ self.nodes[0].sendtoaddress(addr, 10)
+ self.nodes[0].sendtoaddress(wallet.getnewaddress(), 10)
+ self.generate(self.nodes[0], 6)
+ self.sync_all()
+ ext_utxo = self.nodes[0].listunspent(addresses=[addr])[0]
+
+ # An external input without solving data should result in an error
+ raw_tx = wallet.createrawtransaction([ext_utxo], {self.nodes[0].getnewaddress(): 15})
+ assert_raises_rpc_error(-4, "Insufficient funds", wallet.fundrawtransaction, raw_tx)
+
+ # Error conditions
+ assert_raises_rpc_error(-5, "'not a pubkey' is not hex", wallet.fundrawtransaction, raw_tx, {"solving_data": {"pubkeys":["not a pubkey"]}})
+ assert_raises_rpc_error(-5, "'01234567890a0b0c0d0e0f' is not a valid public key", wallet.fundrawtransaction, raw_tx, {"solving_data": {"pubkeys":["01234567890a0b0c0d0e0f"]}})
+ assert_raises_rpc_error(-5, "'not a script' is not hex", wallet.fundrawtransaction, raw_tx, {"solving_data": {"scripts":["not a script"]}})
+ assert_raises_rpc_error(-8, "Unable to parse descriptor 'not a descriptor'", wallet.fundrawtransaction, raw_tx, {"solving_data": {"descriptors":["not a descriptor"]}})
+
+ # But funding should work when the solving data is provided
+ funded_tx = wallet.fundrawtransaction(raw_tx, {"solving_data": {"pubkeys": [addr_info['pubkey']], "scripts": [addr_info["embedded"]["scriptPubKey"]]}})
+ signed_tx = wallet.signrawtransactionwithwallet(funded_tx['hex'])
+ assert not signed_tx['complete']
+ signed_tx = self.nodes[0].signrawtransactionwithwallet(signed_tx['hex'])
+ assert signed_tx['complete']
+
+ funded_tx = wallet.fundrawtransaction(raw_tx, {"solving_data": {"descriptors": [desc]}})
+ signed_tx = wallet.signrawtransactionwithwallet(funded_tx['hex'])
+ assert not signed_tx['complete']
+ signed_tx = self.nodes[0].signrawtransactionwithwallet(signed_tx['hex'])
+ assert signed_tx['complete']
+ self.nodes[2].unloadwallet("extfund")
def test_include_unsafe(self):
self.log.info("Test fundrawtxn with unsafe inputs")
@@ -944,31 +1046,32 @@ class RawTransactionsTest(BitcoinTestFramework):
# We receive unconfirmed funds from external keys (unsafe outputs).
addr = wallet.getnewaddress()
- txid1 = self.nodes[2].sendtoaddress(addr, 6)
- txid2 = self.nodes[2].sendtoaddress(addr, 4)
- self.sync_all()
- vout1 = find_vout_for_address(wallet, txid1, addr)
- vout2 = find_vout_for_address(wallet, txid2, addr)
+ inputs = []
+ for i in range(0, 2):
+ txid = self.nodes[2].sendtoaddress(addr, 5)
+ self.sync_mempools()
+ vout = find_vout_for_address(wallet, txid, addr)
+ inputs.append((txid, vout))
# Unsafe inputs are ignored by default.
- rawtx = wallet.createrawtransaction([], [{self.nodes[2].getnewaddress(): 5}])
+ rawtx = wallet.createrawtransaction([], [{self.nodes[2].getnewaddress(): 7.5}])
assert_raises_rpc_error(-4, "Insufficient funds", wallet.fundrawtransaction, rawtx)
# But we can opt-in to use them for funding.
fundedtx = wallet.fundrawtransaction(rawtx, {"include_unsafe": True})
tx_dec = wallet.decoderawtransaction(fundedtx['hex'])
- assert any([txin['txid'] == txid1 and txin['vout'] == vout1 for txin in tx_dec['vin']])
+ assert all((txin["txid"], txin["vout"]) in inputs for txin in tx_dec["vin"])
signedtx = wallet.signrawtransactionwithwallet(fundedtx['hex'])
- wallet.sendrawtransaction(signedtx['hex'])
+ assert wallet.testmempoolaccept([signedtx['hex']])[0]["allowed"]
# And we can also use them once they're confirmed.
- self.nodes[0].generate(1)
- rawtx = wallet.createrawtransaction([], [{self.nodes[2].getnewaddress(): 3}])
- fundedtx = wallet.fundrawtransaction(rawtx, {"include_unsafe": True})
+ self.generate(self.nodes[0], 1)
+ fundedtx = wallet.fundrawtransaction(rawtx, {"include_unsafe": False})
tx_dec = wallet.decoderawtransaction(fundedtx['hex'])
- assert any([txin['txid'] == txid2 and txin['vout'] == vout2 for txin in tx_dec['vin']])
+ assert all((txin["txid"], txin["vout"]) in inputs for txin in tx_dec["vin"])
signedtx = wallet.signrawtransactionwithwallet(fundedtx['hex'])
- wallet.sendrawtransaction(signedtx['hex'])
+ assert wallet.testmempoolaccept([signedtx['hex']])[0]["allowed"]
+ self.nodes[0].unloadwallet("unsafe")
def test_22670(self):
# In issue #22670, it was observed that ApproximateBestSubset may
@@ -993,7 +1096,7 @@ class RawTransactionsTest(BitcoinTestFramework):
# than any single input available, and require more than 1 input. So we make 3 outputs
for i in range(0, 3):
funds.sendtoaddress(tester.getnewaddress(address_type="bech32"), 1)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
# Create transactions in order to calculate fees for the target bounds that can trigger this bug
change_tx = tester.fundrawtransaction(tester.createrawtransaction([], [{funds.getnewaddress(): 1.5}]))
diff --git a/test/functional/rpc_generateblock.py b/test/functional/rpc_generateblock.py
index 7424416484..3c6b3fb125 100755
--- a/test/functional/rpc_generateblock.py
+++ b/test/functional/rpc_generateblock.py
@@ -24,13 +24,13 @@ class GenerateBlockTest(BitcoinTestFramework):
self.log.info('Generate an empty block to address')
address = node.getnewaddress()
- hash = node.generateblock(output=address, transactions=[])['hash']
+ hash = self.generateblock(node, output=address, transactions=[])['hash']
block = node.getblock(blockhash=hash, verbose=2)
assert_equal(len(block['tx']), 1)
assert_equal(block['tx'][0]['vout'][0]['scriptPubKey']['address'], address)
self.log.info('Generate an empty block to a descriptor')
- hash = node.generateblock('addr(' + address + ')', [])['hash']
+ hash = self.generateblock(node, 'addr(' + address + ')', [])['hash']
block = node.getblock(blockhash=hash, verbosity=2)
assert_equal(len(block['tx']), 1)
assert_equal(block['tx'][0]['vout'][0]['scriptPubKey']['address'], address)
@@ -38,7 +38,7 @@ class GenerateBlockTest(BitcoinTestFramework):
self.log.info('Generate an empty block to a combo descriptor with compressed pubkey')
combo_key = '0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'
combo_address = 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080'
- hash = node.generateblock('combo(' + combo_key + ')', [])['hash']
+ hash = self.generateblock(node, 'combo(' + combo_key + ')', [])['hash']
block = node.getblock(hash, 2)
assert_equal(len(block['tx']), 1)
assert_equal(block['tx'][0]['vout'][0]['scriptPubKey']['address'], combo_address)
@@ -46,13 +46,13 @@ class GenerateBlockTest(BitcoinTestFramework):
self.log.info('Generate an empty block to a combo descriptor with uncompressed pubkey')
combo_key = '0408ef68c46d20596cc3f6ddf7c8794f71913add807f1dc55949fa805d764d191c0b7ce6894c126fce0babc6663042f3dde9b0cf76467ea315514e5a6731149c67'
combo_address = 'mkc9STceoCcjoXEXe6cm66iJbmjM6zR9B2'
- hash = node.generateblock('combo(' + combo_key + ')', [])['hash']
+ hash = self.generateblock(node, 'combo(' + combo_key + ')', [])['hash']
block = node.getblock(hash, 2)
assert_equal(len(block['tx']), 1)
assert_equal(block['tx'][0]['vout'][0]['scriptPubKey']['address'], combo_address)
# Generate 110 blocks to spend
- node.generatetoaddress(110, address)
+ self.generatetoaddress(node, 110, address)
# Generate some extra mempool transactions to verify they don't get mined
for _ in range(10):
@@ -60,7 +60,7 @@ class GenerateBlockTest(BitcoinTestFramework):
self.log.info('Generate block with txid')
txid = node.sendtoaddress(address, 1)
- hash = node.generateblock(address, [txid])['hash']
+ hash = self.generateblock(node, address, [txid])['hash']
block = node.getblock(hash, 1)
assert_equal(len(block['tx']), 2)
assert_equal(block['tx'][1], txid)
@@ -69,7 +69,7 @@ class GenerateBlockTest(BitcoinTestFramework):
utxos = node.listunspent(addresses=[address])
raw = node.createrawtransaction([{'txid':utxos[0]['txid'], 'vout':utxos[0]['vout']}],[{address:1}])
signed_raw = node.signrawtransactionwithwallet(raw)['hex']
- hash = node.generateblock(address, [signed_raw])['hash']
+ hash = self.generateblock(node, address, [signed_raw])['hash']
block = node.getblock(hash, 1)
assert_equal(len(block['tx']), 2)
txid = block['tx'][1]
@@ -81,26 +81,26 @@ class GenerateBlockTest(BitcoinTestFramework):
txid1 = node.sendrawtransaction(signed_raw1)
raw2 = node.createrawtransaction([{'txid':txid1, 'vout':0}],[{address:0.999}])
signed_raw2 = node.signrawtransactionwithwallet(raw2)['hex']
- assert_raises_rpc_error(-25, 'TestBlockValidity failed: bad-txns-inputs-missingorspent', node.generateblock, address, [signed_raw2, txid1])
+ assert_raises_rpc_error(-25, 'TestBlockValidity failed: bad-txns-inputs-missingorspent', self.generateblock, node, address, [signed_raw2, txid1])
self.log.info('Fail to generate block with txid not in mempool')
missing_txid = '0000000000000000000000000000000000000000000000000000000000000000'
- assert_raises_rpc_error(-5, 'Transaction ' + missing_txid + ' not in mempool.', node.generateblock, address, [missing_txid])
+ assert_raises_rpc_error(-5, 'Transaction ' + missing_txid + ' not in mempool.', self.generateblock, node, address, [missing_txid])
self.log.info('Fail to generate block with invalid raw tx')
invalid_raw_tx = '0000'
- assert_raises_rpc_error(-22, 'Transaction decode failed for ' + invalid_raw_tx, node.generateblock, address, [invalid_raw_tx])
+ assert_raises_rpc_error(-22, 'Transaction decode failed for ' + invalid_raw_tx, self.generateblock, node, address, [invalid_raw_tx])
self.log.info('Fail to generate block with invalid address/descriptor')
- assert_raises_rpc_error(-5, 'Invalid address or descriptor', node.generateblock, '1234', [])
+ assert_raises_rpc_error(-5, 'Invalid address or descriptor', self.generateblock, node, '1234', [])
self.log.info('Fail to generate block with a ranged descriptor')
ranged_descriptor = 'pkh(tpubD6NzVbkrYhZ4XgiXtGrdW5XDAPFCL9h7we1vwNCpn8tGbBcgfVYjXyhWo4E1xkh56hjod1RhGjxbaTLV3X4FyWuejifB9jusQ46QzG87VKp/0/*)'
- assert_raises_rpc_error(-8, 'Ranged descriptor not accepted. Maybe pass through deriveaddresses first?', node.generateblock, ranged_descriptor, [])
+ assert_raises_rpc_error(-8, 'Ranged descriptor not accepted. Maybe pass through deriveaddresses first?', self.generateblock, node, ranged_descriptor, [])
self.log.info('Fail to generate block with a descriptor missing a private key')
child_descriptor = 'pkh(tpubD6NzVbkrYhZ4XgiXtGrdW5XDAPFCL9h7we1vwNCpn8tGbBcgfVYjXyhWo4E1xkh56hjod1RhGjxbaTLV3X4FyWuejifB9jusQ46QzG87VKp/0\'/0)'
- assert_raises_rpc_error(-5, 'Cannot derive script without private keys', node.generateblock, child_descriptor, [])
+ assert_raises_rpc_error(-5, 'Cannot derive script without private keys', self.generateblock, node, child_descriptor, [])
if __name__ == '__main__':
GenerateBlockTest().main()
diff --git a/test/functional/rpc_getblockfilter.py b/test/functional/rpc_getblockfilter.py
index a99e50f29f..4d860d0f36 100755
--- a/test/functional/rpc_getblockfilter.py
+++ b/test/functional/rpc_getblockfilter.py
@@ -21,8 +21,8 @@ class GetBlockFilterTest(BitcoinTestFramework):
# Create two chains by disconnecting nodes 0 & 1, mining, then reconnecting
self.disconnect_nodes(0, 1)
- self.nodes[0].generate(3)
- self.nodes[1].generate(4)
+ self.generate(self.nodes[0], 3)
+ self.generate(self.nodes[1], 4)
assert_equal(self.nodes[0].getblockcount(), 3)
chain0_hashes = [self.nodes[0].getblockhash(block_height) for block_height in range(4)]
diff --git a/test/functional/rpc_getblockstats.py b/test/functional/rpc_getblockstats.py
index 4af518c870..456e2cb0ad 100755
--- a/test/functional/rpc_getblockstats.py
+++ b/test/functional/rpc_getblockstats.py
@@ -43,11 +43,11 @@ class GetblockstatsTest(BitcoinTestFramework):
def generate_test_data(self, filename):
mocktime = 1525107225
self.nodes[0].setmocktime(mocktime)
- self.nodes[0].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[0], COINBASE_MATURITY + 1)
address = self.nodes[0].get_deterministic_priv_key().address
self.nodes[0].sendtoaddress(address=address, amount=10, subtractfeefromamount=True)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
self.nodes[0].sendtoaddress(address=address, amount=10, subtractfeefromamount=True)
@@ -55,7 +55,7 @@ class GetblockstatsTest(BitcoinTestFramework):
self.nodes[0].settxfee(amount=0.003)
self.nodes[0].sendtoaddress(address=address, amount=1, subtractfeefromamount=True)
self.sync_all()
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.expected_stats = self.get_stats()
diff --git a/test/functional/rpc_getchaintips.py b/test/functional/rpc_getchaintips.py
index 8dc8474374..ab0ee9142d 100755
--- a/test/functional/rpc_getchaintips.py
+++ b/test/functional/rpc_getchaintips.py
@@ -26,8 +26,8 @@ class GetChainTipsTest (BitcoinTestFramework):
# Split the network and build two chains of different lengths.
self.split_network()
- self.nodes[0].generatetoaddress(10, self.nodes[0].get_deterministic_priv_key().address)
- self.nodes[2].generatetoaddress(20, self.nodes[2].get_deterministic_priv_key().address)
+ self.generatetoaddress(self.nodes[0], 10, self.nodes[0].get_deterministic_priv_key().address)
+ self.generatetoaddress(self.nodes[2], 20, self.nodes[2].get_deterministic_priv_key().address)
self.sync_all(self.nodes[:2])
self.sync_all(self.nodes[2:])
diff --git a/test/functional/rpc_invalidateblock.py b/test/functional/rpc_invalidateblock.py
index 114bd5e7e9..a91ce85855 100755
--- a/test/functional/rpc_invalidateblock.py
+++ b/test/functional/rpc_invalidateblock.py
@@ -22,12 +22,12 @@ class InvalidateTest(BitcoinTestFramework):
def run_test(self):
self.log.info("Make sure we repopulate setBlockIndexCandidates after InvalidateBlock:")
self.log.info("Mine 4 blocks on Node 0")
- self.nodes[0].generatetoaddress(4, self.nodes[0].get_deterministic_priv_key().address)
+ self.generatetoaddress(self.nodes[0], 4, self.nodes[0].get_deterministic_priv_key().address)
assert_equal(self.nodes[0].getblockcount(), 4)
besthash_n0 = self.nodes[0].getbestblockhash()
self.log.info("Mine competing 6 blocks on Node 1")
- self.nodes[1].generatetoaddress(6, self.nodes[1].get_deterministic_priv_key().address)
+ self.generatetoaddress(self.nodes[1], 6, self.nodes[1].get_deterministic_priv_key().address)
assert_equal(self.nodes[1].getblockcount(), 6)
self.log.info("Connect nodes to force a reorg")
@@ -53,14 +53,14 @@ class InvalidateTest(BitcoinTestFramework):
self.nodes[2].invalidateblock(self.nodes[2].getblockhash(3))
assert_equal(self.nodes[2].getblockcount(), 2)
self.log.info("..and then mine a block")
- self.nodes[2].generatetoaddress(1, self.nodes[2].get_deterministic_priv_key().address)
+ self.generatetoaddress(self.nodes[2], 1, self.nodes[2].get_deterministic_priv_key().address)
self.log.info("Verify all nodes are at the right height")
self.wait_until(lambda: self.nodes[2].getblockcount() == 3, timeout=5)
self.wait_until(lambda: self.nodes[0].getblockcount() == 4, timeout=5)
self.wait_until(lambda: self.nodes[1].getblockcount() == 4, timeout=5)
self.log.info("Verify that we reconsider all ancestors as well")
- blocks = self.nodes[1].generatetodescriptor(10, ADDRESS_BCRT1_UNSPENDABLE_DESCRIPTOR)
+ blocks = self.generatetodescriptor(self.nodes[1], 10, ADDRESS_BCRT1_UNSPENDABLE_DESCRIPTOR)
assert_equal(self.nodes[1].getbestblockhash(), blocks[-1])
# Invalidate the two blocks at the tip
self.nodes[1].invalidateblock(blocks[-1])
@@ -72,7 +72,7 @@ class InvalidateTest(BitcoinTestFramework):
assert_equal(self.nodes[1].getbestblockhash(), blocks[-1])
self.log.info("Verify that we reconsider all descendants")
- blocks = self.nodes[1].generatetodescriptor(10, ADDRESS_BCRT1_UNSPENDABLE_DESCRIPTOR)
+ blocks = self.generatetodescriptor(self.nodes[1], 10, ADDRESS_BCRT1_UNSPENDABLE_DESCRIPTOR)
assert_equal(self.nodes[1].getbestblockhash(), blocks[-1])
# Invalidate the two blocks at the tip
self.nodes[1].invalidateblock(blocks[-2])
diff --git a/test/functional/rpc_misc.py b/test/functional/rpc_misc.py
index 13f33c321f..ac2a7a309b 100755
--- a/test/functional/rpc_misc.py
+++ b/test/functional/rpc_misc.py
@@ -57,7 +57,7 @@ class RpcMiscTest(BitcoinTestFramework):
self.log.info("test logging rpc and help")
# Test logging RPC returns the expected number of logging categories.
- assert_equal(len(node.logging()), 25)
+ assert_equal(len(node.logging()), 26)
# Test toggling a logging category on/off/on with the logging RPC.
assert_equal(node.logging()['qt'], True)
diff --git a/test/functional/rpc_net.py b/test/functional/rpc_net.py
index 6e5ef770d1..0f3bbce54c 100755
--- a/test/functional/rpc_net.py
+++ b/test/functional/rpc_net.py
@@ -12,11 +12,10 @@ from itertools import product
import time
from test_framework.blocktools import COINBASE_MATURITY
-from test_framework.p2p import P2PInterface
import test_framework.messages
-from test_framework.messages import (
- NODE_NETWORK,
- NODE_WITNESS,
+from test_framework.p2p import (
+ P2PInterface,
+ P2P_SERVICES,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
@@ -52,9 +51,9 @@ class NetTest(BitcoinTestFramework):
def run_test(self):
# We need miniwallet to make a transaction
self.wallet = MiniWallet(self.nodes[0])
- self.wallet.generate(1)
+ self.generate(self.wallet, 1)
# Get out of IBD for the minfeefilter and getpeerinfo tests.
- self.nodes[0].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[0], COINBASE_MATURITY + 1)
# By default, the test framework sets up an addnode connection from
# node 1 --> node0. By connecting node0 --> node 1, we're left with
@@ -81,7 +80,7 @@ class NetTest(BitcoinTestFramework):
self.log.info("Test getpeerinfo")
# Create a few getpeerinfo last_block/last_transaction values.
self.wallet.send_self_transfer(from_node=self.nodes[0]) # Make a transaction so we can see it in the getpeerinfo results
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
self.sync_all()
time_now = int(time.time())
peer_info = [x.getpeerinfo() for x in self.nodes]
@@ -189,7 +188,6 @@ class NetTest(BitcoinTestFramework):
def test_getnodeaddresses(self):
self.log.info("Test getnodeaddresses")
self.nodes[0].add_p2p_connection(P2PInterface())
- services = NODE_NETWORK | NODE_WITNESS
# Add an IPv6 address to the address manager.
ipv6_addr = "1233:3432:2434:2343:3234:2345:6546:4534"
@@ -217,7 +215,7 @@ class NetTest(BitcoinTestFramework):
assert_greater_than(10000, len(node_addresses))
for a in node_addresses:
assert_greater_than(a["time"], 1527811200) # 1st June 2018
- assert_equal(a["services"], services)
+ assert_equal(a["services"], P2P_SERVICES)
assert a["address"] in imported_addrs
assert_equal(a["port"], 8333)
assert_equal(a["network"], "ipv4")
@@ -228,7 +226,7 @@ class NetTest(BitcoinTestFramework):
assert_equal(res[0]["address"], ipv6_addr)
assert_equal(res[0]["network"], "ipv6")
assert_equal(res[0]["port"], 8333)
- assert_equal(res[0]["services"], services)
+ assert_equal(res[0]["services"], P2P_SERVICES)
# Test for the absence of onion and I2P addresses.
for network in ["onion", "i2p"]:
@@ -239,7 +237,16 @@ class NetTest(BitcoinTestFramework):
assert_raises_rpc_error(-8, "Network not recognized: Foo", self.nodes[0].getnodeaddresses, 1, "Foo")
def test_addpeeraddress(self):
+ """RPC addpeeraddress sets the source address equal to the destination address.
+ If an address with the same /16 as an existing new entry is passed, it will be
+ placed in the same new bucket and have a 1/64 chance of the bucket positions
+ colliding (depending on the value of nKey in the addrman), in which case the
+ new address won't be added. The probability of collision can be reduced to
+ 1/2^16 = 1/65536 by using an address from a different /16. We avoid this here
+ by first testing adding a tried table entry before testing adding a new table one.
+ """
self.log.info("Test addpeeraddress")
+ self.restart_node(1, ["-checkaddrman=1"])
node = self.nodes[1]
self.log.debug("Test that addpeerinfo is a hidden RPC")
@@ -251,17 +258,25 @@ class NetTest(BitcoinTestFramework):
assert_equal(node.addpeeraddress(address="", port=8333), {"success": False})
assert_equal(node.getnodeaddresses(count=0), [])
- self.log.debug("Test that adding a valid address succeeds")
- assert_equal(node.addpeeraddress(address="1.2.3.4", port=8333), {"success": True})
- addrs = node.getnodeaddresses(count=0)
- assert_equal(len(addrs), 1)
- assert_equal(addrs[0]["address"], "1.2.3.4")
- assert_equal(addrs[0]["port"], 8333)
-
- self.log.debug("Test that adding the same address again when already present fails")
- assert_equal(node.addpeeraddress(address="1.2.3.4", port=8333), {"success": False})
+ self.log.debug("Test that adding a valid address to the tried table succeeds")
+ assert_equal(node.addpeeraddress(address="1.2.3.4", tried=True, port=8333), {"success": True})
+ with node.assert_debug_log(expected_msgs=["Addrman checks started: new 0, tried 1, total 1"]):
+ addrs = node.getnodeaddresses(count=0) # getnodeaddresses re-runs the addrman checks
+ assert_equal(len(addrs), 1)
+ assert_equal(addrs[0]["address"], "1.2.3.4")
+ assert_equal(addrs[0]["port"], 8333)
+
+ self.log.debug("Test that adding an already-present tried address to the new and tried tables fails")
+ for value in [True, False]:
+ assert_equal(node.addpeeraddress(address="1.2.3.4", tried=value, port=8333), {"success": False})
assert_equal(len(node.getnodeaddresses(count=0)), 1)
+ self.log.debug("Test that adding a second address, this time to the new table, succeeds")
+ assert_equal(node.addpeeraddress(address="2.0.0.0", port=8333), {"success": True})
+ with node.assert_debug_log(expected_msgs=["Addrman checks started: new 1, tried 1, total 2"]):
+ addrs = node.getnodeaddresses(count=0) # getnodeaddresses re-runs the addrman checks
+ assert_equal(len(addrs), 2)
+
if __name__ == '__main__':
NetTest().main()
diff --git a/test/functional/rpc_packages.py b/test/functional/rpc_packages.py
index 3cb4154601..63533affd0 100755
--- a/test/functional/rpc_packages.py
+++ b/test/functional/rpc_packages.py
@@ -51,7 +51,7 @@ class RPCPackagesTest(BitcoinTestFramework):
self.address = node.get_deterministic_priv_key().address
self.coins = []
# The last 100 coinbase transactions are premature
- for b in node.generatetoaddress(200, self.address)[:100]:
+ for b in self.generatetoaddress(node, 200, self.address)[:100]:
coinbase = node.getblock(blockhash=b, verbosity=2)["tx"][0]
self.coins.append({
"txid": coinbase["txid"],
@@ -151,7 +151,7 @@ class RPCPackagesTest(BitcoinTestFramework):
assert_equal(testres_single, testres_multiple)
# Clean up by clearing the mempool
- node.generate(1)
+ self.generate(node, 1)
def test_multiple_children(self):
node = self.nodes[0]
diff --git a/test/functional/rpc_preciousblock.py b/test/functional/rpc_preciousblock.py
index 7d3a5cc9ce..3a00992ddc 100755
--- a/test/functional/rpc_preciousblock.py
+++ b/test/functional/rpc_preciousblock.py
@@ -43,18 +43,18 @@ class PreciousTest(BitcoinTestFramework):
def run_test(self):
self.log.info("Ensure submitblock can in principle reorg to a competing chain")
gen_address = lambda i: self.nodes[i].get_deterministic_priv_key().address # A non-wallet address to mine to
- self.nodes[0].generatetoaddress(1, gen_address(0))
+ self.generatetoaddress(self.nodes[0], 1, gen_address(0))
assert_equal(self.nodes[0].getblockcount(), 1)
- hashZ = self.nodes[1].generatetoaddress(2, gen_address(1))[-1]
+ hashZ = self.generatetoaddress(self.nodes[1], 2, gen_address(1))[-1]
assert_equal(self.nodes[1].getblockcount(), 2)
node_sync_via_rpc(self.nodes[0:3])
assert_equal(self.nodes[0].getbestblockhash(), hashZ)
self.log.info("Mine blocks A-B-C on Node 0")
- hashC = self.nodes[0].generatetoaddress(3, gen_address(0))[-1]
+ hashC = self.generatetoaddress(self.nodes[0], 3, gen_address(0))[-1]
assert_equal(self.nodes[0].getblockcount(), 5)
self.log.info("Mine competing blocks E-F-G on Node 1")
- hashG = self.nodes[1].generatetoaddress(3, gen_address(1))[-1]
+ hashG = self.generatetoaddress(self.nodes[1], 3, gen_address(1))[-1]
assert_equal(self.nodes[1].getblockcount(), 5)
assert hashC != hashG
self.log.info("Connect nodes and check no reorg occurs")
@@ -83,7 +83,7 @@ class PreciousTest(BitcoinTestFramework):
self.nodes[1].preciousblock(hashC)
assert_equal(self.nodes[1].getbestblockhash(), hashC)
self.log.info("Mine another block (E-F-G-)H on Node 0 and reorg Node 1")
- self.nodes[0].generatetoaddress(1, gen_address(0))
+ self.generatetoaddress(self.nodes[0], 1, gen_address(0))
assert_equal(self.nodes[0].getblockcount(), 6)
self.sync_blocks(self.nodes[0:2])
hashH = self.nodes[0].getbestblockhash()
@@ -92,7 +92,7 @@ class PreciousTest(BitcoinTestFramework):
self.nodes[1].preciousblock(hashC)
assert_equal(self.nodes[1].getbestblockhash(), hashH)
self.log.info("Mine competing blocks I-J-K-L on Node 2")
- self.nodes[2].generatetoaddress(4, gen_address(2))
+ self.generatetoaddress(self.nodes[2], 4, gen_address(2))
assert_equal(self.nodes[2].getblockcount(), 6)
hashL = self.nodes[2].getbestblockhash()
self.log.info("Connect nodes and check no reorg occurs")
diff --git a/test/functional/rpc_psbt.py b/test/functional/rpc_psbt.py
index cf4d8a134c..b132ac3d31 100755
--- a/test/functional/rpc_psbt.py
+++ b/test/functional/rpc_psbt.py
@@ -8,6 +8,8 @@
from decimal import Decimal
from itertools import product
+from test_framework.descriptors import descsum_create
+from test_framework.key import ECKey
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_approx,
@@ -16,6 +18,7 @@ from test_framework.util import (
assert_raises_rpc_error,
find_output,
)
+from test_framework.wallet_util import bytes_to_wif
import json
import os
@@ -57,7 +60,7 @@ class PSBTTest(BitcoinTestFramework):
online_addr = w2.getnewaddress(address_type="p2sh-segwit")
wonline.importaddress(offline_addr, "", False)
mining_node.sendtoaddress(address=offline_addr, amount=1.0)
- mining_node.generate(nblocks=1)
+ self.generate(mining_node, nblocks=1)
self.sync_blocks([mining_node, online_node])
# Construct an unsigned PSBT on the online node (who doesn't know the output is Segwit, so will include a non-witness UTXO)
@@ -72,7 +75,7 @@ class PSBTTest(BitcoinTestFramework):
# Make sure we can mine the resulting transaction
txid = mining_node.sendrawtransaction(mining_node.finalizepsbt(signed_psbt)["hex"])
- mining_node.generate(1)
+ self.generate(mining_node, 1)
self.sync_blocks([mining_node, online_node])
assert_equal(online_node.gettxout(txid,0)["confirmations"], 1)
@@ -108,6 +111,16 @@ class PSBTTest(BitcoinTestFramework):
psbtx = self.nodes[1].walletprocesspsbt(psbtx1)['psbt']
assert_equal(psbtx1, psbtx)
+ # Node 0 should not be able to sign the transaction with the wallet is locked
+ self.nodes[0].encryptwallet("password")
+ assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].walletprocesspsbt, psbtx)
+
+ # Node 0 should be able to process without signing though
+ unsigned_tx = self.nodes[0].walletprocesspsbt(psbtx, False)
+ assert_equal(unsigned_tx['complete'], False)
+
+ self.nodes[0].walletpassphrase(passphrase="password", timeout=1000000)
+
# Sign the transaction and send
signed_tx = self.nodes[0].walletprocesspsbt(psbtx)['psbt']
final_tx = self.nodes[0].finalizepsbt(signed_tx)['hex']
@@ -148,7 +161,7 @@ class PSBTTest(BitcoinTestFramework):
rawtx = self.nodes[0].fundrawtransaction(rawtx, {"changePosition":3})
signed_tx = self.nodes[0].signrawtransactionwithwallet(rawtx['hex'])['hex']
txid = self.nodes[0].sendrawtransaction(signed_tx)
- self.nodes[0].generate(6)
+ self.generate(self.nodes[0], 6)
self.sync_all()
# Find the output pos
@@ -307,7 +320,7 @@ class PSBTTest(BitcoinTestFramework):
node2_addr = self.nodes[2].getnewaddress()
txid1 = self.nodes[0].sendtoaddress(node1_addr, 13)
txid2 = self.nodes[0].sendtoaddress(node2_addr, 13)
- blockhash = self.nodes[0].generate(6)[0]
+ blockhash = self.generate(self.nodes[0], 6)[0]
self.sync_all()
vout1 = find_output(self.nodes[1], txid1, 13, blockhash=blockhash)
vout2 = find_output(self.nodes[2], txid2, 13, blockhash=blockhash)
@@ -335,7 +348,7 @@ class PSBTTest(BitcoinTestFramework):
combined = self.nodes[0].combinepsbt([psbt1, psbt2])
finalized = self.nodes[0].finalizepsbt(combined)['hex']
self.nodes[0].sendrawtransaction(finalized)
- self.nodes[0].generate(6)
+ self.generate(self.nodes[0], 6)
self.sync_all()
# Test additional args in walletcreatepsbt
@@ -530,7 +543,7 @@ class PSBTTest(BitcoinTestFramework):
addr4 = self.nodes[1].getnewaddress("", "p2sh-segwit")
txid4 = self.nodes[0].sendtoaddress(addr4, 5)
vout4 = find_output(self.nodes[0], txid4, 5)
- self.nodes[0].generate(6)
+ self.generate(self.nodes[0], 6)
self.sync_all()
psbt2 = self.nodes[1].createpsbt([{"txid":txid4, "vout":vout4}], {self.nodes[0].getnewaddress():Decimal('4.999')})
psbt2 = self.nodes[1].walletprocesspsbt(psbt2)['psbt']
@@ -554,7 +567,7 @@ class PSBTTest(BitcoinTestFramework):
addr = self.nodes[1].getnewaddress("", "p2sh-segwit")
txid = self.nodes[0].sendtoaddress(addr, 7)
addrinfo = self.nodes[1].getaddressinfo(addr)
- blockhash = self.nodes[0].generate(6)[0]
+ blockhash = self.generate(self.nodes[0], 6)[0]
self.sync_all()
vout = find_output(self.nodes[0], txid, 7, blockhash=blockhash)
psbt = self.nodes[1].createpsbt([{"txid":txid, "vout":vout}], {self.nodes[0].getnewaddress("", "p2sh-segwit"):Decimal('6.999')})
@@ -598,5 +611,43 @@ class PSBTTest(BitcoinTestFramework):
assert_raises_rpc_error(-25, 'Inputs missing or spent', self.nodes[0].walletprocesspsbt, 'cHNidP8BAJoCAAAAAkvEW8NnDtdNtDpsmze+Ht2LH35IJcKv00jKAlUs21RrAwAAAAD/////S8Rbw2cO1020OmybN74e3Ysffkglwq/TSMoCVSzbVGsBAAAAAP7///8CwLYClQAAAAAWABSNJKzjaUb3uOxixsvh1GGE3fW7zQD5ApUAAAAAFgAUKNw0x8HRctAgmvoevm4u1SbN7XIAAAAAAAEAnQIAAAACczMa321tVHuN4GKWKRncycI22aX3uXgwSFUKM2orjRsBAAAAAP7///9zMxrfbW1Ue43gYpYpGdzJwjbZpfe5eDBIVQozaiuNGwAAAAAA/v///wIA+QKVAAAAABl2qRT9zXUVA8Ls5iVqynLHe5/vSe1XyYisQM0ClQAAAAAWABRmWQUcjSjghQ8/uH4Bn/zkakwLtAAAAAAAAQEfQM0ClQAAAAAWABRmWQUcjSjghQ8/uH4Bn/zkakwLtAAAAA==')
+ # Test that we can fund psbts with external inputs specified
+ eckey = ECKey()
+ eckey.generate()
+ privkey = bytes_to_wif(eckey.get_bytes())
+
+ # Make a weird but signable script. sh(pkh()) descriptor accomplishes this
+ desc = descsum_create("sh(pkh({}))".format(privkey))
+ if self.options.descriptors:
+ res = self.nodes[0].importdescriptors([{"desc": desc, "timestamp": "now"}])
+ else:
+ res = self.nodes[0].importmulti([{"desc": desc, "timestamp": "now"}])
+ assert res[0]["success"]
+ addr = self.nodes[0].deriveaddresses(desc)[0]
+ addr_info = self.nodes[0].getaddressinfo(addr)
+
+ self.nodes[0].sendtoaddress(addr, 10)
+ self.generate(self.nodes[0], 6)
+ self.sync_all()
+ ext_utxo = self.nodes[0].listunspent(addresses=[addr])[0]
+
+ # An external input without solving data should result in an error
+ assert_raises_rpc_error(-4, "Insufficient funds", self.nodes[1].walletcreatefundedpsbt, [ext_utxo], {self.nodes[0].getnewaddress(): 10 + ext_utxo['amount']}, 0, {'add_inputs': True})
+
+ # But funding should work when the solving data is provided
+ psbt = self.nodes[1].walletcreatefundedpsbt([ext_utxo], {self.nodes[0].getnewaddress(): 15}, 0, {'add_inputs': True, "solving_data": {"pubkeys": [addr_info['pubkey']], "scripts": [addr_info["embedded"]["scriptPubKey"]]}})
+ signed = self.nodes[1].walletprocesspsbt(psbt['psbt'])
+ assert not signed['complete']
+ signed = self.nodes[0].walletprocesspsbt(signed['psbt'])
+ assert signed['complete']
+ self.nodes[0].finalizepsbt(signed['psbt'])
+
+ psbt = self.nodes[1].walletcreatefundedpsbt([ext_utxo], {self.nodes[0].getnewaddress(): 15}, 0, {'add_inputs': True, "solving_data":{"descriptors": [desc]}})
+ signed = self.nodes[1].walletprocesspsbt(psbt['psbt'])
+ assert not signed['complete']
+ signed = self.nodes[0].walletprocesspsbt(signed['psbt'])
+ assert signed['complete']
+ self.nodes[0].finalizepsbt(signed['psbt'])
+
if __name__ == '__main__':
PSBTTest().main()
diff --git a/test/functional/rpc_rawtransaction.py b/test/functional/rpc_rawtransaction.py
index fbf8c6ef15..fc812340fa 100755
--- a/test/functional/rpc_rawtransaction.py
+++ b/test/functional/rpc_rawtransaction.py
@@ -74,14 +74,14 @@ class RawTransactionsTest(BitcoinTestFramework):
def run_test(self):
self.log.info("Prepare some coins for multiple *rawtransaction commands")
- self.nodes[2].generate(1)
+ self.generate(self.nodes[2], 1)
self.sync_all()
- self.nodes[0].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[0], COINBASE_MATURITY + 1)
self.sync_all()
for amount in [1.5, 1.0, 5.0]:
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), amount)
self.sync_all()
- self.nodes[0].generate(5)
+ self.generate(self.nodes[0], 5)
self.sync_all()
self.getrawtransaction_tests()
@@ -97,13 +97,13 @@ class RawTransactionsTest(BitcoinTestFramework):
def getrawtransaction_tests(self):
addr = self.nodes[1].getnewaddress()
txid = self.nodes[0].sendtoaddress(addr, 10)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
vout = find_vout_for_address(self.nodes[1], txid, addr)
rawTx = self.nodes[1].createrawtransaction([{'txid': txid, 'vout': vout}], {self.nodes[1].getnewaddress(): 9.999})
rawTxSigned = self.nodes[1].signrawtransactionwithwallet(rawTx)
txId = self.nodes[1].sendrawtransaction(rawTxSigned['hex'])
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
for n in [0, 3]:
@@ -136,7 +136,7 @@ class RawTransactionsTest(BitcoinTestFramework):
# Make a tx by sending, then generate 2 blocks; block1 has the tx in it
tx = self.nodes[2].sendtoaddress(self.nodes[1].getnewaddress(), 1)
- block1, block2 = self.nodes[2].generate(2)
+ block1, block2 = self.generate(self.nodes[2], 2)
self.sync_all()
for n in [0, 3]:
self.log.info(f"Test getrawtransaction {'with' if n == 0 else 'without'} -txindex, with blockhash")
@@ -368,7 +368,7 @@ class RawTransactionsTest(BitcoinTestFramework):
self.nodes[2].sendrawtransaction(hexstring=rawTxSigned['hex'], maxfeerate='0.20000000')
self.log.info("Test sendrawtransaction/testmempoolaccept with tx already in the chain")
- self.nodes[2].generate(1)
+ self.generate(self.nodes[2], 1)
self.sync_blocks()
for node in self.nodes:
testres = node.testmempoolaccept([rawTxSigned['hex']])[0]
@@ -442,7 +442,7 @@ class RawTransactionsTest(BitcoinTestFramework):
# send 1.2 BTC to msig adr
txId = self.nodes[0].sendtoaddress(mSigObj, 1.2)
self.sync_all()
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# node2 has both keys of the 2of2 ms addr, tx should affect the balance
assert_equal(self.nodes[2].getbalance(), bal + Decimal('1.20000000'))
@@ -464,7 +464,7 @@ class RawTransactionsTest(BitcoinTestFramework):
decTx = self.nodes[0].gettransaction(txId)
rawTx = self.nodes[0].decoderawtransaction(decTx['hex'])
self.sync_all()
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# THIS IS AN INCOMPLETE FEATURE
@@ -487,7 +487,7 @@ class RawTransactionsTest(BitcoinTestFramework):
self.nodes[2].sendrawtransaction(rawTxSigned['hex'])
rawTx = self.nodes[0].decoderawtransaction(rawTxSigned['hex'])
self.sync_all()
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
assert_equal(self.nodes[0].getbalance(), bal + Decimal('50.00000000') + Decimal('2.19000000')) # block reward + tx
@@ -507,7 +507,7 @@ class RawTransactionsTest(BitcoinTestFramework):
decTx = self.nodes[0].gettransaction(txId)
rawTx2 = self.nodes[0].decoderawtransaction(decTx['hex'])
self.sync_all()
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
assert_equal(self.nodes[2].getbalance(), bal) # the funds of a 2of2 multisig tx should not be marked as spendable
@@ -532,7 +532,7 @@ class RawTransactionsTest(BitcoinTestFramework):
self.nodes[2].sendrawtransaction(rawTxComb)
rawTx2 = self.nodes[0].decoderawtransaction(rawTxComb)
self.sync_all()
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
assert_equal(self.nodes[0].getbalance(), bal + Decimal('50.00000000') + Decimal('2.19000000')) # block reward + tx
diff --git a/test/functional/rpc_scantxoutset.py b/test/functional/rpc_scantxoutset.py
index 070f59d314..ec8205acd5 100755
--- a/test/functional/rpc_scantxoutset.py
+++ b/test/functional/rpc_scantxoutset.py
@@ -23,7 +23,7 @@ class ScantxoutsetTest(BitcoinTestFramework):
def run_test(self):
self.log.info("Mining blocks...")
- self.nodes[0].generate(110)
+ self.generate(self.nodes[0], 110)
addr_P2SH_SEGWIT = self.nodes[0].getnewaddress("", "p2sh-segwit")
pubk1 = self.nodes[0].getaddressinfo(addr_P2SH_SEGWIT)['pubkey']
@@ -50,14 +50,14 @@ class ScantxoutsetTest(BitcoinTestFramework):
self.nodes[0].sendtoaddress("mpQ8rokAhp1TAtJQR6F6TaUmjAWkAWYYBq", 16.384) # (m/1/1/1500)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.log.info("Stop node, remove wallet, mine again some blocks...")
self.stop_node(0)
shutil.rmtree(os.path.join(self.nodes[0].datadir, self.chain, 'wallets'))
self.start_node(0, ['-nowallet'])
self.import_deterministic_coinbase_privkeys()
- self.nodes[0].generate(110)
+ self.generate(self.nodes[0], 110)
scan = self.nodes[0].scantxoutset("start", [])
info = self.nodes[0].gettxoutsetinfo()
diff --git a/test/functional/rpc_signer.py b/test/functional/rpc_signer.py
index 3188763f49..5c3722ef8f 100755
--- a/test/functional/rpc_signer.py
+++ b/test/functional/rpc_signer.py
@@ -27,6 +27,9 @@ class RPCSignerTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 4
+ # The experimental syscall sandbox feature (-sandbox) is not compatible with -signer (which
+ # invokes execve).
+ self.disable_syscall_sandbox = True
self.extra_args = [
[],
@@ -53,8 +56,12 @@ class RPCSignerTest(BitcoinTestFramework):
)
# Handle script missing:
- assert_raises_rpc_error(-1, 'execve failed: No such file or directory',
- self.nodes[3].enumeratesigners
+ assert_raises_rpc_error(
+ -1,
+ "CreateProcess failed: The system cannot find the file specified."
+ if platform.system() == "Windows"
+ else "execve failed: No such file or directory",
+ self.nodes[3].enumeratesigners,
)
# Handle error thrown by script
diff --git a/test/functional/rpc_signrawtransaction.py b/test/functional/rpc_signrawtransaction.py
index e6fef7e838..c519d0c7d1 100755
--- a/test/functional/rpc_signrawtransaction.py
+++ b/test/functional/rpc_signrawtransaction.py
@@ -6,7 +6,6 @@
from test_framework.blocktools import (
COINBASE_MATURITY,
- CSV_ACTIVATION_HEIGHT,
)
from test_framework.address import (
script_to_p2sh,
@@ -18,7 +17,6 @@ from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
find_vout_for_address,
- generate_to_height,
)
from test_framework.messages import (
CTxInWitness,
@@ -27,12 +25,12 @@ from test_framework.messages import (
from test_framework.script import (
CScript,
OP_CHECKLOCKTIMEVERIFY,
- OP_CHECKSIG,
OP_CHECKSEQUENCEVERIFY,
OP_DROP,
OP_TRUE,
)
from test_framework.script_util import (
+ key_to_p2pk_script,
key_to_p2pkh_script,
script_to_p2sh_p2wsh_script,
script_to_p2wsh_script,
@@ -183,7 +181,7 @@ class SignRawTransactionsTest(BitcoinTestFramework):
def test_fully_signed_tx(self):
self.log.info("Test signing a fully signed transaction does nothing")
self.nodes[0].walletpassphrase("password", 9999)
- self.nodes[0].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[0], COINBASE_MATURITY + 1)
rawtx = self.nodes[0].createrawtransaction([], [{self.nodes[0].getnewaddress(): 10}])
fundedtx = self.nodes[0].fundrawtransaction(rawtx)
signedtx = self.nodes[0].signrawtransactionwithwallet(fundedtx["hex"])
@@ -202,9 +200,9 @@ class SignRawTransactionsTest(BitcoinTestFramework):
embedded_pubkey = eckey.get_pubkey().get_bytes().hex()
p2sh_p2wsh_address = self.nodes[1].createmultisig(1, [embedded_pubkey], "p2sh-segwit")
# send transaction to P2SH-P2WSH 1-of-1 multisig address
- self.nodes[0].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[0], COINBASE_MATURITY + 1)
self.nodes[0].sendtoaddress(p2sh_p2wsh_address["address"], 49.999)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# Get the UTXO info from scantxoutset
unspent_output = self.nodes[1].scantxoutset('start', [p2sh_p2wsh_address['descriptor']])['unspents'][0]
@@ -231,7 +229,7 @@ class SignRawTransactionsTest(BitcoinTestFramework):
embedded_pubkey = eckey.get_pubkey().get_bytes().hex()
witness_script = {
'P2PKH': key_to_p2pkh_script(embedded_pubkey).hex(),
- 'P2PK': CScript([bytes.fromhex(embedded_pubkey), OP_CHECKSIG]).hex()
+ 'P2PK': key_to_p2pk_script(embedded_pubkey).hex()
}.get(tx_type, "Invalid tx_type")
redeem_script = script_to_p2wsh_script(witness_script).hex()
addr = script_to_p2sh(redeem_script)
@@ -239,7 +237,7 @@ class SignRawTransactionsTest(BitcoinTestFramework):
# Fund that address
txid = self.nodes[0].sendtoaddress(addr, 10)
vout = find_vout_for_address(self.nodes[0], txid, addr)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
# Now create and sign a transaction spending that output on node[0], which doesn't know the scripts or keys
spending_tx = self.nodes[0].createrawtransaction([{'txid': txid, 'vout': vout}], {self.nodes[1].getnewaddress(): Decimal("9.999")})
spending_tx_signed = self.nodes[0].signrawtransactionwithkey(spending_tx, [embedded_privkey], [{'txid': txid, 'vout': vout, 'scriptPubKey': script_pub_key, 'redeemScript': redeem_script, 'witnessScript': witness_script, 'amount': 10}])
@@ -273,7 +271,6 @@ class SignRawTransactionsTest(BitcoinTestFramework):
getcontext().prec = 8
# Make sure CSV is active
- generate_to_height(self, self.nodes[0], CSV_ACTIVATION_HEIGHT)
assert self.nodes[0].getblockchaininfo()['softforks']['csv']['active']
# Create a P2WSH script with CSV
@@ -283,7 +280,7 @@ class SignRawTransactionsTest(BitcoinTestFramework):
# Fund that address and make the spend
txid = self.nodes[0].sendtoaddress(address, 1)
vout = find_vout_for_address(self.nodes[0], txid, address)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
utxo = self.nodes[0].listunspent()[0]
amt = Decimal(1) + utxo["amount"] - Decimal(0.00001)
tx = self.nodes[0].createrawtransaction(
@@ -318,7 +315,7 @@ class SignRawTransactionsTest(BitcoinTestFramework):
# Fund that address and make the spend
txid = self.nodes[0].sendtoaddress(address, 1)
vout = find_vout_for_address(self.nodes[0], txid, address)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
utxo = self.nodes[0].listunspent()[0]
amt = Decimal(1) + utxo["amount"] - Decimal(0.00001)
tx = self.nodes[0].createrawtransaction(
diff --git a/test/functional/rpc_txoutproof.py b/test/functional/rpc_txoutproof.py
index 67af6b8f8e..a45694328a 100755
--- a/test/functional/rpc_txoutproof.py
+++ b/test/functional/rpc_txoutproof.py
@@ -29,8 +29,8 @@ class MerkleBlockTest(BitcoinTestFramework):
def run_test(self):
miniwallet = MiniWallet(self.nodes[0])
# Add enough mature utxos to the wallet, so that all txs spend confirmed coins
- miniwallet.generate(5)
- self.nodes[0].generate(COINBASE_MATURITY)
+ self.generate(miniwallet, 5)
+ self.generate(self.nodes[0], COINBASE_MATURITY)
self.sync_all()
chain_height = self.nodes[1].getblockcount()
@@ -41,7 +41,7 @@ class MerkleBlockTest(BitcoinTestFramework):
# This will raise an exception because the transaction is not yet in a block
assert_raises_rpc_error(-5, "Transaction not yet in block", self.nodes[0].gettxoutproof, [txid1])
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
blockhash = self.nodes[0].getblockhash(chain_height + 1)
self.sync_all()
@@ -57,7 +57,7 @@ class MerkleBlockTest(BitcoinTestFramework):
txin_spent = miniwallet.get_utxo() # Get the change from txid2
tx3 = miniwallet.send_self_transfer(from_node=self.nodes[0], utxo_to_spend=txin_spent)
txid3 = tx3['txid']
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
txid_spent = txin_spent["txid"]
diff --git a/test/functional/test-shell.md b/test/functional/test-shell.md
index b8e899d675..78737509cb 100644
--- a/test/functional/test-shell.md
+++ b/test/functional/test-shell.md
@@ -94,7 +94,7 @@ rewards to a wallet address owned by the mining node.
```
>>> address = test.nodes[0].getnewaddress()
->>> test.nodes[0].generatetoaddress(101, address)
+>>> test.self.generatetoaddress(nodes[0], 101, address)
['2b98dd0044aae6f1cca7f88a0acf366a4bfe053c7f7b00da3c0d115f03d67efb', ...
```
Since the two nodes are both initialized by default to establish an outbound
diff --git a/test/functional/test_framework/authproxy.py b/test/functional/test_framework/authproxy.py
index 81eb881234..c4ffd1fbf6 100644
--- a/test/functional/test_framework/authproxy.py
+++ b/test/functional/test_framework/authproxy.py
@@ -113,10 +113,8 @@ class AuthServiceProxy():
self.__conn.request(method, path, postdata, headers)
return self._get_response()
except OSError as e:
- retry = (
- '[WinError 10053] An established connection was aborted by the software in your host machine' in str(e))
# Workaround for a bug on macOS. See https://bugs.python.org/issue33450
- retry = retry or ('[Errno 41] Protocol wrong type for socket' in str(e))
+ retry = '[Errno 41] Protocol wrong type for socket' in str(e)
if retry:
self.__conn.close()
self.__conn.request(method, path, postdata, headers)
diff --git a/test/functional/test_framework/blocktools.py b/test/functional/test_framework/blocktools.py
index 25b36b6a91..85e3c2a383 100644
--- a/test/functional/test_framework/blocktools.py
+++ b/test/functional/test_framework/blocktools.py
@@ -33,11 +33,11 @@ from .script import (
CScriptOp,
OP_1,
OP_CHECKMULTISIG,
- OP_CHECKSIG,
OP_RETURN,
OP_TRUE,
)
from .script_util import (
+ key_to_p2pk_script,
key_to_p2wpkh_script,
script_to_p2wsh_script,
)
@@ -53,11 +53,6 @@ TIME_GENESIS_BLOCK = 1296688602
# Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
COINBASE_MATURITY = 100
-# Soft-fork activation heights
-DERSIG_HEIGHT = 102 # BIP 66
-CLTV_HEIGHT = 111 # BIP 65
-CSV_ACTIVATION_HEIGHT = 432
-
# From BIP141
WITNESS_COMMITMENT_HEADER = b"\xaa\x21\xa9\xed"
@@ -139,7 +134,7 @@ def create_coinbase(height, pubkey=None, extra_output_script=None, fees=0, nValu
coinbaseoutput.nValue >>= halvings
coinbaseoutput.nValue += fees
if pubkey is not None:
- coinbaseoutput.scriptPubKey = CScript([pubkey, OP_CHECKSIG])
+ coinbaseoutput.scriptPubKey = key_to_p2pk_script(pubkey)
else:
coinbaseoutput.scriptPubKey = CScript([OP_TRUE])
coinbase.vout = [coinbaseoutput]
diff --git a/test/functional/test_framework/p2p.py b/test/functional/test_framework/p2p.py
index b7d5bd8fab..78c63b57a1 100755
--- a/test/functional/test_framework/p2p.py
+++ b/test/functional/test_framework/p2p.py
@@ -356,7 +356,7 @@ class P2PInterface(P2PConnection):
return create_conn
- def peer_accept_connection(self, *args, services=NODE_NETWORK | NODE_WITNESS, **kwargs):
+ def peer_accept_connection(self, *args, services=P2P_SERVICES, **kwargs):
create_conn = super().peer_accept_connection(*args, **kwargs)
self.peer_connect_send_version(services)
@@ -577,6 +577,8 @@ class NetworkThread(threading.Thread):
NetworkThread.listeners = {}
NetworkThread.protos = {}
+ if sys.platform == 'win32':
+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
NetworkThread.network_event_loop = asyncio.new_event_loop()
def run(self):
diff --git a/test/functional/test_framework/script_util.py b/test/functional/test_framework/script_util.py
index 5d1d7ea45c..82a9067dd2 100755
--- a/test/functional/test_framework/script_util.py
+++ b/test/functional/test_framework/script_util.py
@@ -3,7 +3,17 @@
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Useful Script constants and utils."""
-from test_framework.script import CScript, hash160, sha256, OP_0, OP_DUP, OP_HASH160, OP_CHECKSIG, OP_EQUAL, OP_EQUALVERIFY
+from test_framework.script import (
+ CScript,
+ OP_0,
+ OP_CHECKSIG,
+ OP_DUP,
+ OP_EQUAL,
+ OP_EQUALVERIFY,
+ OP_HASH160,
+ hash160,
+ sha256,
+)
# To prevent a "tx-size-small" policy rule error, a transaction has to have a
# non-witness size of at least 82 bytes (MIN_STANDARD_TX_NONWITNESS_SIZE in
@@ -25,28 +35,39 @@ from test_framework.script import CScript, hash160, sha256, OP_0, OP_DUP, OP_HAS
DUMMY_P2WPKH_SCRIPT = CScript([b'a' * 21])
DUMMY_2_P2WPKH_SCRIPT = CScript([b'b' * 21])
-def keyhash_to_p2pkh_script(hash, main = False):
+
+def key_to_p2pk_script(key):
+ key = check_key(key)
+ return CScript([key, OP_CHECKSIG])
+
+
+def keyhash_to_p2pkh_script(hash):
assert len(hash) == 20
return CScript([OP_DUP, OP_HASH160, hash, OP_EQUALVERIFY, OP_CHECKSIG])
-def scripthash_to_p2sh_script(hash, main = False):
+
+def scripthash_to_p2sh_script(hash):
assert len(hash) == 20
return CScript([OP_HASH160, hash, OP_EQUAL])
-def key_to_p2pkh_script(key, main = False):
+
+def key_to_p2pkh_script(key):
key = check_key(key)
- return keyhash_to_p2pkh_script(hash160(key), main)
+ return keyhash_to_p2pkh_script(hash160(key))
+
-def script_to_p2sh_script(script, main = False):
+def script_to_p2sh_script(script):
script = check_script(script)
- return scripthash_to_p2sh_script(hash160(script), main)
+ return scripthash_to_p2sh_script(hash160(script))
-def key_to_p2sh_p2wpkh_script(key, main = False):
+
+def key_to_p2sh_p2wpkh_script(key):
key = check_key(key)
p2shscript = CScript([OP_0, hash160(key)])
- return script_to_p2sh_script(p2shscript, main)
+ return script_to_p2sh_script(p2shscript)
+
-def program_to_witness_script(version, program, main = False):
+def program_to_witness_script(version, program):
if isinstance(program, str):
program = bytes.fromhex(program)
assert 0 <= version <= 16
@@ -54,29 +75,34 @@ def program_to_witness_script(version, program, main = False):
assert version > 0 or len(program) in [20, 32]
return CScript([version, program])
-def script_to_p2wsh_script(script, main = False):
+
+def script_to_p2wsh_script(script):
script = check_script(script)
- return program_to_witness_script(0, sha256(script), main)
+ return program_to_witness_script(0, sha256(script))
+
-def key_to_p2wpkh_script(key, main = False):
+def key_to_p2wpkh_script(key):
key = check_key(key)
- return program_to_witness_script(0, hash160(key), main)
+ return program_to_witness_script(0, hash160(key))
-def script_to_p2sh_p2wsh_script(script, main = False):
+
+def script_to_p2sh_p2wsh_script(script):
script = check_script(script)
p2shscript = CScript([OP_0, sha256(script)])
- return script_to_p2sh_script(p2shscript, main)
+ return script_to_p2sh_script(p2shscript)
+
def check_key(key):
if isinstance(key, str):
- key = bytes.fromhex(key) # Assuming this is hex string
+ key = bytes.fromhex(key) # Assuming this is hex string
if isinstance(key, bytes) and (len(key) == 33 or len(key) == 65):
return key
assert False
+
def check_script(script):
if isinstance(script, str):
- script = bytes.fromhex(script) # Assuming this is hex string
+ script = bytes.fromhex(script) # Assuming this is hex string
if isinstance(script, bytes) or isinstance(script, CScript):
return script
assert False
diff --git a/test/functional/test_framework/test_framework.py b/test/functional/test_framework/test_framework.py
index f382e0fdb3..d87d0cacfd 100755
--- a/test/functional/test_framework/test_framework.py
+++ b/test/functional/test_framework/test_framework.py
@@ -101,6 +101,7 @@ class BitcoinTestFramework(metaclass=BitcoinTestMetaClass):
self.supports_cli = True
self.bind_to_localhost_only = True
self.parse_args()
+ self.disable_syscall_sandbox = self.options.nosandbox
self.default_wallet_name = "default_wallet" if self.options.descriptors else ""
self.wallet_data_filename = "wallet.dat"
# Optional list of wallet names that can be set in set_test_params to
@@ -159,6 +160,8 @@ class BitcoinTestFramework(metaclass=BitcoinTestMetaClass):
parser = argparse.ArgumentParser(usage="%(prog)s [options]")
parser.add_argument("--nocleanup", dest="nocleanup", default=False, action="store_true",
help="Leave bitcoinds and test.* datadir on exit or error")
+ parser.add_argument("--nosandbox", dest="nosandbox", default=False, action="store_true",
+ help="Don't use the syscall sandbox")
parser.add_argument("--noshutdown", dest="noshutdown", default=False, action="store_true",
help="Don't stop bitcoinds after the test execution")
parser.add_argument("--cachedir", dest="cachedir", default=os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/../../cache"),
@@ -468,6 +471,10 @@ class BitcoinTestFramework(metaclass=BitcoinTestMetaClass):
extra_args = [[]] * num_nodes
if versions is None:
versions = [None] * num_nodes
+ if self.is_syscall_sandbox_compiled() and not self.disable_syscall_sandbox:
+ for i in range(len(extra_args)):
+ if versions[i] is None or versions[i] >= 219900:
+ extra_args[i] = extra_args[i] + ["-sandbox=log-and-abort"]
if binary is None:
binary = [get_bin_from_version(v, 'bitcoind', self.options.bitcoind) for v in versions]
if binary_cli is None:
@@ -560,18 +567,19 @@ class BitcoinTestFramework(metaclass=BitcoinTestMetaClass):
self.nodes[i].process.wait(timeout)
def connect_nodes(self, a, b):
- def connect_nodes_helper(from_connection, node_num):
- ip_port = "127.0.0.1:" + str(p2p_port(node_num))
- from_connection.addnode(ip_port, "onetry")
- # poll until version handshake complete to avoid race conditions
- # with transaction relaying
- # See comments in net_processing:
- # * Must have a version message before anything else
- # * Must have a verack message before anything else
- wait_until_helper(lambda: all(peer['version'] != 0 for peer in from_connection.getpeerinfo()))
- wait_until_helper(lambda: all(peer['bytesrecv_per_msg'].pop('verack', 0) == 24 for peer in from_connection.getpeerinfo()))
-
- connect_nodes_helper(self.nodes[a], b)
+ from_connection = self.nodes[a]
+ to_connection = self.nodes[b]
+ ip_port = "127.0.0.1:" + str(p2p_port(b))
+ from_connection.addnode(ip_port, "onetry")
+ # poll until version handshake complete to avoid race conditions
+ # with transaction relaying
+ # See comments in net_processing:
+ # * Must have a version message before anything else
+ # * Must have a verack message before anything else
+ wait_until_helper(lambda: all(peer['version'] != 0 for peer in from_connection.getpeerinfo()))
+ wait_until_helper(lambda: all(peer['version'] != 0 for peer in to_connection.getpeerinfo()))
+ wait_until_helper(lambda: all(peer['bytesrecv_per_msg'].pop('verack', 0) == 24 for peer in from_connection.getpeerinfo()))
+ wait_until_helper(lambda: all(peer['bytesrecv_per_msg'].pop('verack', 0) == 24 for peer in to_connection.getpeerinfo()))
def disconnect_nodes(self, a, b):
def disconnect_nodes_helper(from_connection, node_num):
@@ -886,3 +894,7 @@ class BitcoinTestFramework(metaclass=BitcoinTestMetaClass):
def is_bdb_compiled(self):
"""Checks whether the wallet module was compiled with BDB support."""
return self.config["components"].getboolean("USE_BDB")
+
+ def is_syscall_sandbox_compiled(self):
+ """Checks whether the syscall sandbox was compiled."""
+ return self.config["components"].getboolean("ENABLE_SYSCALL_SANDBOX")
diff --git a/test/functional/test_framework/util.py b/test/functional/test_framework/util.py
index ec27fd7f85..9f5bca6884 100644
--- a/test/functional/test_framework/util.py
+++ b/test/functional/test_framework/util.py
@@ -34,13 +34,14 @@ def assert_approx(v, vexp, vspan=0.00001):
raise AssertionError("%s > [%s..%s]" % (str(v), str(vexp - vspan), str(vexp + vspan)))
-def assert_fee_amount(fee, tx_size, fee_per_kB):
- """Assert the fee was in range"""
- target_fee = round(tx_size * fee_per_kB / 1000, 8)
+def assert_fee_amount(fee, tx_size, feerate_BTC_kvB):
+ """Assert the fee is in range."""
+ feerate_BTC_vB = feerate_BTC_kvB / 1000
+ target_fee = satoshi_round(tx_size * feerate_BTC_vB)
if fee < target_fee:
raise AssertionError("Fee of %s BTC too low! (Should be %s BTC)" % (str(fee), str(target_fee)))
# allow the wallet's estimation to be at most 2 bytes off
- if fee > (tx_size + 2) * fee_per_kB / 1000:
+ if fee > (tx_size + 2) * feerate_BTC_vB:
raise AssertionError("Fee of %s BTC too high! (Should be %s BTC)" % (str(fee), str(target_fee)))
@@ -364,6 +365,11 @@ def write_config(config_path, *, n, chain, extra_config="", disable_autoconnect=
f.write("dnsseed=0\n")
f.write("fixedseeds=0\n")
f.write("listenonion=0\n")
+ # Increase peertimeout to avoid disconnects while using mocktime.
+ # peertimeout is measured in wall clock time, so setting it to the
+ # duration of the longest test is sufficient. It can be overridden in
+ # tests.
+ f.write("peertimeout=999999\n")
f.write("printtoconsole=0\n")
f.write("upnp=0\n")
f.write("natpmp=0\n")
@@ -555,17 +561,6 @@ def mine_large_block(test_framework, node, utxos=None):
test_framework.generate(node, 1)
-def generate_to_height(test_framework, node, target_height):
- """Generates blocks until a given target block height has been reached.
- To prevent timeouts, only up to 200 blocks are generated per RPC call.
- Can be used to activate certain soft-forks (e.g. CSV, CLTV)."""
- current_height = node.getblockcount()
- while current_height < target_height:
- nblocks = min(200, target_height - current_height)
- current_height += len(test_framework.generate(node, nblocks))
- assert_equal(node.getblockcount(), target_height)
-
-
def find_vout_for_address(node, txid, addr):
"""
Locate the vout index of the given transaction sending to the
diff --git a/test/functional/test_framework/wallet.py b/test/functional/test_framework/wallet.py
index ba5b95f930..b0b578e544 100644
--- a/test/functional/test_framework/wallet.py
+++ b/test/functional/test_framework/wallet.py
@@ -10,6 +10,7 @@ from enum import Enum
from random import choice
from typing import Optional
from test_framework.address import ADDRESS_BCRT1_P2WSH_OP_TRUE
+from test_framework.descriptors import descsum_create
from test_framework.key import ECKey
from test_framework.messages import (
COIN,
@@ -23,15 +24,17 @@ from test_framework.messages import (
from test_framework.script import (
CScript,
LegacySignatureHash,
- OP_CHECKSIG,
OP_TRUE,
OP_NOP,
SIGHASH_ALL,
)
+from test_framework.script_util import (
+ key_to_p2pk_script,
+ key_to_p2wpkh_script,
+)
from test_framework.util import (
assert_equal,
assert_greater_than_or_equal,
- satoshi_round,
)
DEFAULT_FEE = Decimal("0.0001")
@@ -74,17 +77,18 @@ class MiniWallet:
self._priv_key = ECKey()
self._priv_key.set((1).to_bytes(32, 'big'), True)
pub_key = self._priv_key.get_pubkey()
- self._scriptPubKey = bytes(CScript([pub_key.get_bytes(), OP_CHECKSIG]))
+ self._scriptPubKey = key_to_p2pk_script(pub_key.get_bytes())
elif mode == MiniWalletMode.ADDRESS_OP_TRUE:
self._address = ADDRESS_BCRT1_P2WSH_OP_TRUE
self._scriptPubKey = bytes.fromhex(self._test_node.validateaddress(self._address)['scriptPubKey'])
- def scan_blocks(self, *, start=1, num):
- """Scan the blocks for self._address outputs and add them to self._utxos"""
- for i in range(start, start + num):
- block = self._test_node.getblock(blockhash=self._test_node.getblockhash(i), verbosity=2)
- for tx in block['tx']:
- self.scan_tx(tx)
+ def rescan_utxos(self):
+ """Drop all utxos and rescan the utxo set"""
+ self._utxos = []
+ res = self._test_node.scantxoutset(action="start", scanobjects=[self.get_descriptor()])
+ assert_equal(True, res['success'])
+ for utxo in res['unspents']:
+ self._utxos.append({'txid': utxo['txid'], 'vout': utxo['vout'], 'value': utxo['amount']})
def scan_tx(self, tx):
"""Scan the tx for self._scriptPubKey outputs and add them to self._utxos"""
@@ -109,12 +113,15 @@ class MiniWallet:
def generate(self, num_blocks):
"""Generate blocks with coinbase outputs to the internal address, and append the outputs to the internal list"""
- blocks = self._test_node.generatetodescriptor(num_blocks, f'raw({self._scriptPubKey.hex()})')
+ blocks = self._test_node.generatetodescriptor(num_blocks, self.get_descriptor())
for b in blocks:
cb_tx = self._test_node.getblock(blockhash=b, verbosity=2)['tx'][0]
self._utxos.append({'txid': cb_tx['txid'], 'vout': 0, 'value': cb_tx['vout'][0]['value']})
return blocks
+ def get_descriptor(self):
+ return descsum_create(f'raw({self._scriptPubKey.hex()})')
+
def get_address(self):
return self._address
@@ -142,6 +149,25 @@ class MiniWallet:
self.sendrawtransaction(from_node=kwargs['from_node'], tx_hex=tx['hex'])
return tx
+ def send_to(self, *, from_node, scriptPubKey, amount, fee=1000):
+ """
+ Create and send a tx with an output to a given scriptPubKey/amount,
+ plus a change output to our internal address. To keep things simple, a
+ fixed fee given in Satoshi is used.
+
+ Note that this method fails if there is no single internal utxo
+ available that can cover the cost for the amount and the fixed fee
+ (the utxo with the largest value is taken).
+
+ Returns a tuple (txid, n) referring to the created external utxo outpoint.
+ """
+ tx = self.create_self_transfer(from_node=from_node, fee_rate=0, mempool_valid=False)['tx']
+ assert_greater_than_or_equal(tx.vout[0].nValue, amount + fee)
+ tx.vout[0].nValue -= (amount + fee) # change output -> MiniWallet
+ tx.vout.append(CTxOut(amount, scriptPubKey)) # arbitrary output -> to be returned
+ txid = self.sendrawtransaction(from_node=from_node, tx_hex=tx.serialize().hex())
+ return txid, 1
+
def create_self_transfer(self, *, fee_rate=Decimal("0.003"), from_node, utxo_to_spend=None, mempool_valid=True, locktime=0, sequence=0):
"""Create and return a tx with the specified fee_rate. Fee may be exact or at most one satoshi higher than needed."""
self._utxos = sorted(self._utxos, key=lambda k: k['value'])
@@ -150,13 +176,12 @@ class MiniWallet:
vsize = Decimal(96) # anyone-can-spend
else:
vsize = Decimal(168) # P2PK (73 bytes scriptSig + 35 bytes scriptPubKey + 60 bytes other)
- send_value = satoshi_round(utxo_to_spend['value'] - fee_rate * (vsize / 1000))
- fee = utxo_to_spend['value'] - send_value
+ send_value = int(COIN * (utxo_to_spend['value'] - fee_rate * (vsize / 1000)))
assert send_value > 0
tx = CTransaction()
tx.vin = [CTxIn(COutPoint(int(utxo_to_spend['txid'], 16), utxo_to_spend['vout']), nSequence=sequence)]
- tx.vout = [CTxOut(int(send_value * COIN), self._scriptPubKey)]
+ tx.vout = [CTxOut(send_value, self._scriptPubKey)]
tx.nLockTime = locktime
if not self._address:
# raw script
@@ -175,12 +200,22 @@ class MiniWallet:
assert_equal(mempool_valid, tx_info['allowed'])
if mempool_valid:
assert_equal(tx_info['vsize'], vsize)
- assert_equal(tx_info['fees']['base'], fee)
+ assert_equal(tx_info['fees']['base'], utxo_to_spend['value'] - Decimal(send_value) / COIN)
return {'txid': tx_info['txid'], 'wtxid': tx_info['wtxid'], 'hex': tx_hex, 'tx': tx}
def sendrawtransaction(self, *, from_node, tx_hex):
- from_node.sendrawtransaction(tx_hex)
+ txid = from_node.sendrawtransaction(tx_hex)
self.scan_tx(from_node.decoderawtransaction(tx_hex))
+ return txid
+
+
+def random_p2wpkh():
+ """Generate a random P2WPKH scriptPubKey. Can be used when a random destination is needed,
+ but no compiled wallet is available (e.g. as replacement to the getnewaddress RPC)."""
+ key = ECKey()
+ key.generate()
+ return key_to_p2wpkh_script(key.get_pubkey().get_bytes())
+
def make_chain(node, address, privkeys, parent_txid, parent_value, n=0, parent_locking_script=None, fee=DEFAULT_FEE):
"""Build a transaction that spends parent_txid.vout[n] and produces one output with
diff --git a/test/functional/test_runner.py b/test/functional/test_runner.py
index 3792d751de..c5f08b27f2 100755
--- a/test/functional/test_runner.py
+++ b/test/functional/test_runner.py
@@ -98,6 +98,7 @@ BASE_SCRIPTS = [
'rpc_fundrawtransaction.py --legacy-wallet',
'rpc_fundrawtransaction.py --descriptors',
'p2p_compactblocks.py',
+ 'p2p_compactblocks_blocksonly.py',
'feature_segwit.py --legacy-wallet',
# vv Tests less than 2m vv
'wallet_basic.py --legacy-wallet',
@@ -170,11 +171,13 @@ BASE_SCRIPTS = [
'rpc_users.py',
'rpc_whitelist.py',
'feature_proxy.py',
+ 'feature_syscall_sandbox.py',
'rpc_signrawtransaction.py --legacy-wallet',
'rpc_signrawtransaction.py --descriptors',
'rpc_rawtransaction.py --legacy-wallet',
'rpc_rawtransaction.py --descriptors',
'wallet_groups.py --legacy-wallet',
+ 'wallet_transactiontime_rescan.py',
'p2p_addrv2_relay.py',
'wallet_groups.py --descriptors',
'p2p_compactblocks_hb.py',
@@ -304,7 +307,6 @@ BASE_SCRIPTS = [
'feature_presegwit_node_upgrade.py',
'feature_settings.py',
'rpc_getdescriptorinfo.py',
- 'rpc_addresses_deprecation.py',
'rpc_help.py',
'feature_help.py',
'feature_shutdown.py',
@@ -401,8 +403,9 @@ def main():
for test in tests:
script = test.split("/")[-1]
script = script + ".py" if ".py" not in script else script
- if script in ALL_SCRIPTS:
- test_list.append(script)
+ matching_scripts = [s for s in ALL_SCRIPTS if s.startswith(script)]
+ if matching_scripts:
+ test_list.extend(matching_scripts)
else:
print("{}WARNING!{} Test '{}' not found in full test list.".format(BOLD[1], BOLD[0], test))
elif args.extended:
diff --git a/test/functional/tool_wallet.py b/test/functional/tool_wallet.py
index 28103793df..4bf3927879 100755
--- a/test/functional/tool_wallet.py
+++ b/test/functional/tool_wallet.py
@@ -242,7 +242,7 @@ class ToolWalletTest(BitcoinTestFramework):
"""
self.start_node(0)
self.log.info('Generating transaction to mutate wallet')
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.stop_node(0)
self.log.info('Calling wallet tool info after generating a transaction, testing output')
@@ -344,7 +344,7 @@ class ToolWalletTest(BitcoinTestFramework):
non_exist_dump = os.path.join(self.nodes[0].datadir, "wallet.nodump")
self.assert_raises_tool_error('Unknown wallet file format "notaformat" provided. Please provide one of "bdb" or "sqlite".', '-wallet=todump', '-format=notaformat', '-dumpfile={}'.format(wallet_dump), 'createfromdump')
self.assert_raises_tool_error('Dump file {} does not exist.'.format(non_exist_dump), '-wallet=todump', '-dumpfile={}'.format(non_exist_dump), 'createfromdump')
- wallet_path = os.path.join(self.nodes[0].datadir, 'regtest/wallets/todump2')
+ wallet_path = os.path.join(self.nodes[0].datadir, 'regtest', 'wallets', 'todump2')
self.assert_raises_tool_error('Failed to create database path \'{}\'. Database already exists.'.format(wallet_path), '-wallet=todump2', '-dumpfile={}'.format(wallet_dump), 'createfromdump')
self.assert_raises_tool_error("The -descriptors option can only be used with the 'create' command.", '-descriptors', '-wallet=todump2', '-dumpfile={}'.format(wallet_dump), 'createfromdump')
diff --git a/test/functional/wallet_abandonconflict.py b/test/functional/wallet_abandonconflict.py
index d24cc802a4..70ca5a2fe4 100755
--- a/test/functional/wallet_abandonconflict.py
+++ b/test/functional/wallet_abandonconflict.py
@@ -29,14 +29,14 @@ class AbandonConflictTest(BitcoinTestFramework):
self.skip_if_no_wallet()
def run_test(self):
- self.nodes[1].generate(COINBASE_MATURITY)
+ self.generate(self.nodes[1], COINBASE_MATURITY)
self.sync_blocks()
balance = self.nodes[0].getbalance()
txA = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), Decimal("10"))
txB = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), Decimal("10"))
txC = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), Decimal("10"))
self.sync_mempools()
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
# Can not abandon non-wallet transaction
assert_raises_rpc_error(-5, 'Invalid or non-wallet transaction id', lambda: self.nodes[0].abandontransaction(txid='ff' * 32))
@@ -149,6 +149,7 @@ class AbandonConflictTest(BitcoinTestFramework):
assert_equal(newbalance, balance - Decimal("24.9996"))
balance = newbalance
+ self.log.info("Test transactions conflicted by a double spend")
# Create a double spend of AB1 by spending again from only A's 10 output
# Mine double spend from node 1
inputs = []
@@ -158,11 +159,39 @@ class AbandonConflictTest(BitcoinTestFramework):
tx = self.nodes[0].createrawtransaction(inputs, outputs)
signed = self.nodes[0].signrawtransactionwithwallet(tx)
self.nodes[1].sendrawtransaction(signed["hex"])
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
self.connect_nodes(0, 1)
self.sync_blocks()
+ tx_list = self.nodes[0].listtransactions()
+
+ conflicted = [tx for tx in tx_list if tx["confirmations"] < 0]
+ assert_equal(4, len(conflicted))
+
+ wallet_conflicts = [tx for tx in conflicted if tx["walletconflicts"]]
+ assert_equal(2, len(wallet_conflicts))
+
+ double_spends = [tx for tx in tx_list if tx["walletconflicts"] and tx["confirmations"] > 0]
+ assert_equal(1, len(double_spends))
+ double_spend = double_spends[0]
+
+ # Test the properties of the conflicted transactions, i.e. with confirmations < 0.
+ for tx in conflicted:
+ assert_equal(tx["abandoned"], False)
+ assert_equal(tx["confirmations"], -1)
+ assert_equal(tx["trusted"], False)
+
+ # Test the properties of the double-spend transaction, i.e. having wallet conflicts and confirmations > 0.
+ assert_equal(double_spend["abandoned"], False)
+ assert_equal(double_spend["confirmations"], 1)
+ assert "trusted" not in double_spend.keys() # "trusted" only returned if tx has 0 or negative confirmations.
+
+ # Test the walletconflicts field of each.
+ for tx in wallet_conflicts:
+ assert_equal(double_spend["walletconflicts"], [tx["txid"]])
+ assert_equal(tx["walletconflicts"], [double_spend["txid"]])
+
# Verify that B and C's 10 BTC outputs are available for spending again because AB1 is now conflicted
newbalance = self.nodes[0].getbalance()
assert_equal(newbalance, balance + Decimal("20"))
diff --git a/test/functional/wallet_address_types.py b/test/functional/wallet_address_types.py
index 9b97d08424..bdee22e62b 100755
--- a/test/functional/wallet_address_types.py
+++ b/test/functional/wallet_address_types.py
@@ -221,7 +221,7 @@ class AddressTypeTest(BitcoinTestFramework):
def run_test(self):
# Mine 101 blocks on node5 to bring nodes out of IBD and make sure that
# no coinbases are maturing for the nodes-under-test during the test
- self.nodes[5].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[5], COINBASE_MATURITY + 1)
self.sync_blocks()
uncompressed_1 = "0496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858ee"
@@ -306,7 +306,7 @@ class AddressTypeTest(BitcoinTestFramework):
assert_equal(unconf_balances[to_node], to_send * 10 * (2 + n))
# node5 collects fee and block subsidy to keep accounting simple
- self.nodes[5].generate(1)
+ self.generate(self.nodes[5], 1)
self.sync_blocks()
# Verify that the receiving wallet contains a UTXO with the expected address, and expected descriptor
@@ -336,7 +336,7 @@ class AddressTypeTest(BitcoinTestFramework):
# Fund node 4:
self.nodes[5].sendtoaddress(self.nodes[4].getnewaddress(), Decimal("1"))
- self.nodes[5].generate(1)
+ self.generate(self.nodes[5], 1)
self.sync_blocks()
assert_equal(self.nodes[4].getbalance(), 1)
diff --git a/test/functional/wallet_avoidreuse.py b/test/functional/wallet_avoidreuse.py
index c13d8de4b5..12357e2d63 100755
--- a/test/functional/wallet_avoidreuse.py
+++ b/test/functional/wallet_avoidreuse.py
@@ -79,7 +79,7 @@ class AvoidReuseTest(BitcoinTestFramework):
self.test_persistence()
self.test_immutable()
- self.nodes[0].generate(110)
+ self.generate(self.nodes[0], 110)
self.sync_all()
self.test_change_remains_change(self.nodes[1])
reset_balance(self.nodes[1], self.nodes[0].getnewaddress())
@@ -174,7 +174,7 @@ class AvoidReuseTest(BitcoinTestFramework):
retaddr = self.nodes[0].getnewaddress()
self.nodes[0].sendtoaddress(fundaddr, 10)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# listunspent should show 1 single, unused 10 btc output
@@ -185,7 +185,7 @@ class AvoidReuseTest(BitcoinTestFramework):
assert("used" not in self.nodes[0].getbalances()["mine"])
self.nodes[1].sendtoaddress(retaddr, 5)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# listunspent should show 1 single, unused 5 btc output
@@ -194,7 +194,7 @@ class AvoidReuseTest(BitcoinTestFramework):
assert_balances(self.nodes[1], mine={"used": 0, "trusted": 5})
self.nodes[0].sendtoaddress(fundaddr, 10)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# listunspent should show 2 total outputs (5, 10 btc), one unused (5), one reused (10)
@@ -228,7 +228,7 @@ class AvoidReuseTest(BitcoinTestFramework):
retaddr = self.nodes[0].getnewaddress()
self.nodes[0].sendtoaddress(fundaddr, 10)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# listunspent should show 1 single, unused 10 btc output
@@ -237,7 +237,7 @@ class AvoidReuseTest(BitcoinTestFramework):
assert_balances(self.nodes[1], mine={"used": 0, "trusted": 10})
self.nodes[1].sendtoaddress(retaddr, 5)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# listunspent should show 1 single, unused 5 btc output
@@ -259,7 +259,7 @@ class AvoidReuseTest(BitcoinTestFramework):
assert_equal(second_addr_type, "legacy")
self.nodes[0].sendtoaddress(new_fundaddr, 10)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# listunspent should show 2 total outputs (5, 10 btc), one unused (5), one reused (10)
@@ -302,7 +302,7 @@ class AvoidReuseTest(BitcoinTestFramework):
for _ in range(101):
self.nodes[0].sendtoaddress(new_addr, 1)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# send transaction that should not use all the available outputs
@@ -334,7 +334,7 @@ class AvoidReuseTest(BitcoinTestFramework):
for _ in range(101):
self.nodes[0].sendtoaddress(new_addr, 1)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# Sending a transaction that is smaller than each one of the
@@ -363,7 +363,7 @@ class AvoidReuseTest(BitcoinTestFramework):
for _ in range(202):
self.nodes[0].sendtoaddress(new_addr, 1)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# Sending a transaction that needs to use the full groups
diff --git a/test/functional/wallet_backup.py b/test/functional/wallet_backup.py
index c7a983556d..bc6d6206e5 100755
--- a/test/functional/wallet_backup.py
+++ b/test/functional/wallet_backup.py
@@ -88,7 +88,7 @@ class WalletBackupTest(BitcoinTestFramework):
# Have the miner (node3) mine a block.
# Must sync mempools before mining.
self.sync_mempools()
- self.nodes[3].generate(1)
+ self.generate(self.nodes[3], 1)
self.sync_blocks()
# As above, this mirrors the original bash test.
@@ -130,13 +130,13 @@ class WalletBackupTest(BitcoinTestFramework):
def run_test(self):
self.log.info("Generating initial blockchain")
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
self.sync_blocks()
- self.nodes[2].generate(1)
+ self.generate(self.nodes[2], 1)
self.sync_blocks()
- self.nodes[3].generate(COINBASE_MATURITY)
+ self.generate(self.nodes[3], COINBASE_MATURITY)
self.sync_blocks()
assert_equal(self.nodes[0].getbalance(), 50)
@@ -165,7 +165,7 @@ class WalletBackupTest(BitcoinTestFramework):
self.do_one_round()
# Generate 101 more blocks, so any fees paid mature
- self.nodes[3].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[3], COINBASE_MATURITY + 1)
self.sync_all()
balance0 = self.nodes[0].getbalance()
diff --git a/test/functional/wallet_balance.py b/test/functional/wallet_balance.py
index 204a866c55..2abac7bb92 100755
--- a/test/functional/wallet_balance.py
+++ b/test/functional/wallet_balance.py
@@ -70,10 +70,10 @@ class WalletTest(BitcoinTestFramework):
assert 'watchonly' not in self.nodes[1].getbalances()
self.log.info("Mining blocks ...")
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
- self.nodes[1].generate(1)
- self.nodes[1].generatetoaddress(COINBASE_MATURITY + 1, ADDRESS_WATCHONLY)
+ self.generate(self.nodes[1], 1)
+ self.generatetoaddress(self.nodes[1], COINBASE_MATURITY + 1, ADDRESS_WATCHONLY)
self.sync_all()
if not self.options.descriptors:
@@ -196,7 +196,7 @@ class WalletTest(BitcoinTestFramework):
self.log.info("Test getbalance and getbalances.mine.untrusted_pending with conflicted unconfirmed inputs")
test_balances(fee_node_1=Decimal('0.02'))
- self.nodes[1].generatetoaddress(1, ADDRESS_WATCHONLY)
+ self.generatetoaddress(self.nodes[1], 1, ADDRESS_WATCHONLY)
self.sync_all()
# balances are correct after the transactions are confirmed
@@ -210,7 +210,7 @@ class WalletTest(BitcoinTestFramework):
# Send total balance away from node 1
txs = create_transactions(self.nodes[1], self.nodes[0].getnewaddress(), Decimal('29.97'), [Decimal('0.01')])
self.nodes[1].sendrawtransaction(txs[0]['hex'])
- self.nodes[1].generatetoaddress(2, ADDRESS_WATCHONLY)
+ self.generatetoaddress(self.nodes[1], 2, ADDRESS_WATCHONLY)
self.sync_all()
# getbalance with a minconf incorrectly excludes coins that have been spent more recently than the minconf blocks ago
@@ -257,7 +257,7 @@ class WalletTest(BitcoinTestFramework):
self.nodes[1].sendrawtransaction(hexstring=tx_replace, maxfeerate=0)
# Now confirm tx_replace
- block_reorg = self.nodes[1].generatetoaddress(1, ADDRESS_WATCHONLY)[0]
+ block_reorg = self.generatetoaddress(self.nodes[1], 1, ADDRESS_WATCHONLY)[0]
self.sync_all()
assert_equal(self.nodes[0].getbalance(minconf=0), total_amount)
@@ -265,7 +265,7 @@ class WalletTest(BitcoinTestFramework):
self.nodes[0].invalidateblock(block_reorg)
self.nodes[1].invalidateblock(block_reorg)
assert_equal(self.nodes[0].getbalance(minconf=0), 0) # wallet txs not in the mempool are untrusted
- self.nodes[0].generatetoaddress(1, ADDRESS_WATCHONLY)
+ self.generatetoaddress(self.nodes[0], 1, ADDRESS_WATCHONLY)
assert_equal(self.nodes[0].getbalance(minconf=0), 0) # wallet txs not in the mempool are untrusted
# Now confirm tx_orig
@@ -273,7 +273,7 @@ class WalletTest(BitcoinTestFramework):
self.connect_nodes(0, 1)
self.sync_blocks()
self.nodes[1].sendrawtransaction(tx_orig)
- self.nodes[1].generatetoaddress(1, ADDRESS_WATCHONLY)
+ self.generatetoaddress(self.nodes[1], 1, ADDRESS_WATCHONLY)
self.sync_all()
assert_equal(self.nodes[0].getbalance(minconf=0), total_amount + 1) # The reorg recovered our fee of 1 coin
diff --git a/test/functional/wallet_basic.py b/test/functional/wallet_basic.py
index ab38ddb996..599e506f98 100755
--- a/test/functional/wallet_basic.py
+++ b/test/functional/wallet_basic.py
@@ -13,6 +13,7 @@ from test_framework.util import (
assert_equal,
assert_fee_amount,
assert_raises_rpc_error,
+ find_vout_for_address,
)
from test_framework.wallet_util import test_address
@@ -59,14 +60,14 @@ class WalletTest(BitcoinTestFramework):
self.log.info("Mining blocks...")
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
walletinfo = self.nodes[0].getwalletinfo()
assert_equal(walletinfo['immature_balance'], 50)
assert_equal(walletinfo['balance'], 0)
self.sync_all(self.nodes[0:3])
- self.nodes[1].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[1], COINBASE_MATURITY + 1)
self.sync_all(self.nodes[0:3])
assert_equal(self.nodes[0].getbalance(), 50)
@@ -115,19 +116,55 @@ class WalletTest(BitcoinTestFramework):
assert_equal(walletinfo['immature_balance'], 0)
# Have node0 mine a block, thus it will collect its own fee.
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all(self.nodes[0:3])
# Exercise locking of unspent outputs
unspent_0 = self.nodes[2].listunspent()[0]
unspent_0 = {"txid": unspent_0["txid"], "vout": unspent_0["vout"]}
+ # Trying to unlock an output which isn't locked should error
assert_raises_rpc_error(-8, "Invalid parameter, expected locked output", self.nodes[2].lockunspent, True, [unspent_0])
+
+ # Locking an already-locked output should error
self.nodes[2].lockunspent(False, [unspent_0])
assert_raises_rpc_error(-8, "Invalid parameter, output already locked", self.nodes[2].lockunspent, False, [unspent_0])
+
+ # Restarting the node should clear the lock
+ self.restart_node(2)
+ self.nodes[2].lockunspent(False, [unspent_0])
+
+ # Unloading and reloating the wallet should clear the lock
+ assert_equal(self.nodes[0].listwallets(), [self.default_wallet_name])
+ self.nodes[2].unloadwallet(self.default_wallet_name)
+ self.nodes[2].loadwallet(self.default_wallet_name)
+ assert_equal(len(self.nodes[2].listlockunspent()), 0)
+
+ # Locking non-persistently, then re-locking persistently, is allowed
+ self.nodes[2].lockunspent(False, [unspent_0])
+ self.nodes[2].lockunspent(False, [unspent_0], True)
+
+ # Restarting the node with the lock written to the wallet should keep the lock
+ self.restart_node(2)
+ assert_raises_rpc_error(-8, "Invalid parameter, output already locked", self.nodes[2].lockunspent, False, [unspent_0])
+
+ # Unloading and reloading the wallet with a persistent lock should keep the lock
+ self.nodes[2].unloadwallet(self.default_wallet_name)
+ self.nodes[2].loadwallet(self.default_wallet_name)
+ assert_raises_rpc_error(-8, "Invalid parameter, output already locked", self.nodes[2].lockunspent, False, [unspent_0])
+
+ # Locked outputs should not be used, even if they are the only available funds
assert_raises_rpc_error(-6, "Insufficient funds", self.nodes[2].sendtoaddress, self.nodes[2].getnewaddress(), 20)
assert_equal([unspent_0], self.nodes[2].listlockunspent())
+
+ # Unlocking should remove the persistent lock
self.nodes[2].lockunspent(True, [unspent_0])
+ self.restart_node(2)
assert_equal(len(self.nodes[2].listlockunspent()), 0)
+
+ # Reconnect node 2 after restarts
+ self.connect_nodes(1, 2)
+ self.connect_nodes(0, 2)
+
assert_raises_rpc_error(-8, "txid must be of length 64 (not 34, for '0000000000000000000000000000000000')",
self.nodes[2].lockunspent, False,
[{"txid": "0000000000000000000000000000000000", "vout": 0}])
@@ -159,7 +196,7 @@ class WalletTest(BitcoinTestFramework):
assert_equal(len(self.nodes[1].listlockunspent()), 0)
# Have node1 generate 100 blocks (so node0 can recover the fee)
- self.nodes[1].generate(COINBASE_MATURITY)
+ self.generate(self.nodes[1], COINBASE_MATURITY)
self.sync_all(self.nodes[0:3])
# node0 should end up with 100 btc in block rewards plus fees, but
@@ -188,7 +225,7 @@ class WalletTest(BitcoinTestFramework):
self.nodes[1].sendrawtransaction(hexstring=txns_to_send[1]["hex"], maxfeerate=0)
# Have node1 mine a block to confirm transactions:
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
self.sync_all(self.nodes[0:3])
assert_equal(self.nodes[0].getbalance(), 0)
@@ -203,14 +240,14 @@ class WalletTest(BitcoinTestFramework):
fee_per_byte = Decimal('0.001') / 1000
self.nodes[2].settxfee(fee_per_byte * 1000)
txid = self.nodes[2].sendtoaddress(address, 10, "", "", False)
- self.nodes[2].generate(1)
+ self.generate(self.nodes[2], 1)
self.sync_all(self.nodes[0:3])
node_2_bal = self.check_fee_amount(self.nodes[2].getbalance(), Decimal('84'), fee_per_byte, self.get_vsize(self.nodes[2].gettransaction(txid)['hex']))
assert_equal(self.nodes[0].getbalance(), Decimal('10'))
# Send 10 BTC with subtract fee from amount
txid = self.nodes[2].sendtoaddress(address, 10, "", "", True)
- self.nodes[2].generate(1)
+ self.generate(self.nodes[2], 1)
self.sync_all(self.nodes[0:3])
node_2_bal -= Decimal('10')
assert_equal(self.nodes[2].getbalance(), node_2_bal)
@@ -220,7 +257,7 @@ class WalletTest(BitcoinTestFramework):
# Sendmany 10 BTC
txid = self.nodes[2].sendmany('', {address: 10}, 0, "", [])
- self.nodes[2].generate(1)
+ self.generate(self.nodes[2], 1)
self.sync_all(self.nodes[0:3])
node_0_bal += Decimal('10')
node_2_bal = self.check_fee_amount(self.nodes[2].getbalance(), node_2_bal - Decimal('10'), fee_per_byte, self.get_vsize(self.nodes[2].gettransaction(txid)['hex']))
@@ -228,7 +265,7 @@ class WalletTest(BitcoinTestFramework):
# Sendmany 10 BTC with subtract fee from amount
txid = self.nodes[2].sendmany('', {address: 10}, 0, "", [address])
- self.nodes[2].generate(1)
+ self.generate(self.nodes[2], 1)
self.sync_all(self.nodes[0:3])
node_2_bal -= Decimal('10')
assert_equal(self.nodes[2].getbalance(), node_2_bal)
@@ -241,7 +278,7 @@ class WalletTest(BitcoinTestFramework):
# Test passing fee_rate as a string
txid = self.nodes[2].sendmany(amounts={address: 10}, fee_rate=str(fee_rate_sat_vb))
- self.nodes[2].generate(1)
+ self.generate(self.nodes[2], 1)
self.sync_all(self.nodes[0:3])
balance = self.nodes[2].getbalance()
node_2_bal = self.check_fee_amount(balance, node_2_bal - Decimal('10'), explicit_fee_rate_btc_kvb, self.get_vsize(self.nodes[2].gettransaction(txid)['hex']))
@@ -252,7 +289,7 @@ class WalletTest(BitcoinTestFramework):
# Test passing fee_rate as an integer
amount = Decimal("0.0001")
txid = self.nodes[2].sendmany(amounts={address: amount}, fee_rate=fee_rate_sat_vb)
- self.nodes[2].generate(1)
+ self.generate(self.nodes[2], 1)
self.sync_all(self.nodes[0:3])
balance = self.nodes[2].getbalance()
node_2_bal = self.check_fee_amount(balance, node_2_bal - amount, explicit_fee_rate_btc_kvb, self.get_vsize(self.nodes[2].gettransaction(txid)['hex']))
@@ -314,7 +351,7 @@ class WalletTest(BitcoinTestFramework):
self.nodes[1].sendrawtransaction(signed_raw_tx['hex'])
self.sync_all()
- self.nodes[1].generate(1) # mine a block
+ self.generate(self.nodes[1], 1) # mine a block
self.sync_all()
unspent_txs = self.nodes[0].listunspent() # zero value tx must be in listunspents output
@@ -337,13 +374,13 @@ class WalletTest(BitcoinTestFramework):
txid_not_broadcast = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 2)
tx_obj_not_broadcast = self.nodes[0].gettransaction(txid_not_broadcast)
- self.nodes[1].generate(1) # mine a block, tx should not be in there
+ self.generate(self.nodes[1], 1) # mine a block, tx should not be in there
self.sync_all(self.nodes[0:3])
assert_equal(self.nodes[2].getbalance(), node_2_bal) # should not be changed because tx was not broadcasted
# now broadcast from another node, mine a block, sync, and check the balance
self.nodes[1].sendrawtransaction(tx_obj_not_broadcast['hex'])
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
self.sync_all(self.nodes[0:3])
node_2_bal += 2
tx_obj_not_broadcast = self.nodes[0].gettransaction(txid_not_broadcast)
@@ -362,7 +399,7 @@ class WalletTest(BitcoinTestFramework):
self.connect_nodes(0, 2)
self.sync_blocks(self.nodes[0:3])
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks(self.nodes[0:3])
node_2_bal += 2
@@ -391,7 +428,7 @@ class WalletTest(BitcoinTestFramework):
assert_raises_rpc_error(-3, "Invalid amount", self.nodes[0].sendtoaddress, self.nodes[2].getnewaddress(), "1f-4")
# This will raise an exception since generate does not accept a string
- assert_raises_rpc_error(-1, "not an integer", self.nodes[0].generate, "2")
+ assert_raises_rpc_error(-1, "not an integer", self.generate, self.nodes[0], "2")
if not self.options.descriptors:
@@ -427,7 +464,10 @@ class WalletTest(BitcoinTestFramework):
# 1. Send some coins to generate new UTXO
address_to_import = self.nodes[2].getnewaddress()
txid = self.nodes[0].sendtoaddress(address_to_import, 1)
- self.nodes[0].generate(1)
+ self.sync_mempools(self.nodes[0:3])
+ vout = find_vout_for_address(self.nodes[2], txid, address_to_import)
+ self.nodes[2].lockunspent(False, [{"txid": txid, "vout": vout}])
+ self.generate(self.nodes[0], 1)
self.sync_all(self.nodes[0:3])
self.log.info("Test sendtoaddress with fee_rate param (explicit fee rate in sat/vB)")
@@ -440,7 +480,7 @@ class WalletTest(BitcoinTestFramework):
# Test passing fee_rate as an integer
txid = self.nodes[2].sendtoaddress(address=address, amount=amount, fee_rate=fee_rate_sat_vb)
tx_size = self.get_vsize(self.nodes[2].gettransaction(txid)['hex'])
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all(self.nodes[0:3])
postbalance = self.nodes[2].getbalance()
fee = prebalance - postbalance - Decimal(amount)
@@ -453,7 +493,7 @@ class WalletTest(BitcoinTestFramework):
# Test passing fee_rate as a string
txid = self.nodes[2].sendtoaddress(address=address, amount=amount, fee_rate=str(fee_rate_sat_vb))
tx_size = self.get_vsize(self.nodes[2].gettransaction(txid)['hex'])
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all(self.nodes[0:3])
postbalance = self.nodes[2].getbalance()
fee = prebalance - postbalance - amount
@@ -515,7 +555,7 @@ class WalletTest(BitcoinTestFramework):
# Mine a block from node0 to an address from node1
coinbase_addr = self.nodes[1].getnewaddress()
- block_hash = self.nodes[0].generatetoaddress(1, coinbase_addr)[0]
+ block_hash = self.generatetoaddress(self.nodes[0], 1, coinbase_addr)[0]
coinbase_txid = self.nodes[0].getblock(block_hash)['tx'][0]
self.sync_all(self.nodes[0:3])
@@ -524,7 +564,7 @@ class WalletTest(BitcoinTestFramework):
# check if wallet or blockchain maintenance changes the balance
self.sync_all(self.nodes[0:3])
- blocks = self.nodes[0].generate(2)
+ blocks = self.generate(self.nodes[0], 2)
self.sync_all(self.nodes[0:3])
balance_nodes = [self.nodes[i].getbalance() for i in range(3)]
block_count = self.nodes[0].getblockcount()
@@ -542,23 +582,17 @@ class WalletTest(BitcoinTestFramework):
assert label in self.nodes[0].listlabels()
self.nodes[0].rpc.ensure_ascii = True # restore to default
- # maintenance tests
- maintenance = [
- '-rescan',
- '-reindex',
- ]
+ # -reindex tests
chainlimit = 6
- for m in maintenance:
- self.log.info("Test " + m)
- self.stop_nodes()
- # set lower ancestor limit for later
- self.start_node(0, [m, "-limitancestorcount=" + str(chainlimit)])
- self.start_node(1, [m, "-limitancestorcount=" + str(chainlimit)])
- self.start_node(2, [m, "-limitancestorcount=" + str(chainlimit)])
- if m == '-reindex':
- # reindex will leave rpc warm up "early"; Wait for it to finish
- self.wait_until(lambda: [block_count] * 3 == [self.nodes[i].getblockcount() for i in range(3)])
- assert_equal(balance_nodes, [self.nodes[i].getbalance() for i in range(3)])
+ self.log.info("Test -reindex")
+ self.stop_nodes()
+ # set lower ancestor limit for later
+ self.start_node(0, ['-reindex', "-limitancestorcount=" + str(chainlimit)])
+ self.start_node(1, ['-reindex', "-limitancestorcount=" + str(chainlimit)])
+ self.start_node(2, ['-reindex', "-limitancestorcount=" + str(chainlimit)])
+ # reindex will leave rpc warm up "early"; Wait for it to finish
+ self.wait_until(lambda: [block_count] * 3 == [self.nodes[i].getblockcount() for i in range(3)])
+ assert_equal(balance_nodes, [self.nodes[i].getbalance() for i in range(3)])
# Exercise listsinceblock with the last two blocks
coinbase_tx_1 = self.nodes[0].listsinceblock(blocks[0])
@@ -572,13 +606,13 @@ class WalletTest(BitcoinTestFramework):
# Get all non-zero utxos together
chain_addrs = [self.nodes[0].getnewaddress(), self.nodes[0].getnewaddress()]
singletxid = self.nodes[0].sendtoaddress(chain_addrs[0], self.nodes[0].getbalance(), "", "", True)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
node0_balance = self.nodes[0].getbalance()
# Split into two chains
rawtx = self.nodes[0].createrawtransaction([{"txid": singletxid, "vout": 0}], {chain_addrs[0]: node0_balance / 2 - Decimal('0.01'), chain_addrs[1]: node0_balance / 2 - Decimal('0.01')})
signedtx = self.nodes[0].signrawtransactionwithwallet(rawtx)
singletxid = self.nodes[0].sendrawtransaction(hexstring=signedtx["hex"], maxfeerate=0)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
# Make a long chain of unconfirmed payments without hitting mempool limit
# Each tx we make leaves only one output of change on a chain 1 longer
@@ -629,7 +663,7 @@ class WalletTest(BitcoinTestFramework):
assert not address_info["ischange"]
# Test getaddressinfo 'ischange' field on change address.
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
destination = self.nodes[1].getnewaddress()
txid = self.nodes[0].sendtoaddress(destination, 0.123)
tx = self.nodes[0].decoderawtransaction(self.nodes[0].gettransaction(txid)['hex'])
diff --git a/test/functional/wallet_bumpfee.py b/test/functional/wallet_bumpfee.py
index c04986038d..a1676fffa5 100755
--- a/test/functional/wallet_bumpfee.py
+++ b/test/functional/wallet_bumpfee.py
@@ -59,7 +59,7 @@ class BumpFeeTest(BitcoinTestFramework):
def clear_mempool(self):
# Clear mempool between subtests. The subtests may only depend on chainstate (utxos)
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
self.sync_all()
def run_test(self):
@@ -72,12 +72,12 @@ class BumpFeeTest(BitcoinTestFramework):
# fund rbf node with 10 coins of 0.001 btc (100,000 satoshis)
self.log.info("Mining blocks...")
- peer_node.generate(110)
+ self.generate(peer_node, 110)
self.sync_all()
for _ in range(25):
peer_node.sendtoaddress(rbf_node_address, 0.001)
self.sync_all()
- peer_node.generate(1)
+ self.generate(peer_node, 1)
self.sync_all()
assert_equal(rbf_node.getbalance(), Decimal("0.025"))
@@ -272,7 +272,7 @@ def test_small_output_with_feerate_succeeds(self, rbf_node, dest_address):
self.log.info('Testing small output with feerate bump succeeds')
# Make sure additional inputs exist
- rbf_node.generatetoaddress(COINBASE_MATURITY + 1, rbf_node.getnewaddress())
+ self.generatetoaddress(rbf_node, COINBASE_MATURITY + 1, rbf_node.getnewaddress())
rbfid = spend_one_input(rbf_node, dest_address)
input_list = rbf_node.getrawtransaction(rbfid, 1)["vin"]
assert_equal(len(input_list), 1)
@@ -305,7 +305,7 @@ def test_small_output_with_feerate_succeeds(self, rbf_node, dest_address):
if txin["txid"] == original_txin["txid"]
and txin["vout"] == original_txin["vout"]]
- rbf_node.generatetoaddress(1, rbf_node.getnewaddress())
+ self.generatetoaddress(rbf_node, 1, rbf_node.getnewaddress())
assert_equal(rbf_node.gettransaction(rbfid)["confirmations"], 1)
self.clear_mempool()
@@ -433,7 +433,7 @@ def test_watchonly_psbt(self, peer_node, rbf_node, dest_address):
funding_address1 = watcher.getnewaddress(address_type='bech32')
funding_address2 = watcher.getnewaddress(address_type='bech32')
peer_node.sendmany("", {funding_address1: 0.001, funding_address2: 0.001})
- peer_node.generate(1)
+ self.generate(peer_node, 1)
self.sync_all()
# Create single-input PSBT for transaction to be bumped
@@ -519,7 +519,7 @@ def test_unconfirmed_not_spendable(self, rbf_node, rbf_node_address):
assert_equal([t for t in rbf_node.listunspent(minconf=0, include_unsafe=False) if t["txid"] == rbfid], [])
# check that the main output from the rbf tx is spendable after confirmed
- rbf_node.generate(1)
+ self.generate(rbf_node, 1)
assert_equal(
sum(1 for t in rbf_node.listunspent(minconf=0, include_unsafe=False)
if t["txid"] == rbfid and t["address"] == rbf_node_address and t["spendable"]), 1)
@@ -529,7 +529,7 @@ def test_unconfirmed_not_spendable(self, rbf_node, rbf_node_address):
def test_bumpfee_metadata(self, rbf_node, dest_address):
self.log.info('Test that bumped txn metadata persists to new txn record')
assert(rbf_node.getbalance() < 49)
- rbf_node.generatetoaddress(101, rbf_node.getnewaddress())
+ self.generatetoaddress(rbf_node, 101, rbf_node.getnewaddress())
rbfid = rbf_node.sendtoaddress(dest_address, 49, "comment value", "to value")
bumped_tx = rbf_node.bumpfee(rbfid)
bumped_wtx = rbf_node.gettransaction(bumped_tx["txid"])
@@ -599,7 +599,7 @@ def submit_block_with_tx(node, tx):
def test_no_more_inputs_fails(self, rbf_node, dest_address):
self.log.info('Test that bumpfee fails when there are no available confirmed outputs')
# feerate rbf requires confirmed outputs when change output doesn't exist or is insufficient
- rbf_node.generatetoaddress(1, dest_address)
+ self.generatetoaddress(rbf_node, 1, dest_address)
# spend all funds, no change output
rbfid = rbf_node.sendtoaddress(rbf_node.getnewaddress(), rbf_node.getbalance(), "", "", True)
assert_raises_rpc_error(-4, "Unable to create transaction. Insufficient funds", rbf_node.bumpfee, rbfid)
diff --git a/test/functional/wallet_coinbase_category.py b/test/functional/wallet_coinbase_category.py
index 7aa8b44ebd..3c7abd0800 100755
--- a/test/functional/wallet_coinbase_category.py
+++ b/test/functional/wallet_coinbase_category.py
@@ -33,7 +33,7 @@ class CoinbaseCategoryTest(BitcoinTestFramework):
def run_test(self):
# Generate one block to an address
address = self.nodes[0].getnewaddress()
- self.nodes[0].generatetoaddress(1, address)
+ self.generatetoaddress(self.nodes[0], 1, address)
hash = self.nodes[0].getbestblockhash()
txid = self.nodes[0].getblock(hash)["tx"][0]
@@ -41,12 +41,12 @@ class CoinbaseCategoryTest(BitcoinTestFramework):
self.assert_category("immature", address, txid, 0)
# Mine another 99 blocks on top
- self.nodes[0].generate(99)
+ self.generate(self.nodes[0], 99)
# Coinbase transaction is still immature after 100 confirmations
self.assert_category("immature", address, txid, 99)
# Mine one more block
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
# Coinbase transaction is now matured, so category is "generate"
self.assert_category("generate", address, txid, 100)
diff --git a/test/functional/wallet_create_tx.py b/test/functional/wallet_create_tx.py
index a39a3c8d9b..c8b92ef1bf 100755
--- a/test/functional/wallet_create_tx.py
+++ b/test/functional/wallet_create_tx.py
@@ -24,7 +24,7 @@ class CreateTxWalletTest(BitcoinTestFramework):
def run_test(self):
self.log.info('Create some old blocks')
self.nodes[0].setmocktime(TIME_GENESIS_BLOCK)
- self.nodes[0].generate(200)
+ self.generate(self.nodes[0], 200)
self.nodes[0].setmocktime(0)
self.test_anti_fee_sniping()
@@ -38,7 +38,7 @@ class CreateTxWalletTest(BitcoinTestFramework):
assert_equal(tx['locktime'], 0)
self.log.info('Check that anti-fee-sniping is enabled when we mine a recent block')
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
tx = self.nodes[0].decoderawtransaction(self.nodes[0].gettransaction(txid)['hex'])
assert 0 < tx['locktime'] <= 201
diff --git a/test/functional/wallet_createwallet.py b/test/functional/wallet_createwallet.py
index 16a0a50b07..d806f8f6d2 100755
--- a/test/functional/wallet_createwallet.py
+++ b/test/functional/wallet_createwallet.py
@@ -24,7 +24,7 @@ class CreateWalletTest(BitcoinTestFramework):
def run_test(self):
node = self.nodes[0]
- node.generate(1) # Leave IBD for sethdseed
+ self.generate(node, 1) # Leave IBD for sethdseed
self.nodes[0].createwallet(wallet_name='w0')
w0 = node.get_wallet_rpc('w0')
diff --git a/test/functional/wallet_disable.py b/test/functional/wallet_disable.py
index 78cf378642..d0043e9bbb 100755
--- a/test/functional/wallet_disable.py
+++ b/test/functional/wallet_disable.py
@@ -28,8 +28,8 @@ class DisableWalletTest (BitcoinTestFramework):
# Checking mining to an address without a wallet. Generating to a valid address should succeed
# but generating to an invalid address will fail.
- self.nodes[0].generatetoaddress(1, 'mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ')
- assert_raises_rpc_error(-5, "Invalid address", self.nodes[0].generatetoaddress, 1, '3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy')
+ self.generatetoaddress(self.nodes[0], 1, 'mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ')
+ assert_raises_rpc_error(-5, "Invalid address", self.generatetoaddress, self.nodes[0], 1, '3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy')
if __name__ == '__main__':
DisableWalletTest ().main ()
diff --git a/test/functional/wallet_dump.py b/test/functional/wallet_dump.py
index 91d6121679..06460e17d2 100755
--- a/test/functional/wallet_dump.py
+++ b/test/functional/wallet_dump.py
@@ -134,7 +134,7 @@ class WalletDumpTest(BitcoinTestFramework):
self.log.info('Mine a block one second before the wallet is dumped')
dump_time = int(time.time())
self.nodes[0].setmocktime(dump_time - 1)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.nodes[0].setmocktime(dump_time)
dump_time_str = '# * Created on {}Z'.format(
datetime.datetime.fromtimestamp(
diff --git a/test/functional/wallet_fallbackfee.py b/test/functional/wallet_fallbackfee.py
index b28f3ecebc..674c37dc73 100755
--- a/test/functional/wallet_fallbackfee.py
+++ b/test/functional/wallet_fallbackfee.py
@@ -17,7 +17,7 @@ class WalletRBFTest(BitcoinTestFramework):
self.skip_if_no_wallet()
def run_test(self):
- self.nodes[0].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[0], COINBASE_MATURITY + 1)
# sending a transaction without fee estimations must be possible by default on regtest
self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
diff --git a/test/functional/wallet_groups.py b/test/functional/wallet_groups.py
index d9d135a986..802fed6e7d 100755
--- a/test/functional/wallet_groups.py
+++ b/test/functional/wallet_groups.py
@@ -34,7 +34,7 @@ class WalletGroupTest(BitcoinTestFramework):
def run_test(self):
self.log.info("Setting up")
# Mine some coins
- self.nodes[0].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[0], COINBASE_MATURITY + 1)
# Get some addresses from the two nodes
addr1 = [self.nodes[1].getnewaddress() for _ in range(3)]
@@ -45,7 +45,7 @@ class WalletGroupTest(BitcoinTestFramework):
[self.nodes[0].sendtoaddress(addr, 1.0) for addr in addrs]
[self.nodes[0].sendtoaddress(addr, 0.5) for addr in addrs]
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# For each node, send 0.2 coins back to 0;
@@ -77,7 +77,7 @@ class WalletGroupTest(BitcoinTestFramework):
self.log.info("Test avoiding partial spends if warranted, even if avoidpartialspends is disabled")
self.sync_all()
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
# Nodes 1-2 now have confirmed UTXOs (letters denote destinations):
# Node #1: Node #2:
# - A 1.0 - D0 1.0
@@ -113,7 +113,7 @@ class WalletGroupTest(BitcoinTestFramework):
addr_aps = self.nodes[3].getnewaddress()
self.nodes[0].sendtoaddress(addr_aps, 1.0)
self.nodes[0].sendtoaddress(addr_aps, 1.0)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
with self.nodes[3].assert_debug_log(['Fee non-grouped = 2820, grouped = 4160, using grouped']):
txid4 = self.nodes[3].sendtoaddress(self.nodes[0].getnewaddress(), 0.1)
@@ -125,7 +125,7 @@ class WalletGroupTest(BitcoinTestFramework):
addr_aps2 = self.nodes[3].getnewaddress()
[self.nodes[0].sendtoaddress(addr_aps2, 1.0) for _ in range(5)]
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
with self.nodes[3].assert_debug_log(['Fee non-grouped = 5520, grouped = 8240, using non-grouped']):
txid5 = self.nodes[3].sendtoaddress(self.nodes[0].getnewaddress(), 2.95)
@@ -139,7 +139,7 @@ class WalletGroupTest(BitcoinTestFramework):
self.log.info("Test wallet option maxapsfee threshold from non-grouped to grouped")
addr_aps3 = self.nodes[4].getnewaddress()
[self.nodes[0].sendtoaddress(addr_aps3, 1.0) for _ in range(5)]
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
with self.nodes[4].assert_debug_log(['Fee non-grouped = 5520, grouped = 8240, using grouped']):
txid6 = self.nodes[4].sendtoaddress(self.nodes[0].getnewaddress(), 2.95)
@@ -151,7 +151,7 @@ class WalletGroupTest(BitcoinTestFramework):
# Empty out node2's wallet
self.nodes[2].sendtoaddress(address=self.nodes[0].getnewaddress(), amount=self.nodes[2].getbalance(), subtractfeefromamount=True)
self.sync_all()
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.log.info("Fill a wallet with 10,000 outputs corresponding to the same scriptPubKey")
for _ in range(5):
@@ -162,7 +162,7 @@ class WalletGroupTest(BitcoinTestFramework):
funded_tx = self.nodes[0].fundrawtransaction(tx.serialize().hex())
signed_tx = self.nodes[0].signrawtransactionwithwallet(funded_tx['hex'])
self.nodes[0].sendrawtransaction(signed_tx['hex'])
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# Check that we can create a transaction that only requires ~100 of our
diff --git a/test/functional/wallet_hd.py b/test/functional/wallet_hd.py
index d41a389197..974ce7f381 100755
--- a/test/functional/wallet_hd.py
+++ b/test/functional/wallet_hd.py
@@ -49,7 +49,7 @@ class WalletHDTest(BitcoinTestFramework):
# Derive some HD addresses and remember the last
# Also send funds to each add
- self.nodes[0].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[0], COINBASE_MATURITY + 1)
hd_add = None
NUM_HD_ADDS = 10
for i in range(1, NUM_HD_ADDS + 1):
@@ -61,9 +61,9 @@ class WalletHDTest(BitcoinTestFramework):
assert_equal(hd_info["hdkeypath"], "m/0'/0'/" + str(i) + "'")
assert_equal(hd_info["hdmasterfingerprint"], hd_fingerprint)
self.nodes[0].sendtoaddress(hd_add, 1)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.nodes[0].sendtoaddress(non_hd_add, 1)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
# create an internal key (again)
change_addr = self.nodes[1].getrawchangeaddress()
@@ -103,7 +103,7 @@ class WalletHDTest(BitcoinTestFramework):
self.sync_all()
# Needs rescan
- self.restart_node(1, extra_args=self.extra_args[1] + ['-rescan'])
+ self.nodes[1].rescanblockchain()
assert_equal(self.nodes[1].getbalance(), NUM_HD_ADDS + 1)
# Try a RPC based rescan
@@ -179,7 +179,7 @@ class WalletHDTest(BitcoinTestFramework):
assert_raises_rpc_error(-5, "Already have this key", self.nodes[1].sethdseed, False, self.nodes[1].dumpprivkey(self.nodes[1].getnewaddress()))
self.log.info('Test sethdseed restoring with keys outside of the initial keypool')
- self.nodes[0].generate(10)
+ self.generate(self.nodes[0], 10)
# Restart node 1 with keypool of 3 and a different wallet
self.nodes[1].createwallet(wallet_name='origin', blank=True)
self.restart_node(1, extra_args=['-keypool=3', '-wallet=origin'])
@@ -228,7 +228,7 @@ class WalletHDTest(BitcoinTestFramework):
# The wallet that has set a new seed (restore_rpc) should not detect this transaction.
txid = self.nodes[0].sendtoaddress(addr, 1)
origin_rpc.sendrawtransaction(self.nodes[0].gettransaction(txid)['hex'])
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
origin_rpc.gettransaction(txid)
assert_raises_rpc_error(-5, 'Invalid or non-wallet transaction id', restore_rpc.gettransaction, txid)
@@ -239,7 +239,7 @@ class WalletHDTest(BitcoinTestFramework):
# The previous transaction (out_of_kp_txid) should still not be detected as a rescan is required.
txid = self.nodes[0].sendtoaddress(last_addr, 1)
origin_rpc.sendrawtransaction(self.nodes[0].gettransaction(txid)['hex'])
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
origin_rpc.gettransaction(txid)
restore_rpc.gettransaction(txid)
diff --git a/test/functional/wallet_import_rescan.py b/test/functional/wallet_import_rescan.py
index 59089456e9..cbe3e9bfdd 100755
--- a/test/functional/wallet_import_rescan.py
+++ b/test/functional/wallet_import_rescan.py
@@ -178,7 +178,7 @@ class ImportRescanTest(BitcoinTestFramework):
variant.key = self.nodes[1].dumpprivkey(variant.address["address"])
variant.initial_amount = get_rand_amount()
variant.initial_txid = self.nodes[0].sendtoaddress(variant.address["address"], variant.initial_amount)
- self.nodes[0].generate(1) # Generate one block for each send
+ self.generate(self.nodes[0], 1) # Generate one block for each send
variant.confirmation_height = self.nodes[0].getblockcount()
variant.timestamp = self.nodes[0].getblockheader(self.nodes[0].getbestblockhash())["time"]
self.sync_all() # Conclude sync before calling setmocktime to avoid timeouts
@@ -189,7 +189,7 @@ class ImportRescanTest(BitcoinTestFramework):
self.nodes,
self.nodes[0].getblockheader(self.nodes[0].getbestblockhash())["time"] + TIMESTAMP_WINDOW + 1,
)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# For each variation of wallet key import, invoke the import RPC and
@@ -212,7 +212,7 @@ class ImportRescanTest(BitcoinTestFramework):
for i, variant in enumerate(IMPORT_VARIANTS):
variant.sent_amount = get_rand_amount()
variant.sent_txid = self.nodes[0].sendtoaddress(variant.address["address"], variant.sent_amount)
- self.nodes[0].generate(1) # Generate one block for each send
+ self.generate(self.nodes[0], 1) # Generate one block for each send
variant.confirmation_height = self.nodes[0].getblockcount()
assert_equal(self.nodes[0].getrawmempool(), [])
diff --git a/test/functional/wallet_importdescriptors.py b/test/functional/wallet_importdescriptors.py
index 4cb311983c..d86c3737fe 100755
--- a/test/functional/wallet_importdescriptors.py
+++ b/test/functional/wallet_importdescriptors.py
@@ -451,12 +451,12 @@ class ImportDescriptorsTest(BitcoinTestFramework):
assert_equal(change_addr, 'bcrt1qt9uhe3a9hnq7vajl7a094z4s3crm9ttf8zw3f5v9gr2nyd7e3lnsy44n8e')
assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 1000)
txid = w0.sendtoaddress(addr, 10)
- self.nodes[0].generate(6)
+ self.generate(self.nodes[0], 6)
self.sync_all()
send_txid = wmulti_priv.sendtoaddress(w0.getnewaddress(), 8)
decoded = wmulti_priv.decoderawtransaction(wmulti_priv.gettransaction(send_txid)['hex'])
assert_equal(len(decoded['vin'][0]['txinwitness']), 4)
- self.nodes[0].generate(6)
+ self.generate(self.nodes[0], 6)
self.sync_all()
self.nodes[1].createwallet(wallet_name="wmulti_pub", disable_private_keys=True, blank=True, descriptors=True)
@@ -494,7 +494,7 @@ class ImportDescriptorsTest(BitcoinTestFramework):
txid2 = w0.sendtoaddress(addr2, 10)
vout2 = find_vout_for_address(self.nodes[0], txid2, addr2)
- self.nodes[0].generate(6)
+ self.generate(self.nodes[0], 6)
self.sync_all()
assert_equal(wmulti_pub.getbalance(), wmulti_priv.getbalance())
@@ -582,7 +582,7 @@ class ImportDescriptorsTest(BitcoinTestFramework):
addr = wmulti_priv_big.getnewaddress()
w0.sendtoaddress(addr, 10)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# It is standard and would relay.
txid = wmulti_priv_big.sendtoaddress(w0.getnewaddress(), 9.999)
@@ -617,7 +617,7 @@ class ImportDescriptorsTest(BitcoinTestFramework):
addr = multi_priv_big.getnewaddress("", "legacy")
w0.sendtoaddress(addr, 10)
- self.nodes[0].generate(6)
+ self.generate(self.nodes[0], 6)
self.sync_all()
# It is standard and would relay.
txid = multi_priv_big.sendtoaddress(w0.getnewaddress(), 10, "", "",
diff --git a/test/functional/wallet_importmulti.py b/test/functional/wallet_importmulti.py
index baeac655df..4e8907bc3d 100755
--- a/test/functional/wallet_importmulti.py
+++ b/test/functional/wallet_importmulti.py
@@ -62,8 +62,8 @@ class ImportMultiTest(BitcoinTestFramework):
def run_test(self):
self.log.info("Mining blocks...")
- self.nodes[0].generate(1)
- self.nodes[1].generate(1)
+ self.generate(self.nodes[0], 1)
+ self.generate(self.nodes[1], 1)
timestamp = self.nodes[1].getblock(self.nodes[1].getbestblockhash())['mediantime']
self.nodes[1].syncwithvalidationinterfacequeue() # Sync the timestamp to the wallet, so that importmulti works
@@ -256,9 +256,9 @@ class ImportMultiTest(BitcoinTestFramework):
# P2SH address
multisig = get_multisig(self.nodes[0])
- self.nodes[1].generate(COINBASE_MATURITY)
+ self.generate(self.nodes[1], COINBASE_MATURITY)
self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
timestamp = self.nodes[1].getblock(self.nodes[1].getbestblockhash())['mediantime']
self.nodes[1].syncwithvalidationinterfacequeue()
@@ -277,9 +277,9 @@ class ImportMultiTest(BitcoinTestFramework):
# P2SH + Redeem script
multisig = get_multisig(self.nodes[0])
- self.nodes[1].generate(COINBASE_MATURITY)
+ self.generate(self.nodes[1], COINBASE_MATURITY)
self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
timestamp = self.nodes[1].getblock(self.nodes[1].getbestblockhash())['mediantime']
self.nodes[1].syncwithvalidationinterfacequeue()
@@ -298,9 +298,9 @@ class ImportMultiTest(BitcoinTestFramework):
# P2SH + Redeem script + Private Keys + !Watchonly
multisig = get_multisig(self.nodes[0])
- self.nodes[1].generate(COINBASE_MATURITY)
+ self.generate(self.nodes[1], COINBASE_MATURITY)
self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
timestamp = self.nodes[1].getblock(self.nodes[1].getbestblockhash())['mediantime']
self.nodes[1].syncwithvalidationinterfacequeue()
@@ -324,9 +324,9 @@ class ImportMultiTest(BitcoinTestFramework):
# P2SH + Redeem script + Private Keys + Watchonly
multisig = get_multisig(self.nodes[0])
- self.nodes[1].generate(COINBASE_MATURITY)
+ self.generate(self.nodes[1], COINBASE_MATURITY)
self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
timestamp = self.nodes[1].getblock(self.nodes[1].getbestblockhash())['mediantime']
self.nodes[1].syncwithvalidationinterfacequeue()
diff --git a/test/functional/wallet_importprunedfunds.py b/test/functional/wallet_importprunedfunds.py
index ded0e64b1d..74c5100f40 100755
--- a/test/functional/wallet_importprunedfunds.py
+++ b/test/functional/wallet_importprunedfunds.py
@@ -25,7 +25,7 @@ class ImportPrunedFundsTest(BitcoinTestFramework):
def run_test(self):
self.log.info("Mining blocks...")
- self.nodes[0].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[0], COINBASE_MATURITY + 1)
self.sync_all()
@@ -64,17 +64,17 @@ class ImportPrunedFundsTest(BitcoinTestFramework):
# Send funds to self
txnid1 = self.nodes[0].sendtoaddress(address1, 0.1)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
rawtxn1 = self.nodes[0].gettransaction(txnid1)['hex']
proof1 = self.nodes[0].gettxoutproof([txnid1])
txnid2 = self.nodes[0].sendtoaddress(address2, 0.05)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
rawtxn2 = self.nodes[0].gettransaction(txnid2)['hex']
proof2 = self.nodes[0].gettxoutproof([txnid2])
txnid3 = self.nodes[0].sendtoaddress(address3, 0.025)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
rawtxn3 = self.nodes[0].gettransaction(txnid3)['hex']
proof3 = self.nodes[0].gettxoutproof([txnid3])
diff --git a/test/functional/wallet_keypool.py b/test/functional/wallet_keypool.py
index 28bfc9116f..c714993234 100755
--- a/test/functional/wallet_keypool.py
+++ b/test/functional/wallet_keypool.py
@@ -156,7 +156,7 @@ class KeyPoolTest(BitcoinTestFramework):
w1.walletpassphrase('test', 100)
res = w1.sendtoaddress(address=address, amount=0.00010000)
- nodes[0].generate(1)
+ self.generate(nodes[0], 1)
destination = addr.pop()
# Using a fee rate (10 sat / byte) well above the minimum relay rate
diff --git a/test/functional/wallet_keypool_topup.py b/test/functional/wallet_keypool_topup.py
index 1ecf08b9ac..f730f82397 100755
--- a/test/functional/wallet_keypool_topup.py
+++ b/test/functional/wallet_keypool_topup.py
@@ -32,7 +32,7 @@ class KeypoolRestoreTest(BitcoinTestFramework):
def run_test(self):
wallet_path = os.path.join(self.nodes[1].datadir, self.chain, "wallets", self.default_wallet_name, self.wallet_data_filename)
wallet_backup_path = os.path.join(self.nodes[1].datadir, "wallet.bak")
- self.nodes[0].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[0], COINBASE_MATURITY + 1)
self.log.info("Make backup of wallet")
self.stop_node(1)
@@ -63,9 +63,9 @@ class KeypoolRestoreTest(BitcoinTestFramework):
self.log.info("Send funds to wallet")
self.nodes[0].sendtoaddress(addr_oldpool, 10)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.nodes[0].sendtoaddress(addr_extpool, 5)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
self.log.info("Restart node with wallet backup")
diff --git a/test/functional/wallet_labels.py b/test/functional/wallet_labels.py
index a571454acf..150f2b341e 100755
--- a/test/functional/wallet_labels.py
+++ b/test/functional/wallet_labels.py
@@ -32,8 +32,8 @@ class WalletLabelsTest(BitcoinTestFramework):
# Note each time we call generate, all generated coins go into
# the same address, so we call twice to get two addresses w/50 each
- node.generatetoaddress(nblocks=1, address=node.getnewaddress(label='coinbase'))
- node.generatetoaddress(nblocks=COINBASE_MATURITY + 1, address=node.getnewaddress(label='coinbase'))
+ self.generatetoaddress(node, nblocks=1, address=node.getnewaddress(label='coinbase'))
+ self.generatetoaddress(node, nblocks=COINBASE_MATURITY + 1, address=node.getnewaddress(label='coinbase'))
assert_equal(node.getbalance(), 100)
# there should be 2 address groups
@@ -65,7 +65,7 @@ class WalletLabelsTest(BitcoinTestFramework):
assert_equal(set([a[0] for a in address_groups[0]]), linked_addresses)
assert_equal([a[1] for a in address_groups[0]], [0, 0])
- node.generate(1)
+ self.generate(node, 1)
# we want to reset so that the "" label has what's expected.
# otherwise we're off by exactly the fee amount as that's mined
@@ -89,7 +89,7 @@ class WalletLabelsTest(BitcoinTestFramework):
label.verify(node)
# Check the amounts received.
- node.generate(1)
+ self.generate(node, 1)
for label in labels:
assert_equal(
node.getreceivedbyaddress(label.addresses[0]), amount_to_send)
@@ -98,14 +98,14 @@ class WalletLabelsTest(BitcoinTestFramework):
for i, label in enumerate(labels):
to_label = labels[(i + 1) % len(labels)]
node.sendtoaddress(to_label.addresses[0], amount_to_send)
- node.generate(1)
+ self.generate(node, 1)
for label in labels:
address = node.getnewaddress(label.name)
label.add_receive_address(address)
label.verify(node)
assert_equal(node.getreceivedbylabel(label.name), 2)
label.verify(node)
- node.generate(COINBASE_MATURITY + 1)
+ self.generate(node, COINBASE_MATURITY + 1)
# Check that setlabel can assign a label to a new unused address.
for label in labels:
@@ -125,7 +125,7 @@ class WalletLabelsTest(BitcoinTestFramework):
label.add_address(multisig_address)
label.purpose[multisig_address] = "send"
label.verify(node)
- node.generate(COINBASE_MATURITY + 1)
+ self.generate(node, COINBASE_MATURITY + 1)
# Check that setlabel can change the label of an address from a
# different label.
@@ -152,7 +152,7 @@ class WalletLabelsTest(BitcoinTestFramework):
for l in BECH32_VALID:
ad = BECH32_VALID[l]
wallet_watch_only.importaddress(label=l, rescan=False, address=ad)
- node.generatetoaddress(1, ad)
+ self.generatetoaddress(node, 1, ad)
assert_equal(wallet_watch_only.getaddressesbylabel(label=l), {ad: {'purpose': 'receive'}})
assert_equal(wallet_watch_only.getreceivedbylabel(label=l), 0)
for l in BECH32_INVALID:
diff --git a/test/functional/wallet_listreceivedby.py b/test/functional/wallet_listreceivedby.py
index b0590b149a..975bf9a84b 100755
--- a/test/functional/wallet_listreceivedby.py
+++ b/test/functional/wallet_listreceivedby.py
@@ -24,7 +24,7 @@ class ReceivedByTest(BitcoinTestFramework):
def run_test(self):
# Generate block to get out of IBD
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
# save the number of coinbase reward addresses so far
@@ -43,7 +43,7 @@ class ReceivedByTest(BitcoinTestFramework):
{},
True)
# Bury Tx under 10 block so it will be returned by listreceivedbyaddress
- self.nodes[1].generate(10)
+ self.generate(self.nodes[1], 10)
self.sync_all()
assert_array_result(self.nodes[1].listreceivedbyaddress(),
{"address": addr},
@@ -78,7 +78,7 @@ class ReceivedByTest(BitcoinTestFramework):
assert_equal(len(res), 2 + num_cb_reward_addresses) # Right now 2 entries
other_addr = self.nodes[1].getnewaddress()
txid2 = self.nodes[0].sendtoaddress(other_addr, 0.1)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# Same test as above should still pass
expected = {"address": addr, "label": "", "amount": Decimal("0.1"), "confirmations": 11, "txids": [txid, ]}
@@ -115,7 +115,7 @@ class ReceivedByTest(BitcoinTestFramework):
assert_equal(balance, Decimal("0.1"))
# Bury Tx under 10 block so it will be returned by the default getreceivedbyaddress
- self.nodes[1].generate(10)
+ self.generate(self.nodes[1], 10)
self.sync_all()
balance = self.nodes[1].getreceivedbyaddress(addr)
assert_equal(balance, Decimal("0.1"))
@@ -144,7 +144,7 @@ class ReceivedByTest(BitcoinTestFramework):
balance = self.nodes[1].getreceivedbylabel(label)
assert_equal(balance, balance_by_label)
- self.nodes[1].generate(10)
+ self.generate(self.nodes[1], 10)
self.sync_all()
# listreceivedbylabel should return updated received list
assert_array_result(self.nodes[1].listreceivedbylabel(),
diff --git a/test/functional/wallet_listsinceblock.py b/test/functional/wallet_listsinceblock.py
index 3899971bd7..bd3b29c81c 100755
--- a/test/functional/wallet_listsinceblock.py
+++ b/test/functional/wallet_listsinceblock.py
@@ -30,7 +30,7 @@ class ListSinceBlockTest(BitcoinTestFramework):
# All nodes are in IBD from genesis, so they'll need the miner (node2) to be an outbound connection, or have
# only one connection. (See fPreferredDownload in net_processing)
self.connect_nodes(1, 2)
- self.nodes[2].generate(COINBASE_MATURITY + 1)
+ self.generate(self.nodes[2], COINBASE_MATURITY + 1)
self.sync_all()
self.test_no_blockhash()
@@ -44,7 +44,7 @@ class ListSinceBlockTest(BitcoinTestFramework):
def test_no_blockhash(self):
self.log.info("Test no blockhash")
txid = self.nodes[2].sendtoaddress(self.nodes[0].getnewaddress(), 1)
- blockhash, = self.nodes[2].generate(1)
+ blockhash, = self.generate(self.nodes[2], 1)
blockheight = self.nodes[2].getblockheader(blockhash)['height']
self.sync_all()
@@ -86,7 +86,7 @@ class ListSinceBlockTest(BitcoinTestFramework):
a -8 invalid parameter error is thrown.
'''
self.log.info("Test target_confirmations")
- blockhash, = self.nodes[2].generate(1)
+ blockhash, = self.generate(self.nodes[2], 1)
blockheight = self.nodes[2].getblockheader(blockhash)['height']
self.sync_all()
@@ -136,8 +136,8 @@ class ListSinceBlockTest(BitcoinTestFramework):
senttx = self.nodes[2].sendtoaddress(self.nodes[0].getnewaddress(), 1)
# generate on both sides
- nodes1_last_blockhash = self.nodes[1].generate(6)[-1]
- nodes2_first_blockhash = self.nodes[2].generate(7)[0]
+ nodes1_last_blockhash = self.generate(self.nodes[1], 6)[-1]
+ nodes2_first_blockhash = self.generate(self.nodes[2], 7)[0]
self.log.debug("nodes[1] last blockhash = {}".format(nodes1_last_blockhash))
self.log.debug("nodes[2] first blockhash = {}".format(nodes2_first_blockhash))
@@ -191,7 +191,7 @@ class ListSinceBlockTest(BitcoinTestFramework):
privkey = bytes_to_wif(eckey.get_bytes())
address = key_to_p2wpkh(eckey.get_pubkey().get_bytes())
self.nodes[2].sendtoaddress(address, 10)
- self.nodes[2].generate(6)
+ self.generate(self.nodes[2], 6)
self.sync_all()
self.nodes[2].importprivkey(privkey)
utxos = self.nodes[2].listunspent()
@@ -225,8 +225,8 @@ class ListSinceBlockTest(BitcoinTestFramework):
self.nodes[2].createrawtransaction(utxo_dicts, recipient_dict2))['hex'])
# generate on both sides
- lastblockhash = self.nodes[1].generate(3)[2]
- self.nodes[2].generate(4)
+ lastblockhash = self.generate(self.nodes[1], 3)[2]
+ self.generate(self.nodes[2], 4)
self.join_network()
@@ -297,7 +297,7 @@ class ListSinceBlockTest(BitcoinTestFramework):
txid1 = self.nodes[1].sendrawtransaction(signedtx)
# generate bb1-bb2 on right side
- self.nodes[2].generate(2)
+ self.generate(self.nodes[2], 2)
# send from nodes[2]; this will end up in bb3
txid2 = self.nodes[2].sendrawtransaction(signedtx)
@@ -305,8 +305,8 @@ class ListSinceBlockTest(BitcoinTestFramework):
assert_equal(txid1, txid2)
# generate on both sides
- lastblockhash = self.nodes[1].generate(3)[2]
- self.nodes[2].generate(2)
+ lastblockhash = self.generate(self.nodes[1], 3)[2]
+ self.generate(self.nodes[2], 2)
self.join_network()
@@ -365,7 +365,7 @@ class ListSinceBlockTest(BitcoinTestFramework):
assert_equal(original_found, True)
assert_equal(double_found, True)
- lastblockhash = spending_node.generate(1)[0]
+ lastblockhash = self.generate(spending_node, 1)[0]
# check that neither transaction exists
block_hash = spending_node.listsinceblock(lastblockhash)
diff --git a/test/functional/wallet_listtransactions.py b/test/functional/wallet_listtransactions.py
index c0386f5d70..a14bfe345c 100755
--- a/test/functional/wallet_listtransactions.py
+++ b/test/functional/wallet_listtransactions.py
@@ -36,7 +36,7 @@ class ListTransactionsTest(BitcoinTestFramework):
{"txid": txid},
{"category": "receive", "amount": Decimal("0.1"), "confirmations": 0})
self.log.info("Test confirmations change after mining a block")
- blockhash = self.nodes[0].generate(1)[0]
+ blockhash = self.generate(self.nodes[0], 1)[0]
blockheight = self.nodes[0].getblockheader(blockhash)['height']
self.sync_all()
assert_array_result(self.nodes[0].listtransactions(),
@@ -94,7 +94,7 @@ class ListTransactionsTest(BitcoinTestFramework):
multisig = self.nodes[1].createmultisig(1, [pubkey])
self.nodes[0].importaddress(multisig["redeemScript"], "watchonly", False, True)
txid = self.nodes[1].sendtoaddress(multisig["address"], 0.1)
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
self.sync_all()
assert_equal(len(self.nodes[0].listtransactions(label="watchonly", include_watchonly=True)), 1)
assert_equal(len(self.nodes[0].listtransactions(dummy="watchonly", include_watchonly=True)), 1)
@@ -205,7 +205,7 @@ class ListTransactionsTest(BitcoinTestFramework):
assert_equal(n.gettransaction(txid_4)["bip125-replaceable"], "unknown")
self.log.info("Test mined transactions are no longer bip125-replaceable")
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
assert txid_3b not in self.nodes[0].getrawmempool()
assert_equal(self.nodes[0].gettransaction(txid_3b)["bip125-replaceable"], "no")
assert_equal(self.nodes[0].gettransaction(txid_4)["bip125-replaceable"], "unknown")
diff --git a/test/functional/wallet_multiwallet.py b/test/functional/wallet_multiwallet.py
index 00d2c9ffe4..d4768f5043 100755
--- a/test/functional/wallet_multiwallet.py
+++ b/test/functional/wallet_multiwallet.py
@@ -185,7 +185,7 @@ class MultiWalletTest(BitcoinTestFramework):
self.nodes[0].createwallet("w5")
assert_equal(set(node.listwallets()), {"w4", "w5"})
w5 = wallet("w5")
- node.generatetoaddress(nblocks=1, address=w5.getnewaddress())
+ self.generatetoaddress(node, nblocks=1, address=w5.getnewaddress())
# now if wallets/ exists again, but the rootdir is specified as the walletdir, w4 and w5 should still be loaded
os.rename(wallet_dir2, wallet_dir())
@@ -217,7 +217,7 @@ class MultiWalletTest(BitcoinTestFramework):
wallet_bad = wallet("bad")
# check wallet names and balances
- node.generatetoaddress(nblocks=1, address=wallets[0].getnewaddress())
+ self.generatetoaddress(node, nblocks=1, address=wallets[0].getnewaddress())
for wallet_name, wallet in zip(wallet_names, wallets):
info = wallet.getwalletinfo()
assert_equal(info['immature_balance'], 50 if wallet is wallets[0] else 0)
@@ -230,7 +230,7 @@ class MultiWalletTest(BitcoinTestFramework):
assert_raises_rpc_error(-19, "Wallet file not specified", node.getwalletinfo)
w1, w2, w3, w4, *_ = wallets
- node.generatetoaddress(nblocks=COINBASE_MATURITY + 1, address=w1.getnewaddress())
+ self.generatetoaddress(node, nblocks=COINBASE_MATURITY + 1, address=w1.getnewaddress())
assert_equal(w1.getbalance(), 100)
assert_equal(w2.getbalance(), 0)
assert_equal(w3.getbalance(), 0)
@@ -239,7 +239,7 @@ class MultiWalletTest(BitcoinTestFramework):
w1.sendtoaddress(w2.getnewaddress(), 1)
w1.sendtoaddress(w3.getnewaddress(), 2)
w1.sendtoaddress(w4.getnewaddress(), 3)
- node.generatetoaddress(nblocks=1, address=w1.getnewaddress())
+ self.generatetoaddress(node, nblocks=1, address=w1.getnewaddress())
assert_equal(w2.getbalance(), 1)
assert_equal(w3.getbalance(), 2)
assert_equal(w4.getbalance(), 3)
diff --git a/test/functional/wallet_orphanedreward.py b/test/functional/wallet_orphanedreward.py
index 097df2cf41..ff1d1bd49b 100755
--- a/test/functional/wallet_orphanedreward.py
+++ b/test/functional/wallet_orphanedreward.py
@@ -18,19 +18,19 @@ class OrphanedBlockRewardTest(BitcoinTestFramework):
def run_test(self):
# Generate some blocks and obtain some coins on node 0. We send
# some balance to node 1, which will hold it as a single coin.
- self.nodes[0].generate(150)
+ self.generate(self.nodes[0], 150)
self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 10)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
# Get a block reward with node 1 and remember the block so we can orphan
# it later.
self.sync_blocks()
- blk = self.nodes[1].generate(1)[0]
+ blk = self.generate(self.nodes[1], 1)[0]
self.sync_blocks()
# Let the block reward mature and send coins including both
# the existing balance and the block reward.
- self.nodes[0].generate(150)
+ self.generate(self.nodes[0], 150)
self.sync_blocks()
assert_equal(self.nodes[1].getbalance(), 10 + 25)
txid = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 30)
@@ -38,7 +38,7 @@ class OrphanedBlockRewardTest(BitcoinTestFramework):
# Orphan the block reward and make sure that the original coins
# from the wallet can still be spent.
self.nodes[0].invalidateblock(blk)
- self.nodes[0].generate(152)
+ self.generate(self.nodes[0], 152)
self.sync_blocks()
# Without the following abandontransaction call, the coins are
# not considered available yet.
diff --git a/test/functional/wallet_reorgsrestore.py b/test/functional/wallet_reorgsrestore.py
index 9a5866a361..1f452f8337 100755
--- a/test/functional/wallet_reorgsrestore.py
+++ b/test/functional/wallet_reorgsrestore.py
@@ -32,7 +32,7 @@ class ReorgsRestoreTest(BitcoinTestFramework):
def run_test(self):
# Send a tx from which to conflict outputs later
txid_conflict_from = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), Decimal("10"))
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
# Disconnect node1 from others to reorg its chain later
@@ -43,7 +43,7 @@ class ReorgsRestoreTest(BitcoinTestFramework):
# Send a tx to be unconfirmed later
txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), Decimal("10"))
tx = self.nodes[0].gettransaction(txid)
- self.nodes[0].generate(4)
+ self.generate(self.nodes[0], 4)
tx_before_reorg = self.nodes[0].gettransaction(txid)
assert_equal(tx_before_reorg["confirmations"], 4)
@@ -62,9 +62,9 @@ class ReorgsRestoreTest(BitcoinTestFramework):
conflicting = self.nodes[0].signrawtransactionwithwallet(self.nodes[0].createrawtransaction(inputs, outputs_2))
conflicted_txid = self.nodes[0].sendrawtransaction(conflicted["hex"])
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
conflicting_txid = self.nodes[2].sendrawtransaction(conflicting["hex"])
- self.nodes[2].generate(9)
+ self.generate(self.nodes[2], 9)
# Reconnect node0 and node2 and check that conflicted_txid is effectively conflicted
self.connect_nodes(0, 2)
@@ -78,11 +78,11 @@ class ReorgsRestoreTest(BitcoinTestFramework):
self.restart_node(0)
# The block chain re-orgs and the tx is included in a different block
- self.nodes[1].generate(9)
+ self.generate(self.nodes[1], 9)
self.nodes[1].sendrawtransaction(tx["hex"])
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
self.nodes[1].sendrawtransaction(conflicted["hex"])
- self.nodes[1].generate(1)
+ self.generate(self.nodes[1], 1)
# Node0 wallet file is loaded on longest sync'ed node1
self.stop_node(1)
diff --git a/test/functional/wallet_send.py b/test/functional/wallet_send.py
index d24d1693af..c9daeabeb9 100755
--- a/test/functional/wallet_send.py
+++ b/test/functional/wallet_send.py
@@ -9,6 +9,7 @@ from itertools import product
from test_framework.authproxy import JSONRPCException
from test_framework.descriptors import descsum_create
+from test_framework.key import ECKey
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
@@ -16,6 +17,7 @@ from test_framework.util import (
assert_greater_than,
assert_raises_rpc_error,
)
+from test_framework.wallet_util import bytes_to_wif
class WalletSendTest(BitcoinTestFramework):
def set_test_params(self):
@@ -35,7 +37,7 @@ class WalletSendTest(BitcoinTestFramework):
conf_target=None, estimate_mode=None, fee_rate=None, add_to_wallet=None, psbt=None,
inputs=None, add_inputs=None, include_unsafe=None, change_address=None, change_position=None, change_type=None,
include_watching=None, locktime=None, lock_unspents=None, replaceable=None, subtract_fee_from_outputs=None,
- expect_error=None):
+ expect_error=None, solving_data=None):
assert (amount is None) != (data is None)
from_balance_before = from_wallet.getbalances()["mine"]["trusted"]
@@ -94,6 +96,8 @@ class WalletSendTest(BitcoinTestFramework):
options["replaceable"] = replaceable
if subtract_fee_from_outputs is not None:
options["subtract_fee_from_outputs"] = subtract_fee_from_outputs
+ if solving_data is not None:
+ options["solving_data"] = solving_data
if len(options.keys()) == 0:
options = None
@@ -241,7 +245,7 @@ class WalletSendTest(BitcoinTestFramework):
assert_equal(res, [{"success": True}, {"success": True}])
w0.sendtoaddress(a2_receive, 10) # fund w3
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
if not self.options.descriptors:
@@ -260,7 +264,7 @@ class WalletSendTest(BitcoinTestFramework):
assert_equal(res, [{"success": True}])
w0.sendtoaddress(a2_receive, 10) # fund w4
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks()
self.log.info("Send to address...")
@@ -435,14 +439,14 @@ class WalletSendTest(BitcoinTestFramework):
assert not res[0]["allowed"]
assert_equal(res[0]["reject-reason"], "non-final")
# It shouldn't be confirmed in the next block
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
assert_equal(self.nodes[0].gettransaction(txid)["confirmations"], 0)
# The mempool should allow it now:
res = self.nodes[0].testmempoolaccept([hex])
assert res[0]["allowed"]
# Don't wait for wallet to add it to the mempool:
res = self.nodes[0].sendrawtransaction(hex)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
assert_equal(self.nodes[0].gettransaction(txid)["confirmations"], 1)
self.sync_all()
@@ -476,6 +480,47 @@ class WalletSendTest(BitcoinTestFramework):
res = self.test_send(from_wallet=w5, to_wallet=w0, amount=1, include_unsafe=True)
assert res["complete"]
+ self.log.info("External outputs")
+ eckey = ECKey()
+ eckey.generate()
+ privkey = bytes_to_wif(eckey.get_bytes())
+
+ self.nodes[1].createwallet("extsend")
+ ext_wallet = self.nodes[1].get_wallet_rpc("extsend")
+ self.nodes[1].createwallet("extfund")
+ ext_fund = self.nodes[1].get_wallet_rpc("extfund")
+
+ # Make a weird but signable script. sh(pkh()) descriptor accomplishes this
+ desc = descsum_create("sh(pkh({}))".format(privkey))
+ if self.options.descriptors:
+ res = ext_fund.importdescriptors([{"desc": desc, "timestamp": "now"}])
+ else:
+ res = ext_fund.importmulti([{"desc": desc, "timestamp": "now"}])
+ assert res[0]["success"]
+ addr = self.nodes[0].deriveaddresses(desc)[0]
+ addr_info = ext_fund.getaddressinfo(addr)
+
+ self.nodes[0].sendtoaddress(addr, 10)
+ self.nodes[0].sendtoaddress(ext_wallet.getnewaddress(), 10)
+ self.generate(self.nodes[0], 6)
+ self.sync_all()
+ ext_utxo = ext_fund.listunspent(addresses=[addr])[0]
+
+ # An external input without solving data should result in an error
+ self.test_send(from_wallet=ext_wallet, to_wallet=self.nodes[0], amount=15, inputs=[ext_utxo], add_inputs=True, psbt=True, include_watching=True, expect_error=(-4, "Insufficient funds"))
+
+ # But funding should work when the solving data is provided
+ res = self.test_send(from_wallet=ext_wallet, to_wallet=self.nodes[0], amount=15, inputs=[ext_utxo], add_inputs=True, psbt=True, include_watching=True, solving_data={"pubkeys": [addr_info['pubkey']], "scripts": [addr_info["embedded"]["scriptPubKey"]]})
+ signed = ext_wallet.walletprocesspsbt(res["psbt"])
+ signed = ext_fund.walletprocesspsbt(res["psbt"])
+ assert signed["complete"]
+ self.nodes[0].finalizepsbt(signed["psbt"])
+
+ res = self.test_send(from_wallet=ext_wallet, to_wallet=self.nodes[0], amount=15, inputs=[ext_utxo], add_inputs=True, psbt=True, include_watching=True, solving_data={"descriptors": [desc]})
+ signed = ext_wallet.walletprocesspsbt(res["psbt"])
+ signed = ext_fund.walletprocesspsbt(res["psbt"])
+ assert signed["complete"]
+ self.nodes[0].finalizepsbt(signed["psbt"])
if __name__ == '__main__':
WalletSendTest().main()
diff --git a/test/functional/wallet_signer.py b/test/functional/wallet_signer.py
index afd4fd3691..c6c1cc8784 100755
--- a/test/functional/wallet_signer.py
+++ b/test/functional/wallet_signer.py
@@ -27,6 +27,9 @@ class WalletSignerTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
+ # The experimental syscall sandbox feature (-sandbox) is not compatible with -signer (which
+ # invokes execve).
+ self.disable_syscall_sandbox = True
self.extra_args = [
[],
@@ -108,7 +111,7 @@ class WalletSignerTest(BitcoinTestFramework):
self.log.info('Prepare mock PSBT')
self.nodes[0].sendtoaddress(address1, 1)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_all()
# Load private key into wallet to generate a signed PSBT for the mock
diff --git a/test/functional/wallet_taproot.py b/test/functional/wallet_taproot.py
index 9eb204bf37..4f84dbd125 100755
--- a/test/functional/wallet_taproot.py
+++ b/test/functional/wallet_taproot.py
@@ -272,11 +272,11 @@ class WalletTaprootTest(BitcoinTestFramework):
boring_balance = int(self.boring.getbalance() * 100000000)
to_amnt = random.randrange(1000000, boring_balance)
self.boring.sendtoaddress(address=addr_g, amount=Decimal(to_amnt) / 100000000, subtractfeefromamount=True)
- self.nodes[0].generatetoaddress(1, self.boring.getnewaddress())
+ self.generatetoaddress(self.nodes[0], 1, self.boring.getnewaddress())
test_balance = int(self.rpc_online.getbalance() * 100000000)
ret_amnt = random.randrange(100000, test_balance)
res = self.rpc_online.sendtoaddress(address=self.boring.getnewaddress(), amount=Decimal(ret_amnt) / 100000000, subtractfeefromamount=True)
- self.nodes[0].generatetoaddress(1, self.boring.getnewaddress())
+ self.generatetoaddress(self.nodes[0], 1, self.boring.getnewaddress())
assert(self.rpc_online.gettransaction(res)["confirmations"] > 0)
def do_test_psbt(self, comment, pattern, privmap, treefn, keys_pay, keys_change):
@@ -303,7 +303,7 @@ class WalletTaprootTest(BitcoinTestFramework):
boring_balance = int(self.boring.getbalance() * 100000000)
to_amnt = random.randrange(1000000, boring_balance)
self.boring.sendtoaddress(address=addr_g, amount=Decimal(to_amnt) / 100000000, subtractfeefromamount=True)
- self.nodes[0].generatetoaddress(1, self.boring.getnewaddress())
+ self.generatetoaddress(self.nodes[0], 1, self.boring.getnewaddress())
test_balance = int(self.psbt_online.getbalance() * 100000000)
ret_amnt = random.randrange(100000, test_balance)
psbt = self.psbt_online.walletcreatefundedpsbt([], [{self.boring.getnewaddress(): Decimal(ret_amnt) / 100000000}], None, {"subtractFeeFromOutputs":[0]})['psbt']
@@ -311,7 +311,7 @@ class WalletTaprootTest(BitcoinTestFramework):
assert(res['complete'])
rawtx = self.nodes[0].finalizepsbt(res['psbt'])['hex']
txid = self.nodes[0].sendrawtransaction(rawtx)
- self.nodes[0].generatetoaddress(1, self.boring.getnewaddress())
+ self.generatetoaddress(self.nodes[0], 1, self.boring.getnewaddress())
assert(self.psbt_online.gettransaction(txid)['confirmations'] > 0)
def do_test(self, comment, pattern, privmap, treefn, nkeys):
@@ -343,7 +343,7 @@ class WalletTaprootTest(BitcoinTestFramework):
self.log.info("Mining blocks...")
gen_addr = self.boring.getnewaddress()
- self.nodes[0].generatetoaddress(101, gen_addr)
+ self.generatetoaddress(self.nodes[0], 101, gen_addr)
self.do_test(
"tr(XPRV)",
@@ -412,7 +412,7 @@ class WalletTaprootTest(BitcoinTestFramework):
self.log.info("Sending everything back...")
txid = self.rpc_online.sendtoaddress(address=self.boring.getnewaddress(), amount=self.rpc_online.getbalance(), subtractfeefromamount=True)
- self.nodes[0].generatetoaddress(1, self.boring.getnewaddress())
+ self.generatetoaddress(self.nodes[0], 1, self.boring.getnewaddress())
assert(self.rpc_online.gettransaction(txid)["confirmations"] > 0)
psbt = self.psbt_online.walletcreatefundedpsbt([], [{self.boring.getnewaddress(): self.psbt_online.getbalance()}], None, {"subtractFeeFromOutputs": [0]})['psbt']
@@ -420,7 +420,7 @@ class WalletTaprootTest(BitcoinTestFramework):
assert(res['complete'])
rawtx = self.nodes[0].finalizepsbt(res['psbt'])['hex']
txid = self.nodes[0].sendrawtransaction(rawtx)
- self.nodes[0].generatetoaddress(1, self.boring.getnewaddress())
+ self.generatetoaddress(self.nodes[0], 1, self.boring.getnewaddress())
assert(self.psbt_online.gettransaction(txid)['confirmations'] > 0)
if __name__ == '__main__':
diff --git a/test/functional/wallet_transactiontime_rescan.py b/test/functional/wallet_transactiontime_rescan.py
new file mode 100755
index 0000000000..78859e6131
--- /dev/null
+++ b/test/functional/wallet_transactiontime_rescan.py
@@ -0,0 +1,161 @@
+#!/usr/bin/env python3
+# Copyright (c) 2018-2019 The Bitcoin Core developers
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+"""Test transaction time during old block rescanning
+"""
+
+import time
+
+from test_framework.blocktools import COINBASE_MATURITY
+from test_framework.test_framework import BitcoinTestFramework
+from test_framework.util import (
+ assert_equal
+)
+
+
+class TransactionTimeRescanTest(BitcoinTestFramework):
+ def set_test_params(self):
+ self.setup_clean_chain = False
+ self.num_nodes = 3
+
+ def skip_test_if_missing_module(self):
+ self.skip_if_no_wallet()
+
+ def run_test(self):
+ self.log.info('Prepare nodes and wallet')
+
+ minernode = self.nodes[0] # node used to mine BTC and create transactions
+ usernode = self.nodes[1] # user node with correct time
+ restorenode = self.nodes[2] # node used to restore user wallet and check time determination in ComputeSmartTime (wallet.cpp)
+
+ # time constant
+ cur_time = int(time.time())
+ ten_days = 10 * 24 * 60 * 60
+
+ # synchronize nodes and time
+ self.sync_all()
+ minernode.setmocktime(cur_time)
+ usernode.setmocktime(cur_time)
+ restorenode.setmocktime(cur_time)
+
+ # prepare miner wallet
+ minernode.createwallet(wallet_name='default')
+ miner_wallet = minernode.get_wallet_rpc('default')
+ m1 = miner_wallet.getnewaddress()
+
+ # prepare the user wallet with 3 watch only addresses
+ wo1 = usernode.getnewaddress()
+ wo2 = usernode.getnewaddress()
+ wo3 = usernode.getnewaddress()
+
+ usernode.createwallet(wallet_name='wo', disable_private_keys=True)
+ wo_wallet = usernode.get_wallet_rpc('wo')
+
+ wo_wallet.importaddress(wo1)
+ wo_wallet.importaddress(wo2)
+ wo_wallet.importaddress(wo3)
+
+ self.log.info('Start transactions')
+
+ # check blockcount
+ assert_equal(minernode.getblockcount(), 200)
+
+ # generate some btc to create transactions and check blockcount
+ initial_mine = COINBASE_MATURITY + 1
+ minernode.generatetoaddress(initial_mine, m1)
+ assert_equal(minernode.getblockcount(), initial_mine + 200)
+
+ # synchronize nodes and time
+ self.sync_all()
+ minernode.setmocktime(cur_time + ten_days)
+ usernode.setmocktime(cur_time + ten_days)
+ restorenode.setmocktime(cur_time + ten_days)
+ # send 10 btc to user's first watch-only address
+ self.log.info('Send 10 btc to user')
+ miner_wallet.sendtoaddress(wo1, 10)
+
+ # generate blocks and check blockcount
+ minernode.generatetoaddress(COINBASE_MATURITY, m1)
+ assert_equal(minernode.getblockcount(), initial_mine + 300)
+
+ # synchronize nodes and time
+ self.sync_all()
+ minernode.setmocktime(cur_time + ten_days + ten_days)
+ usernode.setmocktime(cur_time + ten_days + ten_days)
+ restorenode.setmocktime(cur_time + ten_days + ten_days)
+ # send 5 btc to our second watch-only address
+ self.log.info('Send 5 btc to user')
+ miner_wallet.sendtoaddress(wo2, 5)
+
+ # generate blocks and check blockcount
+ minernode.generatetoaddress(COINBASE_MATURITY, m1)
+ assert_equal(minernode.getblockcount(), initial_mine + 400)
+
+ # synchronize nodes and time
+ self.sync_all()
+ minernode.setmocktime(cur_time + ten_days + ten_days + ten_days)
+ usernode.setmocktime(cur_time + ten_days + ten_days + ten_days)
+ restorenode.setmocktime(cur_time + ten_days + ten_days + ten_days)
+ # send 1 btc to our third watch-only address
+ self.log.info('Send 1 btc to user')
+ miner_wallet.sendtoaddress(wo3, 1)
+
+ # generate more blocks and check blockcount
+ minernode.generatetoaddress(COINBASE_MATURITY, m1)
+ assert_equal(minernode.getblockcount(), initial_mine + 500)
+
+ self.log.info('Check user\'s final balance and transaction count')
+ assert_equal(wo_wallet.getbalance(), 16)
+ assert_equal(len(wo_wallet.listtransactions()), 3)
+
+ self.log.info('Check transaction times')
+ for tx in wo_wallet.listtransactions():
+ if tx['address'] == wo1:
+ assert_equal(tx['blocktime'], cur_time + ten_days)
+ assert_equal(tx['time'], cur_time + ten_days)
+ elif tx['address'] == wo2:
+ assert_equal(tx['blocktime'], cur_time + ten_days + ten_days)
+ assert_equal(tx['time'], cur_time + ten_days + ten_days)
+ elif tx['address'] == wo3:
+ assert_equal(tx['blocktime'], cur_time + ten_days + ten_days + ten_days)
+ assert_equal(tx['time'], cur_time + ten_days + ten_days + ten_days)
+
+ # restore user wallet without rescan
+ self.log.info('Restore user wallet on another node without rescan')
+ restorenode.createwallet(wallet_name='wo', disable_private_keys=True)
+ restorewo_wallet = restorenode.get_wallet_rpc('wo')
+
+ restorewo_wallet.importaddress(wo1, rescan=False)
+ restorewo_wallet.importaddress(wo2, rescan=False)
+ restorewo_wallet.importaddress(wo3, rescan=False)
+
+ # check user has 0 balance and no transactions
+ assert_equal(restorewo_wallet.getbalance(), 0)
+ assert_equal(len(restorewo_wallet.listtransactions()), 0)
+
+ # proceed to rescan, first with an incomplete one, then with a full rescan
+ self.log.info('Rescan last history part')
+ restorewo_wallet.rescanblockchain(initial_mine + 350)
+ self.log.info('Rescan all history')
+ restorewo_wallet.rescanblockchain()
+
+ self.log.info('Check user\'s final balance and transaction count after restoration')
+ assert_equal(restorewo_wallet.getbalance(), 16)
+ assert_equal(len(restorewo_wallet.listtransactions()), 3)
+
+ self.log.info('Check transaction times after restoration')
+ for tx in restorewo_wallet.listtransactions():
+ if tx['address'] == wo1:
+ assert_equal(tx['blocktime'], cur_time + ten_days)
+ assert_equal(tx['time'], cur_time + ten_days)
+ elif tx['address'] == wo2:
+ assert_equal(tx['blocktime'], cur_time + ten_days + ten_days)
+ assert_equal(tx['time'], cur_time + ten_days + ten_days)
+ elif tx['address'] == wo3:
+ assert_equal(tx['blocktime'], cur_time + ten_days + ten_days + ten_days)
+ assert_equal(tx['time'], cur_time + ten_days + ten_days + ten_days)
+
+
+if __name__ == '__main__':
+ TransactionTimeRescanTest().main()
diff --git a/test/functional/wallet_txn_clone.py b/test/functional/wallet_txn_clone.py
index 76b39201e3..7f178d7d46 100755
--- a/test/functional/wallet_txn_clone.py
+++ b/test/functional/wallet_txn_clone.py
@@ -7,6 +7,7 @@
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
+ find_vout_for_address
)
from test_framework.messages import (
COIN,
@@ -33,6 +34,13 @@ class TxnMallTest(BitcoinTestFramework):
super().setup_network()
self.disconnect_nodes(1, 2)
+ def spend_txid(self, txid, vout, outputs):
+ inputs = [{"txid": txid, "vout": vout}]
+ tx = self.nodes[0].createrawtransaction(inputs, outputs)
+ tx = self.nodes[0].fundrawtransaction(tx)
+ tx = self.nodes[0].signrawtransactionwithwallet(tx['hex'])
+ return self.nodes[0].sendrawtransaction(tx['hex'])
+
def run_test(self):
if self.options.segwit:
output_type = "p2sh-segwit"
@@ -49,6 +57,7 @@ class TxnMallTest(BitcoinTestFramework):
node0_address1 = self.nodes[0].getnewaddress(address_type=output_type)
node0_txid1 = self.nodes[0].sendtoaddress(node0_address1, 1219)
node0_tx1 = self.nodes[0].gettransaction(node0_txid1)
+ self.nodes[0].lockunspent(False, [{"txid":node0_txid1, "vout": find_vout_for_address(self.nodes[0], node0_txid1, node0_address1)}])
node0_address2 = self.nodes[0].getnewaddress(address_type=output_type)
node0_txid2 = self.nodes[0].sendtoaddress(node0_address2, 29)
@@ -61,8 +70,8 @@ class TxnMallTest(BitcoinTestFramework):
node1_address = self.nodes[1].getnewaddress()
# Send tx1, and another transaction tx2 that won't be cloned
- txid1 = self.nodes[0].sendtoaddress(node1_address, 40)
- txid2 = self.nodes[0].sendtoaddress(node1_address, 20)
+ txid1 = self.spend_txid(node0_txid1, find_vout_for_address(self.nodes[0], node0_txid1, node0_address1), {node1_address: 40})
+ txid2 = self.spend_txid(node0_txid2, find_vout_for_address(self.nodes[0], node0_txid2, node0_address2), {node1_address: 20})
# Construct a clone of tx1, to be malleated
rawtx1 = self.nodes[0].getrawtransaction(txid1, 1)
@@ -84,7 +93,7 @@ class TxnMallTest(BitcoinTestFramework):
# Have node0 mine a block, if requested:
if (self.options.mine_block):
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks(self.nodes[0:2])
tx1 = self.nodes[0].gettransaction(txid1)
@@ -114,13 +123,13 @@ class TxnMallTest(BitcoinTestFramework):
return
# ... mine a block...
- self.nodes[2].generate(1)
+ self.generate(self.nodes[2], 1)
# Reconnect the split network, and sync chain:
self.connect_nodes(1, 2)
self.nodes[2].sendrawtransaction(node0_tx2["hex"])
self.nodes[2].sendrawtransaction(tx2["hex"])
- self.nodes[2].generate(1) # Mine another block to make sure we sync
+ self.generate(self.nodes[2], 1) # Mine another block to make sure we sync
self.sync_blocks()
# Re-fetch transaction info:
diff --git a/test/functional/wallet_txn_doublespend.py b/test/functional/wallet_txn_doublespend.py
index 0cb7328948..150e4083b9 100755
--- a/test/functional/wallet_txn_doublespend.py
+++ b/test/functional/wallet_txn_doublespend.py
@@ -9,6 +9,7 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
find_output,
+ find_vout_for_address
)
@@ -29,6 +30,13 @@ class TxnMallTest(BitcoinTestFramework):
super().setup_network()
self.disconnect_nodes(1, 2)
+ def spend_txid(self, txid, vout, outputs):
+ inputs = [{"txid": txid, "vout": vout}]
+ tx = self.nodes[0].createrawtransaction(inputs, outputs)
+ tx = self.nodes[0].fundrawtransaction(tx)
+ tx = self.nodes[0].signrawtransactionwithwallet(tx['hex'])
+ return self.nodes[0].sendrawtransaction(tx['hex'])
+
def run_test(self):
# All nodes should start with 1,250 BTC:
starting_balance = 1250
@@ -47,6 +55,7 @@ class TxnMallTest(BitcoinTestFramework):
node0_address_foo = self.nodes[0].getnewaddress()
fund_foo_txid = self.nodes[0].sendtoaddress(node0_address_foo, 1219)
fund_foo_tx = self.nodes[0].gettransaction(fund_foo_txid)
+ self.nodes[0].lockunspent(False, [{"txid":fund_foo_txid, "vout": find_vout_for_address(self.nodes[0], fund_foo_txid, node0_address_foo)}])
node0_address_bar = self.nodes[0].getnewaddress()
fund_bar_txid = self.nodes[0].sendtoaddress(node0_address_bar, 29)
@@ -77,12 +86,12 @@ class TxnMallTest(BitcoinTestFramework):
assert_equal(doublespend["complete"], True)
# Create two spends using 1 50 BTC coin each
- txid1 = self.nodes[0].sendtoaddress(node1_address, 40)
- txid2 = self.nodes[0].sendtoaddress(node1_address, 20)
+ txid1 = self.spend_txid(fund_foo_txid, find_vout_for_address(self.nodes[0], fund_foo_txid, node0_address_foo), {node1_address: 40})
+ txid2 = self.spend_txid(fund_bar_txid, find_vout_for_address(self.nodes[0], fund_bar_txid, node0_address_bar), {node1_address: 20})
# Have node0 mine a block:
if (self.options.mine_block):
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
self.sync_blocks(self.nodes[0:2])
tx1 = self.nodes[0].gettransaction(txid1)
@@ -111,11 +120,11 @@ class TxnMallTest(BitcoinTestFramework):
self.nodes[2].sendrawtransaction(fund_bar_tx["hex"])
doublespend_txid = self.nodes[2].sendrawtransaction(doublespend["hex"])
# ... mine a block...
- self.nodes[2].generate(1)
+ self.generate(self.nodes[2], 1)
# Reconnect the split network, and sync chain:
self.connect_nodes(1, 2)
- self.nodes[2].generate(1) # Mine another block to make sure we sync
+ self.generate(self.nodes[2], 1) # Mine another block to make sure we sync
self.sync_blocks()
assert_equal(self.nodes[0].gettransaction(doublespend_txid)["confirmations"], 2)
diff --git a/test/functional/wallet_upgradewallet.py b/test/functional/wallet_upgradewallet.py
index 4d34670ea9..ed98db55c9 100755
--- a/test/functional/wallet_upgradewallet.py
+++ b/test/functional/wallet_upgradewallet.py
@@ -119,7 +119,7 @@ class UpgradeWalletTest(BitcoinTestFramework):
assert_equal(wallet.getwalletinfo()["walletversion"], previous_version)
def run_test(self):
- self.nodes[0].generatetoaddress(COINBASE_MATURITY + 1, self.nodes[0].getnewaddress())
+ self.generatetoaddress(self.nodes[0], COINBASE_MATURITY + 1, self.nodes[0].getnewaddress())
self.dumb_sync_blocks()
# # Sanity check the test framework:
res = self.nodes[0].getblockchaininfo()
@@ -131,7 +131,7 @@ class UpgradeWalletTest(BitcoinTestFramework):
# Send coins to old wallets for later conversion checks.
v16_3_wallet = v16_3_node.get_wallet_rpc('wallet.dat')
v16_3_address = v16_3_wallet.getnewaddress()
- node_master.generatetoaddress(COINBASE_MATURITY + 1, v16_3_address)
+ self.generatetoaddress(node_master, COINBASE_MATURITY + 1, v16_3_address)
self.dumb_sync_blocks()
v16_3_balance = v16_3_wallet.getbalance()
diff --git a/test/functional/wallet_watchonly.py b/test/functional/wallet_watchonly.py
index 6743c4a49b..3a9800111b 100755
--- a/test/functional/wallet_watchonly.py
+++ b/test/functional/wallet_watchonly.py
@@ -37,11 +37,11 @@ class CreateWalletWatchonlyTest(BitcoinTestFramework):
wo_wallet.importpubkey(pubkey=def_wallet.getaddressinfo(wo_change)['pubkey'])
# generate some btc for testing
- node.generatetoaddress(COINBASE_MATURITY + 1, a1)
+ self.generatetoaddress(node, COINBASE_MATURITY + 1, a1)
# send 1 btc to our watch-only address
txid = def_wallet.sendtoaddress(wo_addr, 1)
- self.nodes[0].generate(1)
+ self.generate(self.nodes[0], 1)
# getbalance
self.log.info('include_watchonly should default to true for watch-only wallets')
diff --git a/test/get_previous_releases.py b/test/get_previous_releases.py
index e92bb402b5..62fcad04b3 100755
--- a/test/get_previous_releases.py
+++ b/test/get_previous_releases.py
@@ -190,6 +190,7 @@ def check_host(args) -> int:
'aarch64-*-linux*': 'aarch64-linux-gnu',
'x86_64-*-linux*': 'x86_64-linux-gnu',
'x86_64-apple-darwin*': 'osx64',
+ 'aarch64-apple-darwin*': 'osx64',
}
args.platform = ''
for pattern, target in platforms.items():
diff --git a/test/lint/README.md b/test/lint/README.md
index 7e06308347..c4d76eac94 100644
--- a/test/lint/README.md
+++ b/test/lint/README.md
@@ -27,10 +27,10 @@ Usage: test/lint/git-subtree-check.sh [-r] DIR [COMMIT]
To do a full check with `-r`, make sure that you have fetched the upstream repository branch in which the subtree is
maintained:
* for `src/secp256k1`: https://github.com/bitcoin-core/secp256k1.git (branch master)
-* for `src/leveldb`: https://github.com/bitcoin-core/leveldb.git (branch bitcoin-fork)
-* for `src/univalue`: https://github.com/bitcoin-core/univalue.git (branch master)
+* for `src/leveldb`: https://github.com/bitcoin-core/leveldb-subtree.git (branch bitcoin-fork)
+* for `src/univalue`: https://github.com/bitcoin-core/univalue-subtree.git (branch master)
* for `src/crypto/ctaes`: https://github.com/bitcoin-core/ctaes.git (branch master)
-* for `src/crc32c`: https://github.com/google/crc32c.git (branch master)
+* for `src/crc32c`: https://github.com/bitcoin-core/crc32c-subtree.git (branch bitcoin-fork)
To do so, add the upstream repository as remote:
diff --git a/test/lint/lint-locale-dependence.sh b/test/lint/lint-locale-dependence.sh
index d6312270e7..712c4f0d5b 100755
--- a/test/lint/lint-locale-dependence.sh
+++ b/test/lint/lint-locale-dependence.sh
@@ -37,23 +37,17 @@ export LC_ALL=C
# See https://doc.qt.io/qt-5/qcoreapplication.html#locale-settings and
# https://stackoverflow.com/a/34878283 for more details.
+# TODO: Reduce KNOWN_VIOLATIONS by replacing uses of locale dependent stoul/strtol with locale
+# independent ToIntegral<T>(...).
+# TODO: Reduce KNOWN_VIOLATIONS by replacing uses of locale dependent snprintf with strprintf.
KNOWN_VIOLATIONS=(
"src/bitcoin-tx.cpp.*stoul"
- "src/dbwrapper.cpp.*stoul"
"src/dbwrapper.cpp:.*vsnprintf"
- "src/node/blockstorage.cpp:.*atoi"
- "src/qt/rpcconsole.cpp:.*atoi"
"src/rest.cpp:.*strtol"
"src/test/dbwrapper_tests.cpp:.*snprintf"
"src/test/fuzz/locale.cpp"
- "src/test/fuzz/parse_numbers.cpp:.*atoi"
- "src/torcontrol.cpp:.*atoi"
+ "src/test/fuzz/string.cpp"
"src/torcontrol.cpp:.*strtol"
- "src/util/strencodings.cpp:.*atoi"
- "src/util/strencodings.cpp:.*strtol"
- "src/util/strencodings.cpp:.*strtoul"
- "src/util/strencodings.h:.*atoi"
- "src/util/system.cpp:.*atoi"
)
REGEXP_IGNORE_EXTERNAL_DEPENDENCIES="^src/(crypto/ctaes/|leveldb/|secp256k1/|tinyformat.h|univalue/)"
diff --git a/test/lint/lint-logs.sh b/test/lint/lint-logs.sh
index 2fbb4a38e7..d6c53e8ff3 100755
--- a/test/lint/lint-logs.sh
+++ b/test/lint/lint-logs.sh
@@ -7,7 +7,7 @@
# Check that all logs are terminated with '\n'
#
# Some logs are continued over multiple lines. They should be explicitly
-# commented with \* Continued *\
+# commented with /* Continued */
#
# There are some instances of LogPrintf() in comments. Those can be
# ignored