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 38KB

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