Coverage Report

Created: 2026-07-29 23:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/init.cpp
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#include <bitcoin-build-config.h> // IWYU pragma: keep
7
8
#include <init.h>
9
10
#include <addrdb.h>
11
#include <addrman.h>
12
#include <banman.h>
13
#include <blockfilter.h>
14
#include <chain.h>
15
#include <chainparams.h>
16
#include <chainparamsbase.h>
17
#include <clientversion.h>
18
#include <common/args.h>
19
#include <common/messages.h>
20
#include <common/system.h>
21
#include <compat/compat.h>
22
#include <consensus/params.h>
23
#include <crypto/hex_base.h>
24
#include <dbwrapper.h>
25
#include <httprpc.h>
26
#include <httpserver.h>
27
#include <index/base.h>
28
#include <index/blockfilterindex.h>
29
#include <index/coinstatsindex.h>
30
#include <index/txindex.h>
31
#include <index/txospenderindex.h>
32
#include <init/common.h>
33
#include <interfaces/chain.h>
34
#include <interfaces/init.h>
35
#include <interfaces/ipc.h>
36
#include <interfaces/mining.h>
37
#include <interfaces/node.h>
38
#include <ipc/exception.h>
39
#include <kernel/blockmanager_opts.h>
40
#include <kernel/caches.h>
41
#include <kernel/chainstatemanager_opts.h>
42
#include <kernel/checks.h>
43
#include <kernel/context.h>
44
#include <kernel/notifications_interface.h>
45
#include <key.h>
46
#include <logging.h>
47
#include <mapport.h>
48
#include <net.h>
49
#include <net_permissions.h>
50
#include <net_processing.h>
51
#include <netaddress.h>
52
#include <netbase.h>
53
#include <netgroup.h>
54
#include <node/blockmanager_args.h>
55
#include <node/blockstorage.h>
56
#include <node/caches.h>
57
#include <node/chainstate.h>
58
#include <node/chainstatemanager_args.h>
59
#include <node/context.h>
60
#include <node/interface_ui.h>
61
#include <node/kernel_notifications.h>
62
#include <node/mempool_args.h>
63
#include <node/mempool_persist.h>
64
#include <node/mempool_persist_args.h>
65
#include <node/mining_args.h>
66
#include <node/mining_types.h>
67
#include <node/peerman_args.h>
68
#include <policy/feerate.h>
69
#include <policy/fees/block_policy_estimator.h>
70
#include <policy/fees/block_policy_estimator_args.h>
71
#include <policy/policy.h>
72
#include <policy/settings.h>
73
#include <protocol.h>
74
#include <random.h>
75
#include <rpc/register.h>
76
#include <rpc/server.h>
77
#include <rpc/util.h>
78
#include <scheduler.h>
79
#include <script/sigcache.h>
80
#include <sync.h>
81
#include <tinyformat.h>
82
#include <torcontrol.h>
83
#include <txgraph.h>
84
#include <txmempool.h>
85
#include <uint256.h>
86
#include <util/asmap.h>
87
#include <util/batchpriority.h>
88
#include <util/btcsignals.h>
89
#include <util/chaintype.h>
90
#include <util/check.h>
91
#include <util/fs.h>
92
#include <util/fs_helpers.h>
93
#include <util/moneystr.h>
94
#include <util/result.h>
95
#include <util/signalinterrupt.h>
96
#include <util/strencodings.h>
97
#include <util/string.h>
98
#include <util/syserror.h>
99
#include <util/thread.h>
100
#include <util/threadnames.h>
101
#include <util/time.h>
102
#include <util/translation.h>
103
#include <validation.h>
104
#include <validationinterface.h>
105
#include <walletinitinterface.h>
106
107
#include <algorithm>
108
#include <any>
109
#include <cerrno>
110
#include <condition_variable>
111
#include <cstddef>
112
#include <cstdint>
113
#include <exception>
114
#include <fstream>
115
#include <functional>
116
#include <initializer_list>
117
#include <list>
118
#include <memory>
119
#include <new>
120
#include <optional>
121
#include <set>
122
#include <span>
123
#include <string>
124
#include <system_error>
125
#include <thread>
126
#include <tuple>
127
#include <utility>
128
#include <variant>
129
#include <vector>
130
131
#ifndef WIN32
132
#include <csignal>
133
#endif
134
135
#ifdef ENABLE_ZMQ
136
#include <zmq/zmqabstractnotifier.h>
137
#include <zmq/zmqnotificationinterface.h>
138
#include <zmq/zmqrpc.h>
139
#endif
140
141
#ifdef ENABLE_EMBEDDED_ASMAP
142
#include <node/data/ip_asn.dat.h>
143
#endif
144
145
using common::InvalidPortErrMsg;
146
using common::ResolveErrMsg;
147
148
using http_bitcoin::InitHTTPServer;
149
using http_bitcoin::InterruptHTTPServer;
150
using http_bitcoin::StartHTTPServer;
151
using http_bitcoin::StopHTTPServer;
152
using node::ApplyArgsManOptions;
153
using node::BlockManager;
154
using node::CalculateCacheSizes;
155
using node::ChainstateLoadResult;
156
using node::ChainstateLoadStatus;
157
using node::DEFAULT_PERSIST_MEMPOOL;
158
using node::DEFAULT_PRINT_MODIFIED_FEE;
159
using node::DEFAULT_STOPATHEIGHT;
160
using node::DumpMempool;
161
using node::ImportBlocks;
162
using node::KernelNotifications;
163
using node::LoadChainstate;
164
using node::LoadMempool;
165
using node::MempoolPath;
166
using node::NodeContext;
167
using node::ShouldPersistMempool;
168
using node::VerifyLoadedChainstate;
169
using util::Join;
170
using util::ReplaceAll;
171
using util::ToString;
172
using util::TrimStringView;
173
174
static constexpr bool DEFAULT_PROXYRANDOMIZE{true};
175
static constexpr bool DEFAULT_REST_ENABLE{false};
176
static constexpr bool DEFAULT_I2P_ACCEPT_INCOMING{true};
177
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT{false};
178
179
#ifdef WIN32
180
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
181
// accessing block files don't count towards the fd_set size limit
182
// anyway.
183
#define MIN_LEVELDB_FDS 0
184
#else
185
#define MIN_LEVELDB_FDS 150
186
#endif
187
188
static constexpr int MIN_CORE_FDS = MIN_LEVELDB_FDS + NUM_FDS_MESSAGE_CAPTURE;
189
190
/**
191
 * The PID file facilities.
192
 */
193
static const char* BITCOIN_PID_FILENAME = "bitcoind.pid";
194
/**
195
 * True if this process has created a PID file.
196
 * Used to determine whether we should remove the PID file on shutdown.
197
 */
198
static bool g_generated_pid{false};
199
200
static fs::path GetPidFile(const ArgsManager& args)
201
2.30k
{
202
2.30k
    return AbsPathForConfigVal(args, args.GetPathArg("-pid", BITCOIN_PID_FILENAME));
203
2.30k
}
204
205
[[nodiscard]] static bool CreatePidFile(const ArgsManager& args)
206
1.15k
{
207
1.15k
    if (args.IsArgNegated("-pid")) return true;
208
209
1.15k
    std::ofstream file{GetPidFile(args).std_path()};
210
1.15k
    if (file) {
211
#ifdef WIN32
212
        tfm::format(file, "%d\n", GetCurrentProcessId());
213
#else
214
1.15k
        tfm::format(file, "%d\n", getpid());
215
1.15k
#endif
216
1.15k
        g_generated_pid = true;
217
1.15k
        return true;
218
1.15k
    } else {
219
0
        return InitError(strprintf(_("Unable to create the PID file '%s': %s"), fs::PathToString(GetPidFile(args)), SysErrorString(errno)));
220
0
    }
221
1.15k
}
222
223
static void RemovePidFile(const ArgsManager& args)
224
1.17k
{
225
1.17k
    if (!g_generated_pid) return;
226
1.15k
    const auto pid_path{GetPidFile(args)};
227
1.15k
    if (std::error_code error; !fs::remove(pid_path, error)) {
228
0
        std::string msg{error ? error.message() : "File does not exist"};
229
0
        LogWarning("Unable to remove PID file (%s): %s", fs::PathToString(pid_path), msg);
230
0
    }
231
1.15k
}
232
233
static std::optional<util::SignalInterrupt> g_shutdown;
234
235
void InitContext(NodeContext& node)
236
1.21k
{
237
1.21k
    assert(!g_shutdown);
238
1.21k
    g_shutdown.emplace();
239
240
1.21k
    node.args = &gArgs;
241
1.21k
    node.shutdown_signal = &*g_shutdown;
242
1.21k
    node.shutdown_request = [&node] {
243
996
        assert(node.shutdown_signal);
244
996
        if (!(*node.shutdown_signal)()) return false;
245
996
        return true;
246
996
    };
247
1.21k
}
248
249
//////////////////////////////////////////////////////////////////////////////
250
//
251
// Shutdown
252
//
253
254
//
255
// Thread management and startup/shutdown:
256
//
257
// The network-processing threads are all part of a thread group
258
// created by AppInit() or the Qt main() function.
259
//
260
// A clean exit happens when the SignalInterrupt object is triggered, which
261
// makes the main thread's SignalInterrupt::wait() call return, and join all
262
// other ongoing threads in the thread group to the main thread.
263
// Shutdown() is then called to clean up database connections, and stop other
264
// threads that should only be stopped after the main network-processing
265
// threads have exited.
266
//
267
// Shutdown for Qt is very similar, only it uses a QTimer to detect
268
// ShutdownRequested() getting set, and then does the normal Qt
269
// shutdown thing.
270
//
271
272
bool ShutdownRequested(node::NodeContext& node)
273
83.3k
{
274
83.3k
    return bool{*Assert(node.shutdown_signal)};
275
83.3k
}
276
277
#if HAVE_SYSTEM
278
static void ShutdownNotify(const ArgsManager& args)
279
1.17k
{
280
1.17k
    std::vector<std::thread> threads;
281
1.17k
    for (const auto& cmd : args.GetArgs("-shutdownnotify")) {
282
1
        threads.emplace_back(runCommand, cmd);
283
1
    }
284
1.17k
    for (auto& t : threads) {
285
1
        t.join();
286
1
    }
287
1.17k
}
288
#endif
289
290
void Interrupt(NodeContext& node)
291
1.17k
{
292
1.17k
#if HAVE_SYSTEM
293
1.17k
    ShutdownNotify(*node.args);
294
1.17k
#endif
295
    // Wake any threads that may be waiting for the tip to change.
296
1.17k
    if (node.notifications) WITH_LOCK(node.notifications->m_tip_block_mutex, node.notifications->m_tip_block_cv.notify_all());
297
1.17k
    InterruptHTTPServer();
298
1.17k
    InterruptHTTPRPC();
299
1.17k
    InterruptRPC();
300
1.17k
    InterruptREST();
301
1.17k
    if (node.tor_controller) {
302
8
        node.tor_controller->Interrupt();
303
8
    }
304
1.17k
    InterruptMapPort();
305
1.17k
    if (node.connman)
306
1.08k
        node.connman->Interrupt();
307
1.17k
    for (auto* index : node.indexes) {
308
134
        index->Interrupt();
309
134
    }
310
1.17k
}
311
312
void Shutdown(NodeContext& node)
313
1.17k
{
314
1.17k
    static Mutex g_shutdown_mutex;
315
1.17k
    TRY_LOCK(g_shutdown_mutex, lock_shutdown);
316
1.17k
    if (!lock_shutdown) return;
317
1.17k
    LogInfo("Shutdown in progress...");
318
1.17k
    Assert(node.args);
319
320
    /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
321
    /// for example if the data directory was found to be locked.
322
    /// Be sure that anything that writes files or flushes caches only does this if the respective
323
    /// module was initialized.
324
1.17k
    util::ThreadRename("shutoff");
325
1.17k
    if (node.mempool) node.mempool->AddTransactionsUpdated(1);
326
327
1.17k
    StopHTTPRPC();
328
1.17k
    StopREST();
329
1.17k
    StopRPC();
330
1.17k
    StopHTTPServer();
331
1.17k
    for (auto& client : node.chain_clients) {
332
403
        try {
333
403
            client->stop();
334
403
        } catch (const ipc::Exception& e) {
335
0
            LogDebug(BCLog::IPC, "Chain client did not disconnect cleanly: %s", e.what());
336
0
            client.reset();
337
0
        }
338
403
    }
339
1.17k
    StopMapPort();
340
341
    // Because these depend on each-other, we make sure that neither can be
342
    // using the other before destroying them.
343
1.17k
    if (node.peerman && node.validation_signals) node.validation_signals->UnregisterValidationInterface(node.peerman.get());
344
1.17k
    if (node.connman) node.connman->Stop();
345
346
1.17k
    if (node.tor_controller) {
347
8
        node.tor_controller->Join();
348
8
        node.tor_controller.reset();
349
8
    }
350
351
1.17k
    if (node.background_init_thread.joinable()) node.background_init_thread.join();
352
    // After everything has been shut down, but before things get flushed, stop the
353
    // the scheduler. After this point, SyncWithValidationInterfaceQueue() should not be called anymore
354
    // as this would prevent the shutdown from completing.
355
1.17k
    if (node.scheduler) node.scheduler->stop();
356
357
    // After the threads that potentially access these pointers have been stopped,
358
    // destruct and reset all to nullptr.
359
1.17k
    node.peerman.reset();
360
1.17k
    node.connman.reset();
361
1.17k
    node.banman.reset();
362
1.17k
    node.addrman.reset();
363
1.17k
    node.netgroupman.reset();
364
365
1.17k
    if (node.mempool && node.mempool->GetLoadTried() && ShouldPersistMempool(*node.args)) {
366
950
        DumpMempool(*node.mempool, MempoolPath(*node.args));
367
950
    }
368
369
    // Drop transactions we were still watching, record fee estimations and unregister
370
    // fee estimator from validation interface.
371
1.17k
    if (node.fee_estimator) {
372
1.07k
        node.fee_estimator->Flush();
373
1.07k
        if (node.validation_signals) {
374
1.07k
            node.validation_signals->UnregisterValidationInterface(node.fee_estimator.get());
375
1.07k
        }
376
1.07k
    }
377
378
    // FlushStateToDisk generates a ChainStateFlushed callback, which we should avoid missing
379
1.17k
    if (node.chainman) {
380
1.06k
        LOCK(cs_main);
381
1.06k
        for (const auto& chainstate : node.chainman->m_chainstates) {
382
1.06k
            if (chainstate->CanFlushToDisk()) {
383
1.05k
                chainstate->ForceFlushStateToDisk();
384
1.05k
            }
385
1.06k
        }
386
1.06k
    }
387
388
    // After there are no more peers/RPC left to give us new data which may generate
389
    // CValidationInterface callbacks, flush them...
390
1.17k
    if (node.validation_signals) node.validation_signals->FlushBackgroundCallbacks();
391
392
    // Stop and delete all indexes only after flushing background callbacks.
393
1.17k
    for (auto* index : node.indexes) index->Stop();
394
1.17k
    if (g_txindex) g_txindex.reset();
395
1.17k
    if (g_txospenderindex) g_txospenderindex.reset();
396
1.17k
    if (g_coin_stats_index) g_coin_stats_index.reset();
397
1.17k
    DestroyAllBlockFilterIndexes();
398
1.17k
    node.indexes.clear(); // all instances are nullptr now
399
400
    // Any future callbacks will be dropped. This should absolutely be safe - if
401
    // missing a callback results in an unrecoverable situation, unclean shutdown
402
    // would too. The only reason to do the above flushes is to let the wallet catch
403
    // up with our current chain to avoid any strange pruning edge cases and make
404
    // next startup faster by avoiding rescan.
405
406
1.17k
    if (node.chainman) {
407
1.06k
        LOCK(cs_main);
408
1.06k
        for (const auto& chainstate : node.chainman->m_chainstates) {
409
1.06k
            if (chainstate->CanFlushToDisk()) {
410
1.05k
                chainstate->ForceFlushStateToDisk();
411
1.05k
                chainstate->ResetCoinsViews();
412
1.05k
            }
413
1.06k
        }
414
1.06k
    }
415
416
    // If any -ipcbind clients are still connected, disconnect them now so they
417
    // do not block shutdown.
418
1.17k
    if (interfaces::Ipc* ipc = node.init->ipc()) {
419
1
        ipc->disconnectIncoming();
420
1
    }
421
422
#ifdef ENABLE_ZMQ
423
    if (g_zmq_notification_interface) {
424
        if (node.validation_signals) node.validation_signals->UnregisterValidationInterface(g_zmq_notification_interface.get());
425
        g_zmq_notification_interface.reset();
426
    }
427
#endif
428
429
1.17k
    node.chain_clients.clear();
430
1.17k
    if (node.validation_signals) {
431
1.14k
        node.validation_signals->UnregisterAllValidationInterfaces();
432
1.14k
    }
433
1.17k
    node.mempool.reset();
434
1.17k
    node.fee_estimator.reset();
435
1.17k
    node.chainman.reset();
436
1.17k
    node.validation_signals.reset();
437
1.17k
    node.scheduler.reset();
438
1.17k
    node.ecc_context.reset();
439
1.17k
    node.kernel.reset();
440
441
1.17k
    RemovePidFile(*node.args);
442
443
1.17k
    LogInfo("Shutdown done");
444
1.17k
}
445
446
/**
447
 * Signal handlers are very limited in what they are allowed to do.
448
 * The execution context the handler is invoked in is not guaranteed,
449
 * so we restrict handler operations to just touching variables:
450
 */
451
#ifndef WIN32
452
static void HandleSIGTERM(int)
453
23
{
454
    // Return value is intentionally ignored because there is not a better way
455
    // of handling this failure in a signal handler.
456
23
    (void)(*Assert(g_shutdown))();
457
23
}
458
459
static void HandleSIGHUP(int)
460
0
{
461
0
    LogInstance().m_reopen_file = true;
462
0
}
463
#else
464
static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
465
{
466
    if (!(*Assert(g_shutdown))()) {
467
        LogError("Failed to send shutdown signal on Ctrl-C\n");
468
        return false;
469
    }
470
    Sleep(INFINITE);
471
    return true;
472
}
473
#endif
474
475
#ifndef WIN32
476
static void registerSignalHandler(int signal, void(*handler)(int))
477
3.51k
{
478
3.51k
    struct sigaction sa;
479
3.51k
    sa.sa_handler = handler;
480
3.51k
    sigemptyset(&sa.sa_mask);
481
3.51k
    sa.sa_flags = 0;
482
3.51k
    sigaction(signal, &sa, nullptr);
483
3.51k
}
484
#endif
485
486
void SetupServerArgs(ArgsManager& argsman, bool can_listen_ipc)
487
1.92k
{
488
1.92k
    SetupHelpOptions(argsman);
489
1.92k
    argsman.AddArg("-help-debug", "Print help message with debugging options and exit", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); // server-only for now
490
491
1.92k
    init::AddLoggingArgs(argsman);
492
493
1.92k
    const auto defaultBaseParams = CreateBaseChainParams(ChainType::MAIN);
494
1.92k
    const auto testnetBaseParams = CreateBaseChainParams(ChainType::TESTNET);
495
1.92k
    const auto testnet4BaseParams = CreateBaseChainParams(ChainType::TESTNET4);
496
1.92k
    const auto signetBaseParams = CreateBaseChainParams(ChainType::SIGNET);
497
1.92k
    const auto regtestBaseParams = CreateBaseChainParams(ChainType::REGTEST);
498
1.92k
    const auto defaultChainParams = CreateChainParams(argsman, ChainType::MAIN);
499
1.92k
    const auto testnetChainParams = CreateChainParams(argsman, ChainType::TESTNET);
500
1.92k
    const auto testnet4ChainParams = CreateChainParams(argsman, ChainType::TESTNET4);
501
1.92k
    const auto signetChainParams = CreateChainParams(argsman, ChainType::SIGNET);
502
1.92k
    const auto regtestChainParams = CreateChainParams(argsman, ChainType::REGTEST);
503
504
    // Hidden Options
505
1.92k
    std::vector<std::string> hidden_args = {
506
1.92k
        "-dbcrashratio", "-forcecompactdb",
507
        // GUI args. These will be overwritten by SetupUIArgs for the GUI
508
1.92k
        "-choosedatadir", "-lang=<lang>", "-min", "-resetguisettings", "-splash", "-uiplatform"};
509
510
1.92k
    argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
511
1.92k
#if HAVE_SYSTEM
512
1.92k
    argsman.AddArg("-alertnotify=<cmd>", "Execute command when an alert is raised (%s in cmd is replaced by message)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
513
1.92k
#endif
514
1.92k
    argsman.AddArg("-assumevalid=<hex>", strprintf("If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet3: %s, testnet4: %s, signet: %s)", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnet4ChainParams->GetConsensus().defaultAssumeValid.GetHex(), signetChainParams->GetConsensus().defaultAssumeValid.GetHex()), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
515
1.92k
    argsman.AddArg("-blocksdir=<dir>", "Specify directory to hold blocks subdirectory for *.dat files (default: <datadir>)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
516
1.92k
    argsman.AddArg("-blocksxor",
517
1.92k
                   strprintf("Whether an XOR-key applies to blocksdir *.dat files. "
518
1.92k
                             "The created XOR-key will be zeros for an existing blocksdir or when `-blocksxor=0` is "
519
1.92k
                             "set, and random for a freshly initialized blocksdir. "
520
1.92k
                             "(default: %u)",
521
1.92k
                             kernel::DEFAULT_XOR_BLOCKSDIR),
522
1.92k
                   ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
523
1.92k
    argsman.AddArg("-fastprune", "Use smaller block files and lower minimum prune height for testing purposes", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
524
1.92k
#if HAVE_SYSTEM
525
1.92k
    argsman.AddArg("-blocknotify=<cmd>", "Execute command when the best block changes (%s in cmd is replaced by block hash)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
526
1.92k
#endif
527
1.92k
    argsman.AddArg("-blockreconstructionextratxn=<n>", strprintf("Extra transactions to keep in memory for compact block reconstructions (default: %u)", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
528
1.92k
    argsman.AddArg("-blocksonly", strprintf("Whether to reject transactions from network peers. Disables automatic broadcast and rebroadcast of transactions, unless the source peer has the 'forcerelay' permission. RPC transactions are not affected. (default: %u)", DEFAULT_BLOCKSONLY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
529
1.92k
    argsman.AddArg("-coinstatsindex", strprintf("Maintain coinstats index used by the gettxoutsetinfo RPC (default: %u)", DEFAULT_COINSTATSINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
530
1.92k
    argsman.AddArg("-conf=<file>", strprintf("Specify path to read-only configuration file. Relative paths will be prefixed by datadir location (only useable from command line, not configuration file) (default: %s)", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
531
1.92k
    argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_NEGATION, OptionsCategory::OPTIONS);
532
1.92k
    argsman.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", DEFAULT_DB_CACHE_BATCH), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
533
1.92k
    argsman.AddArg("-dbcache=<n>", strprintf("Maximum database cache size <n> MiB (minimum %d, default: %d). Make sure you have enough RAM. In addition, unused memory allocated to the mempool is shared with this cache (see -maxmempool).", MIN_DB_CACHE >> 20, node::GetDefaultDBCache() >> 20), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
534
1.92k
    argsman.AddArg("-includeconf=<file>", "Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
535
1.92k
    argsman.AddArg("-allowignoredconf", strprintf("For backwards compatibility, treat an unused %s file in the datadir as a warning, not an error.", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
536
1.92k
    argsman.AddArg("-loadblock=<file>", "Imports blocks from an external file on startup. Obfuscated blocks are not supported.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
537
1.92k
    argsman.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE_MB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
538
1.92k
    argsman.AddArg("-mempoolexpiry=<n>", strprintf("Do not keep transactions in the mempool longer than <n> hours (default: %u)", DEFAULT_MEMPOOL_EXPIRY_HOURS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
539
1.92k
    argsman.AddArg("-minimumchainwork=<hex>", strprintf("Minimum work assumed to exist on a valid chain in hex (default: %s, testnet3: %s, testnet4: %s, signet: %s)", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnet4ChainParams->GetConsensus().nMinimumChainWork.GetHex(), signetChainParams->GetConsensus().nMinimumChainWork.GetHex()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
540
1.92k
    argsman.AddArg("-par=<n>", strprintf("Set the number of script verification threads (0 = auto, up to %d, <0 = leave that many cores free, default: %d)",
541
1.92k
        MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
542
1.92k
    argsman.AddArg("-prevoutfetchthreads=<n>", strprintf("Set the number of threads used to prefetch block input prevouts from the chainstate database (0 disables, up to %d, default: %d). Negative values are rejected.", MAX_PREVOUTFETCH_THREADS, DEFAULT_PREVOUTFETCH_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
543
1.92k
    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);
544
1.92k
    argsman.AddArg("-persistmempoolv1",
545
1.92k
                   strprintf("Whether a mempool.dat file created by -persistmempool or the savemempool RPC will be written in the legacy format "
546
1.92k
                             "(version 1) or the current format (version 2). This temporary option will be removed in the future. (default: %u)",
547
1.92k
                             DEFAULT_PERSIST_V1_DAT),
548
1.92k
                   ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
549
1.92k
    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);
550
1.92k
    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. "
551
1.92k
            "Warning: Reverting this setting requires re-downloading the entire blockchain. Wallets and indexes should be loaded at startup and kept active while pruning is enabled so they stay synchronized before old block data is deleted; wallets or indexes that fall behind pruned data may require a reindex. "
552
1.92k
            "(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 / 1_MiB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
553
1.92k
    argsman.AddArg("-reindex", "If enabled, wipe chain state and block index, and rebuild them from blk*.dat files on disk. Also wipe and rebuild other optional indexes that are active. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
554
1.92k
    argsman.AddArg("-reindex-chainstate", "If enabled, wipe chain state, and rebuild it from blk*.dat files on disk. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
555
1.92k
    argsman.AddArg("-settings=<file>", strprintf("Specify path to dynamic settings data file. Can be disabled with -nosettings. File is written at runtime and not meant to be edited by users (use %s instead for custom settings). Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME, BITCOIN_SETTINGS_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
556
1.92k
#if HAVE_SYSTEM
557
1.92k
    argsman.AddArg("-startupnotify=<cmd>", "Execute command on startup.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
558
1.92k
    argsman.AddArg("-shutdownnotify=<cmd>", "Execute command immediately before beginning shutdown. The need for shutdown may be urgent, so be careful not to delay it long (if the command doesn't require interaction with the server, consider having it fork into the background).", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
559
1.92k
#endif
560
1.92k
    argsman.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
561
1.92k
    argsman.AddArg("-txospenderindex", strprintf("Maintain a transaction output spender index, used by the gettxspendingprevout rpc call (default: %u)", DEFAULT_TXOSPENDERINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
562
1.92k
    argsman.AddArg("-blockfilterindex=<type>",
563
1.92k
                 strprintf("Maintain an index of compact filters by block (default: %s, values: %s).", DEFAULT_BLOCKFILTERINDEX, ListBlockFilterTypes()) +
564
1.92k
                 " If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.",
565
1.92k
                 ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
566
567
1.92k
    argsman.AddArg("-addnode=<ip>", strprintf("Add a node to connect to and attempt to keep the connection open (see the addnode RPC help for more info). This option can be specified multiple times to add multiple nodes; connections are limited to %u at a time and are counted separately from the -maxconnections limit.", MAX_ADDNODE_CONNECTIONS), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
568
1.92k
    argsman.AddArg("-asmap=<file>", strprintf("Specify asn mapping used for bucketing of the peers. Relative paths will be prefixed by the net-specific datadir location.%s",
569
1.92k
                #ifdef ENABLE_EMBEDDED_ASMAP
570
1.92k
                    " If a bool arg is given (-asmap or -asmap=1), the embedded mapping data in the binary will be used."
571
                #else
572
                    ""
573
                #endif
574
1.92k
                ), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
575
1.92k
    argsman.AddArg("-bantime=<n>", strprintf("Default duration (in seconds) of manually configured bans (default: %u)", DEFAULT_MISBEHAVING_BANTIME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
576
1.92k
    argsman.AddArg("-bind=<addr>[:<port>][=onion]", strprintf("Bind to given address and always listen on it (default: 0.0.0.0). Use [host]:port notation for IPv6. Append =onion to tag any incoming connections to that address and port as incoming Tor connections (default: 127.0.0.1:%u=onion, testnet3: 127.0.0.1:%u=onion, testnet4: 127.0.0.1:%u=onion, signet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)", defaultChainParams->GetDefaultPort() + 1, testnetChainParams->GetDefaultPort() + 1, testnet4ChainParams->GetDefaultPort() + 1, signetChainParams->GetDefaultPort() + 1, regtestChainParams->GetDefaultPort() + 1), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
577
1.92k
    argsman.AddArg("-cjdnsreachable", "If set, then this host is configured for CJDNS (connecting to fc00::/8 addresses would lead us to the CJDNS network, see doc/cjdns.md) (default: 0)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
578
1.92k
    argsman.AddArg("-connect=<ip>", "Connect only to the specified node; -noconnect disables automatic connections (the rules for this peer are the same as for -addnode). This option can be specified multiple times to connect to multiple nodes.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
579
1.92k
    argsman.AddArg("-discover", "Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
580
1.92k
    argsman.AddArg("-dns", strprintf("Allow DNS lookups for -addnode, -seednode and -connect (default: %u)", DEFAULT_NAME_LOOKUP), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
581
1.92k
    argsman.AddArg("-dnsseed", strprintf("Query for peer addresses via DNS lookup, if low on addresses (default: %u unless -connect used or -maxconnections=0)", DEFAULT_DNSSEED), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
582
1.92k
    argsman.AddArg("-externalip=<ip>", "Specify your own public address", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
583
1.92k
    argsman.AddArg("-fixedseeds", strprintf("Allow fixed seeds if DNS seeds don't provide peers (default: %u)", DEFAULT_FIXEDSEEDS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
584
1.92k
    argsman.AddArg("-forcednsseed", strprintf("Always query for peer addresses via DNS lookup (default: %u)", DEFAULT_FORCEDNSSEED), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
585
1.92k
    argsman.AddArg("-listen", strprintf("Accept connections from outside (default: %u if no -proxy, -connect or -maxconnections=0)", DEFAULT_LISTEN), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
586
1.92k
    argsman.AddArg("-listenonion", strprintf("Automatically create Tor onion service (default: %d)", DEFAULT_LISTEN_ONION), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
587
1.92k
    argsman.AddArg("-maxconnections=<n>", strprintf("Maintain at most <n> automatic connections to peers (default: %u). %u slots of these are reserved for outgoing connections. See -inboundrelaypercent for more information about limits applied to transaction relay inbound peers. "
588
1.92k
                                                    "This limit does not apply to connections manually added via -addnode or the addnode RPC, which have a separate limit of %u. "
589
1.92k
                                                    "It does not apply to short-lived private broadcast connections either, which have a separate limit of %u.",
590
1.92k
                                                    DEFAULT_MAX_PEER_CONNECTIONS, MAX_OUTBOUND_FULL_RELAY_CONNECTIONS + MAX_BLOCK_RELAY_ONLY_CONNECTIONS + MAX_FEELER_CONNECTIONS, MAX_ADDNODE_CONNECTIONS, MAX_PRIVATE_BROADCAST_CONNECTIONS),
591
1.92k
                   ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
592
1.92k
    argsman.AddArg("-inboundrelaypercent=<n>", strprintf("Permit a maximum percent of inbound connections to relay transactions, to limit memory utilization (0 to 100, default: %u).", DEFAULT_FULL_RELAY_INBOUND_PCT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
593
1.92k
    argsman.AddArg("-maxreceivebuffer=<n>", strprintf("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXRECEIVEBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
594
1.92k
    argsman.AddArg("-maxsendbuffer=<n>", strprintf("Maximum per-connection memory usage for the send buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXSENDBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
595
1.92k
    argsman.AddArg("-maxuploadtarget=<n>", strprintf("Tries to keep outbound traffic under the given target per 24h. Limit does not apply to peers with 'download' permission or blocks created within past week. 0 = no limit (default: %s). Optional suffix units [k|K|m|M|g|G|t|T] (default: M). Lowercase is 1000 base while uppercase is 1024 base", DEFAULT_MAX_UPLOAD_TARGET), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
596
1.92k
#ifdef HAVE_SOCKADDR_UN
597
1.92k
    argsman.AddArg("-onion=<ip:port|path>", "Use separate SOCKS5 proxy to reach peers via Tor onion services, set -noonion to disable (default: -proxy). May be a local file path prefixed with 'unix:'.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
598
#else
599
    argsman.AddArg("-onion=<ip:port>", "Use separate SOCKS5 proxy to reach peers via Tor onion services, set -noonion to disable (default: -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
600
#endif
601
1.92k
    argsman.AddArg("-i2psam=<ip:port>", "I2P SAM proxy to reach I2P peers and accept I2P connections", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
602
1.92k
    argsman.AddArg("-i2pacceptincoming", strprintf("Whether to accept inbound I2P connections (default: %i). Ignored if -i2psam is not set. Listening for inbound I2P connections is done through the SAM proxy, not by binding to a local address and port.", DEFAULT_I2P_ACCEPT_INCOMING), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
603
1.92k
    argsman.AddArg("-onlynet=<net>", "Make automatic outbound connections only to network <net> (" + Join(GetNetworkNames(), ", ") + "). Inbound and manual connections are not affected by this option. It can be specified multiple times to allow multiple networks.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
604
1.92k
    argsman.AddArg("-v2transport", strprintf("Support v2 transport (default: %u)", DEFAULT_V2_TRANSPORT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
605
1.92k
    argsman.AddArg("-peerbloomfilters", strprintf("Support filtering of blocks and transaction with bloom filters (default: %u)", DEFAULT_PEERBLOOMFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
606
1.92k
    argsman.AddArg("-peerblockfilters", strprintf("Serve compact block filters to peers per BIP 157 (default: %u)", DEFAULT_PEERBLOCKFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
607
1.92k
    argsman.AddArg("-txreconciliation", strprintf("Enable transaction reconciliations per BIP 330 (default: %d)", DEFAULT_TXRECONCILIATION_ENABLE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION);
608
1.92k
    argsman.AddArg("-port=<port>", strprintf("Listen for connections on <port> (default: %u, testnet3: %u, testnet4: %u, signet: %u, regtest: %u). Not relevant for I2P (see doc/i2p.md). If set to a value x, the default onion listening port will be set to x+1.", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), testnet4ChainParams->GetDefaultPort(), signetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
609
1.92k
    const std::string proxy_doc_for_value =
610
1.92k
#ifdef HAVE_SOCKADDR_UN
611
1.92k
        "<ip>[:<port>]|unix:<path>";
612
#else
613
        "<ip>[:<port>]";
614
#endif
615
1.92k
    const std::string proxy_doc_for_unix_socket =
616
1.92k
#ifdef HAVE_SOCKADDR_UN
617
1.92k
        "May be a local file path prefixed with 'unix:' if the proxy supports it. ";
618
#else
619
        "";
620
#endif
621
1.92k
    argsman.AddArg("-proxy=" + proxy_doc_for_value + "[=<network>]",
622
1.92k
                   "Connect through SOCKS5 proxy, set -noproxy to disable. " +
623
1.92k
                   proxy_doc_for_unix_socket +
624
1.92k
                   "Could end in =network to set the proxy only for that network. " +
625
1.92k
                   "The network can be any of ipv4, ipv6, tor or cjdns. " +
626
1.92k
                   "(default: disabled)",
627
1.92k
                   ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_ELISION,
628
1.92k
                   OptionsCategory::CONNECTION);
629
1.92k
    argsman.AddArg("-proxyrandomize", strprintf("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)", DEFAULT_PROXYRANDOMIZE), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
630
1.92k
    argsman.AddArg("-seednode=<ip>", "Connect to a node to retrieve peer addresses, and disconnect. This option can be specified multiple times to connect to multiple nodes. During startup, seednodes will be tried before dnsseeds.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
631
1.92k
    argsman.AddArg("-networkactive", "Enable all P2P network activity (default: 1). Can be changed by the setnetworkactive RPC command", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
632
1.92k
    argsman.AddArg("-timeout=<n>", strprintf("Specify socket connection timeout in milliseconds. If an initial attempt to connect is unsuccessful after this amount of time, drop it (minimum: 1, default: %d)", DEFAULT_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
633
1.92k
    argsman.AddArg("-peertimeout=<n>", strprintf("Specify a p2p connection timeout delay in seconds. After connecting to a peer, wait this amount of time before considering disconnection based on inactivity (minimum: 1, default: %d)", DEFAULT_PEER_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION);
634
1.92k
    argsman.AddArg("-torcontrol=<ip>:<port>", strprintf("Tor control host and port to use if onion listening enabled (default: %s). If no port is specified, the default port of %i will be used.", DEFAULT_TOR_CONTROL, DEFAULT_TOR_CONTROL_PORT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
635
1.92k
    argsman.AddArg("-torpassword=<pass>", "Tor control port password (default: empty)", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::CONNECTION);
636
1.92k
    argsman.AddArg("-natpmp", strprintf("Use PCP or NAT-PMP to map the listening port (default: %u)", DEFAULT_NATPMP), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
637
1.92k
    argsman.AddArg("-whitebind=<[permissions@]addr>", "Bind to the given address and add permission flags to the peers connecting to it. "
638
1.92k
        "Use [host]:port notation for IPv6. Allowed permissions: " + Join(NET_PERMISSIONS_DOC, ", ") + ". "
639
1.92k
        "Specify multiple permissions separated by commas (default: download,noban,mempool,relay). Can be specified multiple times.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
640
641
1.92k
    argsman.AddArg("-whitelist=<[permissions@]IP address or network>", "Add permission flags to the peers using the given IP address (e.g. 1.2.3.4) or "
642
1.92k
        "CIDR-notated network (e.g. 1.2.3.0/24). Uses the same permissions as "
643
1.92k
        "-whitebind. "
644
1.92k
        "Additional flags \"in\" and \"out\" control whether permissions apply to incoming connections and/or manual (default: incoming only). "
645
1.92k
        "Can be specified multiple times.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
646
647
1.92k
    g_wallet_init_interface.AddWalletOptions(argsman);
648
649
#ifdef ENABLE_ZMQ
650
    argsman.AddArg("-zmqpubhashblock=<address>", "Enable publish hash block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
651
    argsman.AddArg("-zmqpubhashtx=<address>", "Enable publish hash transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
652
    argsman.AddArg("-zmqpubrawblock=<address>", "Enable publish raw block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
653
    argsman.AddArg("-zmqpubrawtx=<address>", "Enable publish raw transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
654
    argsman.AddArg("-zmqpubsequence=<address>", "Enable publish hash block and tx sequence in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
655
    argsman.AddArg("-zmqpubhashblockhwm=<n>", strprintf("Set publish hash block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
656
    argsman.AddArg("-zmqpubhashtxhwm=<n>", strprintf("Set publish hash transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
657
    argsman.AddArg("-zmqpubrawblockhwm=<n>", strprintf("Set publish raw block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
658
    argsman.AddArg("-zmqpubrawtxhwm=<n>", strprintf("Set publish raw transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
659
    argsman.AddArg("-zmqpubsequencehwm=<n>", strprintf("Set publish hash sequence message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
660
#else
661
1.92k
    hidden_args.emplace_back("-zmqpubhashblock=<address>");
662
1.92k
    hidden_args.emplace_back("-zmqpubhashtx=<address>");
663
1.92k
    hidden_args.emplace_back("-zmqpubrawblock=<address>");
664
1.92k
    hidden_args.emplace_back("-zmqpubrawtx=<address>");
665
1.92k
    hidden_args.emplace_back("-zmqpubsequence=<n>");
666
1.92k
    hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
667
1.92k
    hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
668
1.92k
    hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
669
1.92k
    hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
670
1.92k
    hidden_args.emplace_back("-zmqpubsequencehwm=<n>");
671
1.92k
#endif
672
673
1.92k
    argsman.AddArg("-checkblocks=<n>", strprintf("How many blocks to check at startup (default: %u, 0 = all)", DEFAULT_CHECKBLOCKS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
674
1.92k
    argsman.AddArg("-checklevel=<n>", strprintf("How thorough the block verification of -checkblocks is: %s (0-4, default: %u)", Join(CHECKLEVEL_DOC, ", "), DEFAULT_CHECKLEVEL), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
675
1.92k
    argsman.AddArg("-checkblockindex", strprintf("Do a consistency check for the block tree, chainstate, and other validation data structures every <n> operations. Use 0 to disable. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
676
1.92k
    argsman.AddArg("-checkaddrman=<n>", strprintf("Run addrman consistency checks every <n> operations. Use 0 to disable. (default: %u)", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
677
1.92k
    argsman.AddArg("-checkmempool=<n>", strprintf("Run mempool consistency checks every <n> transactions. Use 0 to disable. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
678
    // Checkpoints were removed. We keep `-checkpoints` as a hidden arg to display a more user friendly error when set.
679
1.92k
    argsman.AddArg("-checkpoints", "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN);
680
1.92k
    argsman.AddArg("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
681
1.92k
    argsman.AddArg("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
682
1.92k
    argsman.AddArg("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u). Blocks after target height may be processed during shutdown.", DEFAULT_STOPATHEIGHT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
683
1.92k
    argsman.AddArg("-limitancestorcount=<n>", strprintf("Deprecated setting to not accept transactions if number of in-mempool ancestors is <n> or more (default: %u); replaced by cluster limits (see -limitclustercount) and only used by wallet for coin selection", DEFAULT_ANCESTOR_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
684
    // Ancestor and descendant size limits were removed. We keep
685
    // -limitancestorsize/-limitdescendantsize as hidden args to display a more
686
    // user friendly error when set.
687
1.92k
    argsman.AddArg("-limitancestorsize", "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN);
688
1.92k
    argsman.AddArg("-limitdescendantsize", "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN);
689
1.92k
    argsman.AddArg("-limitdescendantcount=<n>", strprintf("Deprecated setting to not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u); replaced by cluster limits (see -limitclustercount) and only used by wallet for coin selection", DEFAULT_DESCENDANT_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
690
1.92k
    argsman.AddArg("-test=<option>", "Pass a test-only option. Options include : " + Join(TEST_OPTIONS_DOC, ", ") + ".", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
691
1.92k
    argsman.AddArg("-limitclustercount=<n>", strprintf("Do not accept transactions into mempool which are directly or indirectly connected to <n> or more other unconfirmed transactions (default: %u, maximum: %u)", DEFAULT_CLUSTER_LIMIT, MAX_CLUSTER_COUNT_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
692
1.92k
    argsman.AddArg("-limitclustersize=<n>", strprintf("Do not accept transactions whose virtual size with all in-mempool connected transactions exceeds <n> kilobytes (default: %u)", DEFAULT_CLUSTER_SIZE_LIMIT_KVB), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
693
1.92k
    argsman.AddArg("-capturemessages", "Capture all P2P messages to disk", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
694
1.92k
    argsman.AddArg("-mocktime=<n>", "Replace actual time with " + UNIX_EPOCH_TIME + " (default: 0)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
695
1.92k
    argsman.AddArg("-maxsigcachesize=<n>", strprintf("Limit sum of signature cache and script execution cache sizes to <n> MiB (default: %u)", DEFAULT_VALIDATION_CACHE_BYTES >> 20), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
696
1.92k
    argsman.AddArg("-maxtipage=<n>",
697
1.92k
                   strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)",
698
1.92k
                             Ticks<std::chrono::seconds>(DEFAULT_MAX_TIP_AGE)),
699
1.92k
                   ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
700
1.92k
    argsman.AddArg("-printpriority", strprintf("Log transaction fee rate in %s/kvB when mining blocks (default: %u)", CURRENCY_UNIT, DEFAULT_PRINT_MODIFIED_FEE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
701
1.92k
    argsman.AddArg("-uacomment=<cmt>", "Append comment to the user agent string", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
702
703
1.92k
    SetupChainParamsBaseOptions(argsman);
704
705
1.92k
    argsman.AddArg("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (test networks only; default: %u)", DEFAULT_ACCEPT_NON_STD_TXN), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
706
1.92k
    argsman.AddArg("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kvB) used to define cost of relay, used for mempool limiting and replacement policy. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
707
1.92k
    argsman.AddArg("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kvB) used to define dust, the value of an output such that it will cost more than its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
708
1.92k
    argsman.AddArg("-acceptstalefeeestimates", strprintf("Read fee estimates even if they are stale (%sdefault: %u) fee estimates are considered stale if they are %s hours old", "regtest only; ", DEFAULT_ACCEPT_STALE_FEE_ESTIMATES, Ticks<std::chrono::hours>(MAX_FILE_AGE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
709
1.92k
    argsman.AddArg("-bytespersigop", strprintf("Equivalent bytes per sigop in transactions for relay and mining (default: %u)", DEFAULT_BYTES_PER_SIGOP), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
710
1.92k
    argsman.AddArg("-datacarrier", strprintf("Relay and mine data carrier transactions (default: %u)", DEFAULT_ACCEPT_DATACARRIER), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
711
1.92k
    argsman.AddArg("-datacarriersize",
712
1.92k
                   strprintf("Relay and mine transactions whose data-carrying raw scriptPubKeys in aggregate "
713
1.92k
                             "are of this size or less, allowing multiple outputs (default: %u)",
714
1.92k
                             MAX_OP_RETURN_RELAY),
715
1.92k
                   ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
716
1.92k
    argsman.AddArg("-permitbaremultisig", strprintf("Relay transactions creating non-P2SH multisig outputs (default: %u)", DEFAULT_PERMIT_BAREMULTISIG), ArgsManager::ALLOW_ANY,
717
1.92k
                   OptionsCategory::NODE_RELAY);
718
1.92k
    argsman.AddArg("-minrelaytxfee=<amt>", strprintf("Fees (in %s/kvB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
719
1.92k
        CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
720
1.92k
    argsman.AddArg("-txsendrate=<n>",
721
1.92k
                   strprintf("Set the maximum ongoing rate for sending transactions to (inbound) peers (default: %u tx/s)",
722
1.92k
                             DEFAULT_TX_SEND_RATE),
723
1.92k
                   ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
724
1.92k
    argsman.AddArg("-privatebroadcast",
725
1.92k
                   strprintf(
726
1.92k
                       "Broadcast transactions submitted via sendrawtransaction RPC using short-lived "
727
1.92k
                       "connections through the Tor or I2P networks, without putting them in the mempool first. "
728
1.92k
                       "Transactions submitted through the wallet are not affected by this option "
729
1.92k
                       "(default: %u)",
730
1.92k
                   DEFAULT_PRIVATE_BROADCAST),
731
1.92k
                   ArgsManager::ALLOW_ANY,
732
1.92k
                   OptionsCategory::NODE_RELAY);
733
1.92k
    argsman.AddArg("-whitelistforcerelay", strprintf("Add 'forcerelay' permission to whitelisted peers with default permissions. This will relay transactions even if the transactions were already in the mempool. (default: %d)", DEFAULT_WHITELISTFORCERELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
734
1.92k
    argsman.AddArg("-whitelistrelay", strprintf("Add 'relay' permission to whitelisted peers with default permissions. This will accept relayed transactions even when not relaying transactions (default: %d)", DEFAULT_WHITELISTRELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
735
736
737
1.92k
    argsman.AddArg("-blockmaxweight=<n>", strprintf("Set maximum BIP141 block weight (default: %d)", DEFAULT_BLOCK_MAX_WEIGHT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::BLOCK_CREATION);
738
1.92k
    argsman.AddArg("-blockreservedweight=<n>", strprintf("Reserve space for the fixed-size block header plus the largest coinbase transaction the mining software may add to the block. Only affects mining RPC clients, not IPC clients. (default: %d).", DEFAULT_BLOCK_RESERVED_WEIGHT), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
739
1.92k
    argsman.AddArg("-blockmintxfee=<amt>", strprintf("Set lowest fee rate (in %s/kvB) for transactions to be included in block creation. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
740
1.92k
    argsman.AddArg("-blockversion=<n>", "Override block version to test forking scenarios", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::BLOCK_CREATION);
741
742
1.92k
    argsman.AddArg("-rest", strprintf("Accept public REST requests (default: %u)", DEFAULT_REST_ENABLE), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
743
1.92k
    argsman.AddArg("-rpcallowip=<ip>", "Allow JSON-RPC connections from specified source. Valid values for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0), a network/CIDR (e.g. 1.2.3.4/24), all ipv4 (0.0.0.0/0), or all ipv6 (::/0). RFC4193 is allowed only if -cjdnsreachable=0. This option can be specified multiple times", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
744
1.92k
    argsman.AddArg("-rpcauth=<userpw>", "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcauth. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
745
1.92k
    argsman.AddArg("-rpcbind=<addr>[:port]", "Bind to given address to listen for JSON-RPC connections. Do not expose the RPC server to untrusted networks such as the public internet! This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost)", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::RPC);
746
1.92k
    argsman.AddArg("-rpcdoccheck", strprintf("Throw a non-fatal error at runtime if the documentation for an RPC is incorrect (default: %u)", DEFAULT_RPC_DOC_CHECK), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
747
1.92k
    argsman.AddArg("-rpccookiefile=<loc>", "Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
748
1.92k
    argsman.AddArg("-rpccookieperms=<readable-by>", strprintf("Set permissions on the RPC auth cookie file so that it is readable by [owner|group|all] (default: owner [via umask 0077])"), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
749
1.92k
    argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
750
1.92k
    argsman.AddArg("-rpcport=<port>", strprintf("Listen for JSON-RPC connections on <port> (default: %u, testnet3: %u, testnet4: %u, signet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), testnet4BaseParams->RPCPort(), signetBaseParams->RPCPort(), regtestBaseParams->RPCPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::RPC);
751
1.92k
    argsman.AddArg("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
752
1.92k
    argsman.AddArg("-rpcthreads=<n>", strprintf("Set the number of threads to service RPC calls (default: %d)", DEFAULT_HTTP_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
753
1.92k
    argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
754
1.92k
    argsman.AddArg("-rpcwhitelist=<whitelist>", "Set a whitelist to filter incoming RPC calls for a specific user. The field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc 2>,...,<rpc n>. If multiple whitelists are set for a given user, they are set-intersected. See -rpcwhitelistdefault documentation for information on default whitelist behavior.", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
755
1.92k
    argsman.AddArg("-rpcwhitelistdefault", "Sets default behavior for rpc whitelisting. Unless rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc server acts as if all rpc users are subject to empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault is set to 1 and no -rpcwhitelist is set, rpc server acts as if all rpc users are subject to empty whitelists.", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
756
1.92k
    argsman.AddArg("-rpcworkqueue=<n>", strprintf("Set the maximum depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
757
1.92k
    argsman.AddArg("-server", "Accept command line and JSON-RPC commands", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
758
1.92k
    if (can_listen_ipc) {
759
5
        argsman.AddArg("-ipcbind=<address>", "Bind to Unix socket address and listen for incoming connections. Valid address values are \"unix\" to listen on the default path, <datadir>/node.sock, or \"unix:/custom/path\" to specify a custom path. Can be specified multiple times to listen on multiple paths. Default behavior is not to listen on any path. If relative paths are specified, they are interpreted relative to the network data directory. If paths include any parent directory components and the parent directories do not exist, they will be created. Enabling this gives local processes that can access the socket unauthenticated RPC access, so it's important to choose a path with secure permissions if customizing this.", ArgsManager::ALLOW_ANY, OptionsCategory::IPC);
760
5
    }
761
762
1.92k
#if HAVE_DECL_FORK
763
1.92k
    argsman.AddArg("-daemon", strprintf("Run in the background as a daemon and accept commands (default: %d)", DEFAULT_DAEMON), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
764
1.92k
    argsman.AddArg("-daemonwait", strprintf("Wait for initialization to be finished before exiting. This implies -daemon (default: %d)", DEFAULT_DAEMONWAIT), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
765
#else
766
    hidden_args.emplace_back("-daemon");
767
    hidden_args.emplace_back("-daemonwait");
768
#endif
769
770
    // Add the hidden options
771
1.92k
    argsman.AddHiddenArgs(hidden_args);
772
1.92k
}
773
774
#if HAVE_SYSTEM
775
static void StartupNotify(const ArgsManager& args)
776
1.00k
{
777
1.00k
    std::string cmd = args.GetArg("-startupnotify", "");
778
1.00k
    if (!cmd.empty()) {
779
1
        std::thread t(runCommand, cmd);
780
1
        t.detach(); // thread runs free
781
1
    }
782
1.00k
}
783
#endif
784
785
static bool AppInitServers(NodeContext& node)
786
1.13k
{
787
1.13k
    const ArgsManager& args = *Assert(node.args);
788
1.13k
    if (!InitHTTPServer()) {
789
1
        return false;
790
1
    }
791
1.13k
    StartRPC();
792
1.13k
    node.rpc_interruption_point = RpcInterruptionPoint;
793
1.13k
    if (!StartHTTPRPC(&node))
794
12
        return false;
795
1.11k
    if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) StartREST(&node);
796
1.11k
    StartHTTPServer();
797
1.11k
    return true;
798
1.13k
}
799
800
// Parameter interaction based on rules
801
void InitParameterInteraction(ArgsManager& args)
802
1.17k
{
803
    // when specifying an explicit binding address, you want to listen on it
804
    // even when -connect or -proxy is specified
805
1.17k
    if (!args.GetArgs("-bind").empty()) {
806
1.13k
        if (args.SoftSetBoolArg("-listen", true))
807
1.13k
            LogInfo("parameter interaction: -bind set -> setting -listen=1\n");
808
1.13k
    }
809
1.17k
    if (!args.GetArgs("-whitebind").empty()) {
810
9
        if (args.SoftSetBoolArg("-listen", true))
811
9
            LogInfo("parameter interaction: -whitebind set -> setting -listen=1\n");
812
9
    }
813
814
1.17k
    if (!args.GetArgs("-connect").empty() || args.IsArgNegated("-connect") || args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS) <= 0) {
815
        // when only connecting to trusted nodes, do not seed via DNS, or listen by default
816
        // do the same when connections are disabled
817
1.13k
        if (args.SoftSetBoolArg("-dnsseed", false))
818
1.13k
            LogInfo("parameter interaction: -connect or -maxconnections=0 set -> setting -dnsseed=0\n");
819
1.13k
        if (args.SoftSetBoolArg("-listen", false))
820
1.13k
            LogInfo("parameter interaction: -connect or -maxconnections=0 set -> setting -listen=0\n");
821
1.13k
    }
822
823
1.17k
    std::string proxy_arg = args.GetArg("-proxy", "");
824
1.17k
    if (proxy_arg != "" && proxy_arg != "0") {
825
        // to protect privacy, do not listen by default if a default proxy server is specified
826
48
        if (args.SoftSetBoolArg("-listen", false))
827
48
            LogInfo("parameter interaction: -proxy set -> setting -listen=0\n");
828
        // to protect privacy, do not map ports when a proxy is set. The user may still specify -listen=1
829
        // to listen locally, so don't rely on this happening through -listen below.
830
48
        if (args.SoftSetBoolArg("-natpmp", false)) {
831
0
            LogInfo("parameter interaction: -proxy set -> setting -natpmp=0\n");
832
0
        }
833
        // to protect privacy, do not discover addresses by default
834
48
        if (args.SoftSetBoolArg("-discover", false))
835
48
            LogInfo("parameter interaction: -proxy set -> setting -discover=0\n");
836
48
    }
837
838
1.17k
    if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
839
        // do not map ports or try to retrieve public IP when not listening (pointless)
840
33
        if (args.SoftSetBoolArg("-natpmp", false)) {
841
0
            LogInfo("parameter interaction: -listen=0 -> setting -natpmp=0\n");
842
0
        }
843
33
        if (args.SoftSetBoolArg("-discover", false))
844
33
            LogInfo("parameter interaction: -listen=0 -> setting -discover=0\n");
845
33
        if (args.SoftSetBoolArg("-listenonion", false))
846
33
            LogInfo("parameter interaction: -listen=0 -> setting -listenonion=0\n");
847
33
        if (args.SoftSetBoolArg("-i2pacceptincoming", false)) {
848
33
            LogInfo("parameter interaction: -listen=0 -> setting -i2pacceptincoming=0\n");
849
33
        }
850
33
    }
851
852
1.17k
    if (!args.GetArgs("-externalip").empty()) {
853
        // if an explicit public IP is specified, do not try to find others
854
13
        if (args.SoftSetBoolArg("-discover", false))
855
13
            LogInfo("parameter interaction: -externalip set -> setting -discover=0\n");
856
13
    }
857
858
1.17k
    if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
859
        // disable whitelistrelay in blocksonly mode
860
7
        if (args.SoftSetBoolArg("-whitelistrelay", false))
861
7
            LogInfo("parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n");
862
        // Reduce default mempool size in blocksonly mode to avoid unexpected resource usage
863
7
        if (args.SoftSetArg("-maxmempool", ToString(DEFAULT_BLOCKSONLY_MAX_MEMPOOL_SIZE_MB)))
864
7
            LogInfo("parameter interaction: -blocksonly=1 -> setting -maxmempool=%d\n", DEFAULT_BLOCKSONLY_MAX_MEMPOOL_SIZE_MB);
865
7
    }
866
867
    // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
868
1.17k
    if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
869
3
        if (args.SoftSetBoolArg("-whitelistrelay", true))
870
3
            LogInfo("parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n");
871
3
    }
872
1.17k
    const auto onlynets = args.GetArgs("-onlynet");
873
1.17k
    if (!onlynets.empty()) {
874
9
        bool clearnet_reachable = std::any_of(onlynets.begin(), onlynets.end(), [](const auto& net) {
875
9
            const auto n = ParseNetwork(net);
876
9
            return n == NET_IPV4 || n == NET_IPV6;
877
9
        });
878
9
        if (!clearnet_reachable && args.SoftSetBoolArg("-dnsseed", false)) {
879
0
            LogInfo("parameter interaction: -onlynet excludes IPv4 and IPv6 -> setting -dnsseed=0\n");
880
0
        }
881
9
    }
882
1.17k
}
883
884
/**
885
 * Initialize global loggers.
886
 *
887
 * Note that this is called very early in the process lifetime, so you should be
888
 * careful about what global state you rely on here.
889
 */
890
void InitLogging(const ArgsManager& args)
891
1.87k
{
892
1.87k
    init::SetLoggingOptions(args);
893
1.87k
    init::LogPackageVersion();
894
1.87k
}
895
896
namespace { // Variables internal to initialization process only
897
898
int nMaxConnections;
899
int available_fds;
900
ServiceFlags g_local_services = ServiceFlags(NODE_NETWORK_LIMITED | NODE_WITNESS);
901
int64_t peer_connect_timeout;
902
std::set<BlockFilterType> g_enabled_filter_types;
903
904
} // namespace
905
906
[[noreturn]] static void new_handler_terminate()
907
0
{
908
    // Rather than throwing std::bad-alloc if allocation fails, terminate
909
    // immediately to (try to) avoid chain corruption.
910
    // Since logging may itself allocate memory, set the handler directly
911
    // to terminate first.
912
0
    std::set_new_handler(std::terminate);
913
0
    LogError("Out of memory. Terminating.\n");
914
915
    // The log was successful, terminate now.
916
0
    std::terminate();
917
0
};
918
919
bool AppInitBasicSetup(const ArgsManager& args, std::atomic<int>& exit_status)
920
1.17k
{
921
    // ********************************************************* Step 1: setup
922
#ifdef _MSC_VER
923
    // Turn off Microsoft heap dump noise
924
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
925
    _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
926
    // Disable confusing "helpful" text message on abort, Ctrl-C
927
    _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
928
#endif
929
#ifdef WIN32
930
    // Enable heap terminate-on-corruption
931
    HeapSetInformation(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0);
932
#endif
933
1.17k
    if (!SetupNetworking()) {
934
0
        return InitError(Untranslated("Initializing networking failed."));
935
0
    }
936
937
1.17k
#ifndef WIN32
938
    // Clean shutdown on SIGTERM
939
1.17k
    registerSignalHandler(SIGTERM, HandleSIGTERM);
940
1.17k
    registerSignalHandler(SIGINT, HandleSIGTERM);
941
942
    // Reopen debug.log on SIGHUP
943
1.17k
    registerSignalHandler(SIGHUP, HandleSIGHUP);
944
945
    // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
946
1.17k
    signal(SIGPIPE, SIG_IGN);
947
#else
948
    SetConsoleCtrlHandler(consoleCtrlHandler, true);
949
#endif
950
951
1.17k
    std::set_new_handler(new_handler_terminate);
952
953
1.17k
    return true;
954
1.17k
}
955
956
bool AppInitParameterInteraction(const ArgsManager& args)
957
3.73k
{
958
3.73k
    const CChainParams& chainparams = Params();
959
    // ********************************************************* Step 2: parameter interactions
960
961
    // also see: InitParameterInteraction()
962
963
    // We removed checkpoints but keep the option to warn users who still have it in their config.
964
3.73k
    if (args.IsArgSet("-checkpoints")) {
965
0
        InitWarning(_("Option '-checkpoints' is set but checkpoints were removed. This option has no effect."));
966
0
    }
967
3.73k
    if (args.IsArgSet("-limitancestorsize")) {
968
0
        InitWarning(_("Option '-limitancestorsize' is given but ancestor size limits have been replaced with cluster size limits (see -limitclustersize). This option has no effect."));
969
0
    }
970
3.73k
    if (args.IsArgSet("-limitdescendantsize")) {
971
0
        InitWarning(_("Option '-limitdescendantsize' is given but descendant size limits have been replaced with cluster size limits (see -limitclustersize). This option has no effect."));
972
0
    }
973
974
    // Error if network-specific options (-addnode, -connect, etc) are
975
    // specified in default section of config file, but not overridden
976
    // on the command line or in this chain's section of the config file.
977
3.73k
    ChainType chain = args.GetChainType();
978
3.73k
    if (chain == ChainType::SIGNET) {
979
13
        LogInfo("Signet derived magic (message start): %s", HexStr(chainparams.MessageStart()));
980
13
    }
981
3.73k
    bilingual_str errors;
982
3.73k
    for (const auto& arg : args.GetUnsuitableSectionOnlyArgs()) {
983
1
        errors += strprintf(_("Config setting for %s only applied on %s network when in [%s] section."), arg, ChainTypeToString(chain), ChainTypeToString(chain)) + Untranslated("\n");
984
1
    }
985
986
3.73k
    if (!errors.empty()) {
987
1
        return InitError(errors);
988
1
    }
989
990
    // Testnet3 deprecation warning
991
3.73k
    if (chain == ChainType::TESTNET) {
992
2
        LogInfo("Warning: Support for testnet3 is deprecated and will be removed in an upcoming release. Consider switching to testnet4.\n");
993
2
    }
994
995
    // Warn if unrecognized section name are present in the config file.
996
3.73k
    bilingual_str warnings;
997
3.73k
    for (const auto& section : args.GetUnrecognizedSections()) {
998
2
        warnings += Untranslated(strprintf("%s:%i ", section.m_file, section.m_line)) + strprintf(_("Section [%s] is not recognized."), section.m_name) + Untranslated("\n");
999
2
    }
1000
1001
3.73k
    if (!warnings.empty()) {
1002
1
        InitWarning(warnings);
1003
1
    }
1004
1005
3.73k
    if (!fs::is_directory(args.GetBlocksDirPath())) {
1006
1
        return InitError(strprintf(_("Specified blocks directory \"%s\" does not exist."), args.GetArg("-blocksdir", "")));
1007
1
    }
1008
1009
    // parse and validate enabled filter types
1010
3.73k
    std::string blockfilterindex_value = args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
1011
3.73k
    if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
1012
50
        g_enabled_filter_types = AllBlockFilterTypes();
1013
3.68k
    } else if (blockfilterindex_value != "0") {
1014
1
        const std::vector<std::string> names = args.GetArgs("-blockfilterindex");
1015
1
        for (const auto& name : names) {
1016
1
            BlockFilterType filter_type;
1017
1
            if (!BlockFilterTypeByName(name, filter_type)) {
1018
1
                return InitError(strprintf(_("Unknown -blockfilterindex value %s."), name));
1019
1
            }
1020
0
            g_enabled_filter_types.insert(filter_type);
1021
0
        }
1022
1
    }
1023
1024
    // Signal NODE_P2P_V2 if BIP324 v2 transport is enabled.
1025
3.73k
    if (args.GetBoolArg("-v2transport", DEFAULT_V2_TRANSPORT)) {
1026
764
        g_local_services = ServiceFlags(g_local_services | NODE_P2P_V2);
1027
764
    }
1028
1029
    // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index are both enabled.
1030
3.73k
    if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
1031
2
        if (!g_enabled_filter_types.contains(BlockFilterType::BASIC)) {
1032
1
            return InitError(_("Cannot set -peerblockfilters without -blockfilterindex."));
1033
1
        }
1034
1035
1
        g_local_services = ServiceFlags(g_local_services | NODE_COMPACT_FILTERS);
1036
1
    }
1037
1038
3.73k
    if (args.GetIntArg("-prune", 0)) {
1039
43
        if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX))
1040
0
            return InitError(_("Prune mode is incompatible with -txindex."));
1041
43
        if (args.GetBoolArg("-txospenderindex", DEFAULT_TXOSPENDERINDEX))
1042
0
            return InitError(_("Prune mode is incompatible with -txospenderindex."));
1043
43
        if (args.GetBoolArg("-reindex-chainstate", false)) {
1044
0
            return InitError(_("Prune mode is incompatible with -reindex-chainstate. Use full -reindex instead."));
1045
0
        }
1046
43
    }
1047
1048
    // If -forcednsseed is set to true, ensure -dnsseed has not been set to false
1049
3.73k
    if (args.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED) && !args.GetBoolArg("-dnsseed", DEFAULT_DNSSEED)){
1050
2
        return InitError(_("Cannot set -forcednsseed to true when setting -dnsseed to false."));
1051
2
    }
1052
1053
    // -bind and -whitebind can't be set when not listening
1054
3.73k
    size_t nUserBind = args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size();
1055
3.73k
    if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1056
1
        return InitError(Untranslated("Cannot set -bind or -whitebind together with -listen=0"));
1057
1
    }
1058
1059
    // if listen=0, then disallow listenonion=1
1060
3.73k
    if (!args.GetBoolArg("-listen", DEFAULT_LISTEN) && args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
1061
0
        return InitError(Untranslated("Cannot set -listen=0 together with -listenonion=1"));
1062
0
    }
1063
1064
    // Make sure enough file descriptors are available. We need to reserve enough FDs to account for the bare minimum,
1065
    // plus all manual connections and all bound interfaces. Any remainder will be available for connection sockets
1066
1067
    // Number of bound interfaces (we have at least one)
1068
3.73k
    int nBind = std::max(nUserBind, size_t(1));
1069
    // Maximum number of connections with other nodes, this accounts for all types of outbounds and inbounds except for manual
1070
3.73k
    int user_max_connection = args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
1071
3.73k
    if (user_max_connection < 0) {
1072
0
        return InitError(Untranslated("-maxconnections must be greater or equal than zero"));
1073
0
    }
1074
3.73k
    const size_t max_private{args.GetBoolArg("-privatebroadcast", DEFAULT_PRIVATE_BROADCAST)
1075
3.73k
                             ? MAX_PRIVATE_BROADCAST_CONNECTIONS
1076
3.73k
                             : 0};
1077
    // Reserve enough FDs to account for the bare minimum, plus any manual connections, plus the bound interfaces
1078
3.73k
    int min_required_fds = MIN_CORE_FDS + MAX_ADDNODE_CONNECTIONS + nBind;
1079
1080
    // Try raising the FD limit to what we need (available_fds may be smaller than the requested amount if this fails)
1081
3.73k
    available_fds = RaiseFileDescriptorLimit(user_max_connection + max_private + min_required_fds);
1082
    // If we are using select instead of poll, our actual limit may be even smaller
1083
#ifndef USE_POLL
1084
    available_fds = std::min(FD_SETSIZE, available_fds);
1085
#endif
1086
3.73k
    if (available_fds < min_required_fds)
1087
0
        return InitError(strprintf(_("Not enough file descriptors available. %d available, %d required."), available_fds, min_required_fds));
1088
1089
    // Trim requested connection counts, to fit into system limitations
1090
3.73k
    nMaxConnections = std::min(available_fds - min_required_fds, user_max_connection);
1091
1092
3.73k
    if (nMaxConnections < user_max_connection)
1093
0
        InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), user_max_connection, nMaxConnections));
1094
1095
    // ********************************************************* Step 3: parameter-to-internal-flags
1096
3.73k
    if (auto result{init::SetLoggingCategories(args)}; !result) return InitError(util::ErrorString(result));
1097
3.73k
    if (auto result{init::SetLoggingLevel(args)}; !result) return InitError(util::ErrorString(result));
1098
1099
3.72k
    nConnectTimeout = args.GetIntArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1100
3.72k
    if (nConnectTimeout <= 0) {
1101
0
        nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1102
0
    }
1103
1104
3.72k
    peer_connect_timeout = args.GetIntArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
1105
3.72k
    if (peer_connect_timeout <= 0) {
1106
2
        return InitError(Untranslated("peertimeout must be a positive integer."));
1107
2
    }
1108
1109
3.72k
    auto mining_result{node::ReadMiningArgs(args)};
1110
3.72k
    if (!mining_result) {
1111
4
        return InitError(util::ErrorString(mining_result));
1112
4
    }
1113
1114
3.72k
    nBytesPerSigOp = args.GetIntArg("-bytespersigop", nBytesPerSigOp);
1115
1116
3.72k
    if (!g_wallet_init_interface.ParameterInteraction()) return false;
1117
1118
    // Option to startup with mocktime set (used for regression testing):
1119
3.72k
    if (const auto mocktime{args.GetIntArg("-mocktime")}) {
1120
11
        SetMockTime(std::chrono::seconds{*mocktime});
1121
11
    }
1122
1123
3.72k
    if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1124
4
        g_local_services = ServiceFlags(g_local_services | NODE_BLOOM);
1125
1126
3.72k
    const std::vector<std::string> test_options = args.GetArgs("-test");
1127
3.72k
    if (!test_options.empty()) {
1128
15
        if (chainparams.GetChainType() != ChainType::REGTEST) {
1129
0
            return InitError(Untranslated("-test=<option> can only be used with regtest"));
1130
0
        }
1131
15
        for (const std::string& option : test_options) {
1132
18
            auto it = std::find_if(TEST_OPTIONS_DOC.begin(), TEST_OPTIONS_DOC.end(), [&option](const std::string& doc_option) {
1133
18
                size_t pos = doc_option.find(" (");
1134
18
                return (pos != std::string::npos) && (doc_option.substr(0, pos) == option);
1135
18
            });
1136
15
            if (it == TEST_OPTIONS_DOC.end()) {
1137
0
                InitWarning(strprintf(_("Unrecognised option \"%s\" provided in -test=<option>."), option));
1138
0
            }
1139
15
        }
1140
15
    }
1141
1142
    // Prevent setting deployment parameters on mainnet.
1143
3.72k
    if (chainparams.GetChainType() == ChainType::MAIN) {
1144
607
        if (args.IsArgSet("-testactivationheight")) {
1145
0
            return InitError(_("The -testactivationheight option may not be used on mainnet."));
1146
0
        }
1147
607
        if (args.IsArgSet("-vbparams")) {
1148
0
            return InitError(_("The -vbparams option may not be used on mainnet."));
1149
0
        }
1150
607
    }
1151
1152
    // Also report errors from parsing before daemonization
1153
3.72k
    {
1154
3.72k
        kernel::Notifications notifications{};
1155
3.72k
        ChainstateManager::Options chainman_opts_dummy{
1156
3.72k
            .chainparams = chainparams,
1157
3.72k
            .datadir = args.GetDataDirNet(),
1158
3.72k
            .notifications = notifications,
1159
3.72k
        };
1160
3.72k
        auto chainman_result{ApplyArgsManOptions(args, chainman_opts_dummy)};
1161
3.72k
        if (!chainman_result) {
1162
1
            return InitError(util::ErrorString(chainman_result));
1163
1
        }
1164
3.72k
        BlockManager::Options blockman_opts_dummy{
1165
3.72k
            .chainparams = chainman_opts_dummy.chainparams,
1166
3.72k
            .blocks_dir = args.GetBlocksDirPath(),
1167
3.72k
            .notifications = chainman_opts_dummy.notifications,
1168
3.72k
            .block_tree_db_params = DBParams{
1169
3.72k
                .path = args.GetDataDirNet() / "blocks" / "index",
1170
3.72k
                .cache_bytes = 0,
1171
3.72k
            },
1172
3.72k
        };
1173
3.72k
        auto blockman_result{ApplyArgsManOptions(args, blockman_opts_dummy)};
1174
3.72k
        if (!blockman_result) {
1175
0
            return InitError(util::ErrorString(blockman_result));
1176
0
        }
1177
3.72k
        CTxMemPool::Options mempool_opts{};
1178
3.72k
        auto mempool_result{ApplyArgsManOptions(args, chainparams, mempool_opts)};
1179
3.72k
        if (!mempool_result) {
1180
1
            return InitError(util::ErrorString(mempool_result));
1181
1
        }
1182
3.72k
    }
1183
1184
3.71k
    return true;
1185
3.72k
}
1186
1187
static bool LockDirectory(const fs::path& dir, bool probeOnly)
1188
4.60k
{
1189
    // Make sure only a single process is using the directory.
1190
4.60k
    switch (util::LockDirectory(dir, ".lock", probeOnly)) {
1191
0
    case util::LockResult::ErrorWrite:
1192
0
        return InitError(strprintf(_("Cannot write to directory '%s'; check permissions."), fs::PathToString(dir)));
1193
2
    case util::LockResult::ErrorLock:
1194
2
        return InitError(strprintf(_("Cannot obtain a lock on directory %s. %s is probably already running."), fs::PathToString(dir), CLIENT_NAME));
1195
4.60k
    case util::LockResult::Success: return true;
1196
4.60k
    } // no default case, so the compiler can warn about missing cases
1197
4.60k
    assert(false);
1198
0
}
1199
static bool LockDirectories(bool probeOnly)
1200
2.30k
{
1201
2.30k
    return LockDirectory(gArgs.GetDataDirNet(), probeOnly) && \
1202
2.30k
           LockDirectory(gArgs.GetBlocksDirPath(), probeOnly);
1203
2.30k
}
1204
1205
bool AppInitSanityChecks(const kernel::Context& kernel)
1206
1.15k
{
1207
    // ********************************************************* Step 4: sanity checks
1208
1.15k
    auto result{kernel::SanityChecks(kernel)};
1209
1.15k
    if (!result) {
1210
0
        InitError(util::ErrorString(result));
1211
0
        return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), CLIENT_NAME));
1212
0
    }
1213
1214
1.15k
    if (!ECC_InitSanityCheck()) {
1215
0
        return InitError(strprintf(_("Elliptic curve cryptography sanity check failure. %s is shutting down."), CLIENT_NAME));
1216
0
    }
1217
1218
    // Probe the directory locks to give an early error message, if possible
1219
    // We cannot hold the directory locks here, as the forking for daemon() hasn't yet happened,
1220
    // and a fork will cause weird behavior to them.
1221
1.15k
    return LockDirectories(true);
1222
1.15k
}
1223
1224
bool AppInitLockDirectories()
1225
1.15k
{
1226
    // After daemonization get the directory locks again and hold on to them until exit
1227
    // This creates a slight window for a race condition to happen, however this condition is harmless: it
1228
    // will at most make us exit without printing a message to console.
1229
1.15k
    if (!LockDirectories(false)) {
1230
        // Detailed error printed inside LockDirectory
1231
0
        return false;
1232
0
    }
1233
1.15k
    return true;
1234
1.15k
}
1235
1236
bool AppInitInterfaces(NodeContext& node)
1237
1.15k
{
1238
1.15k
    node.chain = interfaces::MakeChain(node);
1239
    // Specify wait_loaded=false so internal mining interface can be initialized
1240
    // on early startup and does not need to be tied to chainstate loading.
1241
1.15k
    node.mining = interfaces::MakeMining(node, /*wait_loaded=*/false);
1242
1.15k
    return true;
1243
1.15k
}
1244
1245
1.14k
bool CheckHostPortOptions(const ArgsManager& args) {
1246
1.14k
    for (const std::string port_option : {
1247
1.14k
        "-port",
1248
1.14k
        "-rpcport",
1249
2.29k
    }) {
1250
2.29k
        if (const auto port{args.GetArg(port_option)}) {
1251
2.29k
            const auto n{ToIntegral<uint16_t>(*port)};
1252
2.29k
            if (!n || *n == 0) {
1253
2
                return InitError(InvalidPortErrMsg(port_option, *port));
1254
2
            }
1255
2.29k
        }
1256
2.29k
    }
1257
1258
1.14k
    for ([[maybe_unused]] const auto& [param_name, unix, suffix_allowed] : std::vector<std::tuple<std::string, bool, bool>>{
1259
        // arg name          UNIX socket support  =suffix allowed
1260
1.14k
        {"-i2psam",          false,               false},
1261
1.14k
        {"-onion",           true,                false},
1262
1.14k
        {"-proxy",           true,                true},
1263
1.14k
        {"-bind",            false,               true},
1264
1.14k
        {"-rpcbind",         false,               false},
1265
1.14k
        {"-torcontrol",      false,               false},
1266
1.14k
        {"-whitebind",       false,               false},
1267
1.14k
        {"-zmqpubhashblock", true,                false},
1268
1.14k
        {"-zmqpubhashtx",    true,                false},
1269
1.14k
        {"-zmqpubrawblock",  true,                false},
1270
1.14k
        {"-zmqpubrawtx",     true,                false},
1271
1.14k
        {"-zmqpubsequence",  true,                false},
1272
13.6k
    }) {
1273
13.6k
        for (const std::string& param_value : args.GetArgs(param_name)) {
1274
1.23k
            const std::string param_value_hostport{
1275
1.23k
                suffix_allowed ? param_value.substr(0, param_value.rfind('=')) : param_value};
1276
1.23k
            std::string host_out;
1277
1.23k
            uint16_t port_out{0};
1278
1.23k
            if (!SplitHostPort(param_value_hostport, port_out, host_out)) {
1279
14
#ifdef HAVE_SOCKADDR_UN
1280
                // Allow unix domain sockets for some options e.g. unix:/some/file/path
1281
14
                if (!unix || !param_value.starts_with(ADDR_PREFIX_UNIX)) {
1282
11
                    return InitError(InvalidPortErrMsg(param_name, param_value));
1283
11
                }
1284
#else
1285
                return InitError(InvalidPortErrMsg(param_name, param_value));
1286
#endif
1287
14
            }
1288
1.23k
        }
1289
13.6k
    }
1290
1291
1.13k
    return true;
1292
1.14k
}
1293
1294
/**
1295
 * @brief Checks for duplicate bindings across all binding configurations.
1296
 *
1297
 * @param[in] conn_options Connection options containing the binding vectors to check
1298
 * @return std::optional<CService> containing the first duplicate found, or std::nullopt if no duplicates
1299
 */
1300
static std::optional<CService> CheckBindingConflicts(const CConnman::Options& conn_options)
1301
1.02k
{
1302
1.02k
    std::set<CService> seen;
1303
1304
    // Check all whitelisted bindings
1305
1.02k
    for (const auto& wb : conn_options.vWhiteBinds) {
1306
8
        if (!seen.insert(wb.m_service).second) {
1307
1
            return wb.m_service;
1308
1
        }
1309
8
    }
1310
1311
    // Check regular bindings
1312
1.02k
    for (const auto& bind : conn_options.vBinds) {
1313
998
        if (!seen.insert(bind).second) {
1314
2
            return bind;
1315
2
        }
1316
998
    }
1317
1318
    // Check onion bindings
1319
1.02k
    for (const auto& onion_bind : conn_options.onion_binds) {
1320
44
        if (!seen.insert(onion_bind).second) {
1321
3
            return onion_bind;
1322
3
        }
1323
44
    }
1324
1325
1.02k
    return std::nullopt;
1326
1.02k
}
1327
1328
// A GUI user may opt to retry once with do_reindex set if there is a failure during chainstate initialization.
1329
// The function therefore has to support re-entry.
1330
static ChainstateLoadResult InitAndLoadChainstate(
1331
    NodeContext& node,
1332
    bool do_reindex,
1333
    const bool do_reindex_chainstate,
1334
    const kernel::CacheSizes& cache_sizes,
1335
    const ArgsManager& args)
1336
2.13k
{
1337
    // This function may be called twice, so any dirty state must be reset.
1338
2.13k
    node.notifications->setChainstateLoaded(false); // Drop state, such as a cached tip block
1339
2.13k
    node.mempool.reset();
1340
2.13k
    node.chainman.reset(); // Drop state, such as an initialized m_block_tree_db
1341
1342
2.13k
    const CChainParams& chainparams = Params();
1343
1344
2.13k
    CTxMemPool::Options mempool_opts{
1345
2.13k
        .check_ratio = chainparams.DefaultConsistencyChecks() ? 1 : 0,
1346
2.13k
        .signals = node.validation_signals.get(),
1347
2.13k
    };
1348
2.13k
    Assert(ApplyArgsManOptions(args, chainparams, mempool_opts)); // no error can happen, already checked in AppInitParameterInteraction
1349
2.13k
    bilingual_str mempool_error;
1350
2.13k
    Assert(!node.mempool); // Was reset above
1351
2.13k
    node.mempool = std::make_unique<CTxMemPool>(mempool_opts, mempool_error);
1352
2.13k
    if (!mempool_error.empty()) {
1353
1
        return {ChainstateLoadStatus::FAILURE_FATAL, mempool_error};
1354
1
    }
1355
2.13k
    auto mining_args{node::ReadMiningArgs(args)};
1356
2.13k
    Assert(mining_args); // no error can happen, already checked in AppInitParameterInteraction
1357
2.13k
    node.mining_args = std::move(*mining_args);
1358
2.13k
    LogInfo("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)",
1359
2.13k
            cache_sizes.coins / double(1_MiB),
1360
2.13k
            mempool_opts.max_size_bytes / double(1_MiB));
1361
2.13k
    ChainstateManager::Options chainman_opts{
1362
2.13k
        .chainparams = chainparams,
1363
2.13k
        .datadir = args.GetDataDirNet(),
1364
2.13k
        .notifications = *node.notifications,
1365
2.13k
        .signals = node.validation_signals.get(),
1366
2.13k
    };
1367
2.13k
    Assert(ApplyArgsManOptions(args, chainman_opts)); // no error can happen, already checked in AppInitParameterInteraction
1368
1369
2.13k
    BlockManager::Options blockman_opts{
1370
2.13k
        .chainparams = chainman_opts.chainparams,
1371
2.13k
        .blocks_dir = args.GetBlocksDirPath(),
1372
2.13k
        .notifications = chainman_opts.notifications,
1373
2.13k
        .block_tree_db_params = DBParams{
1374
2.13k
            .path = args.GetDataDirNet() / "blocks" / "index",
1375
2.13k
            .cache_bytes = cache_sizes.block_tree_db,
1376
2.13k
            .wipe_data = do_reindex,
1377
2.13k
        },
1378
2.13k
    };
1379
2.13k
    Assert(ApplyArgsManOptions(args, blockman_opts)); // no error can happen, already checked in AppInitParameterInteraction
1380
1381
    // Creating the chainstate manager internally creates a BlockManager, opens
1382
    // the blocks tree db, and wipes existing block files in case of a reindex.
1383
    // The coinsdb is opened at a later point on LoadChainstate.
1384
2.13k
    Assert(!node.chainman); // Was reset above
1385
2.13k
    try {
1386
2.13k
        node.chainman = std::make_unique<ChainstateManager>(*Assert(node.shutdown_signal), chainman_opts, blockman_opts);
1387
2.13k
    } catch (dbwrapper_error& e) {
1388
1
        LogError("%s", e.what());
1389
1
        return {ChainstateLoadStatus::FAILURE, _("Error opening block database")};
1390
1
    } catch (std::exception& e) {
1391
1
        return {ChainstateLoadStatus::FAILURE_FATAL, Untranslated(strprintf("Failed to initialize ChainstateManager: %s", e.what()))};
1392
1
    }
1393
1.06k
    ChainstateManager& chainman = *node.chainman;
1394
1.06k
    if (chainman.m_interrupt) return {ChainstateLoadStatus::INTERRUPTED, {}};
1395
1396
    // This is defined and set here instead of inline in validation.h to avoid a hard
1397
    // dependency between validation and index/base, since the latter is not in
1398
    // libbitcoinkernel.
1399
1.05k
    chainman.snapshot_download_completed = [&node]() {
1400
7
        if (!node.chainman->m_blockman.IsPruneMode()) {
1401
5
            LogInfo("[snapshot] re-enabling NODE_NETWORK services");
1402
5
            node.connman->AddLocalServices(NODE_NETWORK);
1403
5
        }
1404
7
        LogInfo("[snapshot] restarting indexes");
1405
        // Drain the validation interface queue to ensure that the old indexes
1406
        // don't have any pending work.
1407
7
        Assert(node.validation_signals)->SyncWithValidationInterfaceQueue();
1408
8
        for (auto* index : node.indexes) {
1409
8
            index->Interrupt();
1410
8
            index->Stop();
1411
8
            if (!(index->Init() && index->StartBackgroundSync())) {
1412
0
                LogWarning("[snapshot] Failed to restart index %s on snapshot chain", index->GetName());
1413
0
            }
1414
8
        }
1415
7
    };
1416
1.05k
    node::ChainstateLoadOptions options;
1417
1.05k
    options.mempool = Assert(node.mempool.get());
1418
1.05k
    options.wipe_chainstate_db = do_reindex || do_reindex_chainstate;
1419
1.05k
    options.prune = chainman.m_blockman.IsPruneMode();
1420
1.05k
    options.check_blocks = args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);
1421
1.05k
    options.check_level = args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL);
1422
1.05k
    options.require_full_verification = args.IsArgSet("-checkblocks") || args.IsArgSet("-checklevel");
1423
1.05k
    options.coins_error_cb = [] {
1424
0
        uiInterface.ThreadSafeMessageBox(
1425
0
            _("Error reading from database, shutting down."),
1426
0
            CClientUIInterface::MSG_ERROR);
1427
0
    };
1428
1.05k
    uiInterface.InitMessage(_("Loading block index…"));
1429
2.10k
    auto catch_exceptions = [](auto&& f) -> ChainstateLoadResult {
1430
2.10k
        try {
1431
2.10k
            return f();
1432
2.10k
        } catch (const std::exception& e) {
1433
0
            LogError("%s\n", e.what());
1434
0
            return std::make_tuple(node::ChainstateLoadStatus::FAILURE, _("Error loading databases"));
1435
0
        }
1436
2.10k
    };
init.cpp:_ZZL21InitAndLoadChainstateRN4node11NodeContextEbbRKN6kernel10CacheSizesERK11ArgsManagerENK3$_2clIZL21InitAndLoadChainstateS1_bbS5_S8_E3$_3EESt5tupleIJNS_20ChainstateLoadStatusE13bilingual_strEEOT_
Line
Count
Source
1429
1.05k
    auto catch_exceptions = [](auto&& f) -> ChainstateLoadResult {
1430
1.05k
        try {
1431
1.05k
            return f();
1432
1.05k
        } catch (const std::exception& e) {
1433
0
            LogError("%s\n", e.what());
1434
0
            return std::make_tuple(node::ChainstateLoadStatus::FAILURE, _("Error loading databases"));
1435
0
        }
1436
1.05k
    };
init.cpp:_ZZL21InitAndLoadChainstateRN4node11NodeContextEbbRKN6kernel10CacheSizesERK11ArgsManagerENK3$_2clIZL21InitAndLoadChainstateS1_bbS5_S8_E3$_4EESt5tupleIJNS_20ChainstateLoadStatusE13bilingual_strEEOT_
Line
Count
Source
1429
1.04k
    auto catch_exceptions = [](auto&& f) -> ChainstateLoadResult {
1430
1.04k
        try {
1431
1.04k
            return f();
1432
1.04k
        } catch (const std::exception& e) {
1433
0
            LogError("%s\n", e.what());
1434
0
            return std::make_tuple(node::ChainstateLoadStatus::FAILURE, _("Error loading databases"));
1435
0
        }
1436
1.04k
    };
1437
1.05k
    auto [status, error] = catch_exceptions([&] { return LoadChainstate(chainman, cache_sizes, options); });
1438
1.05k
    if (status == node::ChainstateLoadStatus::SUCCESS) {
1439
1.04k
        uiInterface.InitMessage(_("Verifying blocks…"));
1440
1.04k
        if (chainman.m_blockman.m_have_pruned && options.check_blocks > MIN_BLOCKS_TO_KEEP) {
1441
0
            LogWarning("pruned datadir may not have more than %d blocks; only checking available blocks\n",
1442
0
                       MIN_BLOCKS_TO_KEEP);
1443
0
        }
1444
1.04k
        std::tie(status, error) = catch_exceptions([&] { return VerifyLoadedChainstate(chainman, options); });
1445
1.04k
        if (status == node::ChainstateLoadStatus::SUCCESS) {
1446
1.04k
            LogInfo("Block index and chainstate loaded");
1447
1.04k
            node.notifications->setChainstateLoaded(true);
1448
1.04k
        }
1449
1.04k
    }
1450
1.05k
    return {status, error};
1451
1.06k
};
1452
1453
bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
1454
1.15k
{
1455
1.15k
    const ArgsManager& args = *Assert(node.args);
1456
1.15k
    const CChainParams& chainparams = Params();
1457
1458
1.15k
    auto opt_max_upload = ParseByteUnits(args.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET), ByteUnit::M);
1459
1.15k
    if (!opt_max_upload) {
1460
1
        return InitError(strprintf(_("Unable to parse -maxuploadtarget: '%s'"), args.GetArg("-maxuploadtarget", "")));
1461
1
    }
1462
1463
    // ********************************************************* Step 4a: application initialization
1464
1.15k
    if (!CreatePidFile(args)) {
1465
        // Detailed error printed inside CreatePidFile().
1466
0
        return false;
1467
0
    }
1468
1.15k
    if (!init::StartLogging(args)) {
1469
        // Detailed error printed inside StartLogging().
1470
2
        return false;
1471
2
    }
1472
1473
1.14k
    LogInfo("Using at most %i automatic connections (%i file descriptors available)", nMaxConnections, available_fds);
1474
1475
    // Warn about relative -datadir path.
1476
1.14k
    if (args.IsArgSet("-datadir") && !args.GetPathArg("-datadir").is_absolute()) {
1477
0
        LogWarning("Relative datadir option '%s' specified, which will be interpreted relative to the "
1478
0
                   "current working directory '%s'. This is fragile, because if bitcoin is started in the future "
1479
0
                   "from a different location, it will be unable to locate the current data files. There could "
1480
0
                   "also be data loss if bitcoin is started while in a temporary directory.",
1481
0
                   args.GetArg("-datadir", ""), fs::PathToString(fs::current_path()));
1482
0
    }
1483
1484
1.14k
    assert(!node.scheduler);
1485
1.14k
    node.scheduler = std::make_unique<CScheduler>();
1486
1.14k
    auto& scheduler = *node.scheduler;
1487
1488
    // Start the lightweight task scheduler thread
1489
1.14k
    scheduler.m_service_thread = std::thread(util::TraceThread, "scheduler", [&] { scheduler.serviceQueue(); });
1490
1491
    // Gather some entropy once per minute.
1492
1.14k
    scheduler.scheduleEvery([]{
1493
89
        RandAddPeriodic();
1494
89
    }, std::chrono::minutes{1});
1495
1496
    // Check disk space every 5 minutes to avoid db corruption.
1497
1.14k
    scheduler.scheduleEvery([&args, &node]{
1498
10
        constexpr uint64_t min_disk_space{50_MiB};
1499
10
        if (!CheckDiskSpace(args.GetBlocksDirPath(), min_disk_space)) {
1500
0
            LogError("Shutting down due to lack of disk space!\n");
1501
0
            if (!(Assert(node.shutdown_request))()) {
1502
0
                LogError("Failed to send shutdown signal after disk space check\n");
1503
0
            }
1504
0
        }
1505
10
    }, std::chrono::minutes{5});
1506
1507
1.14k
    if (args.GetBoolArg("-logratelimit", BCLog::DEFAULT_LOGRATELIMIT)) {
1508
1
        LogInstance().SetRateLimiting(BCLog::LogRateLimiter::Create(
1509
1
            [&scheduler](auto func, auto window) { scheduler.scheduleEvery(std::move(func), window); },
1510
1
            BCLog::RATELIMIT_MAX_BYTES,
1511
1
            BCLog::RATELIMIT_WINDOW));
1512
1.14k
    } else {
1513
1.14k
        LogInfo("Log rate limiting disabled");
1514
1.14k
    }
1515
1516
1.14k
    assert(!node.validation_signals);
1517
1.14k
    node.validation_signals = std::make_unique<ValidationSignals>(std::make_unique<SerialTaskRunner>(scheduler));
1518
1.14k
    auto& validation_signals = *node.validation_signals;
1519
1520
    // Create KernelNotifications object. Important to do this early before
1521
    // calling ipc->listenAddress() below so makeMining and other IPC methods
1522
    // can use this.
1523
1.14k
    assert(!node.notifications);
1524
1.14k
    node.notifications = std::make_unique<KernelNotifications>(Assert(node.shutdown_request), node.exit_status, *Assert(node.warnings));
1525
1.14k
    ReadNotificationArgs(args, *node.notifications);
1526
1527
    // Create client interfaces for wallets that are supposed to be loaded
1528
    // according to -wallet and -disablewallet options. This only constructs
1529
    // the interfaces, it doesn't load wallet data. Wallets actually get loaded
1530
    // when load() and start() interface methods are called below.
1531
1.14k
    g_wallet_init_interface.Construct(node);
1532
1.14k
    uiInterface.InitWallet();
1533
1534
1.14k
    if (interfaces::Ipc* ipc = node.init->ipc()) {
1535
1
        for (std::string address : gArgs.GetArgs("-ipcbind")) {
1536
1
            try {
1537
1
                ipc->listenAddress(address);
1538
1
            } catch (const std::exception& e) {
1539
0
                return InitError(Untranslated(strprintf("Unable to bind to IPC address '%s'. %s", address, e.what())));
1540
0
            }
1541
1
            LogInfo("Listening for IPC requests on address %s", address);
1542
1
        }
1543
1
    }
1544
1545
    /* Register RPC commands regardless of -server setting so they will be
1546
     * available in the GUI RPC console even if external calls are disabled.
1547
     */
1548
1.14k
    RegisterAllCoreRPCCommands(tableRPC);
1549
1.14k
    for (const auto& client : node.chain_clients) {
1550
403
        client->registerRpcs();
1551
403
    }
1552
#ifdef ENABLE_ZMQ
1553
    RegisterZMQRPCCommands(tableRPC);
1554
#endif
1555
1556
    // Check port numbers
1557
1.14k
    if (!CheckHostPortOptions(args)) return false;
1558
1559
    // Configure reachable networks before we start the RPC server.
1560
    // This is necessary for -rpcallowip to distinguish CJDNS from other RFC4193
1561
1.13k
    const auto onlynets = args.GetArgs("-onlynet");
1562
1.13k
    if (!onlynets.empty()) {
1563
9
        g_reachable_nets.RemoveAll();
1564
9
        for (const std::string& snet : onlynets) {
1565
9
            enum Network net = ParseNetwork(snet);
1566
9
            if (net == NET_UNROUTABLE)
1567
1
                return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1568
8
            g_reachable_nets.Add(net);
1569
8
        }
1570
9
    }
1571
1572
1.13k
    if (!args.IsArgSet("-cjdnsreachable")) {
1573
1.12k
        if (!onlynets.empty() && g_reachable_nets.Contains(NET_CJDNS)) {
1574
1
            return InitError(
1575
1
                _("Outbound connections restricted to CJDNS (-onlynet=cjdns) but "
1576
1
                  "-cjdnsreachable is not provided"));
1577
1
        }
1578
1.12k
        g_reachable_nets.Remove(NET_CJDNS);
1579
1.12k
    }
1580
    // Now g_reachable_nets.Contains(NET_CJDNS) is true if:
1581
    // 1. -cjdnsreachable is given and
1582
    // 2.1. -onlynet is not given or
1583
    // 2.2. -onlynet=cjdns is given
1584
1585
    /* Start the RPC server already.  It will be started in "warmup" mode
1586
     * and not really process calls already (but it will signify connections
1587
     * that the server is there and will be ready later).  Warmup mode will
1588
     * be disabled when initialisation is finished.
1589
     */
1590
1.13k
    if (args.GetBoolArg("-server", false)) {
1591
1.13k
        uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1592
1.13k
        if (!AppInitServers(node))
1593
13
            return InitError(_("Unable to start HTTP server. See debug log for details."));
1594
1.13k
    }
1595
1596
    // ********************************************************* Step 5: verify wallet database integrity
1597
1.12k
    for (const auto& client : node.chain_clients) {
1598
403
        if (!client->verify()) {
1599
23
            return false;
1600
23
        }
1601
403
    }
1602
1603
    // ********************************************************* Step 6: network initialization
1604
    // Note that we absolutely cannot open any actual connections
1605
    // until the very end ("start node") as the UTXO/block state
1606
    // is not yet setup and may end up being set up twice if we
1607
    // need to reindex later.
1608
1609
1.09k
    fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN);
1610
1.09k
    fDiscover = args.GetBoolArg("-discover", true);
1611
1612
1.09k
    PeerManager::Options peerman_opts{};
1613
1.09k
    ApplyArgsManOptions(args, peerman_opts);
1614
1615
1.09k
    {
1616
        // Read asmap file if configured or embedded asmap data and initialize
1617
        // Netgroupman with or without it
1618
1.09k
        assert(!node.netgroupman);
1619
1.09k
        if (args.IsArgSet("-asmap") && !args.IsArgNegated("-asmap")) {
1620
9
            uint256 asmap_version{};
1621
9
            if (!args.GetBoolArg("-asmap", false)) {
1622
7
                fs::path asmap_path = args.GetPathArg("-asmap");
1623
7
                if (!asmap_path.is_absolute()) {
1624
2
                    asmap_path = args.GetDataDirNet() / asmap_path;
1625
2
                }
1626
1627
                // If a specific path was passed with the asmap argument check if
1628
                // the file actually exists in that location
1629
7
                if (!fs::exists(asmap_path)) {
1630
1
                    InitError(strprintf(_("Could not find asmap file %s"), fs::quoted(fs::PathToString(asmap_path))));
1631
1
                    return false;
1632
1
                }
1633
1634
                // If a file exists at the path, try to read the file
1635
6
                std::vector<std::byte> asmap{DecodeAsmap(asmap_path)};
1636
6
                if (asmap.empty()) {
1637
1
                    InitError(strprintf(_("Could not parse asmap file %s"), fs::quoted(fs::PathToString(asmap_path))));
1638
1
                    return false;
1639
1
                }
1640
5
                asmap_version = AsmapVersion(asmap);
1641
5
                node.netgroupman = std::make_unique<NetGroupManager>(NetGroupManager::WithLoadedAsmap(std::move(asmap)));
1642
5
            } else {
1643
2
                #ifdef ENABLE_EMBEDDED_ASMAP
1644
                    // Use the embedded asmap data
1645
2
                    std::span<const std::byte> asmap{node::data::ip_asn};
1646
2
                    if (asmap.empty() || !CheckStandardAsmap(asmap)) {
1647
0
                        InitError(strprintf(_("Could not read embedded asmap data")));
1648
0
                        return false;
1649
0
                    }
1650
2
                    node.netgroupman = std::make_unique<NetGroupManager>(NetGroupManager::WithEmbeddedAsmap(asmap));
1651
2
                    asmap_version = AsmapVersion(asmap);
1652
2
                    LogInfo("Opened asmap data (%zu bytes) from embedded byte array\n", asmap.size());
1653
                #else
1654
                    // If there is no embedded data, fail and report it since
1655
                    // the user tried to use it
1656
                    InitError(strprintf(_("Embedded asmap data not available")));
1657
                    return false;
1658
                #endif
1659
2
            }
1660
7
            LogInfo("Using asmap version %s for IP bucketing", asmap_version.ToString());
1661
1.08k
        } else {
1662
1.08k
            node.netgroupman = std::make_unique<NetGroupManager>(NetGroupManager::NoAsmap());
1663
1.08k
            LogInfo("Using /16 prefix for IP bucketing");
1664
1.08k
        }
1665
1666
        // Initialize addrman
1667
1.09k
        assert(!node.addrman);
1668
1.09k
        uiInterface.InitMessage(_("Loading P2P addresses…"));
1669
1.09k
        auto addrman{LoadAddrman(*node.netgroupman, args)};
1670
1.09k
        if (!addrman) return InitError(util::ErrorString(addrman));
1671
1.08k
        node.addrman = std::move(*addrman);
1672
1.08k
    }
1673
1674
0
    FastRandomContext rng;
1675
1.08k
    assert(!node.banman);
1676
1.08k
    node.banman = std::make_unique<BanMan>(args.GetDataDirNet() / "banlist", &uiInterface, args.GetIntArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
1677
1.08k
    assert(!node.connman);
1678
1.08k
    node.connman = std::make_unique<CConnman>(rng.rand64(),
1679
1.08k
                                              rng.rand64(),
1680
1.08k
                                              *node.addrman, *node.netgroupman, chainparams, args.GetBoolArg("-networkactive", true));
1681
1682
1.08k
    assert(!node.fee_estimator);
1683
    // Don't initialize fee estimation with old data if we don't relay transactions,
1684
    // as they would never get updated.
1685
1.08k
    if (!peerman_opts.ignore_incoming_txs) {
1686
1.07k
        bool read_stale_estimates = args.GetBoolArg("-acceptstalefeeestimates", DEFAULT_ACCEPT_STALE_FEE_ESTIMATES);
1687
1.07k
        if (read_stale_estimates && (chainparams.GetChainType() != ChainType::REGTEST)) {
1688
4
            return InitError(strprintf(_("acceptstalefeeestimates is not supported on %s chain."), chainparams.GetChainTypeString()));
1689
4
        }
1690
1.07k
        node.fee_estimator = std::make_unique<CBlockPolicyEstimator>(FeeestPath(args), read_stale_estimates);
1691
1692
        // Flush estimates to disk periodically
1693
1.07k
        CBlockPolicyEstimator* fee_estimator = node.fee_estimator.get();
1694
1.07k
        scheduler.scheduleEvery([fee_estimator] { fee_estimator->FlushFeeEstimates(); }, FEE_FLUSH_INTERVAL);
1695
1.07k
        validation_signals.RegisterValidationInterface(fee_estimator);
1696
1.07k
    }
1697
1698
1.08k
    for (const std::string& socket_addr : args.GetArgs("-bind")) {
1699
1.07k
        std::string host_out;
1700
1.07k
        uint16_t port_out{0};
1701
1.07k
        std::string bind_socket_addr = socket_addr.substr(0, socket_addr.rfind('='));
1702
1.07k
        if (!SplitHostPort(bind_socket_addr, port_out, host_out)) {
1703
0
            return InitError(InvalidPortErrMsg("-bind", socket_addr));
1704
0
        }
1705
1.07k
    }
1706
1707
    // sanitize comments per BIP-0014, format user agent and check total size
1708
1.08k
    std::vector<std::string> uacomments;
1709
1.09k
    for (const std::string& cmt : args.GetArgs("-uacomment")) {
1710
1.09k
        if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1711
6
            return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1712
1.09k
        uacomments.push_back(cmt);
1713
1.09k
    }
1714
1.07k
    strSubVersion = FormatSubVersion(UA_NAME, CLIENT_VERSION, uacomments);
1715
1.07k
    if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1716
1
        return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1717
1
            strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1718
1
    }
1719
1720
    // Requesting DNS seeds entails connecting to IPv4/IPv6, which -onlynet options may prohibit:
1721
    // If -dnsseed=1 is explicitly specified, abort. If it's left unspecified by the user, we skip
1722
    // the DNS seeds by adjusting -dnsseed in InitParameterInteraction.
1723
1.07k
    if (args.GetBoolArg("-dnsseed") == true && !g_reachable_nets.Contains(NET_IPV4) && !g_reachable_nets.Contains(NET_IPV6)) {
1724
1
        return InitError(strprintf(_("Incompatible options: -dnsseed=1 was explicitly specified, but -onlynet forbids connections to IPv4/IPv6")));
1725
1.07k
    };
1726
1727
    // Check for host lookup allowed before parsing any network related parameters
1728
1.07k
    fNameLookup = args.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1729
1730
1.07k
    bool proxyRandomize = args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1731
    // -proxy sets a proxy for outgoing network traffic, possibly per network.
1732
    // -noproxy, -proxy=0 or -proxy="" can be used to remove the proxy setting, this is the default
1733
1.07k
    Proxy ipv4_proxy;
1734
1.07k
    Proxy ipv6_proxy;
1735
1.07k
    Proxy onion_proxy;
1736
1.07k
    Proxy name_proxy;
1737
1.07k
    Proxy cjdns_proxy;
1738
1.07k
    for (const std::string& param_value : args.GetArgs("-proxy")) {
1739
50
        const auto eq_pos{param_value.rfind('=')};
1740
50
        const std::string proxy_str{param_value.substr(0, eq_pos)}; // e.g. 127.0.0.1:9050=ipv4 -> 127.0.0.1:9050
1741
50
        std::string net_str;
1742
50
        if (eq_pos != std::string::npos) {
1743
7
            if (eq_pos + 1 == param_value.length()) {
1744
1
                return InitError(strprintf(_("Invalid -proxy address or hostname, ends with '=': '%s'"), param_value));
1745
1
            }
1746
6
            net_str = ToLower(param_value.substr(eq_pos + 1)); // e.g. 127.0.0.1:9050=ipv4 -> ipv4
1747
6
        }
1748
1749
49
        Proxy proxy;
1750
49
        if (!proxy_str.empty() && proxy_str != "0") {
1751
48
            if (IsUnixSocketPath(proxy_str)) {
1752
1
                proxy = Proxy{proxy_str, /*tor_stream_isolation=*/proxyRandomize};
1753
47
            } else {
1754
47
                const std::optional<CService> addr{Lookup(proxy_str, DEFAULT_TOR_SOCKS_PORT, fNameLookup)};
1755
47
                if (!addr.has_value()) {
1756
2
                    return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxy_str));
1757
2
                }
1758
45
                proxy = Proxy{addr.value(), /*tor_stream_isolation=*/proxyRandomize};
1759
45
            }
1760
46
            if (!proxy.IsValid()) {
1761
0
                return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxy_str));
1762
0
            }
1763
46
        }
1764
1765
47
        if (net_str.empty()) { // For all networks.
1766
41
            ipv4_proxy = ipv6_proxy = name_proxy = cjdns_proxy = onion_proxy = proxy;
1767
41
        } else if (net_str == "ipv4") {
1768
1
            ipv4_proxy = name_proxy = proxy;
1769
5
        } else if (net_str == "ipv6") {
1770
2
            ipv6_proxy = name_proxy = proxy;
1771
3
        } else if (net_str == "onion") {
1772
1
            onion_proxy = proxy;
1773
2
        } else if (net_str == "cjdns") {
1774
1
            cjdns_proxy = proxy;
1775
1
        } else {
1776
1
            return InitError(strprintf(_("Unrecognized network in -proxy='%s': '%s'"), param_value, net_str));
1777
1
        }
1778
47
    }
1779
1.07k
    if (ipv4_proxy.IsValid()) {
1780
42
        SetProxy(NET_IPV4, ipv4_proxy);
1781
42
    }
1782
1.07k
    if (ipv6_proxy.IsValid()) {
1783
43
        SetProxy(NET_IPV6, ipv6_proxy);
1784
43
    }
1785
1.07k
    if (name_proxy.IsValid()) {
1786
43
        SetNameProxy(name_proxy);
1787
43
    }
1788
1.07k
    if (cjdns_proxy.IsValid()) {
1789
40
        SetProxy(NET_CJDNS, cjdns_proxy);
1790
40
    }
1791
1792
1.07k
    const bool onlynet_used_with_onion{!onlynets.empty() && g_reachable_nets.Contains(NET_ONION)};
1793
1794
    // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1795
    // -noonion (or -onion=0) disables connecting to .onion entirely
1796
    // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1797
1.07k
    std::string onionArg = args.GetArg("-onion", "");
1798
1.07k
    if (onionArg != "") {
1799
12
        if (onionArg == "0") { // Handle -noonion/-onion=0
1800
3
            onion_proxy = Proxy{};
1801
3
            if (onlynet_used_with_onion) {
1802
2
                return InitError(
1803
2
                    _("Outbound connections restricted to Tor (-onlynet=onion) but the proxy for "
1804
2
                      "reaching the Tor network is explicitly forbidden: -onion=0"));
1805
2
            }
1806
9
        } else {
1807
9
            if (IsUnixSocketPath(onionArg)) {
1808
1
                onion_proxy = Proxy(onionArg, /*tor_stream_isolation=*/proxyRandomize);
1809
8
            } else {
1810
8
                const std::optional<CService> addr{Lookup(onionArg, DEFAULT_TOR_SOCKS_PORT, fNameLookup)};
1811
8
                if (!addr.has_value() || !addr->IsValid()) {
1812
1
                    return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1813
1
                }
1814
1815
7
                onion_proxy = Proxy(addr.value(), /*tor_stream_isolation=*/proxyRandomize);
1816
7
            }
1817
9
        }
1818
12
    }
1819
1820
1.06k
    const bool listenonion{args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)};
1821
1.06k
    if (onion_proxy.IsValid()) {
1822
45
        SetProxy(NET_ONION, onion_proxy);
1823
1.02k
    } else {
1824
        // If -listenonion is set, then we will (try to) connect to the Tor control port
1825
        // later from the torcontrol thread and may retrieve the onion proxy from there.
1826
1.02k
        if (onlynet_used_with_onion && !listenonion) {
1827
1
            return InitError(
1828
1
                _("Outbound connections restricted to Tor (-onlynet=onion) but the proxy for "
1829
1
                  "reaching the Tor network is not provided: none of -proxy, -onion or "
1830
1
                  "-listenonion is given"));
1831
1
        }
1832
1.02k
        g_reachable_nets.Remove(NET_ONION);
1833
1.02k
    }
1834
1835
1.06k
    for (const std::string& strAddr : args.GetArgs("-externalip")) {
1836
13
        const std::optional<CService> addrLocal{Lookup(strAddr, GetListenPort(), fNameLookup)};
1837
13
        if (addrLocal.has_value() && addrLocal->IsValid())
1838
13
            AddLocal(addrLocal.value(), LOCAL_MANUAL, /*add_even_if_unreachable=*/true);
1839
0
        else
1840
0
            return InitError(ResolveErrMsg("externalip", strAddr));
1841
13
    }
1842
1843
#ifdef ENABLE_ZMQ
1844
    g_zmq_notification_interface = CZMQNotificationInterface::Create(
1845
        [&chainman = node.chainman](std::vector<std::byte>& block, const CBlockIndex& index) {
1846
            assert(chainman);
1847
            if (auto ret{chainman->m_blockman.ReadRawBlock(WITH_LOCK(cs_main, return index.GetBlockPos()))}) {
1848
                block = std::move(*ret);
1849
                return true;
1850
            }
1851
            return false;
1852
        });
1853
1854
    if (g_zmq_notification_interface) {
1855
        validation_signals.RegisterValidationInterface(g_zmq_notification_interface.get());
1856
    }
1857
#endif
1858
1859
    // ********************************************************* Step 7: load block chain
1860
1861
    // cache size calculations
1862
1.06k
    node::LogOversizedDbCache(args);
1863
1.06k
    const auto [index_cache_sizes, kernel_cache_sizes] = CalculateCacheSizes(args, g_enabled_filter_types.size());
1864
1865
1.06k
    LogInfo("Cache configuration:");
1866
1.06k
    LogInfo("* Using %.1f MiB for block index database", kernel_cache_sizes.block_tree_db / double(1_MiB));
1867
1.06k
    if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1868
46
        LogInfo("* Using %.1f MiB for transaction index database", index_cache_sizes.tx_index / double(1_MiB));
1869
46
    }
1870
1.06k
    if (args.GetBoolArg("-txospenderindex", DEFAULT_TXOSPENDERINDEX)) {
1871
34
        LogInfo("* Using %.1f MiB for transaction output spender index database", index_cache_sizes.txospender_index / double(1_MiB));
1872
34
    }
1873
1.06k
    for (BlockFilterType filter_type : g_enabled_filter_types) {
1874
50
        LogInfo("* Using %.1f MiB for %s block filter index database",
1875
50
                  index_cache_sizes.filter_index / double(1_MiB), BlockFilterTypeName(filter_type));
1876
50
    }
1877
1.06k
    LogInfo("* Using %.1f MiB for chain state database", kernel_cache_sizes.coins_db / double(1_MiB));
1878
1879
1.06k
    assert(!node.mempool);
1880
1.06k
    assert(!node.chainman);
1881
1882
1.06k
    bool do_reindex{args.GetBoolArg("-reindex", false)};
1883
1.06k
    const bool do_reindex_chainstate{args.GetBoolArg("-reindex-chainstate", false)};
1884
1885
    // Chainstate initialization and loading may be retried once with reindexing by GUI users
1886
1.06k
    auto [status, error] = InitAndLoadChainstate(
1887
1.06k
        node,
1888
1.06k
        do_reindex,
1889
1.06k
        do_reindex_chainstate,
1890
1.06k
        kernel_cache_sizes,
1891
1.06k
        args);
1892
1.06k
    if (status == ChainstateLoadStatus::FAILURE && !do_reindex && !ShutdownRequested(node)) {
1893
        // suggest a reindex
1894
12
        bool do_retry{HasTestOption(args, "reindex_after_failure_noninteractive_yes") ||
1895
12
            uiInterface.ThreadSafeQuestion(
1896
11
            error + Untranslated(".\n\n") + _("Do you want to rebuild the databases now?"),
1897
11
            error.original + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1898
11
            CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT)};
1899
12
        if (!do_retry) {
1900
11
            return false;
1901
11
        }
1902
1
        do_reindex = true;
1903
1
        if (!Assert(node.shutdown_signal)->reset()) {
1904
0
            LogError("Internal error: failed to reset shutdown signal.\n");
1905
0
        }
1906
1
        std::tie(status, error) = InitAndLoadChainstate(
1907
1
            node,
1908
1
            do_reindex,
1909
1
            do_reindex_chainstate,
1910
1
            kernel_cache_sizes,
1911
1
            args);
1912
1
    }
1913
1.05k
    if (status != ChainstateLoadStatus::SUCCESS && status != ChainstateLoadStatus::INTERRUPTED) {
1914
3
        return InitError(error);
1915
3
    }
1916
1917
    // As LoadBlockIndex can take several minutes, it's possible the user
1918
    // requested to kill the GUI during the last operation. If so, exit.
1919
1.05k
    if (ShutdownRequested(node)) {
1920
11
        LogInfo("Shutdown requested. Exiting.");
1921
11
        return true;
1922
11
    }
1923
1924
1.04k
    ChainstateManager& chainman = *Assert(node.chainman);
1925
1.04k
    auto& kernel_notifications{*Assert(node.notifications)};
1926
1927
1.04k
    assert(!node.peerman);
1928
1.04k
    node.peerman = PeerManager::make(*node.connman, *node.addrman,
1929
1.04k
                                     node.banman.get(), chainman,
1930
1.04k
                                     *node.mempool, *node.warnings,
1931
1.04k
                                     peerman_opts);
1932
1.04k
    validation_signals.RegisterValidationInterface(node.peerman.get());
1933
1934
    // ********************************************************* Step 8: start indexers
1935
1936
1.04k
    if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1937
36
        g_txindex = std::make_unique<TxIndex>(interfaces::MakeChain(node), index_cache_sizes.tx_index, false, do_reindex);
1938
36
        node.indexes.emplace_back(g_txindex.get());
1939
36
    }
1940
1941
1.04k
    if (args.GetBoolArg("-txospenderindex", DEFAULT_TXOSPENDERINDEX)) {
1942
24
        g_txospenderindex = std::make_unique<TxoSpenderIndex>(interfaces::MakeChain(node), index_cache_sizes.txospender_index, false, do_reindex);
1943
24
        node.indexes.emplace_back(g_txospenderindex.get());
1944
24
    }
1945
1946
1.04k
    for (const auto& filter_type : g_enabled_filter_types) {
1947
40
        InitBlockFilterIndex([&]{ return interfaces::MakeChain(node); }, filter_type, index_cache_sizes.filter_index, false, do_reindex);
1948
40
        node.indexes.emplace_back(GetBlockFilterIndex(filter_type));
1949
40
    }
1950
1951
1.04k
    if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
1952
41
        g_coin_stats_index = std::make_unique<CoinStatsIndex>(interfaces::MakeChain(node), /*cache_size=*/0, false, do_reindex);
1953
41
        node.indexes.emplace_back(g_coin_stats_index.get());
1954
41
    }
1955
1956
    // Init indexes
1957
1.04k
    for (auto index : node.indexes) if (!index->Init()) return false;
1958
1959
    // ********************************************************* Step 9: load wallet
1960
1.04k
    for (const auto& client : node.chain_clients) {
1961
352
        if (!client->load()) {
1962
0
            return false;
1963
0
        }
1964
352
    }
1965
1966
    // ********************************************************* Step 10: data directory maintenance
1967
1968
    // if pruning, perform the initial blockstore prune
1969
    // after any wallet rescanning has taken place.
1970
1.04k
    if (chainman.m_blockman.IsPruneMode()) {
1971
39
        if (chainman.m_blockman.m_blockfiles_indexed) {
1972
37
            LOCK(cs_main);
1973
37
            for (const auto& chainstate : chainman.m_chainstates) {
1974
37
                uiInterface.InitMessage(_("Pruning blockstore…"));
1975
37
                chainstate->PruneAndFlush();
1976
37
            }
1977
37
        }
1978
1.00k
    } else {
1979
        // Prior to setting NODE_NETWORK, check if we can provide historical blocks.
1980
1.00k
        if (!WITH_LOCK(chainman.GetMutex(), return chainman.HistoricalChainstate())) {
1981
994
            LogInfo("Setting NODE_NETWORK in non-prune mode");
1982
994
            g_local_services = ServiceFlags(g_local_services | NODE_NETWORK);
1983
994
        } else {
1984
8
            LogInfo("Running node in NODE_NETWORK_LIMITED mode until snapshot background sync completes");
1985
8
        }
1986
1.00k
    }
1987
1988
    // ********************************************************* Step 11: import blocks
1989
1990
1.04k
    if (!CheckDiskSpace(args.GetDataDirNet())) {
1991
0
        InitError(strprintf(_("Error: Disk space is low for %s"), fs::quoted(fs::PathToString(args.GetDataDirNet()))));
1992
0
        return false;
1993
0
    }
1994
1.04k
    if (!CheckDiskSpace(args.GetBlocksDirPath())) {
1995
0
        InitError(strprintf(_("Error: Disk space is low for %s"), fs::quoted(fs::PathToString(args.GetBlocksDirPath()))));
1996
0
        return false;
1997
0
    }
1998
1999
1.04k
    int chain_active_height = WITH_LOCK(cs_main, return chainman.ActiveChain().Height());
2000
2001
    // On first startup, warn on low block storage space
2002
1.04k
    if (!do_reindex && !do_reindex_chainstate && chain_active_height <= 1) {
2003
428
        uint64_t assumed_chain_bytes{chainparams.AssumedBlockchainSize() * 1_GiB};
2004
428
        uint64_t additional_bytes_needed{
2005
428
            chainman.m_blockman.IsPruneMode() ?
2006
21
                std::min(chainman.m_blockman.GetPruneTarget(), assumed_chain_bytes) :
2007
428
                assumed_chain_bytes};
2008
2009
428
        if (!CheckDiskSpace(args.GetBlocksDirPath(), additional_bytes_needed)) {
2010
1
            InitWarning(strprintf(_(
2011
1
                    "Disk space for %s may not accommodate the block files. " \
2012
1
                    "Approximately %u GB of data will be stored in this directory."
2013
1
                ),
2014
1
                fs::quoted(fs::PathToString(args.GetBlocksDirPath())),
2015
1
                chainparams.AssumedBlockchainSize()
2016
1
            ));
2017
1
        }
2018
428
    }
2019
2020
#ifdef __APPLE__
2021
    auto check_and_warn_fs{[&](const fs::path& path, std::string_view desc) {
2022
        const auto path_desc{strprintf("%s (\"%s\")", desc, fs::PathToString(path))};
2023
        switch (GetFilesystemType(path)) {
2024
        case FSType::EXFAT:
2025
            InitWarning(strprintf(_("The %s path uses exFAT, which is known to have intermittent corruption problems on macOS. "
2026
                "Move this directory to a different filesystem to avoid data loss."), path_desc));
2027
            break;
2028
        case FSType::ERROR:
2029
            LogInfo("Failed to detect filesystem type for %s", path_desc);
2030
            break;
2031
        case FSType::OTHER:
2032
            break;
2033
        }
2034
    }};
2035
2036
    check_and_warn_fs(args.GetDataDirNet(), "data directory");
2037
    check_and_warn_fs(args.GetBlocksDirPath(), "blocks directory");
2038
#endif
2039
2040
1.04k
#if HAVE_SYSTEM
2041
1.04k
    const std::string block_notify = args.GetArg("-blocknotify", "");
2042
1.04k
    if (!block_notify.empty()) {
2043
113
        uiInterface.NotifyBlockTip.connect([block_notify](SynchronizationState sync_state, const CBlockIndex& block, double /* verification_progress */) {
2044
113
            if (sync_state != SynchronizationState::POST_INIT) return;
2045
112
            std::string command = block_notify;
2046
112
            ReplaceAll(command, "%s", block.GetBlockHash().GetHex());
2047
112
            std::thread t(runCommand, command);
2048
112
            t.detach(); // thread runs free
2049
112
        });
2050
1
    }
2051
1.04k
#endif
2052
2053
1.04k
    std::vector<fs::path> vImportFiles;
2054
1.04k
    for (const std::string& strFile : args.GetArgs("-loadblock")) {
2055
1
        vImportFiles.push_back(fs::PathFromString(strFile));
2056
1
    }
2057
2058
    /// \anchor initload
2059
1.04k
    node.background_init_thread = std::thread(&util::TraceThread, "initload", [=, &chainman, &args, &kernel_notifications, &node] {
2060
1.03k
        ScheduleBatchPriority();
2061
        // Import blocks and ActivateBestChain()
2062
1.03k
        ImportBlocks(chainman, vImportFiles);
2063
        // An interrupted import may return without activating genesis. Wake
2064
        // the init thread's genesis wait, which is otherwise only notified
2065
        // on blockTip, and that never fires when the import was interrupted
2066
        // before activating genesis. This wakeup lets the wait observe the
2067
        // shutdown request.
2068
1.03k
        WITH_LOCK(kernel_notifications.m_tip_block_mutex, kernel_notifications.m_tip_block_cv.notify_all());
2069
1.03k
        WITH_LOCK(::cs_main, chainman.UpdateIBDStatus());
2070
1.03k
        if (args.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
2071
0
            LogInfo("Stopping after block import");
2072
0
            if (!(Assert(node.shutdown_request))()) {
2073
0
                LogError("Failed to send shutdown signal after finishing block import\n");
2074
0
            }
2075
0
            return;
2076
0
        }
2077
2078
        // Start indexes initial sync
2079
1.03k
        if (!StartIndexBackgroundSync(node)) {
2080
0
            bilingual_str err_str = _("Failed to start indexes, shutting down…");
2081
0
            chainman.GetNotifications().fatalError(err_str);
2082
0
            return;
2083
0
        }
2084
        // Load mempool from disk
2085
1.03k
        if (auto* pool{chainman.ActiveChainstate().GetMempool()}) {
2086
1.03k
            LoadMempool(*pool, ShouldPersistMempool(args) ? MempoolPath(args) : fs::path{}, chainman.ActiveChainstate(), {});
2087
1.03k
            pool->SetLoadTried(!chainman.m_interrupt);
2088
1.03k
        }
2089
1.03k
    });
2090
2091
    /*
2092
     * Wait for genesis block to be processed. Typically kernel_notifications.m_tip_block
2093
     * has already been set by a call to LoadChainTip() in CompleteChainstateInitialization().
2094
     * But this is skipped if the chainstate doesn't exist yet or is being wiped:
2095
     *
2096
     * 1. first startup with an empty datadir
2097
     * 2. reindex
2098
     * 3. reindex-chainstate
2099
     *
2100
     * In these case it's connected by a call to ActivateBestChain() in the initload thread.
2101
     */
2102
1.04k
    {
2103
1.04k
        WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
2104
1.34k
        kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
2105
1.34k
            return kernel_notifications.TipBlock() || ShutdownRequested(node);
2106
1.34k
        });
2107
1.04k
    }
2108
2109
1.04k
    if (ShutdownRequested(node)) {
2110
1
        return true;
2111
1
    }
2112
2113
    // ********************************************************* Step 12: start node
2114
2115
1.04k
    int64_t best_block_time{};
2116
1.04k
    {
2117
1.04k
        LOCK(chainman.GetMutex());
2118
1.04k
        const auto& tip{*Assert(chainman.ActiveTip())};
2119
1.04k
        LogInfo("block tree size = %u", chainman.BlockIndex().size());
2120
1.04k
        chain_active_height = tip.nHeight;
2121
1.04k
        best_block_time = tip.GetBlockTime();
2122
1.04k
        if (tip_info) {
2123
0
            tip_info->block_height = chain_active_height;
2124
0
            tip_info->block_time = best_block_time;
2125
0
            tip_info->verification_progress = chainman.GuessVerificationProgress(&tip);
2126
0
        }
2127
1.04k
        if (tip_info && chainman.m_best_header) {
2128
0
            tip_info->header_height = chainman.m_best_header->nHeight;
2129
0
            tip_info->header_time = chainman.m_best_header->GetBlockTime();
2130
0
        }
2131
1.04k
    }
2132
1.04k
    LogInfo("nBestHeight = %d", chain_active_height);
2133
1.04k
    if (node.peerman) node.peerman->SetBestBlock(chain_active_height, std::chrono::seconds{best_block_time});
2134
2135
    // Map ports with NAT-PMP
2136
1.04k
    StartMapPort(args.GetBoolArg("-natpmp", DEFAULT_NATPMP));
2137
2138
1.04k
    CConnman::Options connOptions;
2139
1.04k
    connOptions.m_local_services = g_local_services;
2140
1.04k
    connOptions.m_max_automatic_connections = nMaxConnections;
2141
1.04k
    connOptions.m_full_relay_inbound_percent = std::clamp<int>(args.GetIntArg("-inboundrelaypercent", DEFAULT_FULL_RELAY_INBOUND_PCT), 0, 100);
2142
1.04k
    connOptions.uiInterface = &uiInterface;
2143
1.04k
    connOptions.m_banman = node.banman.get();
2144
1.04k
    connOptions.m_msgproc = node.peerman.get();
2145
1.04k
    connOptions.nSendBufferMaxSize = 1000 * args.GetIntArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
2146
1.04k
    connOptions.nReceiveFloodSize = 1000 * args.GetIntArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
2147
1.04k
    for (const std::string& added_node : args.GetArgs("-addnode")) {
2148
        // Such a value is not a valid connection target, but would otherwise be
2149
        // treated as one and retried indefinitely.
2150
6
        if (TrimStringView(added_node).empty()) {
2151
3
            LogWarning("Ignoring empty -addnode value");
2152
3
            continue;
2153
3
        }
2154
3
        connOptions.m_added_nodes.push_back(added_node);
2155
3
    }
2156
1.04k
    connOptions.nMaxOutboundLimit = *opt_max_upload;
2157
1.04k
    connOptions.m_peer_connect_timeout = peer_connect_timeout;
2158
1.04k
    connOptions.whitelist_forcerelay = args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY);
2159
1.04k
    connOptions.whitelist_relay = args.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY);
2160
1.04k
    connOptions.m_capture_messages = args.GetBoolArg("-capturemessages", false);
2161
2162
    // Port to bind to if `-bind=addr` is provided without a `:port` suffix.
2163
1.04k
    const uint16_t default_bind_port =
2164
1.04k
        static_cast<uint16_t>(args.GetIntArg("-port", Params().GetDefaultPort()));
2165
2166
1.04k
    const uint16_t default_bind_port_onion = default_bind_port + 1;
2167
2168
1.04k
    const auto BadPortWarning = [](const char* prefix, uint16_t port) {
2169
0
        return strprintf(_("%s request to listen on port %u. This port is considered \"bad\" and "
2170
0
                           "thus it is unlikely that any peer will connect to it. See "
2171
0
                           "doc/p2p-bad-ports.md for details and a full list."),
2172
0
                         prefix,
2173
0
                         port);
2174
0
    };
2175
2176
1.04k
    for (const std::string& bind_arg : args.GetArgs("-bind")) {
2177
1.02k
        std::optional<CService> bind_addr;
2178
1.02k
        const size_t index = bind_arg.rfind('=');
2179
1.02k
        if (index == std::string::npos) {
2180
1.00k
            bind_addr = Lookup(bind_arg, default_bind_port, /*fAllowLookup=*/false);
2181
1.00k
            if (bind_addr.has_value()) {
2182
1.00k
                connOptions.vBinds.push_back(bind_addr.value());
2183
1.00k
                if (IsBadPort(bind_addr.value().GetPort())) {
2184
0
                    InitWarning(BadPortWarning("-bind", bind_addr.value().GetPort()));
2185
0
                }
2186
1.00k
                continue;
2187
1.00k
            }
2188
1.00k
        } else {
2189
22
            const std::string network_type = bind_arg.substr(index + 1);
2190
22
            if (network_type == "onion") {
2191
22
                const std::string truncated_bind_arg = bind_arg.substr(0, index);
2192
22
                bind_addr = Lookup(truncated_bind_arg, default_bind_port_onion, false);
2193
22
                if (bind_addr.has_value()) {
2194
22
                    connOptions.onion_binds.push_back(bind_addr.value());
2195
22
                    continue;
2196
22
                }
2197
22
            }
2198
22
        }
2199
0
        return InitError(ResolveErrMsg("bind", bind_arg));
2200
1.02k
    }
2201
2202
1.04k
    for (const std::string& strBind : args.GetArgs("-whitebind")) {
2203
9
        NetWhitebindPermissions whitebind;
2204
9
        bilingual_str error;
2205
9
        if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) return InitError(error);
2206
8
        connOptions.vWhiteBinds.push_back(whitebind);
2207
8
    }
2208
2209
    // If the user did not specify -bind= or -whitebind= then we bind
2210
    // on any address - 0.0.0.0 (IPv4) and :: (IPv6).
2211
1.03k
    connOptions.bind_on_any = args.GetArgs("-bind").empty() && args.GetArgs("-whitebind").empty();
2212
2213
    // Emit a warning if a bad port is given to -port= but only if -bind and -whitebind are not
2214
    // given, because if they are, then -port= is ignored.
2215
1.03k
    if (connOptions.bind_on_any && args.IsArgSet("-port")) {
2216
21
        const uint16_t port_arg = args.GetIntArg("-port", 0);
2217
21
        if (IsBadPort(port_arg)) {
2218
0
            InitWarning(BadPortWarning("-port", port_arg));
2219
0
        }
2220
21
    }
2221
2222
1.03k
    CService onion_service_target;
2223
1.03k
    if (!connOptions.onion_binds.empty()) {
2224
20
        onion_service_target = connOptions.onion_binds.front();
2225
1.01k
    } else if (!connOptions.vBinds.empty()) {
2226
989
        onion_service_target = connOptions.vBinds.front();
2227
989
    } else {
2228
30
        onion_service_target = DefaultOnionServiceTarget(default_bind_port_onion);
2229
30
        connOptions.onion_binds.push_back(onion_service_target);
2230
30
    }
2231
2232
1.03k
    if (listenonion) {
2233
8
        if (connOptions.onion_binds.size() > 1) {
2234
0
            InitWarning(strprintf(_("More than one onion bind address is provided. Using %s "
2235
0
                                    "for the automatically created Tor onion service."),
2236
0
                                  onion_service_target.ToStringAddrPort()));
2237
0
        }
2238
8
        node.tor_controller = std::make_unique<TorController>(gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL), onion_service_target);
2239
8
    }
2240
2241
1.03k
    bool should_discover = connOptions.bind_on_any;
2242
1.03k
    if (!should_discover) {
2243
1.01k
        for (const auto& bind : connOptions.vBinds) {
2244
1.00k
            if (bind.IsBindAny()) {
2245
13
                should_discover = true;
2246
13
                break;
2247
13
            }
2248
1.00k
        }
2249
1.01k
    }
2250
2251
1.03k
    if (!should_discover) {
2252
997
        for (const auto& whitebind : connOptions.vWhiteBinds) {
2253
6
            if (whitebind.m_service.IsBindAny()) {
2254
1
                should_discover = true;
2255
1
                break;
2256
1
            }
2257
6
        }
2258
997
    }
2259
2260
1.03k
    if (should_discover) {
2261
        // Only add all IP addresses of the machine if we would be listening on
2262
        // any address - 0.0.0.0 (IPv4) and :: (IPv6).
2263
36
        Discover();
2264
36
    }
2265
2266
1.03k
    for (const auto& net : args.GetArgs("-whitelist")) {
2267
146
        NetWhitelistPermissions subnet;
2268
146
        ConnectionDirection connection_direction;
2269
146
        bilingual_str error;
2270
146
        if (!NetWhitelistPermissions::TryParse(net, subnet, connection_direction, error)) return InitError(error);
2271
143
        if (connection_direction & ConnectionDirection::In) {
2272
142
            connOptions.vWhitelistedRangeIncoming.push_back(subnet);
2273
142
        }
2274
143
        if (connection_direction & ConnectionDirection::Out) {
2275
110
            connOptions.vWhitelistedRangeOutgoing.push_back(subnet);
2276
110
        }
2277
143
    }
2278
2279
1.03k
    connOptions.vSeedNodes = args.GetArgs("-seednode");
2280
2281
1.03k
    const auto connect = args.GetArgs("-connect");
2282
1.03k
    if (!connect.empty() || args.IsArgNegated("-connect")) {
2283
        // Do not initiate other outgoing connections when connecting to trusted
2284
        // nodes, or when -noconnect is specified.
2285
993
        connOptions.m_use_addrman_outgoing = false;
2286
2287
993
        if (connect.size() != 1 || connect[0] != "0") {
2288
9
            connOptions.m_specified_outgoing = connect;
2289
9
        }
2290
993
        if (!connOptions.m_specified_outgoing.empty() && !connOptions.vSeedNodes.empty()) {
2291
1
            LogInfo("-seednode is ignored when -connect is used");
2292
1
        }
2293
2294
993
        if (args.IsArgSet("-dnsseed") && args.GetBoolArg("-dnsseed", DEFAULT_DNSSEED) && args.IsArgSet("-proxy")) {
2295
12
            LogInfo("-dnsseed is ignored when -connect is used and -proxy is specified");
2296
12
        }
2297
993
    }
2298
2299
1.03k
    const std::string& i2psam_arg = args.GetArg("-i2psam", "");
2300
1.03k
    if (!i2psam_arg.empty()) {
2301
8
        const std::optional<CService> addr{Lookup(i2psam_arg, 7656, fNameLookup)};
2302
8
        if (!addr.has_value() || !addr->IsValid()) {
2303
1
            return InitError(strprintf(_("Invalid -i2psam address or hostname: '%s'"), i2psam_arg));
2304
1
        }
2305
7
        SetProxy(NET_I2P, Proxy{addr.value()});
2306
1.02k
    } else {
2307
1.02k
        if (!onlynets.empty() && g_reachable_nets.Contains(NET_I2P)) {
2308
1
            return InitError(
2309
1
                _("Outbound connections restricted to i2p (-onlynet=i2p) but "
2310
1
                  "-i2psam is not provided"));
2311
1
        }
2312
1.02k
        g_reachable_nets.Remove(NET_I2P);
2313
1.02k
    }
2314
2315
1.03k
    connOptions.m_i2p_accept_incoming = args.GetBoolArg("-i2pacceptincoming", DEFAULT_I2P_ACCEPT_INCOMING);
2316
2317
1.03k
    if (auto conflict = CheckBindingConflicts(connOptions)) {
2318
6
        return InitError(strprintf(
2319
6
            _("Duplicate binding configuration for address %s. "
2320
6
                "Please check your -bind, -bind=...=onion and -whitebind settings."),
2321
6
                    conflict->ToStringAddrPort()));
2322
6
    }
2323
2324
1.02k
    if (args.GetBoolArg("-privatebroadcast", DEFAULT_PRIVATE_BROADCAST)) {
2325
        // If -listenonion is set, then NET_ONION may not be reachable now
2326
        // but may become reachable later, thus only error here if it is not
2327
        // reachable and will not become reachable for sure.
2328
8
        const bool onion_may_become_reachable{listenonion && (!args.IsArgSet("-onlynet") || onlynet_used_with_onion)};
2329
8
        if (!g_reachable_nets.Contains(NET_I2P) &&
2330
8
            !g_reachable_nets.Contains(NET_ONION) &&
2331
8
            !onion_may_become_reachable) {
2332
1
            return InitError(_("Private broadcast of own transactions requested (-privatebroadcast), "
2333
1
                               "but none of Tor or I2P networks is reachable"));
2334
1
        }
2335
7
        if (!connOptions.m_use_addrman_outgoing) {
2336
1
            return InitError(_("Private broadcast of own transactions requested (-privatebroadcast), "
2337
1
                               "but -connect is also configured. They are incompatible because the "
2338
1
                               "private broadcast needs to open new connections to randomly "
2339
1
                               "chosen Tor or I2P peers. Consider using -maxconnections=0 -addnode=... "
2340
1
                               "instead"));
2341
1
        }
2342
6
        if (!proxyRandomize && (g_reachable_nets.Contains(NET_ONION) || onion_may_become_reachable)) {
2343
1
            InitWarning(_("Private broadcast of own transactions requested (-privatebroadcast) and "
2344
1
                          "-proxyrandomize is disabled. Tor circuits for private broadcast connections "
2345
1
                          "may be correlated to other connections over Tor. For maximum privacy set "
2346
1
                          "-proxyrandomize=1."));
2347
1
        }
2348
6
    }
2349
2350
1.02k
    if (!node.connman->Start(scheduler, connOptions)) {
2351
11
        return false;
2352
11
    }
2353
2354
    // ********************************************************* Step 13: finished
2355
2356
    // At this point, the RPC is "started", but still in warmup, which means it
2357
    // cannot yet be called. Before we make it callable, we need to make sure
2358
    // that the RPC's view of the best block is valid and consistent with
2359
    // ChainstateManager's active tip.
2360
1.01k
    SetRPCWarmupFinished();
2361
2362
1.01k
    uiInterface.InitMessage(_("Done loading"));
2363
2364
1.01k
    for (const auto& client : node.chain_clients) {
2365
349
        client->start(scheduler);
2366
349
    }
2367
2368
1.01k
    BanMan* banman = node.banman.get();
2369
1.01k
    scheduler.scheduleEvery([banman]{
2370
9
        banman->DumpBanlist();
2371
9
    }, DUMP_BANS_INTERVAL);
2372
2373
1.01k
    if (node.peerman) node.peerman->StartScheduledTasks(scheduler);
2374
2375
1.01k
#if HAVE_SYSTEM
2376
1.01k
    StartupNotify(args);
2377
1.01k
#endif
2378
2379
1.01k
    return true;
2380
1.02k
}
2381
2382
bool StartIndexBackgroundSync(NodeContext& node)
2383
1.03k
{
2384
1.03k
    ChainstateManager& chainman = *Assert(node.chainman);
2385
1.03k
    const Chainstate& chainstate = WITH_LOCK(::cs_main, return chainman.ValidatedChainstate());
2386
1.03k
    const CChain& index_chain = chainstate.m_chain;
2387
1.03k
    const int current_height = WITH_LOCK(::cs_main, return index_chain.Height());
2388
2389
    // Skip checking data availability if we have not synced any blocks yet
2390
1.03k
    if (current_height > 0) {
2391
        // Before starting index sync, verify that all required block data is available
2392
        // on disk from each index's current sync position up to the chain tip.
2393
        //
2394
        // This is done separately for undo and block data: First we verify block + undo
2395
        // data existence from tip down to the lowest height required by any index that
2396
        // needs undo data (e.g., coinstatsindex, blockfilterindex). Then, if any
2397
        // block-only index needs to sync from a lower height than previously covered,
2398
        // verify block data existence down to that lower height.
2399
        //
2400
        // This avoids checking undo data for blocks where no index requires it,
2401
        // though currently block and undo data availability are synchronized on disk
2402
        // under normal circumstances.
2403
614
        std::optional<const CBlockIndex*> block_start;
2404
614
        std::string block_start_name;
2405
614
        std::optional<const CBlockIndex*> undo_start;
2406
614
        std::string undo_start_name;
2407
2408
614
        for (const auto& index : node.indexes) {
2409
116
            const IndexSummary& summary = index->GetSummary();
2410
116
            if (summary.synced) continue;
2411
2412
            // Get the last common block between the index best block and the active chain
2413
72
            const CBlockIndex* pindex = nullptr;
2414
72
            {
2415
72
                LOCK(::cs_main);
2416
72
                pindex = chainman.m_blockman.LookupBlockIndex(summary.best_block_hash);
2417
72
                if (!pindex) {
2418
0
                    LogWarning("Failed to find block manager entry for best block %s from %s, falling back to genesis for index sync",
2419
0
                        summary.best_block_hash.ToString(), summary.name);
2420
72
                } else if (!index_chain.Contains(*pindex)) {
2421
1
                    pindex = index_chain.FindFork(*pindex);
2422
1
                }
2423
72
            }
2424
72
            if (!pindex) {
2425
0
                pindex = index_chain.Genesis();
2426
0
            }
2427
2428
72
            bool need_undo = index->CustomOptions().connect_undo_data;
2429
72
            auto& op_start_index = need_undo ? undo_start : block_start;
2430
72
            auto& name_index = need_undo ? undo_start_name : block_start_name;
2431
2432
72
            if (op_start_index && pindex->nHeight >= op_start_index.value()->nHeight) continue;
2433
59
            op_start_index = pindex;
2434
59
            name_index = summary.name;
2435
59
        }
2436
2437
        // Verify all blocks needed to sync to current tip are present including undo data.
2438
614
        if (undo_start) {
2439
24
            LOCK(::cs_main);
2440
24
            if (!chainman.m_blockman.CheckBlockDataAvailability(*index_chain.Tip(), *Assert(undo_start.value()), BlockStatus{BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO})) {
2441
0
                return InitError(Untranslated(strprintf("%s best block of the index goes beyond pruned data (including undo data). Please disable the index or reindex (which will download the whole blockchain again)", undo_start_name)));
2442
0
            }
2443
24
        }
2444
2445
        // Verify all blocks needed to sync to current tip are present unless we already checked all of them above.
2446
614
        if (block_start && !(undo_start && undo_start.value()->nHeight <= block_start.value()->nHeight)) {
2447
5
            LOCK(::cs_main);
2448
5
            if (!chainman.m_blockman.CheckBlockDataAvailability(*index_chain.Tip(), *Assert(block_start.value()), BlockStatus{BLOCK_HAVE_DATA})) {
2449
0
                return InitError(Untranslated(strprintf("%s best block of the index goes beyond pruned data. Please disable the index or reindex (which will download the whole blockchain again)", block_start_name)));
2450
0
            }
2451
5
        }
2452
614
    }
2453
2454
    // Start threads
2455
1.03k
    for (auto index : node.indexes) if (!index->StartBackgroundSync()) return false;
2456
1.03k
    return true;
2457
1.03k
}