You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

init.cpp 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2012 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "init.h"
  6. #include "main.h"
  7. #include "core.h"
  8. #include "txdb.h"
  9. #include "walletdb.h"
  10. #include "bitcoinrpc.h"
  11. #include "net.h"
  12. #include "util.h"
  13. #include "ui_interface.h"
  14. #include "checkpoints.h"
  15. #include <boost/filesystem.hpp>
  16. #include <boost/filesystem/fstream.hpp>
  17. #include <boost/filesystem/convenience.hpp>
  18. #include <boost/interprocess/sync/file_lock.hpp>
  19. #include <boost/algorithm/string/predicate.hpp>
  20. #include <openssl/crypto.h>
  21. #ifndef WIN32
  22. #include <signal.h>
  23. #endif
  24. using namespace std;
  25. using namespace boost;
  26. CWallet* pwalletMain;
  27. CClientUIInterface uiInterface;
  28. #ifdef WIN32
  29. // Win32 LevelDB doesn't use filedescriptors, and the ones used for
  30. // accessing block files, don't count towards to fd_set size limit
  31. // anyway.
  32. #define MIN_CORE_FILEDESCRIPTORS 0
  33. #else
  34. #define MIN_CORE_FILEDESCRIPTORS 150
  35. #endif
  36. // Used to pass flags to the Bind() function
  37. enum BindFlags {
  38. BF_NONE = 0,
  39. BF_EXPLICIT = (1U << 0),
  40. BF_REPORT_ERROR = (1U << 1)
  41. };
  42. //////////////////////////////////////////////////////////////////////////////
  43. //
  44. // Shutdown
  45. //
  46. //
  47. // Thread management and startup/shutdown:
  48. //
  49. // The network-processing threads are all part of a thread group
  50. // created by AppInit() or the Qt main() function.
  51. //
  52. // A clean exit happens when StartShutdown() or the SIGTERM
  53. // signal handler sets fRequestShutdown, which triggers
  54. // the DetectShutdownThread(), which interrupts the main thread group.
  55. // DetectShutdownThread() then exits, which causes AppInit() to
  56. // continue (it .joins the shutdown thread).
  57. // Shutdown() is then
  58. // called to clean up database connections, and stop other
  59. // threads that should only be stopped after the main network-processing
  60. // threads have exited.
  61. //
  62. // Note that if running -daemon the parent process returns from AppInit2
  63. // before adding any threads to the threadGroup, so .join_all() returns
  64. // immediately and the parent exits from main().
  65. //
  66. // Shutdown for Qt is very similar, only it uses a QTimer to detect
  67. // fRequestShutdown getting set, and then does the normal Qt
  68. // shutdown thing.
  69. //
  70. volatile bool fRequestShutdown = false;
  71. void StartShutdown()
  72. {
  73. fRequestShutdown = true;
  74. }
  75. bool ShutdownRequested()
  76. {
  77. return fRequestShutdown;
  78. }
  79. static CCoinsViewDB *pcoinsdbview;
  80. void Shutdown()
  81. {
  82. static CCriticalSection cs_Shutdown;
  83. TRY_LOCK(cs_Shutdown, lockShutdown);
  84. if (!lockShutdown) return;
  85. RenameThread("bitcoin-shutoff");
  86. nTransactionsUpdated++;
  87. StopRPCThreads();
  88. ShutdownRPCMining();
  89. bitdb.Flush(false);
  90. GenerateBitcoins(false, NULL);
  91. StopNode();
  92. {
  93. LOCK(cs_main);
  94. if (pwalletMain)
  95. pwalletMain->SetBestChain(CBlockLocator(pindexBest));
  96. if (pblocktree)
  97. pblocktree->Flush();
  98. if (pcoinsTip)
  99. pcoinsTip->Flush();
  100. delete pcoinsTip; pcoinsTip = NULL;
  101. delete pcoinsdbview; pcoinsdbview = NULL;
  102. delete pblocktree; pblocktree = NULL;
  103. }
  104. bitdb.Flush(true);
  105. boost::filesystem::remove(GetPidFile());
  106. UnregisterWallet(pwalletMain);
  107. delete pwalletMain;
  108. }
  109. //
  110. // Signal handlers are very limited in what they are allowed to do, so:
  111. //
  112. void HandleSIGTERM(int)
  113. {
  114. fRequestShutdown = true;
  115. }
  116. void HandleSIGHUP(int)
  117. {
  118. fReopenDebugLog = true;
  119. }
  120. bool static InitError(const std::string &str)
  121. {
  122. uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
  123. return false;
  124. }
  125. bool static InitWarning(const std::string &str)
  126. {
  127. uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
  128. return true;
  129. }
  130. bool static Bind(const CService &addr, unsigned int flags) {
  131. if (!(flags & BF_EXPLICIT) && IsLimited(addr))
  132. return false;
  133. std::string strError;
  134. if (!BindListenPort(addr, strError)) {
  135. if (flags & BF_REPORT_ERROR)
  136. return InitError(strError);
  137. return false;
  138. }
  139. return true;
  140. }
  141. // Core-specific options shared between UI and daemon
  142. std::string HelpMessage()
  143. {
  144. string strUsage = _("Options:") + "\n";
  145. strUsage += " -? " + _("This help message") + "\n";
  146. strUsage += " -conf=<file> " + _("Specify configuration file (default: bitcoin.conf)") + "\n";
  147. strUsage += " -pid=<file> " + _("Specify pid file (default: bitcoind.pid)") + "\n";
  148. strUsage += " -gen " + _("Generate coins (default: 0)") + "\n";
  149. strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n";
  150. strUsage += " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n";
  151. strUsage += " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n";
  152. strUsage += " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n";
  153. strUsage += " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n";
  154. strUsage += " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n";
  155. strUsage += " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n";
  156. strUsage += " -port=<port> " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n";
  157. strUsage += " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n";
  158. strUsage += " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n";
  159. strUsage += " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n";
  160. strUsage += " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n";
  161. strUsage += " -externalip=<ip> " + _("Specify your own public address") + "\n";
  162. strUsage += " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n";
  163. strUsage += " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n";
  164. strUsage += " -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n";
  165. strUsage += " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n";
  166. strUsage += " -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n";
  167. strUsage += " -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n";
  168. strUsage += " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n";
  169. strUsage += " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n";
  170. strUsage += " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n";
  171. strUsage += " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n";
  172. #ifdef USE_UPNP
  173. #if USE_UPNP
  174. strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n";
  175. #else
  176. strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n";
  177. #endif
  178. #endif
  179. strUsage += " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n";
  180. if (fHaveGUI)
  181. strUsage += " -server " + _("Accept command line and JSON-RPC commands") + "\n";
  182. #if !defined(WIN32)
  183. if (fHaveGUI)
  184. strUsage += " -daemon " + _("Run in the background as a daemon and accept commands") + "\n";
  185. #endif
  186. strUsage += " -testnet " + _("Use the test network") + "\n";
  187. strUsage += " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n";
  188. strUsage += " -debugnet " + _("Output extra network debugging information") + "\n";
  189. strUsage += " -logtimestamps " + _("Prepend debug output with timestamp") + "\n";
  190. strUsage += " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n";
  191. strUsage += " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n";
  192. #ifdef WIN32
  193. strUsage += " -printtodebugger " + _("Send trace/debug info to debugger") + "\n";
  194. #endif
  195. strUsage += " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n";
  196. strUsage += " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n";
  197. strUsage += " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)") + "\n";
  198. strUsage += " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n";
  199. if (!fHaveGUI)
  200. strUsage += " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n";
  201. strUsage += " -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n";
  202. strUsage += " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n";
  203. strUsage += " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n";
  204. strUsage += " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n";
  205. strUsage += " -upgradewallet " + _("Upgrade wallet to latest format") + "\n";
  206. strUsage += " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n";
  207. strUsage += " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n";
  208. strUsage += " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n";
  209. strUsage += " -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n";
  210. strUsage += " -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n";
  211. strUsage += " -txindex " + _("Maintain a full transaction index (default: 0)") + "\n";
  212. strUsage += " -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n";
  213. strUsage += " -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n";
  214. strUsage += " -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n";
  215. strUsage += "\n"; _("Block creation options:") + "\n";
  216. strUsage += " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n";
  217. strUsage += " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n";
  218. strUsage += " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n";
  219. strUsage += "\n"; _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n";
  220. strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n";
  221. strUsage += " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n";
  222. strUsage += " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n";
  223. strUsage += " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
  224. return strUsage;
  225. }
  226. struct CImportingNow
  227. {
  228. CImportingNow() {
  229. assert(fImporting == false);
  230. fImporting = true;
  231. }
  232. ~CImportingNow() {
  233. assert(fImporting == true);
  234. fImporting = false;
  235. }
  236. };
  237. void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
  238. {
  239. RenameThread("bitcoin-loadblk");
  240. // -reindex
  241. if (fReindex) {
  242. CImportingNow imp;
  243. int nFile = 0;
  244. while (true) {
  245. CDiskBlockPos pos(nFile, 0);
  246. FILE *file = OpenBlockFile(pos, true);
  247. if (!file)
  248. break;
  249. printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
  250. LoadExternalBlockFile(file, &pos);
  251. nFile++;
  252. }
  253. pblocktree->WriteReindexing(false);
  254. fReindex = false;
  255. printf("Reindexing finished\n");
  256. // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
  257. InitBlockIndex();
  258. }
  259. // hardcoded $DATADIR/bootstrap.dat
  260. filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
  261. if (filesystem::exists(pathBootstrap)) {
  262. FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
  263. if (file) {
  264. CImportingNow imp;
  265. filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
  266. printf("Importing bootstrap.dat...\n");
  267. LoadExternalBlockFile(file);
  268. RenameOver(pathBootstrap, pathBootstrapOld);
  269. }
  270. }
  271. // -loadblock=
  272. BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
  273. FILE *file = fopen(path.string().c_str(), "rb");
  274. if (file) {
  275. CImportingNow imp;
  276. printf("Importing %s...\n", path.string().c_str());
  277. LoadExternalBlockFile(file);
  278. }
  279. }
  280. }
  281. /** Initialize bitcoin.
  282. * @pre Parameters should be parsed and config file should be read.
  283. */
  284. bool AppInit2(boost::thread_group& threadGroup)
  285. {
  286. // ********************************************************* Step 1: setup
  287. #ifdef _MSC_VER
  288. // Turn off Microsoft heap dump noise
  289. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
  290. _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
  291. #endif
  292. #if _MSC_VER >= 1400
  293. // Disable confusing "helpful" text message on abort, Ctrl-C
  294. _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
  295. #endif
  296. #ifdef WIN32
  297. // Enable Data Execution Prevention (DEP)
  298. // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
  299. // A failure is non-critical and needs no further attention!
  300. #ifndef PROCESS_DEP_ENABLE
  301. // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
  302. // which is not correct. Can be removed, when GCCs winbase.h is fixed!
  303. #define PROCESS_DEP_ENABLE 0x00000001
  304. #endif
  305. typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
  306. PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
  307. if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
  308. // Initialize Windows Sockets
  309. WSADATA wsadata;
  310. int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
  311. if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
  312. {
  313. return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
  314. }
  315. #endif
  316. #ifndef WIN32
  317. umask(077);
  318. // Clean shutdown on SIGTERM
  319. struct sigaction sa;
  320. sa.sa_handler = HandleSIGTERM;
  321. sigemptyset(&sa.sa_mask);
  322. sa.sa_flags = 0;
  323. sigaction(SIGTERM, &sa, NULL);
  324. sigaction(SIGINT, &sa, NULL);
  325. // Reopen debug.log on SIGHUP
  326. struct sigaction sa_hup;
  327. sa_hup.sa_handler = HandleSIGHUP;
  328. sigemptyset(&sa_hup.sa_mask);
  329. sa_hup.sa_flags = 0;
  330. sigaction(SIGHUP, &sa_hup, NULL);
  331. #endif
  332. // ********************************************************* Step 2: parameter interactions
  333. fTestNet = GetBoolArg("-testnet", false);
  334. Checkpoints::fEnabled = GetBoolArg("-checkpoints", true);
  335. if (mapArgs.count("-bind")) {
  336. // when specifying an explicit binding address, you want to listen on it
  337. // even when -connect or -proxy is specified
  338. SoftSetBoolArg("-listen", true);
  339. }
  340. if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
  341. // when only connecting to trusted nodes, do not seed via DNS, or listen by default
  342. SoftSetBoolArg("-dnsseed", false);
  343. SoftSetBoolArg("-listen", false);
  344. }
  345. if (mapArgs.count("-proxy")) {
  346. // to protect privacy, do not listen by default if a proxy server is specified
  347. SoftSetBoolArg("-listen", false);
  348. }
  349. if (!GetBoolArg("-listen", true)) {
  350. // do not map ports or try to retrieve public IP when not listening (pointless)
  351. SoftSetBoolArg("-upnp", false);
  352. SoftSetBoolArg("-discover", false);
  353. }
  354. if (mapArgs.count("-externalip")) {
  355. // if an explicit public IP is specified, do not try to find others
  356. SoftSetBoolArg("-discover", false);
  357. }
  358. if (GetBoolArg("-salvagewallet", false)) {
  359. // Rewrite just private keys: rescan to find transactions
  360. SoftSetBoolArg("-rescan", true);
  361. }
  362. // Make sure enough file descriptors are available
  363. int nBind = std::max((int)mapArgs.count("-bind"), 1);
  364. nMaxConnections = GetArg("-maxconnections", 125);
  365. nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
  366. int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
  367. if (nFD < MIN_CORE_FILEDESCRIPTORS)
  368. return InitError(_("Not enough file descriptors available."));
  369. if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
  370. nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
  371. // ********************************************************* Step 3: parameter-to-internal-flags
  372. fDebug = GetBoolArg("-debug", false);
  373. fBenchmark = GetBoolArg("-benchmark", false);
  374. // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
  375. nScriptCheckThreads = GetArg("-par", 0);
  376. if (nScriptCheckThreads <= 0)
  377. nScriptCheckThreads += boost::thread::hardware_concurrency();
  378. if (nScriptCheckThreads <= 1)
  379. nScriptCheckThreads = 0;
  380. else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
  381. nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
  382. // -debug implies fDebug*
  383. if (fDebug)
  384. fDebugNet = true;
  385. else
  386. fDebugNet = GetBoolArg("-debugnet", false);
  387. if (fDaemon)
  388. fServer = true;
  389. else
  390. fServer = GetBoolArg("-server", false);
  391. /* force fServer when running without GUI */
  392. if (!fHaveGUI)
  393. fServer = true;
  394. fPrintToConsole = GetBoolArg("-printtoconsole", false);
  395. fPrintToDebugger = GetBoolArg("-printtodebugger", false);
  396. fLogTimestamps = GetBoolArg("-logtimestamps", false);
  397. if (mapArgs.count("-timeout"))
  398. {
  399. int nNewTimeout = GetArg("-timeout", 5000);
  400. if (nNewTimeout > 0 && nNewTimeout < 600000)
  401. nConnectTimeout = nNewTimeout;
  402. }
  403. // Continue to put "/P2SH/" in the coinbase to monitor
  404. // BIP16 support.
  405. // This can be removed eventually...
  406. const char* pszP2SH = "/P2SH/";
  407. COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
  408. // Fee-per-kilobyte amount considered the same as "free"
  409. // If you are mining, be careful setting this:
  410. // if you set it to zero then
  411. // a transaction spammer can cheaply fill blocks using
  412. // 1-satoshi-fee transactions. It should be set above the real
  413. // cost to you of processing a transaction.
  414. if (mapArgs.count("-mintxfee"))
  415. {
  416. int64 n = 0;
  417. if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
  418. CTransaction::nMinTxFee = n;
  419. else
  420. return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str()));
  421. }
  422. if (mapArgs.count("-minrelaytxfee"))
  423. {
  424. int64 n = 0;
  425. if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
  426. CTransaction::nMinRelayTxFee = n;
  427. else
  428. return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str()));
  429. }
  430. if (mapArgs.count("-paytxfee"))
  431. {
  432. if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
  433. return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
  434. if (nTransactionFee > 0.25 * COIN)
  435. InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
  436. }
  437. // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
  438. std::string strDataDir = GetDataDir().string();
  439. // Make sure only a single Bitcoin process is using the data directory.
  440. boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
  441. FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
  442. if (file) fclose(file);
  443. static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
  444. if (!lock.try_lock())
  445. return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), strDataDir.c_str()));
  446. if (GetBoolArg("-shrinkdebugfile", !fDebug))
  447. ShrinkDebugFile();
  448. printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
  449. printf("Bitcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
  450. printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
  451. if (!fLogTimestamps)
  452. printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
  453. printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
  454. printf("Using data directory %s\n", strDataDir.c_str());
  455. printf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
  456. std::ostringstream strErrors;
  457. if (fDaemon)
  458. fprintf(stdout, "Bitcoin server starting\n");
  459. if (nScriptCheckThreads) {
  460. printf("Using %u threads for script verification\n", nScriptCheckThreads);
  461. for (int i=0; i<nScriptCheckThreads-1; i++)
  462. threadGroup.create_thread(&ThreadScriptCheck);
  463. }
  464. int64 nStart;
  465. // ********************************************************* Step 5: verify wallet database integrity
  466. uiInterface.InitMessage(_("Verifying wallet..."));
  467. if (!bitdb.Open(GetDataDir()))
  468. {
  469. // try moving the database env out of the way
  470. boost::filesystem::path pathDatabase = GetDataDir() / "database";
  471. boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime());
  472. try {
  473. boost::filesystem::rename(pathDatabase, pathDatabaseBak);
  474. printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str());
  475. } catch(boost::filesystem::filesystem_error &error) {
  476. // failure is ok (well, not really, but it's not worse than what we started with)
  477. }
  478. // try again
  479. if (!bitdb.Open(GetDataDir())) {
  480. // if it still fails, it probably means we can't even create the database env
  481. string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
  482. return InitError(msg);
  483. }
  484. }
  485. if (GetBoolArg("-salvagewallet", false))
  486. {
  487. // Recover readable keypairs:
  488. if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
  489. return false;
  490. }
  491. if (filesystem::exists(GetDataDir() / "wallet.dat"))
  492. {
  493. CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
  494. if (r == CDBEnv::RECOVER_OK)
  495. {
  496. string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
  497. " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
  498. " your balance or transactions are incorrect you should"
  499. " restore from a backup."), strDataDir.c_str());
  500. InitWarning(msg);
  501. }
  502. if (r == CDBEnv::RECOVER_FAIL)
  503. return InitError(_("wallet.dat corrupt, salvage failed"));
  504. }
  505. // ********************************************************* Step 6: network initialization
  506. RegisterNodeSignals(GetNodeSignals());
  507. int nSocksVersion = GetArg("-socks", 5);
  508. if (nSocksVersion != 4 && nSocksVersion != 5)
  509. return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
  510. if (mapArgs.count("-onlynet")) {
  511. std::set<enum Network> nets;
  512. BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
  513. enum Network net = ParseNetwork(snet);
  514. if (net == NET_UNROUTABLE)
  515. return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
  516. nets.insert(net);
  517. }
  518. for (int n = 0; n < NET_MAX; n++) {
  519. enum Network net = (enum Network)n;
  520. if (!nets.count(net))
  521. SetLimited(net);
  522. }
  523. }
  524. #if defined(USE_IPV6)
  525. #if ! USE_IPV6
  526. else
  527. SetLimited(NET_IPV6);
  528. #endif
  529. #endif
  530. CService addrProxy;
  531. bool fProxy = false;
  532. if (mapArgs.count("-proxy")) {
  533. addrProxy = CService(mapArgs["-proxy"], 9050);
  534. if (!addrProxy.IsValid())
  535. return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
  536. if (!IsLimited(NET_IPV4))
  537. SetProxy(NET_IPV4, addrProxy, nSocksVersion);
  538. if (nSocksVersion > 4) {
  539. #ifdef USE_IPV6
  540. if (!IsLimited(NET_IPV6))
  541. SetProxy(NET_IPV6, addrProxy, nSocksVersion);
  542. #endif
  543. SetNameProxy(addrProxy, nSocksVersion);
  544. }
  545. fProxy = true;
  546. }
  547. // -tor can override normal proxy, -notor disables tor entirely
  548. if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
  549. CService addrOnion;
  550. if (!mapArgs.count("-tor"))
  551. addrOnion = addrProxy;
  552. else
  553. addrOnion = CService(mapArgs["-tor"], 9050);
  554. if (!addrOnion.IsValid())
  555. return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
  556. SetProxy(NET_TOR, addrOnion, 5);
  557. SetReachable(NET_TOR);
  558. }
  559. // see Step 2: parameter interactions for more information about these
  560. fNoListen = !GetBoolArg("-listen", true);
  561. fDiscover = GetBoolArg("-discover", true);
  562. fNameLookup = GetBoolArg("-dns", true);
  563. bool fBound = false;
  564. if (!fNoListen) {
  565. if (mapArgs.count("-bind")) {
  566. BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
  567. CService addrBind;
  568. if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
  569. return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
  570. fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
  571. }
  572. }
  573. else {
  574. struct in_addr inaddr_any;
  575. inaddr_any.s_addr = INADDR_ANY;
  576. #ifdef USE_IPV6
  577. fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
  578. #endif
  579. fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
  580. }
  581. if (!fBound)
  582. return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
  583. }
  584. if (mapArgs.count("-externalip")) {
  585. BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
  586. CService addrLocal(strAddr, GetListenPort(), fNameLookup);
  587. if (!addrLocal.IsValid())
  588. return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
  589. AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
  590. }
  591. }
  592. BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
  593. AddOneShot(strDest);
  594. // ********************************************************* Step 7: load block chain
  595. fReindex = GetBoolArg("-reindex", false);
  596. // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
  597. filesystem::path blocksDir = GetDataDir() / "blocks";
  598. if (!filesystem::exists(blocksDir))
  599. {
  600. filesystem::create_directories(blocksDir);
  601. bool linked = false;
  602. for (unsigned int i = 1; i < 10000; i++) {
  603. filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
  604. if (!filesystem::exists(source)) break;
  605. filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
  606. try {
  607. filesystem::create_hard_link(source, dest);
  608. printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
  609. linked = true;
  610. } catch (filesystem::filesystem_error & e) {
  611. // Note: hardlink creation failing is not a disaster, it just means
  612. // blocks will get re-downloaded from peers.
  613. printf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
  614. break;
  615. }
  616. }
  617. if (linked)
  618. {
  619. fReindex = true;
  620. }
  621. }
  622. // cache size calculations
  623. size_t nTotalCache = GetArg("-dbcache", 25) << 20;
  624. if (nTotalCache < (1 << 22))
  625. nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB
  626. size_t nBlockTreeDBCache = nTotalCache / 8;
  627. if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
  628. nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
  629. nTotalCache -= nBlockTreeDBCache;
  630. size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
  631. nTotalCache -= nCoinDBCache;
  632. nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
  633. bool fLoaded = false;
  634. while (!fLoaded) {
  635. bool fReset = fReindex;
  636. std::string strLoadError;
  637. uiInterface.InitMessage(_("Loading block index..."));
  638. nStart = GetTimeMillis();
  639. do {
  640. try {
  641. UnloadBlockIndex();
  642. delete pcoinsTip;
  643. delete pcoinsdbview;
  644. delete pblocktree;
  645. pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
  646. pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
  647. pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
  648. if (fReindex)
  649. pblocktree->WriteReindexing(true);
  650. if (!LoadBlockIndex()) {
  651. strLoadError = _("Error loading block database");
  652. break;
  653. }
  654. // If the loaded chain has a wrong genesis, bail out immediately
  655. // (we're likely using a testnet datadir, or the other way around).
  656. if (!mapBlockIndex.empty() && pindexGenesisBlock == NULL)
  657. return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
  658. // Check for changed -txindex state (only necessary if we are not reindexing anyway)
  659. if (!fReindex && fTxIndex != GetBoolArg("-txindex", false)) {
  660. strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
  661. break;
  662. }
  663. // Initialize the block index (no-op if non-empty database was already loaded)
  664. if (!InitBlockIndex()) {
  665. strLoadError = _("Error initializing block database");
  666. break;
  667. }
  668. uiInterface.InitMessage(_("Verifying blocks..."));
  669. if (!VerifyDB()) {
  670. strLoadError = _("Corrupted block database detected");
  671. break;
  672. }
  673. } catch(std::exception &e) {
  674. strLoadError = _("Error opening block database");
  675. break;
  676. }
  677. fLoaded = true;
  678. } while(false);
  679. if (!fLoaded) {
  680. // first suggest a reindex
  681. if (!fReset) {
  682. bool fRet = uiInterface.ThreadSafeMessageBox(
  683. strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
  684. "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
  685. if (fRet) {
  686. fReindex = true;
  687. fRequestShutdown = false;
  688. } else {
  689. return false;
  690. }
  691. } else {
  692. return InitError(strLoadError);
  693. }
  694. }
  695. }
  696. // as LoadBlockIndex can take several minutes, it's possible the user
  697. // requested to kill bitcoin-qt during the last operation. If so, exit.
  698. // As the program has not fully started yet, Shutdown() is possibly overkill.
  699. if (fRequestShutdown)
  700. {
  701. printf("Shutdown requested. Exiting.\n");
  702. return false;
  703. }
  704. printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
  705. if (GetBoolArg("-printblockindex", false) || GetBoolArg("-printblocktree", false))
  706. {
  707. PrintBlockTree();
  708. return false;
  709. }
  710. if (mapArgs.count("-printblock"))
  711. {
  712. string strMatch = mapArgs["-printblock"];
  713. int nFound = 0;
  714. for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
  715. {
  716. uint256 hash = (*mi).first;
  717. if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
  718. {
  719. CBlockIndex* pindex = (*mi).second;
  720. CBlock block;
  721. block.ReadFromDisk(pindex);
  722. block.BuildMerkleTree();
  723. block.print();
  724. printf("\n");
  725. nFound++;
  726. }
  727. }
  728. if (nFound == 0)
  729. printf("No blocks matching %s were found\n", strMatch.c_str());
  730. return false;
  731. }
  732. // ********************************************************* Step 8: load wallet
  733. uiInterface.InitMessage(_("Loading wallet..."));
  734. nStart = GetTimeMillis();
  735. bool fFirstRun = true;
  736. pwalletMain = new CWallet("wallet.dat");
  737. DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
  738. if (nLoadWalletRet != DB_LOAD_OK)
  739. {
  740. if (nLoadWalletRet == DB_CORRUPT)
  741. strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
  742. else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
  743. {
  744. string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
  745. " or address book entries might be missing or incorrect."));
  746. InitWarning(msg);
  747. }
  748. else if (nLoadWalletRet == DB_TOO_NEW)
  749. strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
  750. else if (nLoadWalletRet == DB_NEED_REWRITE)
  751. {
  752. strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
  753. printf("%s", strErrors.str().c_str());
  754. return InitError(strErrors.str());
  755. }
  756. else
  757. strErrors << _("Error loading wallet.dat") << "\n";
  758. }
  759. if (GetBoolArg("-upgradewallet", fFirstRun))
  760. {
  761. int nMaxVersion = GetArg("-upgradewallet", 0);
  762. if (nMaxVersion == 0) // the -upgradewallet without argument case
  763. {
  764. printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
  765. nMaxVersion = CLIENT_VERSION;
  766. pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
  767. }
  768. else
  769. printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
  770. if (nMaxVersion < pwalletMain->GetVersion())
  771. strErrors << _("Cannot downgrade wallet") << "\n";
  772. pwalletMain->SetMaxVersion(nMaxVersion);
  773. }
  774. if (fFirstRun)
  775. {
  776. // Create new keyUser and set as default key
  777. RandAddSeedPerfmon();
  778. CPubKey newDefaultKey;
  779. if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
  780. pwalletMain->SetDefaultKey(newDefaultKey);
  781. if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
  782. strErrors << _("Cannot write default address") << "\n";
  783. }
  784. pwalletMain->SetBestChain(CBlockLocator(pindexBest));
  785. }
  786. printf("%s", strErrors.str().c_str());
  787. printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
  788. RegisterWallet(pwalletMain);
  789. CBlockIndex *pindexRescan = pindexBest;
  790. if (GetBoolArg("-rescan", false))
  791. pindexRescan = pindexGenesisBlock;
  792. else
  793. {
  794. CWalletDB walletdb("wallet.dat");
  795. CBlockLocator locator;
  796. if (walletdb.ReadBestBlock(locator))
  797. pindexRescan = locator.GetBlockIndex();
  798. else
  799. pindexRescan = pindexGenesisBlock;
  800. }
  801. if (pindexBest && pindexBest != pindexRescan)
  802. {
  803. uiInterface.InitMessage(_("Rescanning..."));
  804. printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
  805. nStart = GetTimeMillis();
  806. pwalletMain->ScanForWalletTransactions(pindexRescan, true);
  807. printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
  808. pwalletMain->SetBestChain(CBlockLocator(pindexBest));
  809. nWalletDBUpdated++;
  810. }
  811. // ********************************************************* Step 9: import blocks
  812. // scan for better chains in the block chain database, that are not yet connected in the active best chain
  813. CValidationState state;
  814. if (!ConnectBestBlock(state))
  815. strErrors << "Failed to connect best block";
  816. std::vector<boost::filesystem::path> vImportFiles;
  817. if (mapArgs.count("-loadblock"))
  818. {
  819. BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
  820. vImportFiles.push_back(strFile);
  821. }
  822. threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
  823. // ********************************************************* Step 10: load peers
  824. uiInterface.InitMessage(_("Loading addresses..."));
  825. nStart = GetTimeMillis();
  826. {
  827. CAddrDB::SetMessageStart(pchMessageStart);
  828. CAddrDB adb;
  829. if (!adb.Read(addrman))
  830. printf("Invalid or missing peers.dat; recreating\n");
  831. }
  832. printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
  833. addrman.size(), GetTimeMillis() - nStart);
  834. // ********************************************************* Step 11: start node
  835. if (!CheckDiskSpace())
  836. return false;
  837. if (!strErrors.str().empty())
  838. return InitError(strErrors.str());
  839. RandAddSeedPerfmon();
  840. //// debug print
  841. printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
  842. printf("nBestHeight = %d\n", nBestHeight);
  843. printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
  844. printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
  845. printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
  846. StartNode(threadGroup);
  847. // InitRPCMining is needed here so getwork/getblocktemplate in the GUI debug console works properly.
  848. InitRPCMining();
  849. if (fServer)
  850. StartRPCThreads();
  851. // Generate coins in the background
  852. GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
  853. // ********************************************************* Step 12: finished
  854. uiInterface.InitMessage(_("Done loading"));
  855. // Add wallet transactions that aren't already in a block to mapTransactions
  856. pwalletMain->ReacceptWalletTransactions();
  857. // Run a thread to flush wallet periodically
  858. threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
  859. return !fRequestShutdown;
  860. }