6#if defined(HAVE_CONFIG_H)
7#include <config/bitcoin-config.h>
92#include <boost/signals2/signal.hpp>
95#include <chronik-cpp/chronik.h>
110#include <condition_variable>
150#define MIN_CORE_FILEDESCRIPTORS 0
152#define MIN_CORE_FILEDESCRIPTORS 150
216 if (
node.avalanche) {
219 node.avalanche->stopEventLoop();
222 node.connman->Interrupt();
234 static Mutex g_shutdown_mutex;
235 TRY_LOCK(g_shutdown_mutex, lock_shutdown);
236 if (!lock_shutdown) {
239 LogPrintf(
"%s: In progress...\n", __func__);
248 node.mempool->AddTransactionsUpdated(1);
255 for (
const auto &client :
node.chain_clients) {
266 if (
node.avalanche) {
267 node.avalanche->stopEventLoop();
276 node.connman->Stop();
283 if (
node.scheduler) {
284 node.scheduler->stop();
286 if (
node.chainman &&
node.chainman->m_thread_load.joinable()) {
287 node.chainman->m_thread_load.join();
293 node.peerman.reset();
296 node.avalanche.reset();
297 node.connman.reset();
299 node.addrman.reset();
301 if (
node.mempool &&
node.mempool->GetLoadTried() &&
311 if (chainstate->CanFlushToDisk()) {
312 chainstate->ForceFlushStateToDisk();
348 if (chainstate->CanFlushToDisk()) {
349 chainstate->ForceFlushStateToDisk();
350 chainstate->ResetCoinsViews();
354 node.chainman->DumpRecentHeadersTime(
node.chainman->m_options.datadir /
357 for (
const auto &client :
node.chain_clients) {
368 node.chain_clients.clear();
372 node.mempool.reset();
373 node.chainman.reset();
374 node.scheduler.reset();
378 LogPrintf(
"%s: Unable to remove PID file: File does not exist\n",
381 }
catch (
const fs::filesystem_error &e) {
382 LogPrintf(
"%s: Unable to remove PID file: %s\n", __func__,
403static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType) {
414 sigemptyset(&sa.sa_mask);
416 sigaction(signal, &sa, NULL);
441 argsman.
AddArg(
"-help-debug",
442 "Print help message with debugging options and exit",
false,
451 const auto testnetChainParams =
453 const auto regtestChainParams =
457 std::vector<std::string> hidden_args = {
462 "-automaticunparking",
463 "-replayprotectionactivationtime",
465 "-chronikallowpause",
468 "-allowselfsignedrootcertificates",
473 "-rootcertificates=<file>",
477 "-obolenskyactivationtime",
487#if defined(HAVE_SYSTEM)
489 "-alertnotify=<cmd>",
490 "Execute command when a relevant alert is received or we see "
491 "a really long fork (%s in cmd is replaced by message)",
495 "-assumevalid=<hex>",
497 "If this block is in the chain assume that it and its ancestors "
498 "are valid and potentially skip their script verification (0 to "
499 "verify all, default: %s, testnet: %s)",
500 defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(),
501 testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()),
503 argsman.
AddArg(
"-blocksdir=<dir>",
504 "Specify directory to hold blocks subdirectory for *.dat "
505 "files (default: <datadir>)",
507 argsman.
AddArg(
"-fastprune",
508 "Use smaller block files and lower minimum prune height for "
512#if defined(HAVE_SYSTEM)
513 argsman.
AddArg(
"-blocknotify=<cmd>",
514 "Execute command when the best block changes (%s in cmd is "
515 "replaced by block hash)",
518 argsman.
AddArg(
"-blockreconstructionextratxn=<n>",
519 strprintf(
"Extra transactions to keep in memory for compact "
520 "block reconstructions (default: %u)",
525 strprintf(
"Whether to reject transactions from network peers. "
526 "Disables automatic broadcast and rebroadcast of "
527 "transactions, unless the source peer has the "
528 "'forcerelay' permission. RPC transactions are"
529 " not affected. (default: %u)",
532 argsman.
AddArg(
"-coinstatsindex",
533 strprintf(
"Maintain coinstats index used by the "
534 "gettxoutsetinfo RPC (default: %u)",
539 strprintf(
"Specify path to read-only configuration file. Relative "
540 "paths will be prefixed by datadir location. (default: %s)",
543 argsman.
AddArg(
"-datadir=<dir>",
"Specify data directory",
547 strprintf(
"Maximum database write batch size in bytes (default: %u)",
551 argsman.
AddArg(
"-dbcache=<n>",
552 strprintf(
"Maximum database cache size <n> MiB (minimum %d, "
553 "default: %d). Make sure you have enough RAM. In "
554 "addition, unused memory allocated to the mempool "
555 "is shared with this cache (see -maxmempool).",
559 "-includeconf=<file>",
560 "Specify additional configuration file, relative to the -datadir path "
561 "(only useable from configuration file, not command line)",
563 argsman.
AddArg(
"-allowignoredconf",
564 strprintf(
"For backwards compatibility, treat an unused %s "
565 "file in the datadir as a warning, not an error.",
568 argsman.
AddArg(
"-loadblock=<file>",
569 "Imports blocks from external file on startup",
571 argsman.
AddArg(
"-maxmempool=<n>",
572 strprintf(
"Keep the transaction memory pool below <n> "
573 "megabytes (default: %u)",
576 argsman.
AddArg(
"-maxorphantx=<n>",
577 strprintf(
"Keep at most <n> unconnectable transactions in "
578 "memory (default: %u)",
581 argsman.
AddArg(
"-mempoolexpiry=<n>",
582 strprintf(
"Do not keep transactions in the mempool longer "
583 "than <n> hours (default: %u)",
587 "-minimumchainwork=<hex>",
589 "Minimum work assumed to exist on a valid chain in hex "
590 "(default: %s, testnet: %s)",
591 defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(),
592 testnetChainParams->GetConsensus().nMinimumChainWork.GetHex()),
597 strprintf(
"Set the number of script verification threads (%u to %d, 0 "
598 "= auto, <0 = leave that many cores free, default: %d)",
602 argsman.
AddArg(
"-persistmempool",
603 strprintf(
"Whether to save the mempool on shutdown and load "
604 "on restart (default: %u)",
608 "-persistrecentheaderstime",
610 "Whether the node stores the recent headers reception time to a "
611 "file and load it upon startup. This is intended for mining nodes "
612 "to overestimate the real time target upon restart (default: %u)",
617 strprintf(
"Specify pid file. Relative paths will be prefixed "
618 "by a net-specific datadir location. (default: %s)",
623 strprintf(
"Reduce storage requirements by enabling pruning (deleting) "
624 "of old blocks. This allows the pruneblockchain RPC to be "
625 "called to delete specific blocks and enables automatic "
626 "pruning of old blocks if a target size in MiB is provided. "
627 "This mode is incompatible with -txindex and -rescan. "
628 "Warning: Reverting this setting requires re-downloading the "
629 "entire blockchain. (default: 0 = disable pruning blocks, "
630 "1 = allow manual pruning via RPC, >=%u = automatically "
631 "prune block files to stay under the specified target size "
636 "-reindex-chainstate",
637 "Rebuild chain state from the currently indexed blocks. When "
638 "in pruning mode or if blocks on disk might be corrupted, use "
639 "full -reindex instead.",
643 "Rebuild chain state and block index from the blk*.dat files on disk."
644 " This will also rebuild active optional indexes.",
649 "Specify path to dynamic settings data file. Can be disabled with "
650 "-nosettings. File is written at runtime and not meant to be "
651 "edited by users (use %s instead for custom settings). Relative "
652 "paths will be prefixed by datadir location. (default: %s)",
656 argsman.
AddArg(
"-startupnotify=<cmd>",
"Execute command on startup.",
662 "Create new files with system default permissions, instead of umask "
663 "077 (only effective with disabled wallet functionality)",
666 hidden_args.emplace_back(
"-sysperms");
668 argsman.
AddArg(
"-txindex",
669 strprintf(
"Maintain a full transaction index, used by the "
670 "getrawtransaction rpc call (default: %d)",
676 strprintf(
"Enable the Chronik indexer, which can be read via a "
677 "dedicated HTTP/Protobuf interface (default: %d)",
681 "-chronikbind=<addr>[:port]",
683 "Bind the Chronik indexer to the given address to listen for "
684 "HTTP/Protobuf connections to access the index. Unlike the "
685 "JSON-RPC, it's ok to have this publicly exposed on the internet. "
686 "This option can be specified multiple times (default: %s; default "
687 "port: %u, testnet: %u, regtest: %u)",
688 Join(chronik::DEFAULT_BINDS,
", "),
689 defaultBaseParams->ChronikPort(), testnetBaseParams->ChronikPort(),
690 regtestBaseParams->ChronikPort()),
694 argsman.
AddArg(
"-chroniktokenindex",
695 "Enable token indexing in Chronik (default: 1)",
697 argsman.
AddArg(
"-chroniklokadidindex",
698 "Enable LOKAD ID indexing in Chronik (default: 1)",
700 argsman.
AddArg(
"-chronikreindex",
701 "Reindex the Chronik indexer from genesis, but leave the "
702 "other indexes untouched",
705 "-chroniktxnumcachebuckets",
707 "Tuning param of the TxNumCache, specifies how many buckets "
708 "to use on the belt. Caution against setting this too high, "
709 "it may slow down indexing. Set to 0 to disable. (default: %d)",
710 chronik::DEFAULT_TX_NUM_CACHE_BUCKETS),
714 "-chroniktxnumcachebucketsize",
716 "Tuning param of the TxNumCache, specifies the size of each bucket "
717 "on the belt. Unlike the number of buckets, this may be increased "
718 "without much danger of slowing the indexer down. The total cache "
719 "size will be `num_buckets * bucket_size * 40B`, so by default the "
720 "cache will require %dkB of memory. (default: %d)",
721 chronik::DEFAULT_TX_NUM_CACHE_BUCKETS *
722 chronik::DEFAULT_TX_NUM_CACHE_BUCKET_SIZE * 40 / 1000,
723 chronik::DEFAULT_TX_NUM_CACHE_BUCKET_SIZE),
726 argsman.
AddArg(
"-chronikperfstats",
727 "Output some performance statistics (e.g. num cache hits, "
728 "seconds spent) into a <datadir>/perf folder. (default: 0)",
730 argsman.
AddArg(
"-chronikscripthashindex",
731 "Enable the scripthash index for the Chronik indexer "
732 "(default: 1 if chronikelectrumbind is set, 0 otherwise) ",
735 "-chronikelectrumbind=<addr>[:port][:t|s|w|y]",
737 "Bind the Chronik Electrum interface to the given "
738 "address:port:protocol. If not set, the Electrum interface will "
739 "not start. This option can be specified multiple times. The "
740 "protocol is selected by a single letter, where 't' means TCP, 's' "
741 "means TLS, 'w' means WS and 'y' means WSS. If TLS and/or WSS is "
742 "selected, the certificate chain and private key must both be "
743 "passed (see -chronikelectrumcert and -chronikelectrumprivkey "
744 "(default: disabled; default port: %u, testnet: %u, regtest: %u; "
745 "default protocol: TLS)",
746 defaultBaseParams->ChronikElectrumPort(),
747 testnetBaseParams->ChronikElectrumPort(),
748 regtestBaseParams->ChronikElectrumPort()),
753 "-chronikelectrumcert",
754 "Path to the certificate file to be used by the Chronik Electrum "
755 "server when the TLS protocol is selected. The file should contain "
756 "the whole certificate chain (typically a .pem file). If used the "
757 "-chronikelectrumprivkey must be set as well.",
762 "-chronikelectrumprivkey",
763 "Path to the private key file to be used by the Chronik Electrum "
764 "server when the TLS protocol is selected. If used the "
765 "-chronikelectrumcert must be set as well.",
770 "-chronikelectrumurl",
771 "The URL to advertise to the Electrum peers. This needs to be set to "
772 "the server public URL to instruct the other Electrum peers that they "
773 "don't have to drop the connection. See the 'hosts' key in "
774 "https://electrum-cash-protocol.readthedocs.io/en/latest/"
775 "protocol-methods.html#server.features (default: 127.0.0.1).",
780 "-chronikelectrummaxhistory",
781 strprintf(
"Largest tx history we are willing to serve. (default: %u)",
782 chronik::DEFAULT_ELECTRUM_MAX_HISTORY),
786 "-chronikelectrumdonationaddress",
788 "The server donation address. No checks are done on the server "
789 "side to ensure this is a valid eCash address, it is just relayed "
790 "to clients verbatim as a text string (%u characters maximum).",
791 chronik::MAX_LENGTH_DONATION_ADDRESS),
795 "-chronikelectrumpeersvalidationinterval",
797 "The peers submitted via the Chronik Electrum server.add_peer "
798 "endpoint are periodically checked for validity and are only "
799 "returned after they passed the validation. This option controls "
800 "the interval duration between successive peers validation "
801 "processes in seconds (default: %u). Setting this value to 0 "
802 "disables the peer validation completely.",
803 std::chrono::duration_cast<std::chrono::seconds>(
804 chronik::DEFAULT_ELECTRUM_PEER_VALIDATION_INTERVAL)
810 "-blockfilterindex=<type>",
811 strprintf(
"Maintain an index of compact filters by block "
812 "(default: %s, values: %s).",
814 " If <type> is not supplied or if <type> = 1, indexes for "
815 "all known types are enabled.",
819 strprintf(
"Use Cash Address for destination encoding instead of legacy "
820 "base58 addresses (default: %d)",
826 "Add a node to connect to and attempt to keep the connection "
827 "open (see the `addnode` RPC command help for more info)",
830 argsman.
AddArg(
"-asmap=<file>",
831 strprintf(
"Specify asn mapping used for bucketing of the "
832 "peers (default: %s). Relative paths will be "
833 "prefixed by the net-specific datadir location.",
836 argsman.
AddArg(
"-bantime=<n>",
837 strprintf(
"Default duration (in seconds) of manually "
838 "configured bans (default: %u)",
842 "-bind=<addr>[:<port>][=onion]",
843 strprintf(
"Bind to given address and always listen on it (default: "
844 "0.0.0.0). Use [host]:port notation for IPv6. Append =onion "
845 "to tag any incoming connections to that address and port as "
846 "incoming Tor connections (default: 127.0.0.1:%u=onion, "
847 "testnet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)",
848 defaultBaseParams->OnionServiceTargetPort(),
849 testnetBaseParams->OnionServiceTargetPort(),
850 regtestBaseParams->OnionServiceTargetPort()),
855 "Connect only to the specified node(s); -noconnect disables automatic "
856 "connections (the rules for this peer are the same as for -addnode)",
861 "Discover own IP addresses (default: 1 when listening and no "
862 "-externalip or -proxy)",
865 strprintf(
"Allow DNS lookups for -addnode, -seednode and "
866 "-connect (default: %d)",
872 "Query for peer addresses via DNS lookup, if low on addresses "
873 "(default: %u unless -connect used)",
876 argsman.
AddArg(
"-externalip=<ip>",
"Specify your own public address",
881 "Allow fixed seeds if DNS seeds don't provide peers (default: %u)",
887 "Always query for peer addresses via DNS lookup (default: %d)",
890 argsman.
AddArg(
"-overridednsseed",
891 "If set, only use the specified DNS seed when "
892 "querying for peer addresses via DNS lookup.",
896 "Accept connections from outside (default: 1 if no -proxy or -connect)",
900 strprintf(
"Automatically create Tor onion service (default: %d)",
904 "-maxconnections=<n>",
905 strprintf(
"Maintain at most <n> connections to peers. The effective "
906 "limit depends on system limitations and might be lower than "
907 "the specified value (default: %u)",
910 argsman.
AddArg(
"-maxreceivebuffer=<n>",
911 strprintf(
"Maximum per-connection receive buffer, <n>*1000 "
912 "bytes (default: %u)",
916 "-maxsendbuffer=<n>",
918 "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)",
922 "-maxtimeadjustment",
923 strprintf(
"Maximum allowed median peer time offset adjustment. Local "
924 "perspective of time may be influenced by peers forward or "
925 "backward by this amount. (default: %u seconds)",
929 argsman.
AddArg(
"-onion=<ip:port|path>",
930 "Use separate SOCKS5 proxy to reach peers via Tor onion "
931 "services, set -noonion to disable (default: -proxy). May "
932 "be a local file path prefixed with 'unix:'.",
937 strprintf(
"Use separate SOCKS5 proxy to reach peers via Tor "
938 "onion services, set -noonion to disable (default: %s)",
942 argsman.
AddArg(
"-i2psam=<ip:port>",
943 "I2P SAM proxy to reach I2P peers and accept I2P "
944 "connections (default: none)",
947 "-i2pacceptincoming",
948 "If set and -i2psam is also set then incoming I2P connections are "
949 "accepted via the SAM proxy. If this is not set but -i2psam is set "
950 "then only outgoing connections will be made to the I2P network. "
951 "Ignored if -i2psam is not set. Listening for incoming I2P connections "
952 "is done through the SAM proxy, not by binding to a local address and "
958 "Make outgoing connections only through network <net> (" +
960 "). Incoming connections are not affected by this option. This "
961 "option can be specified multiple times to allow multiple "
964 argsman.
AddArg(
"-peerbloomfilters",
965 strprintf(
"Support filtering of blocks and transaction with "
966 "bloom filters (default: %d)",
972 "Serve compact block filters to peers per BIP 157 (default: %u)",
975 argsman.
AddArg(
"-permitbaremultisig",
976 strprintf(
"Relay non-P2SH multisig (default: %d)",
982 argsman.
AddArg(
"-port=<port>",
983 strprintf(
"Listen for connections on <port>. Nodes not "
984 "using the default ports (default: %u, "
985 "testnet: %u, regtest: %u) are unlikely to get "
986 "incoming connections. Not relevant for I2P (see "
988 defaultChainParams->GetDefaultPort(),
989 testnetChainParams->GetDefaultPort(),
990 regtestChainParams->GetDefaultPort()),
994 argsman.
AddArg(
"-proxy=<ip:port|path>",
995 "Connect through SOCKS5 proxy, set -noproxy to disable "
996 "(default: disabled). May be a local file path prefixed "
997 "with 'unix:' if the proxy supports it.",
1001 argsman.
AddArg(
"-proxy=<ip:port>",
1002 "Connect through SOCKS5 proxy, set -noproxy to disable "
1003 "(default: disabled)",
1009 strprintf(
"Randomize credentials for every proxy connection. "
1010 "This enables Tor stream isolation (default: %d)",
1015 "Connect to a node to retrieve peer addresses, and disconnect",
1019 "Enable all P2P network activity (default: 1). Can be changed "
1020 "by the setnetworkactive RPC command",
1022 argsman.
AddArg(
"-timeout=<n>",
1023 strprintf(
"Specify connection timeout in milliseconds "
1024 "(minimum: 1, default: %d)",
1029 strprintf(
"Specify p2p connection timeout in seconds. This option "
1030 "determines the amount of time a peer may be inactive before "
1031 "the connection to it is dropped. (minimum: 1, default: %d)",
1035 "-torcontrol=<ip>:<port>",
1037 "Tor control port to use if onion listening enabled (default: %s)",
1040 argsman.
AddArg(
"-torpassword=<pass>",
1041 "Tor control port password (default: empty)",
1046 strprintf(
"Use UPnP to map the listening port (default: %u)",
1050 hidden_args.emplace_back(
"-upnp");
1055 strprintf(
"Use NAT-PMP to map the listening port (default: %u)",
1059 hidden_args.emplace_back(
"-natpmp");
1062 "-whitebind=<[permissions@]addr>",
1063 "Bind to the given address and add permission flags to the peers "
1065 "Use [host]:port notation for IPv6. Allowed permissions: " +
1068 "Specify multiple permissions separated by commas (default: "
1069 "download,noban,mempool,relay). Can be specified multiple times.",
1072 argsman.
AddArg(
"-whitelist=<[permissions@]IP address or network>",
1073 "Add permission flags to the peers using the given "
1074 "IP address (e.g. 1.2.3.4) or CIDR-notated network "
1075 "(e.g. 1.2.3.0/24). "
1076 "Uses the same permissions as -whitebind. "
1077 "Additional flags \"in\" and \"out\" control whether "
1078 "permissions apply to incoming connections and/or manual "
1079 "(default: incoming only). "
1080 "Can be specified multiple times.",
1083 "-maxuploadtarget=<n>",
1084 strprintf(
"Tries to keep outbound traffic under the given target (in "
1085 "MiB per 24h). Limit does not apply to peers with 'download' "
1086 "permission. 0 = no limit (default: %d)",
1093 argsman.
AddArg(
"-zmqpubhashblock=<address>",
1094 "Enable publish hash block in <address>",
1096 argsman.
AddArg(
"-zmqpubhashtx=<address>",
1097 "Enable publish hash transaction in <address>",
1099 argsman.
AddArg(
"-zmqpubrawblock=<address>",
1100 "Enable publish raw block in <address>",
1102 argsman.
AddArg(
"-zmqpubrawtx=<address>",
1103 "Enable publish raw transaction in <address>",
1105 argsman.
AddArg(
"-zmqpubsequence=<address>",
1106 "Enable publish hash block and tx sequence in <address>",
1109 "-zmqpubhashblockhwm=<n>",
1110 strprintf(
"Set publish hash block outbound message high water "
1111 "mark (default: %d)",
1115 "-zmqpubhashtxhwm=<n>",
1116 strprintf(
"Set publish hash transaction outbound message high "
1117 "water mark (default: %d)",
1121 "-zmqpubrawblockhwm=<n>",
1122 strprintf(
"Set publish raw block outbound message high water "
1123 "mark (default: %d)",
1127 "-zmqpubrawtxhwm=<n>",
1128 strprintf(
"Set publish raw transaction outbound message high "
1129 "water mark (default: %d)",
1132 argsman.
AddArg(
"-zmqpubsequencehwm=<n>",
1133 strprintf(
"Set publish hash sequence message high water mark"
1138 hidden_args.emplace_back(
"-zmqpubhashblock=<address>");
1139 hidden_args.emplace_back(
"-zmqpubhashtx=<address>");
1140 hidden_args.emplace_back(
"-zmqpubrawblock=<address>");
1141 hidden_args.emplace_back(
"-zmqpubrawtx=<address>");
1142 hidden_args.emplace_back(
"-zmqpubsequence=<n>");
1143 hidden_args.emplace_back(
"-zmqpubhashblockhwm=<n>");
1144 hidden_args.emplace_back(
"-zmqpubhashtxhwm=<n>");
1145 hidden_args.emplace_back(
"-zmqpubrawblockhwm=<n>");
1146 hidden_args.emplace_back(
"-zmqpubrawtxhwm=<n>");
1147 hidden_args.emplace_back(
"-zmqpubsequencehwm=<n>");
1152 strprintf(
"How many blocks to check at startup (default: %u, 0 = all)",
1156 argsman.
AddArg(
"-checklevel=<n>",
1157 strprintf(
"How thorough the block verification of "
1158 "-checkblocks is: %s (0-4, default: %u)",
1162 argsman.
AddArg(
"-checkblockindex",
1163 strprintf(
"Do a consistency check for the block tree, "
1164 "chainstate, and other validation data structures "
1165 "occasionally. (default: %u, regtest: %u)",
1166 defaultChainParams->DefaultConsistencyChecks(),
1167 regtestChainParams->DefaultConsistencyChecks()),
1170 argsman.
AddArg(
"-checkaddrman=<n>",
1171 strprintf(
"Run addrman consistency checks every <n> "
1172 "operations. Use 0 to disable. (default: %u)",
1177 "-checkmempool=<n>",
1178 strprintf(
"Run mempool consistency checks every <n> transactions. Use "
1179 "0 to disable. (default: %u, regtest: %u)",
1180 defaultChainParams->DefaultConsistencyChecks(),
1181 regtestChainParams->DefaultConsistencyChecks()),
1184 argsman.
AddArg(
"-checkpoints",
1185 strprintf(
"Only accept block chain matching built-in "
1186 "checkpoints (default: %d)",
1190 argsman.
AddArg(
"-deprecatedrpc=<method>",
1191 "Allows deprecated RPC method(s) to be used",
1195 "-stopafterblockimport",
1196 strprintf(
"Stop running after importing blocks from disk (default: %d)",
1200 argsman.
AddArg(
"-stopatheight",
1201 strprintf(
"Stop running after reaching the given height in "
1202 "the main chain (default: %u)",
1206 argsman.
AddArg(
"-addrmantest",
"Allows to test address relay on localhost",
1209 argsman.
AddArg(
"-capturemessages",
"Capture all P2P messages to disk",
1212 argsman.
AddArg(
"-mocktime=<n>",
1218 "-maxsigcachesize=<n>",
1219 strprintf(
"Limit size of signature cache to <n> MiB (default: %u)",
1224 "-maxscriptcachesize=<n>",
1225 strprintf(
"Limit size of script cache to <n> MiB (default: %u)",
1229 argsman.
AddArg(
"-maxtipage=<n>",
1230 strprintf(
"Maximum tip age in seconds to consider node in "
1231 "initial block download (default: %u)",
1236 argsman.
AddArg(
"-uacomment=<cmt>",
1237 "Append comment to the user agent string",
1239 argsman.
AddArg(
"-uaclientname=<clientname>",
"Set user agent client name",
1241 argsman.
AddArg(
"-uaclientversion=<clientversion>",
1250 "Relay and mine \"non-standard\" transactions (%sdefault: %u)",
1251 "testnet/regtest only; ", defaultChainParams->RequireStandard()),
1254 argsman.
AddArg(
"-excessiveblocksize=<n>",
1255 strprintf(
"Do not accept blocks larger than this limit, in "
1256 "bytes (default: %d)",
1262 "-dustrelayfee=<amt>",
1263 strprintf(
"Fee rate (in %s/kB) used to define dust, the value of an "
1264 "output such that it will cost about 1/3 of its value in "
1265 "fees at this fee rate to spend it. (default: %s)",
1271 "-bytespersigcheck",
1272 strprintf(
"Equivalent bytes per sigCheck in transactions for relay and "
1273 "mining (default: %u).",
1278 strprintf(
"DEPRECATED: Equivalent bytes per sigCheck in transactions "
1279 "for relay and mining (default: %u). This has been "
1280 "deprecated since v0.26.8 and will be removed in the future, "
1281 "please use -bytespersigcheck instead.",
1286 strprintf(
"Relay and mine data carrier transactions (default: %d)",
1291 strprintf(
"Maximum size of data in data carrier transactions "
1292 "we relay and mine (default: %u)",
1296 "-minrelaytxfee=<amt>",
1297 strprintf(
"Fees (in %s/kB) smaller than this are rejected for "
1298 "relaying, mining and transaction creation (default: %s)",
1303 strprintf(
"Add 'relay' permission to whitelisted peers "
1304 "with default permissions. This will accept relayed "
1305 "transactions even when not relaying transactions "
1310 "-whitelistforcerelay",
1311 strprintf(
"Add 'forcerelay' permission to whitelisted peers "
1312 "with default permissions. This will relay transactions "
1313 "even if the transactions were already in the mempool "
1318 argsman.
AddArg(
"-blockmaxsize=<n>",
1319 strprintf(
"Set maximum block size in bytes (default: %d)",
1323 "-blockmintxfee=<amt>",
1324 strprintf(
"Set lowest fee rate (in %s/kB) for transactions to "
1325 "be included in block creation. (default: %s)",
1328 argsman.
AddArg(
"-simplegbt",
1329 "Use a simplified getblocktemplate output (default: 0)",
1332 argsman.
AddArg(
"-blockversion=<n>",
1333 "Override block version to test forking scenarios",
1337 argsman.
AddArg(
"-server",
"Accept command line and JSON-RPC commands",
1340 strprintf(
"Accept public REST requests (default: %d)",
1344 "-rpcbind=<addr>[:port]",
1345 "Bind to given address to listen for JSON-RPC connections. Do not "
1346 "expose the RPC server to untrusted networks such as the public "
1347 "internet! This option is ignored unless -rpcallowip is also passed. "
1348 "Port is optional and overrides -rpcport. Use [host]:port notation "
1349 "for IPv6. This option can be specified multiple times (default: "
1350 "127.0.0.1 and ::1 i.e., localhost)",
1356 strprintf(
"Throw a non-fatal error at runtime if the documentation for "
1357 "an RPC is incorrect (default: %u)",
1361 "-rpccookiefile=<loc>",
1362 "Location of the auth cookie. Relative paths will be prefixed "
1363 "by a net-specific datadir location. (default: data dir)",
1365 argsman.
AddArg(
"-rpcuser=<user>",
"Username for JSON-RPC connections",
1368 argsman.
AddArg(
"-rpcpassword=<pw>",
"Password for JSON-RPC connections",
1372 "-rpcwhitelist=<whitelist>",
1373 "Set a whitelist to filter incoming RPC calls for a specific user. The "
1374 "field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc "
1375 "2>,...,<rpc n>. If multiple whitelists are set for a given user, they "
1376 "are set-intersected. See -rpcwhitelistdefault documentation for "
1377 "information on default whitelist behavior.",
1380 "-rpcwhitelistdefault",
1381 "Sets default behavior for rpc whitelisting. Unless "
1382 "rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc "
1383 "server acts as if all rpc users are subject to "
1384 "empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault "
1385 "is set to 1 and no -rpcwhitelist is set, rpc server acts as if all "
1386 "rpc users are subject to empty whitelists.",
1389 "-rpcauth=<userpw>",
1390 "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. "
1391 "The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A "
1392 "canonical python script is included in share/rpcauth. The client then "
1393 "connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> "
1394 "pair of arguments. This option can be specified multiple times",
1396 argsman.
AddArg(
"-rpcport=<port>",
1397 strprintf(
"Listen for JSON-RPC connections on <port> "
1398 "(default: %u, testnet: %u, regtest: %u)",
1399 defaultBaseParams->RPCPort(),
1400 testnetBaseParams->RPCPort(),
1401 regtestBaseParams->RPCPort()),
1406 "Allow JSON-RPC connections from specified source. Valid for "
1407 "<ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. "
1408 "1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). "
1409 "This option can be specified multiple times",
1414 "Set the number of threads to service RPC calls (default: %d)",
1418 "-rpccorsdomain=value",
1419 "Domain from which to accept cross origin requests (browser enforced)",
1422 argsman.
AddArg(
"-rpcworkqueue=<n>",
1423 strprintf(
"Set the depth of the work queue to service RPC "
1424 "calls (default: %d)",
1428 argsman.
AddArg(
"-rpcservertimeout=<n>",
1429 strprintf(
"Timeout during HTTP requests (default: %d)",
1435 argsman.
AddArg(
"-daemon",
1436 strprintf(
"Run in the background as a daemon and accept "
1437 "commands (default: %d)",
1440 argsman.
AddArg(
"-daemonwait",
1441 strprintf(
"Wait for initialization to be finished before "
1442 "exiting. This implies -daemon (default: %d)",
1446 hidden_args.emplace_back(
"-daemon");
1447 hidden_args.emplace_back(
"-daemonwait");
1451 argsman.
AddArg(
"-avalanche",
1452 strprintf(
"Enable the avalanche feature (default: %u)",
1456 "-avalanchestakingrewards",
1457 strprintf(
"Enable the avalanche staking rewards feature (default: %u, "
1458 "testnet: %u, regtest: %u)",
1459 defaultChainParams->GetConsensus().enableStakingRewards,
1460 testnetChainParams->GetConsensus().enableStakingRewards,
1461 regtestChainParams->GetConsensus().enableStakingRewards),
1463 argsman.
AddArg(
"-avalanchestakingpreconsensus",
1464 strprintf(
"Enable the avalanche staking rewards "
1465 "preconsensus feature (default: %u)",
1469 "-avalanchepreconsensus",
1470 strprintf(
"Enable the avalanche preconsensus feature (default: %u)",
1473 argsman.
AddArg(
"-avalanchepreconsensusmining",
1474 strprintf(
"Enable mining only the avalanche finalized "
1475 "transactions (default: %u)",
1478 argsman.
AddArg(
"-avalancheconflictingproofcooldown",
1479 strprintf(
"Mandatory cooldown before a proof conflicting "
1480 "with an already registered one can be considered "
1481 "in seconds (default: %u)",
1485 argsman.
AddArg(
"-avalanchepeerreplacementcooldown",
1486 strprintf(
"Mandatory cooldown before a peer can be replaced "
1487 "in seconds (default: %u)",
1492 "-avaminquorumstake",
1494 "Minimum amount of known stake for a usable quorum (default: %s)",
1498 "-avaminquorumconnectedstakeratio",
1499 strprintf(
"Minimum proportion of known stake we"
1500 " need nodes for to have a usable quorum (default: %s). "
1501 "This parameter is parsed with a maximum precision of "
1507 "-avaminavaproofsnodecount",
1508 strprintf(
"Minimum number of node that needs to send us an avaproofs"
1509 " message before we consider we have a usable quorum"
1515 "-avastalevotethreshold",
1516 strprintf(
"Number of avalanche votes before a voted item goes stale "
1517 "when voting confidence is low (default: %u)",
1522 "-avastalevotefactor",
1524 "Factor affecting the number of avalanche votes before a voted "
1525 "item goes stale when voting confidence is high (default: %u)",
1529 argsman.
AddArg(
"-avacooldown",
1530 strprintf(
"Mandatory cooldown between two avapoll in "
1531 "milliseconds (default: %u)",
1536 strprintf(
"Avalanche query timeout in milliseconds (default: %u)",
1541 "Avalanche proof delegation to the master key used by this node "
1542 "(default: none). Should be used in conjunction with -avaproof and "
1545 argsman.
AddArg(
"-avaproof",
1546 "Avalanche proof to be used by this node (default: none)",
1549 "-avaproofstakeutxoconfirmations",
1551 "Minimum number of confirmations before a stake utxo is mature"
1552 " enough to be included into a proof. Utxos in the mempool are not "
1553 "accepted (i.e this value must be greater than 0) (default: %s)",
1557 argsman.
AddArg(
"-avaproofstakeutxodustthreshold",
1558 strprintf(
"Minimum value each stake utxo must have to be "
1559 "considered valid (default: %s)",
1562 argsman.
AddArg(
"-avamasterkey",
1563 "Master key associated with the proof. If a proof is "
1564 "required, this is mandatory.",
1567 argsman.
AddArg(
"-avasessionkey",
"Avalanche session key (default: random)",
1570 argsman.
AddArg(
"-enablertt",
1571 strprintf(
"Whether to enforce Real Time Targeting via "
1572 "Avalanche, default (%u)",
1576 "-maxavalancheoutbound",
1578 "Set the maximum number of avalanche outbound peers to connect to. "
1579 "Note that this option takes precedence over the -maxconnections "
1580 "option (default: %u).",
1586 strprintf(
"Whether to save the avalanche peers upon shutdown and load "
1587 "them upon startup (default: %u).",
1600 if (pBlockIndex !=
nullptr) {
1610static void StartupNotify(
const ArgsManager &args) {
1611 std::string cmd = args.
GetArg(
"-startupnotify",
"");
1613 std::thread t(runCommand, cmd);
1651 "%s: parameter interaction: -bind set -> setting -listen=1\n",
1657 LogPrintf(
"%s: parameter interaction: -whitebind set -> setting "
1667 LogPrintf(
"%s: parameter interaction: -connect set -> setting "
1672 LogPrintf(
"%s: parameter interaction: -connect set -> setting "
1683 "%s: parameter interaction: -proxy set -> setting -listen=0\n",
1691 "%s: parameter interaction: -proxy set -> setting -upnp=0\n",
1696 "%s: parameter interaction: -proxy set -> setting -natpmp=0\n",
1701 LogPrintf(
"%s: parameter interaction: -proxy set -> setting "
1712 "%s: parameter interaction: -listen=0 -> setting -upnp=0\n",
1717 "%s: parameter interaction: -listen=0 -> setting -natpmp=0\n",
1722 "%s: parameter interaction: -listen=0 -> setting -discover=0\n",
1726 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting "
1731 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting "
1732 "-i2pacceptincoming=0\n",
1737 if (args.
IsArgSet(
"-externalip")) {
1740 LogPrintf(
"%s: parameter interaction: -externalip set -> setting "
1749 LogPrintf(
"%s: parameter interaction: -blocksonly=1 -> setting "
1750 "-whitelistrelay=0\n",
1759 LogPrintf(
"%s: parameter interaction: -whitelistforcerelay=1 -> "
1760 "setting -whitelistrelay=1\n",
1767 const bool fAvalanche =
1787int nUserMaxConnections;
1790int64_t peer_connect_timeout;
1791std::set<BlockFilterType> g_enabled_filter_types;
1799 std::set_new_handler(std::terminate);
1800 LogPrintf(
"Error: Out of memory. Terminating.\n");
1810 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1811 _CrtSetReportFile(_CRT_WARN, CreateFileA(
"NUL", GENERIC_WRITE, 0,
nullptr,
1812 OPEN_EXISTING, 0, 0));
1814 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
1818 SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
1838 signal(SIGPIPE, SIG_IGN);
1840 SetConsoleCtrlHandler(consoleCtrlHandler,
true);
1861 strprintf(
_(
"Config setting for %s only applied on %s "
1862 "network when in [%s] section.") +
1867 if (!errors.
empty()) {
1875 _(
"Section [%s] is not recognized.") +
1877 section.m_file, section.m_line, section.m_name);
1880 if (!warnings.
empty()) {
1886 strprintf(
_(
"Specified blocks directory \"%s\" does not exist."),
1887 args.
GetArg(
"-blocksdir",
"")));
1891 std::string blockfilterindex_value =
1893 if (blockfilterindex_value ==
"" || blockfilterindex_value ==
"1") {
1895 }
else if (blockfilterindex_value !=
"0") {
1896 const std::vector<std::string> names =
1897 args.
GetArgs(
"-blockfilterindex");
1898 for (
const auto &
name : names) {
1904 g_enabled_filter_types.insert(filter_type);
1913 _(
"Cannot set -peerblockfilters without -blockfilterindex."));
1921 return InitError(
_(
"Prune mode is incompatible with -txindex."));
1923 if (args.
GetBoolArg(
"-reindex-chainstate",
false)) {
1925 _(
"Prune mode is incompatible with -reindex-chainstate. Use "
1926 "full -reindex instead."));
1929 return InitError(
_(
"Prune mode is incompatible with -chronik."));
1935 args.
GetArgs(
"-bind").size() + args.
GetArgs(
"-whitebind").size();
1938 "Cannot set -bind or -whitebind together with -listen=0"));
1942 int nBind = std::max(nUserBind,
size_t(1));
1943 nUserMaxConnections =
1945 nMaxConnections = std::max(nUserMaxConnections, 0);
1948 const int maxAvalancheOutbound = args.
GetIntArg(
1950 const bool fAvalanche =
1952 if (fAvalanche && maxAvalancheOutbound > nMaxConnections) {
1953 nMaxConnections = std::max(maxAvalancheOutbound, nMaxConnections);
1955 LogPrintf(
"Increasing -maxconnections from %d to %d to comply with "
1956 "-maxavalancheoutbound\n",
1957 nUserMaxConnections, nMaxConnections);
1969 int fd_max = FD_SETSIZE;
1971 nMaxConnections = std::max(
1972 std::min<int>(nMaxConnections,
1977 return InitError(
_(
"Not enough file descriptors available."));
1983 if (nMaxConnections < nUserMaxConnections) {
1987 LogPrintf(
"Reducing -maxconnections from %d to %d, because of system "
1989 nUserMaxConnections, nMaxConnections);
1997 const int64_t nProposedExcessiveBlockSize =
1999 if (nProposedExcessiveBlockSize <= 0 ||
2002 _(
"Excessive block size must be > 1,000,000 bytes (1MB)"));
2006 const int64_t nProposedMaxGeneratedBlockSize =
2008 if (nProposedMaxGeneratedBlockSize <= 0) {
2009 return InitError(
_(
"Max generated block size must be greater than 0"));
2011 if (uint64_t(nProposedMaxGeneratedBlockSize) > config.
GetMaxBlockSize()) {
2012 return InitError(
_(
"Max generated block size (blockmaxsize) cannot "
2013 "exceed the excessive block size "
2014 "(excessiveblocksize)"));
2022 peer_connect_timeout =
2024 if (peer_connect_timeout <= 0) {
2026 "peertimeout cannot be configured with a negative value."));
2032 if (args.
IsArgSet(
"-blockmintxfee")) {
2036 args.
GetArg(
"-blockmintxfee",
"")));
2057 const int64_t stakeUtxoMinConfirmations =
2058 args.
GetIntArg(
"-avaproofstakeutxoconfirmations",
2062 stakeUtxoMinConfirmations !=
2064 return InitError(
_(
"Avalanche stake UTXO minimum confirmations can "
2065 "only be set on test chains."));
2068 if (stakeUtxoMinConfirmations <= 0) {
2069 return InitError(
_(
"Avalanche stake UTXO minimum confirmations must be "
2070 "a positive integer."));
2073 if (args.
IsArgSet(
"-avaproofstakeutxodustthreshold")) {
2076 args.
GetArg(
"-avaproofstakeutxodustthreshold",
""), amount);
2079 "avaproofstakeutxodustthreshold",
2080 args.
GetArg(
"-avaproofstakeutxodustthreshold",
"")));
2085 return InitError(
_(
"Avalanche stake UTXO dust threshold can "
2086 "only be set on test chains."));
2091 if (fAvalanche && args.
IsArgSet(
"-avaproof")) {
2093 return InitError(
_(
"Running a staking node requires accepting "
2094 "inbound connections. Please enable -listen."));
2097 return InitError(
_(
"Running a staking node behind a proxy is not "
2098 "supported. Please disable -proxy."));
2101 return InitError(
_(
"Running a staking node behind I2P is not "
2102 "supported. Please disable -i2psam."));
2106 _(
"Restricting the outbound network is not supported when "
2107 "running a staking node. Please disable -onlynet."));
2117 .notifications = notifications,
2122 BlockManager::Options blockman_opts_dummy{
2123 .chainparams = chainman_opts_dummy.config.GetChainParams(),
2125 .notifications = chainman_opts_dummy.notifications,
2141 strprintf(
_(
"Cannot obtain a lock on data directory %s. %s is "
2142 "probably already running."),
2148 _(
"Cannot write to data directory '%s'; check permissions."),
2160 _(
"Initialization sanity check failed. %s is shutting down."),
2209 LogPrintf(
"Using at most %i automatic connections (%i file descriptors "
2211 nMaxConnections, nFD);
2215 !args.
GetPathArg(
"-datadir").is_absolute()) {
2216 LogPrintf(
"Warning: relative datadir option '%s' specified, which will "
2217 "be interpreted relative to the current working directory "
2218 "'%s'. This is fragile, because if bitcoin is started in the "
2219 "future from a different location, it will be unable to "
2220 "locate the current data files. There could also be data "
2221 "loss if bitcoin is started while in a temporary "
2223 args.
GetArg(
"-datadir",
""),
2228 if (script_threads <= 0) {
2236 script_threads = std::max(script_threads - 1, 0);
2241 LogPrintf(
"Script verification uses %d additional threads\n",
2243 if (script_threads >= 1) {
2248 node.scheduler = std::make_unique<CScheduler>();
2249 auto &scheduler = *
node.scheduler;
2252 node.scheduler->m_service_thread =
2254 [&] {
node.scheduler->serviceQueue(); });
2257 node.scheduler->scheduleEvery(
2262 std::chrono::minutes{1});
2266 [&scheduler](
auto func,
auto window) {
2267 scheduler.scheduleEvery(std::move(func), window);
2271 LogInfo(
"Log rate limiting disabled\n");
2281 for (
const auto &client :
node.chain_clients) {
2282 client->registerRpcs();
2298 _(
"Unable to start HTTP server. See debug log for details."));
2303 for (
const auto &client :
node.chain_clients) {
2304 if (!client->verify()) {
2324 std::vector<bool> asmap;
2328 if (!asmap_path.is_absolute()) {
2337 if (asmap.size() == 0) {
2343 LogPrintf(
"Using asmap version %s for IP bucketing\n",
2346 LogPrintf(
"Using /16 prefix for IP bucketing\n");
2349 uiInterface.InitMessage(
_(
"Loading P2P addresses...").translated);
2350 auto addrman{
LoadAddrman(chainparams, asmap, args)};
2354 node.addrman = std::move(*addrman);
2359 node.banman = std::make_unique<BanMan>(
2363 node.connman = std::make_unique<CConnman>(
2368 for (
const std::string port_option : {
2373 const std::string port = args.
GetArg(port_option,
"");
2381 for (
const std::string port_option : {
2394 for (
const std::string &socket_addr : args.
GetArgs(port_option)) {
2395 std::string host_out;
2396 uint16_t port_out{0};
2401 if ((port_option !=
"-proxy" && port_option !=
"-onion") ||
2413 for (
const std::string &socket_addr : args.
GetArgs(
"-bind")) {
2414 std::string host_out;
2415 uint16_t port_out{0};
2416 std::string bind_socket_addr =
2417 socket_addr.substr(0, socket_addr.rfind(
'='));
2424 std::vector<std::string> uacomments;
2425 for (
const std::string &cmt : args.
GetArgs(
"-uacomment")) {
2428 _(
"User Agent comment (%s) contains unsafe characters."), cmt));
2430 uacomments.push_back(cmt);
2433 const std::string client_version =
2437 _(
"-uaclientname (%s) contains invalid characters."), client_name));
2439 if (client_version !=
2442 strprintf(
_(
"-uaclientversion (%s) contains invalid characters."),
2445 const std::string strSubVersion =
2449 _(
"Total length of network version string (%i) exceeds maximum "
2450 "length (%i). Reduce the number or size of uacomments."),
2455 std::set<enum Network> nets;
2456 for (
const std::string &snet : args.
GetArgs(
"-onlynet")) {
2460 _(
"Unknown network specified in -onlynet: '%s'"), snet));
2464 for (
int n = 0; n <
NET_MAX; n++) {
2467 if (!nets.count(net)) {
2479 bool proxyRandomize =
2484 std::string proxyArg = args.
GetArg(
"-proxy",
"");
2485 if (proxyArg !=
"" && proxyArg !=
"0") {
2488 addrProxy =
Proxy(proxyArg, proxyRandomize);
2490 const std::optional<CService> proxyAddr{
2492 if (!proxyAddr.has_value()) {
2494 _(
"Invalid -proxy address or hostname: '%s'"), proxyArg));
2497 addrProxy =
Proxy(proxyAddr.value(), proxyRandomize);
2502 _(
"Invalid -proxy address or hostname: '%s'"), proxyArg));
2508 onion_proxy = addrProxy;
2511 const bool onlynet_used_with_onion{args.
IsArgSet(
"-onlynet") &&
2519 std::string onionArg = args.
GetArg(
"-onion",
"");
2520 if (onionArg !=
"") {
2521 if (onionArg ==
"0") {
2523 onion_proxy =
Proxy{};
2524 if (onlynet_used_with_onion) {
2525 return InitError(
_(
"Outbound connections restricted to Tor "
2526 "(-onlynet=onion) but the proxy for "
2527 "reaching the Tor network is explicitly "
2528 "forbidden: -onion=0"));
2532 onion_proxy =
Proxy(onionArg, proxyRandomize);
2534 const std::optional<CService> addr{
2536 if (!addr.has_value() || !addr->IsValid()) {
2538 strprintf(
_(
"Invalid -onion address or hostname: '%s'"),
2542 onion_proxy =
Proxy(addr.value(), proxyRandomize);
2553 const bool listenonion_disabled{
2555 if (onlynet_used_with_onion && listenonion_disabled) {
2556 return InitError(
_(
"Outbound connections restricted to Tor "
2557 "(-onlynet=onion) but the proxy for "
2558 "reaching the Tor network is not provided: none "
2559 "of -proxy, -onion or "
2560 "-listenonion is given"));
2565 for (
const std::string &strAddr : args.
GetArgs(
"-externalip")) {
2566 const std::optional<CService> addrLocal{
2568 if (addrLocal.has_value() && addrLocal->IsValid()) {
2579 return chainman->m_blockman.ReadBlock(block, index);
2589 node.notifications =
2590 std::make_unique<KernelNotifications>(
node.exit_status);
2592 bool fReindexChainState = args.
GetBoolArg(
"-reindex-chainstate",
false);
2598 .notifications = *
node.notifications,
2603 if (chainman_opts.checkpoints_enabled) {
2604 LogPrintf(
"Checkpoints will be verified.\n");
2606 LogPrintf(
"Skipping checkpoint verification.\n");
2609 BlockManager::Options blockman_opts{
2610 .chainparams = chainman_opts.config.GetChainParams(),
2612 .notifications = chainman_opts.notifications,
2618 const auto [index_cache_sizes, kernel_cache_sizes] =
2621 LogInfo(
"Cache configuration:\n");
2622 LogInfo(
"* Using %.1f MiB for block index database\n",
2623 kernel_cache_sizes.block_tree_db * (1.0 / 1024 / 1024));
2625 LogInfo(
"* Using %.1f MiB for transaction index database\n",
2626 index_cache_sizes.tx_index * (1.0 / 1024 / 1024));
2629 LogInfo(
"* Using %.1f MiB for %s block filter index database\n",
2630 index_cache_sizes.filter_index * (1.0 / 1024 / 1024),
2633 LogInfo(
"* Using %.1f MiB for chain state database\n",
2634 kernel_cache_sizes.coins_db * (1.0 / 1024 / 1024));
2645 mempool_opts.check_ratio =
2646 std::clamp<int>(mempool_opts.check_ratio, 0, 1'000'000);
2652 int64_t nMempoolSizeMin = 101 * 1000 * 40;
2653 if (mempool_opts.max_size_bytes < 0 ||
2655 mempool_opts.max_size_bytes < nMempoolSizeMin)) {
2657 std::ceil(nMempoolSizeMin / 1000000.0)));
2659 LogInfo(
"* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of "
2660 "unused mempool space)\n",
2661 kernel_cache_sizes.coins * (1.0 / 1024 / 1024),
2662 mempool_opts.max_size_bytes * (1.0 / 1024 / 1024));
2665 node.mempool = std::make_unique<CTxMemPool>(config, mempool_opts);
2667 node.chainman = std::make_unique<ChainstateManager>(
2668 node.kernel->interrupt, chainman_opts, blockman_opts);
2675 if (!
node.chainman->m_blockman.IsPruneMode()) {
2676 LogPrintf(
"[snapshot] re-enabling NODE_NETWORK services\n");
2680 LogPrintf(
"[snapshot] restarting indexes\n");
2686 for (
auto *index :
node.indexes) {
2689 if (!(index->Init() && index->StartBackgroundSync())) {
2690 LogPrintf(
"[snapshot] WARNING failed to restart index %s "
2691 "on snapshot chain\n",
2710 _(
"Error reading from database, shutting down."),
"",
2714 uiInterface.InitMessage(
_(
"Loading block index...").translated);
2716 const int64_t load_block_index_start_time =
GetTimeMillis();
2717 auto catch_exceptions = [](
auto &&f) {
2720 }
catch (
const std::exception &e) {
2723 _(
"Error opening block database"));
2726 auto [status, error] =
2727 catch_exceptions([&, &kernel_cache_sizes_ = kernel_cache_sizes] {
2734 LogWarning(
"pruned datadir may not have more than %d "
2735 "blocks; only checking available blocks\n",
2738 std::tie(status, error) = catch_exceptions(
2742 node.chainman->m_options.datadir /
2762 _(
"Do you want to rebuild the block database now?"),
2763 error.
original +
".\nPlease restart with -reindex or "
2764 "-reindex-chainstate to recover.",
2772 LogPrintf(
"Aborted block database rebuild. Exiting.\n");
2786 LogPrintf(
"Shutdown requested. Exiting.\n");
2796 args, *
node.chain,
node.connman.get(), chainman,
node.mempool.get(),
2797 *
node.scheduler, avalancheError);
2798 if (!
node.avalanche) {
2803 if (
node.avalanche->isAvalancheServiceAvailable()) {
2813 node.banman.get(), chainman, *
node.mempool,
2814 node.avalanche.get(), peerman_opts);
2838 for (
const auto &filter_type : g_enabled_filter_types) {
2841 index_cache_sizes.filter_index,
false,
fReindex);
2853 for (
auto index :
node.indexes) {
2854 if (!index->Init()) {
2859 const bool background_sync_in_progress{
WITH_LOCK(
2863 if (background_sync_in_progress) {
2865 _(
"Assumeutxo is incompatible with -chronik. Wait for "
2866 "background sync to complete before enabling Chronik."));
2869 const bool fReindexChronik =
2871 if (!chronik::Start(args, config,
node, fReindexChronik)) {
2878 for (
const auto &client :
node.chain_clients) {
2879 if (!client->load()) {
2892 uiInterface.InitMessage(
_(
"Pruning blockstore...").translated);
2893 chainstate->PruneAndFlush();
2899 if (!background_sync_in_progress) {
2900 LogPrintf(
"Setting NODE_NETWORK on non-prune mode\n");
2903 LogPrintf(
"Running node in NODE_NETWORK_LIMITED mode until "
2904 "snapshot background sync completes\n");
2911 strprintf(
_(
"Error: Disk space is low for %s"),
2917 strprintf(
_(
"Error: Disk space is low for %s"),
2925 boost::signals2::connection block_notify_genesis_wait_connection;
2928 block_notify_genesis_wait_connection =
2935#if defined(HAVE_SYSTEM)
2936 const std::string block_notify = args.
GetArg(
"-blocknotify",
"");
2937 if (!block_notify.empty()) {
2938 uiInterface.NotifyBlockTip_connect([block_notify](
2944 std::string command = block_notify;
2946 std::thread t(runCommand, command);
2953 std::vector<fs::path> vImportFiles;
2954 for (
const std::string &strFile : args.
GetArgs(
"-loadblock")) {
2966 _(
"Failed to start indexes, shutting down..");
2985 block_notify_genesis_wait_connection.disconnect();
2994 int chain_active_height;
3010 if (tip_info && chainman.m_best_header) {
3012 tip_info->
header_time = chainman.m_best_header->GetBlockTime();
3015 LogPrintf(
"nBestHeight = %d\n", chain_active_height);
3017 node.peerman->SetBestHeight(chain_active_height);
3029 ? args.
GetIntArg(
"-maxavalancheoutbound",
3044 if (
node.avalanche) {
3063 const uint16_t default_bind_port =
static_cast<uint16_t
>(
3066 const auto BadPortWarning = [](
const char *
prefix, uint16_t port) {
3067 return strprintf(
_(
"%s request to listen on port %u. This port is "
3068 "considered \"bad\" and "
3069 "thus it is unlikely that any Bitcoin ABC peers "
3070 "connect to it. See "
3071 "doc/p2p-bad-ports.md for details and a full list."),
3075 for (
const std::string &bind_arg : args.
GetArgs(
"-bind")) {
3076 std::optional<CService> bind_addr;
3077 const size_t index = bind_arg.rfind(
'=');
3078 if (index == std::string::npos) {
3080 Lookup(bind_arg, default_bind_port,
false);
3081 if (bind_addr.has_value()) {
3082 connOptions.
vBinds.push_back(bind_addr.value());
3083 if (
IsBadPort(bind_addr.value().GetPort())) {
3085 BadPortWarning(
"-bind", bind_addr.value().GetPort()));
3090 const std::string network_type = bind_arg.substr(index + 1);
3091 if (network_type ==
"onion") {
3092 const std::string truncated_bind_arg =
3093 bind_arg.substr(0, index);
3095 Lookup(truncated_bind_arg,
3096 BaseParams().OnionServiceTargetPort(),
false);
3097 if (bind_addr.has_value()) {
3098 connOptions.
onion_binds.push_back(bind_addr.value());
3106 for (
const std::string &strBind : args.
GetArgs(
"-whitebind")) {
3118 args.
GetArgs(
"-bind").empty() && args.
GetArgs(
"-whitebind").empty();
3123 const uint16_t port_arg = args.
GetIntArg(
"-port", 0);
3131 onion_service_target = connOptions.
onion_binds.front();
3132 }
else if (!connOptions.
vBinds.empty()) {
3133 onion_service_target = connOptions.
vBinds.front();
3136 connOptions.
onion_binds.push_back(onion_service_target);
3142 _(
"More than one onion bind address is provided. Using %s "
3143 "for the automatically created Tor onion service."),
3155 for (
const auto &net : args.
GetArgs(
"-whitelist")) {
3160 connection_direction, error)) {
3176 const auto connect = args.
GetArgs(
"-connect");
3177 if (connect.size() != 1 || connect[0] !=
"0") {
3182 const std::string &i2psam_arg = args.
GetArg(
"-i2psam",
"");
3183 if (!i2psam_arg.empty()) {
3184 const std::optional<CService> addr{
3186 if (!addr.has_value() || !addr->IsValid()) {
3188 _(
"Invalid -i2psam address or hostname: '%s'"), i2psam_arg));
3198 if (!
node.connman->Start(*
node.scheduler, connOptions)) {
3218 for (
const auto &client :
node.chain_clients) {
3219 client->start(*
node.scheduler);
3223 node.scheduler->scheduleEvery(
3231 if (
node.avalanche) {
3232 node.avalanche->startEventLoop(*
node.scheduler);
3236 node.peerman->StartScheduledTasks(*
node.scheduler);
3240 StartupNotify(args);
3251 std::optional<const CBlockIndex *> indexes_start_block;
3252 std::string older_index_name;
3258 for (
auto index :
node.indexes) {
3269 if (!index_chain.
Contains(pindex)) {
3270 pindex = index_chain.
FindFork(pindex);
3273 if (!indexes_start_block || !pindex ||
3274 pindex->
nHeight < indexes_start_block.value()->nHeight) {
3275 indexes_start_block = pindex;
3276 older_index_name = summary.
name;
3285 if (indexes_start_block) {
3287 const CBlockIndex *start_block = *indexes_start_block;
3291 if (!chainman.
m_blockman.CheckBlockDataAvailability(
3292 *index_chain.
Tip(), *
Assert(start_block))) {
3294 Untranslated(
"%s best block of the index goes beyond pruned "
3295 "data. Please disable the index or reindex (which "
3296 "will download the whole blockchain again)"),
3302 for (
auto index :
node.indexes) {
3303 if (!index->StartBackgroundSync()) {
util::Result< std::unique_ptr< AddrMan > > LoadAddrman(const CChainParams &chainparams, const std::vector< bool > &asmap, const ArgsManager &args)
Returns an error string on failure.
static constexpr int32_t DEFAULT_ADDRMAN_CONSISTENCY_CHECKS
Default for -checkaddrman.
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
const char *const BITCOIN_SETTINGS_FILENAME
const char *const BITCOIN_CONF_FILENAME
fs::path AbsPathForConfigVal(const ArgsManager &args, const fs::path &path, bool net_specific=true)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
std::vector< bool > DecodeAsmap(fs::path path)
Read asmap from provided binary file.
static constexpr bool DEFAULT_PERSIST_AVAPEERS
Default for -persistavapeers.
static constexpr double AVALANCHE_DEFAULT_MIN_QUORUM_CONNECTED_STAKE_RATIO
Default minimum percentage of stake-weighted peers we must have a node for to constitute a usable quo...
static constexpr bool DEFAULT_AVALANCHE_STAKING_PRECONSENSUS
Default for -avalanchestakingpreconsensus.
static constexpr size_t AVALANCHE_DEFAULT_PEER_REPLACEMENT_COOLDOWN
Peer replacement cooldown time default value in seconds.
static constexpr double AVALANCHE_DEFAULT_MIN_AVAPROOFS_NODE_COUNT
Default minimum number of nodes that sent us an avaproofs message before we can consider our quorum s...
static constexpr bool DEFAULT_AVALANCHE_PRECONSENSUS
Default for -avalanchepreconsensus.
static constexpr Amount AVALANCHE_DEFAULT_MIN_QUORUM_STAKE
Default minimum cumulative stake of all known peers that constitutes a usable quorum.
static constexpr size_t AVALANCHE_DEFAULT_CONFLICTING_PROOF_COOLDOWN
Conflicting proofs cooldown time default value in seconds.
static constexpr bool DEFAULT_AVALANCHE_MINING_PRECONSENSUS
Default for -avalanchepreconsensusmining.
static constexpr bool AVALANCHE_DEFAULT_ENABLED
Is avalanche enabled by default.
static constexpr size_t AVALANCHE_DEFAULT_COOLDOWN
Avalanche default cooldown in milliseconds.
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
static constexpr std::chrono::minutes DUMP_BANS_INTERVAL
How often to dump banned addresses/subnets to disk.
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
const std::set< BlockFilterType > & AllBlockFilterTypes()
Get a list of known filter types.
const std::string & ListBlockFilterTypes()
Get a comma-separated list of known filter type names.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
bool InitBlockFilterIndex(std::function< std::unique_ptr< interfaces::Chain >()> make_chain, BlockFilterType filter_type, size_t n_cache_size, bool f_memory, bool f_wipe)
Initialize a block filter index for the given type if one does not already exist.
static const char *const DEFAULT_BLOCKFILTERINDEX
std::unique_ptr< const CChainParams > CreateChainParams(const ArgsManager &args, const ChainType chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
const CChainParams & Params()
Return the currently selected parameters.
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const ChainType chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
static constexpr bool DEFAULT_CHECKPOINTS_ENABLED
static constexpr auto DEFAULT_MAX_TIP_AGE
static constexpr int DEFAULT_STOPATHEIGHT
static constexpr bool DEFAULT_STORE_RECENT_HEADERS_TIME
std::string ChainTypeToString(ChainType chain)
#define Assert(val)
Identity function.
std::set< std::string > GetUnsuitableSectionOnlyArgs() const
Log warnings for options in m_section_only_args when they are specified in the default section but no...
std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
@ ALLOW_ANY
disable validation
@ DISALLOW_NEGATION
unimplemented, draft implementation in #16545
@ DISALLOW_ELISION
disallow -foo syntax that doesn't assign any value
ChainType GetChainType() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
fs::path GetBlocksDirPath() const
Get blocks directory path.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
static std::shared_ptr< LogRateLimiter > Create(SchedulerFunction &&scheduler_func, uint64_t max_bytes, std::chrono::seconds reset_window)
void SetRateLimiting(std::shared_ptr< LogRateLimiter > limiter) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
std::atomic< bool > m_reopen_file
void Stop()
Stops the instance from staying in sync with blockchain updates.
bool BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(void Interrupt()
Blocks the current thread until the index is caught up to the current state of the block chain.
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
The block chain is a tree shaped structure starting with the genesis block at the root,...
int64_t GetBlockTime() const
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
An in-memory indexed chain of blocks.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
int Height() const
Return the maximal height in the chain.
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const CBlock & GenesisBlock() const
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
const ChainTxData & TxData() const
bool IsTestChain() const
If this chain is exclusively used for testing.
uint16_t GetDefaultPort() const
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once)
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToStringAddrPort() const
static const int DEFAULT_ZMQ_SNDHWM
static std::unique_ptr< CZMQNotificationInterface > Create(std::function< bool(CBlock &, const CBlockIndex &)> get_block_by_index)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
CChain m_chain
The current chain of blockheaders we consult and build on.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
std::thread m_thread_load
kernel::Notifications & GetNotifications() const
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
std::function< void()> snapshot_download_completed
Function to restart active indexes; set dynamically to avoid a circular dependency on base/index....
const CChainParams & GetParams() const
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
virtual uint64_t GetMaxBlockSize() const =0
virtual const CChainParams & GetChainParams() const =0
virtual bool SetMaxBlockSize(uint64_t maxBlockSize)=0
virtual void SetCashAddrEncoding(bool)=0
uint64_t rand64() noexcept
Generate a random 64-bit integer.
Different type to mark Mutex at global scope.
A writer stream (for serialization) that computes a 256-bit hash.
static bool TryParse(const std::string &str, NetWhitebindPermissions &output, bilingual_str &error)
static bool TryParse(const std::string &str, NetWhitelistPermissions &output, ConnectionDirection &output_connection_direction, bilingual_str &error)
static std::unique_ptr< PeerManager > make(CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, avalanche::Processor *const avalanche, Options opts)
Class for registering and managing all RPC calls.
virtual void AddWalletOptions(ArgsManager &argsman) const =0
Get wallet help string.
virtual void Construct(node::NodeContext &node) const =0
Add wallets that should be opened to list of chain clients.
virtual bool ParameterInteraction() const =0
Check wallet parameter interaction.
static std::unique_ptr< Processor > MakeProcessor(const ArgsManager &argsman, interfaces::Chain &chain, CConnman *connman, ChainstateManager &chainman, CTxMemPool *mempoolIn, CScheduler &scheduler, bilingual_str &error)
std::string ToString() const
std::string GetHex() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
A base class defining functions for notifying about certain kernel events.
virtual void fatalError(const std::string &debug_message, const bilingual_str &user_message={})
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
bool CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND, const CBlockIndex &lower_block LIFETIMEBOUND) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND, std::function< bool(BlockStatus)> status_test, const CBlockIndex *lower_block=nullptr) const EXCLUSIVE_LOCKS_REQUIRED(boo m_have_pruned)
Check if all blocks in the [upper_block, lower_block] range have data available.
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool IsPruneMode() const
Whether running in -prune mode.
std::string FormatVersion(int nVersion)
std::string FormatUserAgent(const std::string &name, const std::string &version, const std::vector< std::string > &comments)
Format the subversion field according to BIP 14 spec.
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
const std::string CLIENT_NAME
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
static constexpr bool DEFAULT_COINSTATSINDEX
static const uint64_t DEFAULT_MAX_BLOCK_SIZE
Default setting for maximum allowed size for a block, in bytes.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
void SetupCurrencyUnitOptions(ArgsManager &argsman)
int RaiseFileDescriptorLimit(int nMinFD)
This function tries to raise the file descriptor limit to the requested number.
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
void StopHTTPRPC()
Stop HTTP RPC subsystem.
bool StartHTTPRPC(HTTPRPCRequestProcessor &httpRPCRequestProcessor)
Start HTTP RPC subsystem.
void StartREST(const std::any &context)
Start HTTP REST subsystem.
void StopREST()
Stop HTTP REST subsystem.
void InterruptREST()
Interrupt RPC REST subsystem.
void InterruptHTTPServer()
Interrupt HTTP server threads.
void StartHTTPServer()
Start HTTP server.
void StopHTTPServer()
Stop HTTP server.
bool InitHTTPServer(Config &config)
Initialize HTTP server.
static const int DEFAULT_HTTP_SERVER_TIMEOUT
static const int DEFAULT_HTTP_WORKQUEUE
static const int DEFAULT_HTTP_THREADS
Common init functions shared by bitcoin-node, bitcoin-wallet, etc.
static const char * BITCOIN_PID_FILENAME
The PID file facilities.
static bool CreatePidFile(const ArgsManager &args)
static const bool DEFAULT_PROXYRANDOMIZE
void Interrupt(NodeContext &node)
Interrupt threads.
void InitLogging(const ArgsManager &args)
Initialize global loggers.
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
static bool AppInitServers(Config &config, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node)
#define MIN_CORE_FILEDESCRIPTORS
void Shutdown(NodeContext &node)
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
static GlobalMutex g_genesis_wait_mutex
static void OnRPCStarted()
static constexpr bool DEFAULT_USEASHADDR
static void HandleSIGHUP(int)
bool AppInitBasicSetup(const ArgsManager &args, std::atomic< int > &exit_status)
Initialize bitcoin: Basic context setup.
static fs::path GetPidFile(const ArgsManager &args)
static std::condition_variable g_genesis_wait_cv
bool AppInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin main initialization.
static constexpr bool DEFAULT_CHRONIK
bool StartIndexBackgroundSync(NodeContext &node)
Validates requirements to run the indexes and spawns each index initial sync thread.
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
static const char * DEFAULT_ASMAP_FILENAME
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
static void OnRPCStopped()
static bool LockDataDirectory(bool probeOnly)
static void registerSignalHandler(int signal, void(*handler)(int))
bool AppInitParameterInteraction(Config &config, const ArgsManager &args)
Initialization: parameter interaction.
static const bool DEFAULT_REST_ENABLE
static boost::signals2::connection rpc_notify_block_change_connection
static void new_handler_terminate()
bool AppInitSanityChecks(const kernel::Context &kernel)
Initialization sanity checks.
static const std::string HEADERS_TIME_FILE_NAME
static constexpr bool DEFAULT_DAEMON
Default value for -daemon option.
static constexpr bool DEFAULT_DAEMONWAIT
Default value for -daemonwait option.
static constexpr size_t DEFAULT_DB_CACHE_BATCH
Default LevelDB write batch size.
BCLog::Logger & LogInstance()
#define LogPrint(category,...)
void StartMapPort(bool use_upnp, bool use_natpmp)
static constexpr bool DEFAULT_NATPMP
static constexpr bool DEFAULT_UPNP
std::optional< bilingual_str > ApplyArgsManOptions(const ArgsManager &argsman, const CChainParams &chainparams, MemPoolOptions &mempool_opts)
Overlay the options set in argsman on top of corresponding members in mempool_opts.
static constexpr unsigned int DEFAULT_MAX_MEMPOOL_SIZE_MB
Default for -maxmempool, maximum megabytes of mempool memory usage.
static constexpr unsigned int DEFAULT_MEMPOOL_EXPIRY_HOURS
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
std::string FormatMoney(const Amount amt)
Do not use these functions to represent or parse monetary amounts to or from JSON but use AmountFromV...
bool ParseMoney(const std::string &money_string, Amount &nRet)
Parse an amount denoted in full coins.
constexpr auto RATELIMIT_WINDOW
constexpr bool DEFAULT_LOGRATELIMIT
constexpr uint64_t RATELIMIT_MAX_BYTES
void OnStarted(std::function< void()> slot)
void OnStopped(std::function< void()> slot)
static constexpr Amount PROOF_DUST_THRESHOLD
Minimum amount per utxo.
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
bilingual_str InvalidPortErrMsg(const std::string &optname, const std::string &invalid_value)
static auto quoted(const std::string &s)
static bool exists(const path &p)
static std::string PathToString(const path &path)
Convert path object to byte string.
static path PathFromString(const std::string &string)
Convert byte string to path object.
std::string get_filesystem_error_message(const fs::filesystem_error &e)
void AddLoggingArgs(ArgsManager &argsman)
void SetLoggingCategories(const ArgsManager &args)
bool StartLogging(const ArgsManager &args)
void SetLoggingLevel(const ArgsManager &args)
void SetLoggingOptions(const ArgsManager &args)
std::unique_ptr< Chain > MakeChain(node::NodeContext &node, const CChainParams ¶ms)
Return implementation of Chain interface.
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
bool DumpMempool(const CTxMemPool &pool, const fs::path &dump_path, FopenFn mockable_fopen_function, bool skip_file_commit)
util::Result< void > SanityChecks(const Context &)
Ensure a usable environment with all necessary library support.
@ FAILURE_INCOMPATIBLE_DB
@ FAILURE_FATAL
Fatal error which should not prompt to reindex.
@ FAILURE
Generic failure which reindexing may fix.
@ FAILURE_INSUFFICIENT_DBCACHE
CacheSizes CalculateCacheSizes(const ArgsManager &args, size_t n_indexes)
fs::path MempoolPath(const ArgsManager &argsman)
bool ShouldPersistMempool(const ArgsManager &argsman)
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
static constexpr bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool, indicating whether the node should attempt to automatically load the mem...
std::atomic_bool fReindex
void ImportBlocks(ChainstateManager &chainman, avalanche::Processor *const avalanche, std::vector< fs::path > vImportFiles)
void ApplyArgsManOptions(const ArgsManager &args, const Config &config, BlockFitter::Options &options)
Apply options from ArgsManager to BlockFitter options.
LockResult LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
bilingual_str ErrorString(const Result< T > &result)
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
bool AddLocal(const CService &addr, int nScore)
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
bool IsReachable(enum Network net)
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
static const size_t DEFAULT_MAXSENDBUFFER
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
static const bool DEFAULT_FORCEDNSSEED
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
static const size_t DEFAULT_MAXRECEIVEBUFFER
static const int DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS
Maximum number of avalanche enabled outgoing connections by default.
static const bool DEFAULT_FIXEDSEEDS
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
static const bool DEFAULT_LISTEN
-listen default
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
static const bool DEFAULT_DNSSEED
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
const std::vector< std::string > NET_PERMISSIONS_DOC
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
static const uint32_t DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of non-mempool transactions to keep around for block reconstruction.
static const uint32_t DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
static const bool DEFAULT_PEERBLOCKFILTERS
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
@ NET_ONION
TOR (v2 or v3)
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
bool SetNameProxy(const Proxy &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
enum Network ParseNetwork(const std::string &net_in)
bool SetProxy(enum Network net, const Proxy &addrProxy)
std::vector< CService > Lookup(const std::string &name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
bool IsUnixSocketPath(const std::string &name)
Check if a string is a valid UNIX domain socket path.
bool IsBadPort(uint16_t port)
Determine if a port is "bad" from the perspective of attempting to connect to a node on that port.
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
static const int DEFAULT_NAME_LOOKUP
-dns default
const std::string ADDR_PREFIX_UNIX
Prefix for unix domain socket addresses (which are local filesystem paths)
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
static constexpr size_t MIN_DB_CACHE
min. -dbcache (bytes)
static constexpr size_t DEFAULT_DB_CACHE
-dbcache default (bytes)
uint32_t nBytesPerSigCheck
static constexpr uint64_t DEFAULT_MAX_GENERATED_BLOCK_SIZE
Default for -blockmaxsize, which controls the maximum size of block the mining code will create.
static constexpr Amount DUST_RELAY_TX_FEE(1000 *SATOSHI)
Min feerate for defining dust.
static constexpr bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
static constexpr Amount DEFAULT_MIN_RELAY_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -minrelaytxfee, minimum relay fee for transactions.
static constexpr unsigned int DEFAULT_BYTES_PER_SIGCHECK
Default for -bytespersigcheck .
static constexpr Amount DEFAULT_BLOCK_MIN_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
static constexpr std::chrono::milliseconds AVALANCHE_DEFAULT_QUERY_TIMEOUT
How long before we consider that a query timed out.
static constexpr int AVALANCHE_DEFAULT_STAKE_UTXO_CONFIRMATIONS
Minimum number of confirmations before a stake utxo is mature enough to be included into a proof.
ServiceFlags
nServices flags.
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
static void RegisterAllRPCCommands(const Config &config, RPCServer &rpcServer, CRPCTable &rpcTable)
Register all context-sensitive RPC commands.
bool(* handler)(Config &config, const std::any &context, HTTPRequest *req, const std::string &strReq)
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
static constexpr bool DEFAULT_RPC_DOC_CHECK
static constexpr bool DEFAULT_ENABLE_RTT
Default for -enablertt.
static constexpr size_t DEFAULT_SCRIPT_EXECUTION_CACHE_BYTES
void SetRPCWarmupFinished()
Mark warmup as done.
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
void StartShutdown()
Request shutdown of the application.
void AbortShutdown()
Clear shutdown flag.
static constexpr size_t DEFAULT_SIGNATURE_CACHE_BYTES
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for nMaxDatacarrierBytes.
static const bool DEFAULT_ACCEPT_DATACARRIER
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
static constexpr Amount zero() noexcept
A BlockHash is a unqiue identifier for a block.
int m_max_outbound_block_relay
unsigned int nReceiveFloodSize
int m_max_outbound_full_relay
std::vector< NetWhitebindPermissions > vWhiteBinds
uint64_t nMaxOutboundLimit
CClientUIInterface * uiInterface
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
int m_max_avalanche_outbound
std::vector< CService > onion_binds
std::vector< std::string > m_specified_outgoing
ServiceFlags nLocalServices
std::vector< std::string > m_added_nodes
int64_t m_peer_connect_timeout
std::vector< CService > vBinds
unsigned int nSendBufferMaxSize
bool m_i2p_accept_incoming
std::vector< std::string > vSeedNodes
bool m_use_addrman_outgoing
std::vector< NetEventsInterface * > m_msgproc
bool whitelist_forcerelay
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
static const Currency & get()
BlockHash best_block_hash
Block and header tip information.
double verification_progress
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
Context struct holding the kernel library's logically global state, and passed to external libbitcoin...
Options struct containing options for constructing a CTxMemPool.
int check_ratio
The ratio used to determine how often sanity checks will run.
bool require_full_verification
std::function< void()> coins_error_cb
std::function< bool()> check_interrupt
NodeContext struct containing references to chain state and connection state.
#define WAIT_LOCK(cs, name)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define TRY_LOCK(cs, name)
std::string SysErrorString(int err)
Return system error string from errno value.
int GetNumCores()
Return the number of cores available on the current system.
int64_t GetTimeMillis()
Returns the system time (not mockable)
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
NodeClock::time_point GetAdjustedTime()
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
CService DefaultOnionServiceTarget()
const std::string DEFAULT_TOR_CONTROL
Default control port.
void InterruptTorControl()
void StartTorControl(CService onion_service_target)
static const bool DEFAULT_LISTEN_ONION
bilingual_str _(const char *psz)
Translation function.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
util::Result< void > CheckLegacyTxindex(CBlockTreeDB &block_tree_db)
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
static constexpr bool DEFAULT_TXINDEX
CClientUIInterface uiInterface
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.
bool ParseUInt16(std::string_view str, uint16_t *out)
Convert decimal string to unsigned 16-bit integer with strict parse error feedback.
bool SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
Splits socket address string into host string and port value.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
std::condition_variable g_best_block_cv
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
static constexpr int DEFAULT_CHECKLEVEL
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev?...
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
SynchronizationState
Current sync state passed to tip changed callbacks.
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
static const signed int DEFAULT_CHECKBLOCKS
static const bool DEFAULT_PEERBLOOMFILTERS
CMainSignals & GetMainSignals()
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
static constexpr uint32_t AVALANCHE_VOTE_STALE_FACTOR
Scaling factor applied to confidence to determine staleness threshold.
static constexpr uint32_t AVALANCHE_VOTE_STALE_THRESHOLD
Number of votes before a record may be considered as stale.
const WalletInitInterface & g_wallet_init_interface
std::unique_ptr< CZMQNotificationInterface > g_zmq_notification_interface
void RegisterZMQRPCCommands(CRPCTable &t)