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