]>
Commit | Line | Data |
---|---|---|
69d605f4 | 1 | // Copyright (c) 2009-2010 Satoshi Nakamoto |
57702541 | 2 | // Copyright (c) 2009-2014 The Bitcoin developers |
69d605f4 | 3 | // Distributed under the MIT/X11 software license, see the accompanying |
3a25a2b9 | 4 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. |
5350ea41 | 5 | |
35b8af92 | 6 | #if defined(HAVE_CONFIG_H) |
f3967bcc | 7 | #include "config/bitcoin-config.h" |
35b8af92 CF |
8 | #endif |
9 | ||
663224c2 | 10 | #include "init.h" |
51ed9ec9 BD |
11 | |
12 | #include "addrman.h" | |
eda37330 | 13 | #include "amount.h" |
51ed9ec9 | 14 | #include "checkpoints.h" |
611116d4 | 15 | #include "compat/sanity.h" |
4a09e1df | 16 | #include "key.h" |
a9a37c8b | 17 | #include "main.h" |
d247a5d1 | 18 | #include "miner.h" |
51ed9ec9 | 19 | #include "net.h" |
a9a37c8b | 20 | #include "rpcserver.h" |
2aa63292 | 21 | #include "script/standard.h" |
51ed9ec9 | 22 | #include "txdb.h" |
ed6d0b5f | 23 | #include "ui_interface.h" |
51ed9ec9 | 24 | #include "util.h" |
ad49c256 | 25 | #include "utilmoneystr.h" |
48ba56cd | 26 | #ifdef ENABLE_WALLET |
df840de5 | 27 | #include "db.h" |
51ed9ec9 BD |
28 | #include "wallet.h" |
29 | #include "walletdb.h" | |
48ba56cd | 30 | #endif |
5350ea41 | 31 | |
51ed9ec9 | 32 | #include <stdint.h> |
283e405c | 33 | #include <stdio.h> |
69d605f4 | 34 | |
ed6d0b5f PW |
35 | #ifndef WIN32 |
36 | #include <signal.h> | |
52d3a481 | 37 | #endif |
5f2e76b8 | 38 | |
51ed9ec9 | 39 | #include <boost/algorithm/string/predicate.hpp> |
e9dd83f0 | 40 | #include <boost/algorithm/string/replace.hpp> |
51ed9ec9 BD |
41 | #include <boost/filesystem.hpp> |
42 | #include <boost/interprocess/sync/file_lock.hpp> | |
ad49c256 | 43 | #include <boost/thread.hpp> |
51ed9ec9 BD |
44 | #include <openssl/crypto.h> |
45 | ||
69d605f4 | 46 | using namespace boost; |
00d1980b | 47 | using namespace std; |
69d605f4 | 48 | |
48ba56cd | 49 | #ifdef ENABLE_WALLET |
20a11ffa | 50 | CWallet* pwalletMain = NULL; |
48ba56cd | 51 | #endif |
94064710 | 52 | bool fFeeEstimatesInitialized = false; |
e8ef3da7 | 53 | |
ba29a559 PW |
54 | #ifdef WIN32 |
55 | // Win32 LevelDB doesn't use filedescriptors, and the ones used for | |
56 | // accessing block files, don't count towards to fd_set size limit | |
57 | // anyway. | |
58 | #define MIN_CORE_FILEDESCRIPTORS 0 | |
59 | #else | |
60 | #define MIN_CORE_FILEDESCRIPTORS 150 | |
61 | #endif | |
62 | ||
c73323ee PK |
63 | // Used to pass flags to the Bind() function |
64 | enum BindFlags { | |
29e214aa PK |
65 | BF_NONE = 0, |
66 | BF_EXPLICIT = (1U << 0), | |
dc942e6f PW |
67 | BF_REPORT_ERROR = (1U << 1), |
68 | BF_WHITELIST = (1U << 2), | |
c73323ee PK |
69 | }; |
70 | ||
171ca774 | 71 | static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat"; |
73ac7abd | 72 | CClientUIInterface uiInterface; |
4751d07e | 73 | |
69d605f4 WL |
74 | ////////////////////////////////////////////////////////////////////////////// |
75 | // | |
76 | // Shutdown | |
77 | // | |
78 | ||
b31499ec GA |
79 | // |
80 | // Thread management and startup/shutdown: | |
81 | // | |
82 | // The network-processing threads are all part of a thread group | |
83 | // created by AppInit() or the Qt main() function. | |
84 | // | |
85 | // A clean exit happens when StartShutdown() or the SIGTERM | |
86 | // signal handler sets fRequestShutdown, which triggers | |
87 | // the DetectShutdownThread(), which interrupts the main thread group. | |
88 | // DetectShutdownThread() then exits, which causes AppInit() to | |
89 | // continue (it .joins the shutdown thread). | |
90 | // Shutdown() is then | |
91 | // called to clean up database connections, and stop other | |
92 | // threads that should only be stopped after the main network-processing | |
93 | // threads have exited. | |
94 | // | |
95 | // Note that if running -daemon the parent process returns from AppInit2 | |
96 | // before adding any threads to the threadGroup, so .join_all() returns | |
97 | // immediately and the parent exits from main(). | |
98 | // | |
99 | // Shutdown for Qt is very similar, only it uses a QTimer to detect | |
723035bb GA |
100 | // fRequestShutdown getting set, and then does the normal Qt |
101 | // shutdown thing. | |
b31499ec GA |
102 | // |
103 | ||
104 | volatile bool fRequestShutdown = false; | |
69d605f4 | 105 | |
9247134e PK |
106 | void StartShutdown() |
107 | { | |
b31499ec | 108 | fRequestShutdown = true; |
9247134e | 109 | } |
723035bb GA |
110 | bool ShutdownRequested() |
111 | { | |
112 | return fRequestShutdown; | |
113 | } | |
9247134e | 114 | |
20a11ffa | 115 | static CCoinsViewDB *pcoinsdbview = NULL; |
ae8bfd12 | 116 | |
b31499ec | 117 | void Shutdown() |
69d605f4 | 118 | { |
00d1980b | 119 | LogPrintf("%s: In progress...\n", __func__); |
69d605f4 | 120 | static CCriticalSection cs_Shutdown; |
b31499ec | 121 | TRY_LOCK(cs_Shutdown, lockShutdown); |
00d1980b PK |
122 | if (!lockShutdown) |
123 | return; | |
96931d6f | 124 | |
94064710 WL |
125 | /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way, |
126 | /// for example if the data directory was found to be locked. | |
127 | /// Be sure that anything that writes files or flushes caches only does this if the respective | |
128 | /// module was initialized. | |
96931d6f | 129 | RenameThread("bitcoin-shutoff"); |
319b1160 | 130 | mempool.AddTransactionsUpdated(1); |
21eb5ada | 131 | StopRPCThreads(); |
4a85e067 | 132 | #ifdef ENABLE_WALLET |
b0730874 JG |
133 | if (pwalletMain) |
134 | bitdb.Flush(false); | |
c8b74258 | 135 | GenerateBitcoins(false, NULL, 0); |
48ba56cd | 136 | #endif |
21eb5ada | 137 | StopNode(); |
b2864d2f | 138 | UnregisterNodeSignals(GetNodeSignals()); |
171ca774 | 139 | |
94064710 | 140 | if (fFeeEstimatesInitialized) |
09c744c2 PW |
141 | { |
142 | boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; | |
143 | CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION); | |
a8738238 | 144 | if (!est_fileout.IsNull()) |
09c744c2 PW |
145 | mempool.WriteFeeEstimates(est_fileout); |
146 | else | |
147 | LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string()); | |
94064710 | 148 | fFeeEstimatesInitialized = false; |
09c744c2 | 149 | } |
171ca774 | 150 | |
69d605f4 | 151 | { |
b31499ec | 152 | LOCK(cs_main); |
51ce901a PW |
153 | if (pcoinsTip != NULL) { |
154 | FlushStateToDisk(); | |
155 | } | |
00d1980b PK |
156 | delete pcoinsTip; |
157 | pcoinsTip = NULL; | |
158 | delete pcoinsdbview; | |
159 | pcoinsdbview = NULL; | |
160 | delete pblocktree; | |
161 | pblocktree = NULL; | |
69d605f4 | 162 | } |
48ba56cd | 163 | #ifdef ENABLE_WALLET |
b0730874 JG |
164 | if (pwalletMain) |
165 | bitdb.Flush(true); | |
48ba56cd | 166 | #endif |
d6712db3 | 167 | #ifndef WIN32 |
b31499ec | 168 | boost::filesystem::remove(GetPidFile()); |
d6712db3 | 169 | #endif |
a96d1139 | 170 | UnregisterAllValidationInterfaces(); |
48ba56cd | 171 | #ifdef ENABLE_WALLET |
20a11ffa PK |
172 | delete pwalletMain; |
173 | pwalletMain = NULL; | |
48ba56cd | 174 | #endif |
00d1980b | 175 | LogPrintf("%s: done\n", __func__); |
69d605f4 WL |
176 | } |
177 | ||
c8c2fbe0 GA |
178 | // |
179 | // Signal handlers are very limited in what they are allowed to do, so: | |
180 | // | |
69d605f4 WL |
181 | void HandleSIGTERM(int) |
182 | { | |
183 | fRequestShutdown = true; | |
184 | } | |
185 | ||
9af080c3 MH |
186 | void HandleSIGHUP(int) |
187 | { | |
188 | fReopenDebugLog = true; | |
189 | } | |
69d605f4 | 190 | |
ac7c7ab9 PW |
191 | bool static InitError(const std::string &str) |
192 | { | |
49d57125 | 193 | uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR); |
ac7c7ab9 | 194 | return false; |
ac7c7ab9 PW |
195 | } |
196 | ||
197 | bool static InitWarning(const std::string &str) | |
198 | { | |
49d57125 | 199 | uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING); |
ac7c7ab9 PW |
200 | return true; |
201 | } | |
202 | ||
29e214aa | 203 | bool static Bind(const CService &addr, unsigned int flags) { |
c73323ee | 204 | if (!(flags & BF_EXPLICIT) && IsLimited(addr)) |
8f10a288 PW |
205 | return false; |
206 | std::string strError; | |
8d657a65 | 207 | if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) { |
c73323ee | 208 | if (flags & BF_REPORT_ERROR) |
587f929c PW |
209 | return InitError(strError); |
210 | return false; | |
211 | } | |
8f10a288 PW |
212 | return true; |
213 | } | |
214 | ||
1020f599 | 215 | std::string HelpMessage(HelpMessageMode mode) |
9f5b11e6 | 216 | { |
1020f599 | 217 | // When adding new options to the categories, please keep and ensure alphabetical ordering. |
c98c88b3 CF |
218 | string strUsage = _("Options:") + "\n"; |
219 | strUsage += " -? " + _("This help message") + "\n"; | |
7398f4a7 CL |
220 | strUsage += " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)") + "\n"; |
221 | strUsage += " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n"; | |
0a08aa8f LD |
222 | strUsage += " -checkblocks=<n> " + strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), 288) + "\n"; |
223 | strUsage += " -checklevel=<n> " + strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), 3) + "\n"; | |
224 | strUsage += " -conf=<file> " + strprintf(_("Specify configuration file (default: %s)"), "bitcoin.conf") + "\n"; | |
1020f599 | 225 | if (mode == HMM_BITCOIND) |
7398f4a7 CL |
226 | { |
227 | #if !defined(WIN32) | |
228 | strUsage += " -daemon " + _("Run in the background as a daemon and accept commands") + "\n"; | |
229 | #endif | |
230 | } | |
c98c88b3 | 231 | strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n"; |
82e96006 | 232 | strUsage += " -dbcache=<n> " + strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache) + "\n"; |
7398f4a7 | 233 | strUsage += " -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + " " + _("on startup") + "\n"; |
7b45d943 | 234 | strUsage += " -maxorphanblocks=<n> " + strprintf(_("Keep at most <n> unconnectable blocks in memory (default: %u)"), DEFAULT_MAX_ORPHAN_BLOCKS) + "\n"; |
aa3c697e | 235 | strUsage += " -maxorphantx=<n> " + strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS) + "\n"; |
5409404d | 236 | strUsage += " -par=<n> " + strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"), -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS) + "\n"; |
d6712db3 | 237 | #ifndef WIN32 |
0a08aa8f | 238 | strUsage += " -pid=<file> " + strprintf(_("Specify pid file (default: %s)"), "bitcoind.pid") + "\n"; |
d6712db3 | 239 | #endif |
7398f4a7 | 240 | strUsage += " -reindex " + _("Rebuild block chain index from current blk000??.dat files") + " " + _("on startup") + "\n"; |
bdd5b587 RS |
241 | #if !defined(WIN32) |
242 | strUsage += " -sysperms " + _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)") + "\n"; | |
243 | #endif | |
0a08aa8f | 244 | strUsage += " -txindex " + strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0) + "\n"; |
7398f4a7 CL |
245 | |
246 | strUsage += "\n" + _("Connection options:") + "\n"; | |
0b47fe6b | 247 | strUsage += " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n"; |
0a08aa8f LD |
248 | strUsage += " -banscore=<n> " + strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100) + "\n"; |
249 | strUsage += " -bantime=<n> " + strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400) + "\n"; | |
7398f4a7 | 250 | strUsage += " -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n"; |
0b47fe6b | 251 | strUsage += " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n"; |
0b47fe6b | 252 | strUsage += " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n"; |
7398f4a7 | 253 | strUsage += " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)") + "\n"; |
2e7009d6 | 254 | strUsage += " -dnsseed " + _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)") + "\n"; |
7398f4a7 | 255 | strUsage += " -externalip=<ip> " + _("Specify your own public address") + "\n"; |
0a08aa8f | 256 | strUsage += " -forcednsseed " + strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0) + "\n"; |
7398f4a7 | 257 | strUsage += " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n"; |
0a08aa8f LD |
258 | strUsage += " -maxconnections=<n> " + strprintf(_("Maintain at most <n> connections to peers (default: %u)"), 125) + "\n"; |
259 | strUsage += " -maxreceivebuffer=<n> " + strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000) + "\n"; | |
260 | strUsage += " -maxsendbuffer=<n> " + strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000) + "\n"; | |
261 | strUsage += " -onion=<ip:port> " + strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy") + "\n"; | |
aa827951 | 262 | strUsage += " -onlynet=<net> " + _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)") + "\n"; |
0a08aa8f LD |
263 | strUsage += " -permitbaremultisig " + strprintf(_("Relay non-P2SH multisig (default: %u)"), 1) + "\n"; |
264 | strUsage += " -port=<port> " + strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 8333, 18333) + "\n"; | |
0127a9be | 265 | strUsage += " -proxy=<ip:port> " + _("Connect through SOCKS5 proxy") + "\n"; |
7398f4a7 | 266 | strUsage += " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n"; |
de10efd1 | 267 | strUsage += " -timeout=<n> " + strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT) + "\n"; |
9f5b11e6 WL |
268 | #ifdef USE_UPNP |
269 | #if USE_UPNP | |
0b47fe6b | 270 | strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n"; |
9f5b11e6 | 271 | #else |
0a08aa8f | 272 | strUsage += " -upnp " + strprintf(_("Use UPnP to map the listening port (default: %u)"), 0) + "\n"; |
2a03a390 | 273 | #endif |
9f5b11e6 | 274 | #endif |
dc942e6f | 275 | strUsage += " -whitebind=<addr> " + _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6") + "\n"; |
9acbb418 | 276 | strUsage += " -whitelist=<netmask> " + _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") + "\n"; |
ebdcc360 | 277 | strUsage += " " + _("Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway") + "\n"; |
7398f4a7 CL |
278 | |
279 | #ifdef ENABLE_WALLET | |
280 | strUsage += "\n" + _("Wallet options:") + "\n"; | |
281 | strUsage += " -disablewallet " + _("Do not load the wallet and disable wallet RPC calls") + "\n"; | |
0a08aa8f | 282 | strUsage += " -keypool=<n> " + strprintf(_("Set key pool size to <n> (default: %u)"), 100) + "\n"; |
d88af560 CL |
283 | if (GetBoolArg("-help-debug", false)) |
284 | strUsage += " -mintxfee=<amt> " + strprintf(_("Fees (in BTC/Kb) smaller than this are considered zero fee for transaction creation (default: %s)"), FormatMoney(CWallet::minTxFee.GetFeePerK())) + "\n"; | |
4aaa0178 | 285 | strUsage += " -paytxfee=<amt> " + strprintf(_("Fee (in BTC/kB) to add to transactions you send (default: %s)"), FormatMoney(payTxFee.GetFeePerK())) + "\n"; |
7398f4a7 CL |
286 | strUsage += " -rescan " + _("Rescan the block chain for missing wallet transactions") + " " + _("on startup") + "\n"; |
287 | strUsage += " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup") + "\n"; | |
c1c9d5b4 | 288 | strUsage += " -sendfreetransactions " + strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0) + "\n"; |
0a08aa8f LD |
289 | strUsage += " -spendzeroconfchange " + strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1) + "\n"; |
290 | strUsage += " -txconfirmtarget=<n> " + strprintf(_("If paytxfee is not set, include enough fee so transactions are confirmed on average within n blocks (default: %u)"), 1) + "\n"; | |
7398f4a7 | 291 | strUsage += " -upgradewallet " + _("Upgrade wallet to latest format") + " " + _("on startup") + "\n"; |
0a08aa8f | 292 | strUsage += " -wallet=<file> " + _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat") + "\n"; |
7398f4a7 | 293 | strUsage += " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n"; |
2b410c2f | 294 | strUsage += " -zapwallettxes=<mode> " + _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") + "\n"; |
c0195b1c | 295 | strUsage += " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)") + "\n"; |
7398f4a7 CL |
296 | #endif |
297 | ||
298 | strUsage += "\n" + _("Debugging/Testing options:") + "\n"; | |
299 | if (GetBoolArg("-help-debug", false)) | |
300 | { | |
0a08aa8f LD |
301 | strUsage += " -checkpoints " + strprintf(_("Only accept block chain matching built-in checkpoints (default: %u)"), 1) + "\n"; |
302 | strUsage += " -dblogsize=<n> " + strprintf(_("Flush database activity from memory pool to disk log every <n> megabytes (default: %u)"), 100) + "\n"; | |
303 | strUsage += " -disablesafemode " + strprintf(_("Disable safemode, override a real safe mode event (default: %u)"), 0) + "\n"; | |
304 | strUsage += " -testsafemode " + strprintf(_("Force safe mode (default: %u)"), 0) + "\n"; | |
7398f4a7 CL |
305 | strUsage += " -dropmessagestest=<n> " + _("Randomly drop 1 of every <n> network messages") + "\n"; |
306 | strUsage += " -fuzzmessagestest=<n> " + _("Randomly fuzz 1 of every <n> network messages") + "\n"; | |
0a08aa8f LD |
307 | strUsage += " -flushwallet " + strprintf(_("Run a thread to flush wallet periodically (default: %u)"), 1) + "\n"; |
308 | strUsage += " -stopafterblockimport " + strprintf(_("Stop running after importing blocks from disk (default: %u)"), 0) + "\n"; | |
7398f4a7 | 309 | } |
0a08aa8f | 310 | strUsage += " -debug=<category> " + strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + "\n"; |
3c955993 PK |
311 | strUsage += " " + _("If <category> is not supplied, output all debugging information.") + "\n"; |
312 | strUsage += " " + _("<category> can be:"); | |
d70bc52e | 313 | strUsage += " addrman, alert, bench, coindb, db, lock, rand, rpc, selectcoins, mempool, net"; // Don't translate these and qt below |
1020f599 | 314 | if (mode == HMM_BITCOIN_QT) |
7398f4a7 CL |
315 | strUsage += ", qt"; |
316 | strUsage += ".\n"; | |
a7e1d503 | 317 | #ifdef ENABLE_WALLET |
0a08aa8f | 318 | strUsage += " -gen " + strprintf(_("Generate coins (default: %u)"), 0) + "\n"; |
f654f004 | 319 | strUsage += " -genproclimit=<n> " + strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1) + "\n"; |
a7e1d503 | 320 | #endif |
7398f4a7 | 321 | strUsage += " -help-debug " + _("Show all debugging options (usage: --help -help-debug)") + "\n"; |
0a08aa8f LD |
322 | strUsage += " -logips " + strprintf(_("Include IP addresses in debug output (default: %u)"), 0) + "\n"; |
323 | strUsage += " -logtimestamps " + strprintf(_("Prepend debug output with timestamp (default: %u)"), 1) + "\n"; | |
7398f4a7 | 324 | if (GetBoolArg("-help-debug", false)) |
3b570559 | 325 | { |
0a08aa8f LD |
326 | strUsage += " -limitfreerelay=<n> " + strprintf(_("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default:%u)"), 15) + "\n"; |
327 | strUsage += " -maxsigcachesize=<n> " + strprintf(_("Limit size of signature cache to <n> entries (default: %u)"), 50000) + "\n"; | |
3b570559 | 328 | } |
13fc83c7 | 329 | strUsage += " -minrelaytxfee=<amt> " + strprintf(_("Fees (in BTC/Kb) smaller than this are considered zero fee for relaying (default: %s)"), FormatMoney(::minRelayTxFee.GetFeePerK())) + "\n"; |
7398f4a7 CL |
330 | strUsage += " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n"; |
331 | if (GetBoolArg("-help-debug", false)) | |
3b570559 | 332 | { |
0a08aa8f LD |
333 | strUsage += " -printpriority " + strprintf(_("Log transaction priority and fee per kB when mining blocks (default: %u)"), 0) + "\n"; |
334 | strUsage += " -privdb " + strprintf(_("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)"), 1) + "\n"; | |
7398f4a7 CL |
335 | strUsage += " -regtest " + _("Enter regression test mode, which uses a special chain in which blocks can be solved instantly.") + "\n"; |
336 | strUsage += " " + _("This is intended for regression testing tools and app development.") + "\n"; | |
337 | strUsage += " " + _("In this mode -genproclimit controls how many blocks are generated immediately.") + "\n"; | |
3b570559 | 338 | } |
0b47fe6b | 339 | strUsage += " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n"; |
7398f4a7 | 340 | strUsage += " -testnet " + _("Use the test network") + "\n"; |
2a03a390 | 341 | |
e44fea55 | 342 | strUsage += "\n" + _("Node relay options:") + "\n"; |
0a08aa8f | 343 | strUsage += " -datacarrier " + strprintf(_("Relay and mine data carrier transactions (default: %u)"), 1) + "\n"; |
2aa63292 | 344 | strUsage += " -datacarriersize " + strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY) + "\n"; |
00d1980b | 345 | |
7398f4a7 | 346 | strUsage += "\n" + _("Block creation options:") + "\n"; |
0a08aa8f | 347 | strUsage += " -blockminsize=<n> " + strprintf(_("Set minimum block size in bytes (default: %u)"), 0) + "\n"; |
7398f4a7 CL |
348 | strUsage += " -blockmaxsize=<n> " + strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE) + "\n"; |
349 | strUsage += " -blockprioritysize=<n> " + strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE) + "\n"; | |
2a03a390 | 350 | |
7398f4a7 CL |
351 | strUsage += "\n" + _("RPC server options:") + "\n"; |
352 | strUsage += " -server " + _("Accept command line and JSON-RPC commands") + "\n"; | |
5dc713bf | 353 | strUsage += " -rest " + strprintf(_("Accept public REST requests (default: %u)"), 0) + "\n"; |
deb3572a | 354 | strUsage += " -rpcbind=<addr> " + _("Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)") + "\n"; |
c98c88b3 CF |
355 | strUsage += " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n"; |
356 | strUsage += " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n"; | |
0a08aa8f | 357 | strUsage += " -rpcport=<port> " + strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), 8332, 18332) + "\n"; |
4278b1df | 358 | strUsage += " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified source. Valid 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) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times") + "\n"; |
0a08aa8f | 359 | strUsage += " -rpcthreads=<n> " + strprintf(_("Set the number of threads to service RPC calls (default: %d)"), 4) + "\n"; |
9f5b11e6 | 360 | |
7398f4a7 | 361 | strUsage += "\n" + _("RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n"; |
c98c88b3 | 362 | strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n"; |
0a08aa8f LD |
363 | strUsage += " -rpcsslcertificatechainfile=<file.cert> " + strprintf(_("Server certificate file (default: %s)"), "server.cert") + "\n"; |
364 | strUsage += " -rpcsslprivatekeyfile=<file.pem> " + strprintf(_("Server private key (default: %s)"), "server.pem") + "\n"; | |
365 | strUsage += " -rpcsslciphers=<ciphers> " + strprintf(_("Acceptable ciphers (default: %s)"), "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH") + "\n"; | |
9f5b11e6 WL |
366 | |
367 | return strUsage; | |
368 | } | |
369 | ||
45615af2 WL |
370 | std::string LicenseInfo() |
371 | { | |
372 | return FormatParagraph(strprintf(_("Copyright (C) 2009-%i The Bitcoin Core Developers"), COPYRIGHT_YEAR)) + "\n" + | |
373 | "\n" + | |
374 | FormatParagraph(_("This is experimental software.")) + "\n" + | |
375 | "\n" + | |
1b2600a1 | 376 | FormatParagraph(_("Distributed under the MIT software license, see the accompanying file COPYING or <http://www.opensource.org/licenses/mit-license.php>.")) + "\n" + |
45615af2 WL |
377 | "\n" + |
378 | FormatParagraph(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.")) + | |
379 | "\n"; | |
380 | } | |
381 | ||
c7b6117d JG |
382 | static void BlockNotifyCallback(const uint256& hashNewTip) |
383 | { | |
384 | std::string strCmd = GetArg("-blocknotify", ""); | |
385 | ||
386 | boost::replace_all(strCmd, "%s", hashNewTip.GetHex()); | |
387 | boost::thread t(runCommand, strCmd); // thread runs free | |
388 | } | |
389 | ||
7a5b7535 PW |
390 | struct CImportingNow |
391 | { | |
392 | CImportingNow() { | |
393 | assert(fImporting == false); | |
394 | fImporting = true; | |
395 | } | |
396 | ||
397 | ~CImportingNow() { | |
398 | assert(fImporting == true); | |
399 | fImporting = false; | |
400 | } | |
401 | }; | |
402 | ||
21eb5ada GA |
403 | void ThreadImport(std::vector<boost::filesystem::path> vImportFiles) |
404 | { | |
7a5b7535 PW |
405 | RenameThread("bitcoin-loadblk"); |
406 | ||
7fea4846 PW |
407 | // -reindex |
408 | if (fReindex) { | |
409 | CImportingNow imp; | |
410 | int nFile = 0; | |
21eb5ada | 411 | while (true) { |
a8a4b967 | 412 | CDiskBlockPos pos(nFile, 0); |
ec7eb0fa SD |
413 | if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk"))) |
414 | break; // No block files left to reindex | |
7fea4846 PW |
415 | FILE *file = OpenBlockFile(pos, true); |
416 | if (!file) | |
ec7eb0fa | 417 | break; // This error is logged in OpenBlockFile |
881a85a2 | 418 | LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile); |
7fea4846 PW |
419 | LoadExternalBlockFile(file, &pos); |
420 | nFile++; | |
421 | } | |
21eb5ada GA |
422 | pblocktree->WriteReindexing(false); |
423 | fReindex = false; | |
881a85a2 | 424 | LogPrintf("Reindexing finished\n"); |
21eb5ada GA |
425 | // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): |
426 | InitBlockIndex(); | |
7a5b7535 PW |
427 | } |
428 | ||
429 | // hardcoded $DATADIR/bootstrap.dat | |
430 | filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat"; | |
21eb5ada | 431 | if (filesystem::exists(pathBootstrap)) { |
7a5b7535 PW |
432 | FILE *file = fopen(pathBootstrap.string().c_str(), "rb"); |
433 | if (file) { | |
7fea4846 | 434 | CImportingNow imp; |
7a5b7535 | 435 | filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; |
881a85a2 | 436 | LogPrintf("Importing bootstrap.dat...\n"); |
7a5b7535 PW |
437 | LoadExternalBlockFile(file); |
438 | RenameOver(pathBootstrap, pathBootstrapOld); | |
d54e819f WL |
439 | } else { |
440 | LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string()); | |
7a5b7535 PW |
441 | } |
442 | } | |
443 | ||
7fea4846 | 444 | // -loadblock= |
21eb5ada | 445 | BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) { |
7fea4846 PW |
446 | FILE *file = fopen(path.string().c_str(), "rb"); |
447 | if (file) { | |
448 | CImportingNow imp; | |
d54e819f | 449 | LogPrintf("Importing blocks file %s...\n", path.string()); |
7fea4846 | 450 | LoadExternalBlockFile(file); |
d54e819f WL |
451 | } else { |
452 | LogPrintf("Warning: Could not open blocks file %s\n", path.string()); | |
7fea4846 PW |
453 | } |
454 | } | |
1569353b WL |
455 | |
456 | if (GetBoolArg("-stopafterblockimport", false)) { | |
457 | LogPrintf("Stopping after block import\n"); | |
458 | StartShutdown(); | |
459 | } | |
7a5b7535 PW |
460 | } |
461 | ||
4a09e1df AP |
462 | /** Sanity checks |
463 | * Ensure that Bitcoin is running in a usable environment with all | |
464 | * necessary library support. | |
465 | */ | |
466 | bool InitSanityCheck(void) | |
467 | { | |
468 | if(!ECC_InitSanityCheck()) { | |
469 | InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more " | |
470 | "information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries"); | |
471 | return false; | |
472 | } | |
92a62207 CF |
473 | if (!glibc_sanity_test() || !glibcxx_sanity_test()) |
474 | return false; | |
4a09e1df AP |
475 | |
476 | return true; | |
477 | } | |
478 | ||
9f5b11e6 WL |
479 | /** Initialize bitcoin. |
480 | * @pre Parameters should be parsed and config file should be read. | |
481 | */ | |
8b9adca4 | 482 | bool AppInit2(boost::thread_group& threadGroup) |
69d605f4 | 483 | { |
7d80d2e3 | 484 | // ********************************************************* Step 1: setup |
69d605f4 | 485 | #ifdef _MSC_VER |
814efd6f | 486 | // Turn off Microsoft heap dump noise |
69d605f4 WL |
487 | _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); |
488 | _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); | |
489 | #endif | |
490 | #if _MSC_VER >= 1400 | |
814efd6f | 491 | // Disable confusing "helpful" text message on abort, Ctrl-C |
69d605f4 WL |
492 | _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); |
493 | #endif | |
3d88c9b4 PK |
494 | #ifdef WIN32 |
495 | // Enable Data Execution Prevention (DEP) | |
496 | // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 | |
497 | // A failure is non-critical and needs no further attention! | |
498 | #ifndef PROCESS_DEP_ENABLE | |
f65dddc7 PK |
499 | // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), |
500 | // which is not correct. Can be removed, when GCCs winbase.h is fixed! | |
3d88c9b4 PK |
501 | #define PROCESS_DEP_ENABLE 0x00000001 |
502 | #endif | |
503 | typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); | |
504 | PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); | |
505 | if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); | |
d23fa49c WL |
506 | |
507 | // Initialize Windows Sockets | |
508 | WSADATA wsadata; | |
509 | int ret = WSAStartup(MAKEWORD(2,2), &wsadata); | |
110257a6 | 510 | if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2) |
d23fa49c | 511 | { |
110257a6 | 512 | return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret)); |
d23fa49c | 513 | } |
69d605f4 | 514 | #endif |
6853e627 | 515 | #ifndef WIN32 |
bdd5b587 RS |
516 | |
517 | if (GetBoolArg("-sysperms", false)) { | |
518 | #ifdef ENABLE_WALLET | |
519 | if (!GetBoolArg("-disablewallet", false)) | |
520 | return InitError("Error: -sysperms is not allowed in combination with enabled wallet functionality"); | |
521 | #endif | |
522 | } else { | |
523 | umask(077); | |
524 | } | |
3d88c9b4 | 525 | |
69d605f4 WL |
526 | // Clean shutdown on SIGTERM |
527 | struct sigaction sa; | |
528 | sa.sa_handler = HandleSIGTERM; | |
529 | sigemptyset(&sa.sa_mask); | |
530 | sa.sa_flags = 0; | |
531 | sigaction(SIGTERM, &sa, NULL); | |
532 | sigaction(SIGINT, &sa, NULL); | |
9af080c3 MH |
533 | |
534 | // Reopen debug.log on SIGHUP | |
535 | struct sigaction sa_hup; | |
536 | sa_hup.sa_handler = HandleSIGHUP; | |
537 | sigemptyset(&sa_hup.sa_mask); | |
538 | sa_hup.sa_flags = 0; | |
539 | sigaction(SIGHUP, &sa_hup, NULL); | |
b34255b7 | 540 | |
541 | #if defined (__SVR4) && defined (__sun) | |
542 | // ignore SIGPIPE on Solaris | |
543 | signal(SIGPIPE, SIG_IGN); | |
544 | #endif | |
69d605f4 WL |
545 | #endif |
546 | ||
7d80d2e3 | 547 | // ********************************************************* Step 2: parameter interactions |
eadcd0c8 MC |
548 | // Set this early so that parameter interactions go to console |
549 | fPrintToConsole = GetBoolArg("-printtoconsole", false); | |
550 | fLogTimestamps = GetBoolArg("-logtimestamps", true); | |
551 | fLogIPs = GetBoolArg("-logips", false); | |
7d80d2e3 | 552 | |
dc942e6f | 553 | if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) { |
587f929c PW |
554 | // when specifying an explicit binding address, you want to listen on it |
555 | // even when -connect or -proxy is specified | |
df966d1b | 556 | if (SoftSetBoolArg("-listen", true)) |
dc942e6f | 557 | LogPrintf("AppInit2 : parameter interaction: -bind or -whitebind set -> setting -listen=1\n"); |
587f929c | 558 | } |
7d80d2e3 | 559 | |
f161a2c2 | 560 | if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { |
587f929c | 561 | // when only connecting to trusted nodes, do not seed via DNS, or listen by default |
df966d1b PK |
562 | if (SoftSetBoolArg("-dnsseed", false)) |
563 | LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -dnsseed=0\n"); | |
564 | if (SoftSetBoolArg("-listen", false)) | |
565 | LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -listen=0\n"); | |
587f929c PW |
566 | } |
567 | ||
568 | if (mapArgs.count("-proxy")) { | |
df966d1b PK |
569 | // to protect privacy, do not listen by default if a default proxy server is specified |
570 | if (SoftSetBoolArg("-listen", false)) | |
571 | LogPrintf("AppInit2 : parameter interaction: -proxy set -> setting -listen=0\n"); | |
845c86d1 GM |
572 | // to protect privacy, do not discover addresses by default |
573 | if (SoftSetBoolArg("-discover", false)) | |
574 | LogPrintf("AppInit2 : parameter interaction: -proxy set -> setting -discover=0\n"); | |
587f929c PW |
575 | } |
576 | ||
3bbb49de | 577 | if (!GetBoolArg("-listen", true)) { |
587f929c | 578 | // do not map ports or try to retrieve public IP when not listening (pointless) |
df966d1b PK |
579 | if (SoftSetBoolArg("-upnp", false)) |
580 | LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -upnp=0\n"); | |
581 | if (SoftSetBoolArg("-discover", false)) | |
582 | LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -discover=0\n"); | |
7d80d2e3 PW |
583 | } |
584 | ||
587f929c PW |
585 | if (mapArgs.count("-externalip")) { |
586 | // if an explicit public IP is specified, do not try to find others | |
df966d1b PK |
587 | if (SoftSetBoolArg("-discover", false)) |
588 | LogPrintf("AppInit2 : parameter interaction: -externalip set -> setting -discover=0\n"); | |
587f929c PW |
589 | } |
590 | ||
3260b4c0 | 591 | if (GetBoolArg("-salvagewallet", false)) { |
eed1785f | 592 | // Rewrite just private keys: rescan to find transactions |
df966d1b PK |
593 | if (SoftSetBoolArg("-rescan", true)) |
594 | LogPrintf("AppInit2 : parameter interaction: -salvagewallet=1 -> setting -rescan=1\n"); | |
eed1785f GA |
595 | } |
596 | ||
518f3bda JG |
597 | // -zapwallettx implies a rescan |
598 | if (GetBoolArg("-zapwallettxes", false)) { | |
599 | if (SoftSetBoolArg("-rescan", true)) | |
77cbd462 | 600 | LogPrintf("AppInit2 : parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n"); |
518f3bda JG |
601 | } |
602 | ||
ba29a559 | 603 | // Make sure enough file descriptors are available |
dc942e6f | 604 | int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1); |
ba29a559 | 605 | nMaxConnections = GetArg("-maxconnections", 125); |
03f49808 | 606 | nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0); |
ba29a559 PW |
607 | int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS); |
608 | if (nFD < MIN_CORE_FILEDESCRIPTORS) | |
609 | return InitError(_("Not enough file descriptors available.")); | |
610 | if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections) | |
611 | nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS; | |
612 | ||
7d80d2e3 PW |
613 | // ********************************************************* Step 3: parameter-to-internal-flags |
614 | ||
3b570559 PK |
615 | fDebug = !mapMultiArgs["-debug"].empty(); |
616 | // Special-case: if -debug=0/-nodebug is set, turn off debugging messages | |
617 | const vector<string>& categories = mapMultiArgs["-debug"]; | |
618 | if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end()) | |
619 | fDebug = false; | |
620 | ||
00d1980b | 621 | // Check for -debugnet |
3b570559 | 622 | if (GetBoolArg("-debugnet", false)) |
00d1980b | 623 | InitWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net.")); |
a339a37b PK |
624 | // Check for -socks - as this is a privacy risk to continue, exit here |
625 | if (mapArgs.count("-socks")) | |
626 | return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.")); | |
1c750dbd PK |
627 | // Check for -tor - as this is a privacy risk to continue, exit here |
628 | if (GetBoolArg("-tor", false)) | |
629 | return InitError(_("Error: Unsupported argument -tor found, use -onion.")); | |
3b570559 | 630 | |
d70bc52e PW |
631 | if (GetBoolArg("-benchmark", false)) |
632 | InitWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench.")); | |
633 | ||
cb9bd83b | 634 | // Checkmempool defaults to true in regtest mode |
635 | mempool.setSanityCheck(GetBoolArg("-checkmempool", Params().DefaultCheckMemPool())); | |
60fc1b40 | 636 | Checkpoints::fEnabled = GetBoolArg("-checkpoints", true); |
d07eaba1 | 637 | |
f9cae832 | 638 | // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency |
5409404d | 639 | nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS); |
ebd7e8bf DS |
640 | if (nScriptCheckThreads <= 0) |
641 | nScriptCheckThreads += boost::thread::hardware_concurrency(); | |
69e07747 | 642 | if (nScriptCheckThreads <= 1) |
f9cae832 PW |
643 | nScriptCheckThreads = 0; |
644 | else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS) | |
645 | nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS; | |
646 | ||
8b9adca4 | 647 | fServer = GetBoolArg("-server", false); |
48ba56cd | 648 | #ifdef ENABLE_WALLET |
e6b7e3dc | 649 | bool fDisableWallet = GetBoolArg("-disablewallet", false); |
48ba56cd | 650 | #endif |
69d605f4 | 651 | |
de10efd1 PK |
652 | nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT); |
653 | if (nConnectTimeout <= 0) | |
654 | nConnectTimeout = DEFAULT_CONNECT_TIMEOUT; | |
7d80d2e3 PW |
655 | |
656 | // Continue to put "/P2SH/" in the coinbase to monitor | |
657 | // BIP16 support. | |
658 | // This can be removed eventually... | |
659 | const char* pszP2SH = "/P2SH/"; | |
660 | COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH)); | |
661 | ||
000dc551 GA |
662 | // Fee-per-kilobyte amount considered the same as "free" |
663 | // If you are mining, be careful setting this: | |
664 | // if you set it to zero then | |
665 | // a transaction spammer can cheaply fill blocks using | |
666 | // 1-satoshi-fee transactions. It should be set above the real | |
667 | // cost to you of processing a transaction. | |
000dc551 GA |
668 | if (mapArgs.count("-minrelaytxfee")) |
669 | { | |
a372168e | 670 | CAmount n = 0; |
000dc551 | 671 | if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0) |
13fc83c7 | 672 | ::minRelayTxFee = CFeeRate(n); |
000dc551 | 673 | else |
7d9d134b | 674 | return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"])); |
000dc551 | 675 | } |
7d80d2e3 | 676 | |
cd7fa8bb | 677 | #ifdef ENABLE_WALLET |
13fc83c7 GA |
678 | if (mapArgs.count("-mintxfee")) |
679 | { | |
a372168e | 680 | CAmount n = 0; |
13fc83c7 GA |
681 | if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0) |
682 | CWallet::minTxFee = CFeeRate(n); | |
683 | else | |
684 | return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"])); | |
685 | } | |
7d80d2e3 PW |
686 | if (mapArgs.count("-paytxfee")) |
687 | { | |
a372168e | 688 | CAmount nFeePerK = 0; |
c6cb21d1 | 689 | if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK)) |
7d9d134b | 690 | return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"])); |
c6cb21d1 | 691 | if (nFeePerK > nHighTransactionFeeWarning) |
e6bc9c35 | 692 | InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.")); |
c6cb21d1 | 693 | payTxFee = CFeeRate(nFeePerK, 1000); |
13fc83c7 | 694 | if (payTxFee < ::minRelayTxFee) |
b33d1f5e GA |
695 | { |
696 | return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"), | |
13fc83c7 | 697 | mapArgs["-paytxfee"], ::minRelayTxFee.ToString())); |
b33d1f5e | 698 | } |
7d80d2e3 | 699 | } |
b33d1f5e | 700 | nTxConfirmTarget = GetArg("-txconfirmtarget", 1); |
1bbca249 | 701 | bSpendZeroConfChange = GetArg("-spendzeroconfchange", true); |
c1c9d5b4 | 702 | fSendFreeTransactions = GetArg("-sendfreetransactions", false); |
7d80d2e3 | 703 | |
7d4dda76 | 704 | std::string strWalletFile = GetArg("-wallet", "wallet.dat"); |
3da434a2 JG |
705 | #endif // ENABLE_WALLET |
706 | ||
8d657a65 | 707 | fIsBareMultisigStd = GetArg("-permitbaremultisig", true) != 0; |
2aa63292 | 708 | nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes); |
3da434a2 | 709 | |
7d80d2e3 | 710 | // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log |
20a11ffa | 711 | |
4a09e1df AP |
712 | // Sanity check |
713 | if (!InitSanityCheck()) | |
714 | return InitError(_("Initialization sanity check failed. Bitcoin Core is shutting down.")); | |
7d80d2e3 | 715 | |
22bb0490 | 716 | std::string strDataDir = GetDataDir().string(); |
48ba56cd | 717 | #ifdef ENABLE_WALLET |
674cb304 NS |
718 | // Wallet file must be a plain filename without a directory |
719 | if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile)) | |
7d9d134b | 720 | return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir)); |
48ba56cd | 721 | #endif |
7d80d2e3 PW |
722 | // Make sure only a single Bitcoin process is using the data directory. |
723 | boost::filesystem::path pathLockFile = GetDataDir() / ".lock"; | |
724 | FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. | |
725 | if (file) fclose(file); | |
726 | static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); | |
727 | if (!lock.try_lock()) | |
9e2872c2 | 728 | return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running."), strDataDir)); |
d6712db3 WL |
729 | #ifndef WIN32 |
730 | CreatePidFile(GetPidFile(), getpid()); | |
731 | #endif | |
7f1de3fe | 732 | if (GetBoolArg("-shrinkdebugfile", !fDebug)) |
69d605f4 | 733 | ShrinkDebugFile(); |
881a85a2 | 734 | LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); |
7d9d134b | 735 | LogPrintf("Bitcoin version %s (%s)\n", FormatFullVersion(), CLIENT_DATE); |
881a85a2 | 736 | LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION)); |
d0a2e2eb WL |
737 | #ifdef ENABLE_WALLET |
738 | LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0)); | |
739 | #endif | |
dcb14198 | 740 | if (!fLogTimestamps) |
7d9d134b WL |
741 | LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime())); |
742 | LogPrintf("Default data directory %s\n", GetDefaultDataDir().string()); | |
743 | LogPrintf("Using data directory %s\n", strDataDir); | |
5bd02cf7 | 744 | LogPrintf("Using config file %s\n", GetConfigFile().string()); |
881a85a2 | 745 | LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD); |
7d80d2e3 | 746 | std::ostringstream strErrors; |
69d605f4 | 747 | |
9bdec760 | 748 | LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads); |
f9cae832 | 749 | if (nScriptCheckThreads) { |
f9cae832 | 750 | for (int i=0; i<nScriptCheckThreads-1; i++) |
21eb5ada | 751 | threadGroup.create_thread(&ThreadScriptCheck); |
f9cae832 PW |
752 | } |
753 | ||
af82884a DK |
754 | /* Start the RPC server already. It will be started in "warmup" mode |
755 | * and not really process calls already (but it will signify connections | |
756 | * that the server is there and will be ready later). Warmup mode will | |
757 | * be disabled when initialisation is finished. | |
758 | */ | |
759 | if (fServer) | |
760 | { | |
761 | uiInterface.InitMessage.connect(SetRPCWarmupStatus); | |
762 | StartRPCThreads(); | |
763 | } | |
764 | ||
51ed9ec9 | 765 | int64_t nStart; |
7d80d2e3 | 766 | |
06494cab | 767 | // ********************************************************* Step 5: verify wallet database integrity |
48ba56cd | 768 | #ifdef ENABLE_WALLET |
e6b7e3dc | 769 | if (!fDisableWallet) { |
8a6894ca | 770 | LogPrintf("Using wallet %s\n", strWalletFile); |
f9ee7a03 | 771 | uiInterface.InitMessage(_("Verifying wallet...")); |
eed1785f | 772 | |
f9ee7a03 JG |
773 | if (!bitdb.Open(GetDataDir())) |
774 | { | |
775 | // try moving the database env out of the way | |
776 | boost::filesystem::path pathDatabase = GetDataDir() / "database"; | |
f48742c2 | 777 | boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime()); |
f9ee7a03 JG |
778 | try { |
779 | boost::filesystem::rename(pathDatabase, pathDatabaseBak); | |
7d9d134b | 780 | LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string()); |
f9ee7a03 JG |
781 | } catch(boost::filesystem::filesystem_error &error) { |
782 | // failure is ok (well, not really, but it's not worse than what we started with) | |
783 | } | |
1859aafe | 784 | |
f9ee7a03 JG |
785 | // try again |
786 | if (!bitdb.Open(GetDataDir())) { | |
787 | // if it still fails, it probably means we can't even create the database env | |
7d9d134b | 788 | string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir); |
f9ee7a03 JG |
789 | return InitError(msg); |
790 | } | |
1859aafe | 791 | } |
eed1785f | 792 | |
f9ee7a03 JG |
793 | if (GetBoolArg("-salvagewallet", false)) |
794 | { | |
795 | // Recover readable keypairs: | |
796 | if (!CWalletDB::Recover(bitdb, strWalletFile, true)) | |
797 | return false; | |
798 | } | |
eed1785f | 799 | |
f9ee7a03 | 800 | if (filesystem::exists(GetDataDir() / strWalletFile)) |
d0b3e77a | 801 | { |
f9ee7a03 JG |
802 | CDBEnv::VerifyResult r = bitdb.Verify(strWalletFile, CWalletDB::Recover); |
803 | if (r == CDBEnv::RECOVER_OK) | |
804 | { | |
805 | string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!" | |
806 | " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if" | |
807 | " your balance or transactions are incorrect you should" | |
7d9d134b | 808 | " restore from a backup."), strDataDir); |
f9ee7a03 JG |
809 | InitWarning(msg); |
810 | } | |
811 | if (r == CDBEnv::RECOVER_FAIL) | |
812 | return InitError(_("wallet.dat corrupt, salvage failed")); | |
d0b3e77a | 813 | } |
e6b7e3dc | 814 | } // (!fDisableWallet) |
48ba56cd | 815 | #endif // ENABLE_WALLET |
eed1785f | 816 | // ********************************************************* Step 6: network initialization |
7d80d2e3 | 817 | |
501da250 | 818 | RegisterNodeSignals(GetNodeSignals()); |
0e4b3175 | 819 | |
7d80d2e3 PW |
820 | if (mapArgs.count("-onlynet")) { |
821 | std::set<enum Network> nets; | |
822 | BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) { | |
823 | enum Network net = ParseNetwork(snet); | |
824 | if (net == NET_UNROUTABLE) | |
7d9d134b | 825 | return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet)); |
7d80d2e3 PW |
826 | nets.insert(net); |
827 | } | |
828 | for (int n = 0; n < NET_MAX; n++) { | |
829 | enum Network net = (enum Network)n; | |
830 | if (!nets.count(net)) | |
831 | SetLimited(net); | |
832 | } | |
833 | } | |
834 | ||
dc942e6f PW |
835 | if (mapArgs.count("-whitelist")) { |
836 | BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) { | |
837 | CSubNet subnet(net); | |
838 | if (!subnet.IsValid()) | |
839 | return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net)); | |
840 | CNode::AddWhitelistedRange(subnet); | |
841 | } | |
842 | } | |
843 | ||
54ce3bad PW |
844 | CService addrProxy; |
845 | bool fProxy = false; | |
587f929c | 846 | if (mapArgs.count("-proxy")) { |
54ce3bad | 847 | addrProxy = CService(mapArgs["-proxy"], 9050); |
587f929c | 848 | if (!addrProxy.IsValid()) |
7d9d134b | 849 | return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"])); |
587f929c | 850 | |
3c777141 GM |
851 | SetProxy(NET_IPV4, addrProxy); |
852 | SetProxy(NET_IPV6, addrProxy); | |
0127a9be | 853 | SetNameProxy(addrProxy); |
54ce3bad PW |
854 | fProxy = true; |
855 | } | |
856 | ||
102518fd | 857 | // -onion can override normal proxy, -noonion disables tor entirely |
102518fd | 858 | if (!(mapArgs.count("-onion") && mapArgs["-onion"] == "0") && |
1c750dbd | 859 | (fProxy || mapArgs.count("-onion"))) { |
54ce3bad | 860 | CService addrOnion; |
1c750dbd | 861 | if (!mapArgs.count("-onion")) |
54ce3bad PW |
862 | addrOnion = addrProxy; |
863 | else | |
1c750dbd | 864 | addrOnion = CService(mapArgs["-onion"], 9050); |
54ce3bad | 865 | if (!addrOnion.IsValid()) |
1c750dbd | 866 | return InitError(strprintf(_("Invalid -onion address: '%s'"), mapArgs["-onion"])); |
0127a9be | 867 | SetProxy(NET_TOR, addrOnion); |
54ce3bad | 868 | SetReachable(NET_TOR); |
587f929c PW |
869 | } |
870 | ||
871 | // see Step 2: parameter interactions for more information about these | |
56b07d2d | 872 | fListen = GetBoolArg("-listen", DEFAULT_LISTEN); |
587f929c PW |
873 | fDiscover = GetBoolArg("-discover", true); |
874 | fNameLookup = GetBoolArg("-dns", true); | |
928d3a01 | 875 | |
7d80d2e3 | 876 | bool fBound = false; |
53a08815 | 877 | if (fListen) { |
dc942e6f | 878 | if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) { |
7d80d2e3 PW |
879 | BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) { |
880 | CService addrBind; | |
881 | if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) | |
7d9d134b | 882 | return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind)); |
c73323ee | 883 | fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR)); |
7d80d2e3 | 884 | } |
dc942e6f PW |
885 | BOOST_FOREACH(std::string strBind, mapMultiArgs["-whitebind"]) { |
886 | CService addrBind; | |
887 | if (!Lookup(strBind.c_str(), addrBind, 0, false)) | |
888 | return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind)); | |
889 | if (addrBind.GetPort() == 0) | |
890 | return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind)); | |
891 | fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST)); | |
892 | } | |
c73323ee PK |
893 | } |
894 | else { | |
7d80d2e3 PW |
895 | struct in_addr inaddr_any; |
896 | inaddr_any.s_addr = INADDR_ANY; | |
c73323ee | 897 | fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE); |
c73323ee | 898 | fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE); |
7d80d2e3 PW |
899 | } |
900 | if (!fBound) | |
587f929c | 901 | return InitError(_("Failed to listen on any port. Use -listen=0 if you want this.")); |
928d3a01 JG |
902 | } |
903 | ||
c73323ee | 904 | if (mapArgs.count("-externalip")) { |
7d80d2e3 PW |
905 | BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) { |
906 | CService addrLocal(strAddr, GetListenPort(), fNameLookup); | |
907 | if (!addrLocal.IsValid()) | |
7d9d134b | 908 | return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr)); |
7d80d2e3 PW |
909 | AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL); |
910 | } | |
911 | } | |
912 | ||
587f929c PW |
913 | BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"]) |
914 | AddOneShot(strDest); | |
915 | ||
729b1806 | 916 | // ********************************************************* Step 7: load block chain |
7d80d2e3 | 917 | |
3260b4c0 | 918 | fReindex = GetBoolArg("-reindex", false); |
7fea4846 | 919 | |
f4445f99 GA |
920 | // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/ |
921 | filesystem::path blocksDir = GetDataDir() / "blocks"; | |
922 | if (!filesystem::exists(blocksDir)) | |
923 | { | |
924 | filesystem::create_directories(blocksDir); | |
925 | bool linked = false; | |
926 | for (unsigned int i = 1; i < 10000; i++) { | |
927 | filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i); | |
928 | if (!filesystem::exists(source)) break; | |
929 | filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1); | |
930 | try { | |
931 | filesystem::create_hard_link(source, dest); | |
7d9d134b | 932 | LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string()); |
f4445f99 GA |
933 | linked = true; |
934 | } catch (filesystem::filesystem_error & e) { | |
935 | // Note: hardlink creation failing is not a disaster, it just means | |
936 | // blocks will get re-downloaded from peers. | |
881a85a2 | 937 | LogPrintf("Error hardlinking blk%04u.dat : %s\n", i, e.what()); |
f4445f99 GA |
938 | break; |
939 | } | |
940 | } | |
941 | if (linked) | |
942 | { | |
943 | fReindex = true; | |
944 | } | |
945 | } | |
946 | ||
1c83b0a3 | 947 | // cache size calculations |
82e96006 PK |
948 | size_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20); |
949 | if (nTotalCache < (nMinDbCache << 20)) | |
950 | nTotalCache = (nMinDbCache << 20); // total cache cannot be less than nMinDbCache | |
951 | else if (nTotalCache > (nMaxDbCache << 20)) | |
952 | nTotalCache = (nMaxDbCache << 20); // total cache cannot be greater than nMaxDbCache | |
1c83b0a3 | 953 | size_t nBlockTreeDBCache = nTotalCache / 8; |
2d1fa42e | 954 | if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false)) |
1c83b0a3 PW |
955 | nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB |
956 | nTotalCache -= nBlockTreeDBCache; | |
957 | size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache | |
958 | nTotalCache -= nCoinDBCache; | |
959 | nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes | |
960 | ||
f7f3a96b PW |
961 | bool fLoaded = false; |
962 | while (!fLoaded) { | |
963 | bool fReset = fReindex; | |
964 | std::string strLoadError; | |
bb41a87d | 965 | |
f7f3a96b | 966 | uiInterface.InitMessage(_("Loading block index...")); |
ae8bfd12 | 967 | |
f7f3a96b PW |
968 | nStart = GetTimeMillis(); |
969 | do { | |
970 | try { | |
971 | UnloadBlockIndex(); | |
972 | delete pcoinsTip; | |
973 | delete pcoinsdbview; | |
974 | delete pblocktree; | |
975 | ||
976 | pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex); | |
977 | pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex); | |
7c70438d | 978 | pcoinsTip = new CCoinsViewCache(pcoinsdbview); |
f7f3a96b PW |
979 | |
980 | if (fReindex) | |
981 | pblocktree->WriteReindexing(true); | |
982 | ||
983 | if (!LoadBlockIndex()) { | |
984 | strLoadError = _("Error loading block database"); | |
985 | break; | |
986 | } | |
987 | ||
5d274c99 PW |
988 | // If the loaded chain has a wrong genesis, bail out immediately |
989 | // (we're likely using a testnet datadir, or the other way around). | |
afc32c5e | 990 | if (!mapBlockIndex.empty() && mapBlockIndex.count(Params().HashGenesisBlock()) == 0) |
5d274c99 PW |
991 | return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?")); |
992 | ||
f7f3a96b PW |
993 | // Initialize the block index (no-op if non-empty database was already loaded) |
994 | if (!InitBlockIndex()) { | |
995 | strLoadError = _("Error initializing block database"); | |
996 | break; | |
997 | } | |
998 | ||
067a6092 PW |
999 | // Check for changed -txindex state |
1000 | if (fTxIndex != GetBoolArg("-txindex", false)) { | |
1001 | strLoadError = _("You need to rebuild the database using -reindex to change -txindex"); | |
1002 | break; | |
1003 | } | |
1004 | ||
e1ca89df | 1005 | uiInterface.InitMessage(_("Verifying blocks...")); |
2e280311 | 1006 | if (!CVerifyDB().VerifyDB(pcoinsdbview, GetArg("-checklevel", 3), |
d78900cc | 1007 | GetArg("-checkblocks", 288))) { |
f7f3a96b PW |
1008 | strLoadError = _("Corrupted block database detected"); |
1009 | break; | |
1010 | } | |
1011 | } catch(std::exception &e) { | |
881a85a2 | 1012 | if (fDebug) LogPrintf("%s\n", e.what()); |
f7f3a96b PW |
1013 | strLoadError = _("Error opening block database"); |
1014 | break; | |
1015 | } | |
1f355b66 | 1016 | |
f7f3a96b PW |
1017 | fLoaded = true; |
1018 | } while(false); | |
1019 | ||
1020 | if (!fLoaded) { | |
1021 | // first suggest a reindex | |
1022 | if (!fReset) { | |
1023 | bool fRet = uiInterface.ThreadSafeMessageBox( | |
0206e38d | 1024 | strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"), |
f7f3a96b PW |
1025 | "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT); |
1026 | if (fRet) { | |
1027 | fReindex = true; | |
1028 | fRequestShutdown = false; | |
1029 | } else { | |
881a85a2 | 1030 | LogPrintf("Aborted block database rebuild. Exiting.\n"); |
f7f3a96b PW |
1031 | return false; |
1032 | } | |
1033 | } else { | |
1034 | return InitError(strLoadError); | |
1035 | } | |
1036 | } | |
1037 | } | |
871c3557 | 1038 | |
46469d0f PK |
1039 | // As LoadBlockIndex can take several minutes, it's possible the user |
1040 | // requested to kill the GUI during the last operation. If so, exit. | |
871c3557 B |
1041 | // As the program has not fully started yet, Shutdown() is possibly overkill. |
1042 | if (fRequestShutdown) | |
1043 | { | |
881a85a2 | 1044 | LogPrintf("Shutdown requested. Exiting.\n"); |
871c3557 B |
1045 | return false; |
1046 | } | |
f48742c2 | 1047 | LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart); |
69d605f4 | 1048 | |
171ca774 | 1049 | boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; |
eee030f6 | 1050 | CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION); |
00d1980b | 1051 | // Allowed to fail as this file IS missing on first startup. |
a8738238 | 1052 | if (!est_filein.IsNull()) |
171ca774 | 1053 | mempool.ReadFeeEstimates(est_filein); |
94064710 | 1054 | fFeeEstimatesInitialized = true; |
171ca774 | 1055 | |
eed1785f | 1056 | // ********************************************************* Step 8: load wallet |
48ba56cd | 1057 | #ifdef ENABLE_WALLET |
e6b7e3dc JG |
1058 | if (fDisableWallet) { |
1059 | pwalletMain = NULL; | |
1060 | LogPrintf("Wallet disabled!\n"); | |
1061 | } else { | |
77cbd462 CL |
1062 | |
1063 | // needed to restore wallet transaction meta data after -zapwallettxes | |
1064 | std::vector<CWalletTx> vWtx; | |
1065 | ||
518f3bda JG |
1066 | if (GetBoolArg("-zapwallettxes", false)) { |
1067 | uiInterface.InitMessage(_("Zapping all transactions from wallet...")); | |
1068 | ||
1069 | pwalletMain = new CWallet(strWalletFile); | |
77cbd462 | 1070 | DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx); |
518f3bda JG |
1071 | if (nZapWalletRet != DB_LOAD_OK) { |
1072 | uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted")); | |
1073 | return false; | |
1074 | } | |
1075 | ||
1076 | delete pwalletMain; | |
1077 | pwalletMain = NULL; | |
1078 | } | |
1079 | ||
f9ee7a03 | 1080 | uiInterface.InitMessage(_("Loading wallet...")); |
bb41a87d | 1081 | |
f9ee7a03 JG |
1082 | nStart = GetTimeMillis(); |
1083 | bool fFirstRun = true; | |
1084 | pwalletMain = new CWallet(strWalletFile); | |
1085 | DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun); | |
1086 | if (nLoadWalletRet != DB_LOAD_OK) | |
eed1785f | 1087 | { |
f9ee7a03 JG |
1088 | if (nLoadWalletRet == DB_CORRUPT) |
1089 | strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n"; | |
1090 | else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) | |
1091 | { | |
1092 | string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data" | |
1093 | " or address book entries might be missing or incorrect.")); | |
1094 | InitWarning(msg); | |
1095 | } | |
1096 | else if (nLoadWalletRet == DB_TOO_NEW) | |
2b410c2f | 1097 | strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin Core") << "\n"; |
f9ee7a03 JG |
1098 | else if (nLoadWalletRet == DB_NEED_REWRITE) |
1099 | { | |
2b410c2f | 1100 | strErrors << _("Wallet needed to be rewritten: restart Bitcoin Core to complete") << "\n"; |
7d9d134b | 1101 | LogPrintf("%s", strErrors.str()); |
f9ee7a03 JG |
1102 | return InitError(strErrors.str()); |
1103 | } | |
1104 | else | |
1105 | strErrors << _("Error loading wallet.dat") << "\n"; | |
eed1785f | 1106 | } |
f9ee7a03 JG |
1107 | |
1108 | if (GetBoolArg("-upgradewallet", fFirstRun)) | |
d764d916 | 1109 | { |
f9ee7a03 JG |
1110 | int nMaxVersion = GetArg("-upgradewallet", 0); |
1111 | if (nMaxVersion == 0) // the -upgradewallet without argument case | |
1112 | { | |
1113 | LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST); | |
1114 | nMaxVersion = CLIENT_VERSION; | |
1115 | pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately | |
1116 | } | |
1117 | else | |
1118 | LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion); | |
1119 | if (nMaxVersion < pwalletMain->GetVersion()) | |
1120 | strErrors << _("Cannot downgrade wallet") << "\n"; | |
1121 | pwalletMain->SetMaxVersion(nMaxVersion); | |
d764d916 | 1122 | } |
439e1497 | 1123 | |
f9ee7a03 | 1124 | if (fFirstRun) |
439e1497 | 1125 | { |
f9ee7a03 JG |
1126 | // Create new keyUser and set as default key |
1127 | RandAddSeedPerfmon(); | |
1128 | ||
1129 | CPubKey newDefaultKey; | |
1130 | if (pwalletMain->GetKeyFromPool(newDefaultKey)) { | |
1131 | pwalletMain->SetDefaultKey(newDefaultKey); | |
1132 | if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive")) | |
1133 | strErrors << _("Cannot write default address") << "\n"; | |
1134 | } | |
439e1497 | 1135 | |
f9ee7a03 | 1136 | pwalletMain->SetBestChain(chainActive.GetLocator()); |
360cfe14 | 1137 | } |
95c7db3d | 1138 | |
7d9d134b | 1139 | LogPrintf("%s", strErrors.str()); |
f48742c2 | 1140 | LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart); |
69d605f4 | 1141 | |
a96d1139 | 1142 | RegisterValidationInterface(pwalletMain); |
e8ef3da7 | 1143 | |
f9ee7a03 JG |
1144 | CBlockIndex *pindexRescan = chainActive.Tip(); |
1145 | if (GetBoolArg("-rescan", false)) | |
4c6d41b8 | 1146 | pindexRescan = chainActive.Genesis(); |
f9ee7a03 JG |
1147 | else |
1148 | { | |
1149 | CWalletDB walletdb(strWalletFile); | |
1150 | CBlockLocator locator; | |
1151 | if (walletdb.ReadBestBlock(locator)) | |
6db83db3 | 1152 | pindexRescan = FindForkInGlobalIndex(chainActive, locator); |
f9ee7a03 JG |
1153 | else |
1154 | pindexRescan = chainActive.Genesis(); | |
1155 | } | |
1156 | if (chainActive.Tip() && chainActive.Tip() != pindexRescan) | |
1157 | { | |
1158 | uiInterface.InitMessage(_("Rescanning...")); | |
1159 | LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight); | |
1160 | nStart = GetTimeMillis(); | |
1161 | pwalletMain->ScanForWalletTransactions(pindexRescan, true); | |
f48742c2 | 1162 | LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart); |
f9ee7a03 JG |
1163 | pwalletMain->SetBestChain(chainActive.GetLocator()); |
1164 | nWalletDBUpdated++; | |
77cbd462 CL |
1165 | |
1166 | // Restore wallet transaction metadata after -zapwallettxes=1 | |
1167 | if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2") | |
1168 | { | |
1169 | BOOST_FOREACH(const CWalletTx& wtxOld, vWtx) | |
1170 | { | |
1171 | uint256 hash = wtxOld.GetHash(); | |
1172 | std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash); | |
1173 | if (mi != pwalletMain->mapWallet.end()) | |
1174 | { | |
1175 | const CWalletTx* copyFrom = &wtxOld; | |
1176 | CWalletTx* copyTo = &mi->second; | |
1177 | copyTo->mapValue = copyFrom->mapValue; | |
1178 | copyTo->vOrderForm = copyFrom->vOrderForm; | |
1179 | copyTo->nTimeReceived = copyFrom->nTimeReceived; | |
1180 | copyTo->nTimeSmart = copyFrom->nTimeSmart; | |
1181 | copyTo->fFromMe = copyFrom->fFromMe; | |
1182 | copyTo->strFromAccount = copyFrom->strFromAccount; | |
1183 | copyTo->nOrderPos = copyFrom->nOrderPos; | |
1184 | copyTo->WriteToDisk(); | |
1185 | } | |
1186 | } | |
1187 | } | |
f9ee7a03 | 1188 | } |
e6b7e3dc | 1189 | } // (!fDisableWallet) |
48ba56cd WL |
1190 | #else // ENABLE_WALLET |
1191 | LogPrintf("No wallet compiled in!\n"); | |
1192 | #endif // !ENABLE_WALLET | |
eed1785f | 1193 | // ********************************************************* Step 9: import blocks |
0fcf91ea | 1194 | |
c7b6117d JG |
1195 | if (mapArgs.count("-blocknotify")) |
1196 | uiInterface.NotifyBlockTip.connect(BlockNotifyCallback); | |
1197 | ||
4fea06db | 1198 | // scan for better chains in the block chain database, that are not yet connected in the active best chain |
ef3988ca | 1199 | CValidationState state; |
75f51f2a | 1200 | if (!ActivateBestChain(state)) |
857c61df | 1201 | strErrors << "Failed to connect best block"; |
4fea06db | 1202 | |
21eb5ada | 1203 | std::vector<boost::filesystem::path> vImportFiles; |
7d80d2e3 | 1204 | if (mapArgs.count("-loadblock")) |
69d605f4 | 1205 | { |
7d80d2e3 | 1206 | BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"]) |
21eb5ada | 1207 | vImportFiles.push_back(strFile); |
52c90a2b | 1208 | } |
21eb5ada | 1209 | threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); |
52c90a2b | 1210 | |
94064710 | 1211 | // ********************************************************* Step 10: start node |
69d605f4 | 1212 | |
69d605f4 WL |
1213 | if (!CheckDiskSpace()) |
1214 | return false; | |
1215 | ||
d605bc4c GA |
1216 | if (!strErrors.str().empty()) |
1217 | return InitError(strErrors.str()); | |
1218 | ||
69d605f4 WL |
1219 | RandAddSeedPerfmon(); |
1220 | ||
7d80d2e3 | 1221 | //// debug print |
783b182c | 1222 | LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size()); |
4c6d41b8 | 1223 | LogPrintf("nBestHeight = %d\n", chainActive.Height()); |
48ba56cd | 1224 | #ifdef ENABLE_WALLET |
783b182c WL |
1225 | LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0); |
1226 | LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0); | |
1227 | LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0); | |
48ba56cd | 1228 | #endif |
7d80d2e3 | 1229 | |
b31499ec | 1230 | StartNode(threadGroup); |
69d605f4 | 1231 | |
48ba56cd | 1232 | #ifdef ENABLE_WALLET |
a0cafb79 | 1233 | // Generate coins in the background |
b0730874 | 1234 | if (pwalletMain) |
f654f004 | 1235 | GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", 1)); |
48ba56cd | 1236 | #endif |
a0cafb79 | 1237 | |
94064710 | 1238 | // ********************************************************* Step 11: finished |
7d80d2e3 | 1239 | |
af82884a | 1240 | SetRPCWarmupFinished(); |
7d80d2e3 | 1241 | uiInterface.InitMessage(_("Done loading")); |
7d80d2e3 | 1242 | |
48ba56cd | 1243 | #ifdef ENABLE_WALLET |
b0730874 JG |
1244 | if (pwalletMain) { |
1245 | // Add wallet transactions that aren't already in a block to mapTransactions | |
1246 | pwalletMain->ReacceptWalletTransactions(); | |
7d80d2e3 | 1247 | |
b0730874 JG |
1248 | // Run a thread to flush wallet periodically |
1249 | threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile))); | |
1250 | } | |
48ba56cd | 1251 | #endif |
69d605f4 | 1252 | |
b31499ec | 1253 | return !fRequestShutdown; |
69d605f4 | 1254 | } |