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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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 license.txt or http://www.opensource.org/licenses/mit-license.php.
  5. #include "headers.h"
  6. #include "db.h"
  7. #include "bitcoinrpc.h"
  8. #include "net.h"
  9. #include "init.h"
  10. #include "strlcpy.h"
  11. #include <boost/filesystem.hpp>
  12. #include <boost/filesystem/fstream.hpp>
  13. #include <boost/filesystem/convenience.hpp>
  14. #include <boost/interprocess/sync/file_lock.hpp>
  15. #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
  16. #define _BITCOIN_QT_PLUGINS_INCLUDED
  17. #define __INSURE__
  18. #include <QtPlugin>
  19. Q_IMPORT_PLUGIN(qcncodecs)
  20. Q_IMPORT_PLUGIN(qjpcodecs)
  21. Q_IMPORT_PLUGIN(qtwcodecs)
  22. Q_IMPORT_PLUGIN(qkrcodecs)
  23. Q_IMPORT_PLUGIN(qtaccessiblewidgets)
  24. #endif
  25. using namespace std;
  26. using namespace boost;
  27. CWallet* pwalletMain;
  28. //////////////////////////////////////////////////////////////////////////////
  29. //
  30. // Shutdown
  31. //
  32. void ExitTimeout(void* parg)
  33. {
  34. #ifdef WIN32
  35. Sleep(5000);
  36. ExitProcess(0);
  37. #endif
  38. }
  39. void Shutdown(void* parg)
  40. {
  41. static CCriticalSection cs_Shutdown;
  42. static bool fTaken;
  43. bool fFirstThread = false;
  44. TRY_CRITICAL_BLOCK(cs_Shutdown)
  45. {
  46. fFirstThread = !fTaken;
  47. fTaken = true;
  48. }
  49. static bool fExit;
  50. if (fFirstThread)
  51. {
  52. fShutdown = true;
  53. nTransactionsUpdated++;
  54. DBFlush(false);
  55. StopNode();
  56. DBFlush(true);
  57. boost::filesystem::remove(GetPidFile());
  58. UnregisterWallet(pwalletMain);
  59. delete pwalletMain;
  60. CreateThread(ExitTimeout, NULL);
  61. Sleep(50);
  62. printf("Bitcoin exiting\n\n");
  63. fExit = true;
  64. exit(0);
  65. }
  66. else
  67. {
  68. while (!fExit)
  69. Sleep(500);
  70. Sleep(100);
  71. ExitThread(0);
  72. }
  73. }
  74. void HandleSIGTERM(int)
  75. {
  76. fRequestShutdown = true;
  77. }
  78. //////////////////////////////////////////////////////////////////////////////
  79. //
  80. // Start
  81. //
  82. #if !defined(QT_GUI)
  83. int main(int argc, char* argv[])
  84. {
  85. bool fRet = false;
  86. fRet = AppInit(argc, argv);
  87. if (fRet && fDaemon)
  88. return 0;
  89. return 1;
  90. }
  91. #endif
  92. bool AppInit(int argc, char* argv[])
  93. {
  94. bool fRet = false;
  95. try
  96. {
  97. fRet = AppInit2(argc, argv);
  98. }
  99. catch (std::exception& e) {
  100. PrintException(&e, "AppInit()");
  101. } catch (...) {
  102. PrintException(NULL, "AppInit()");
  103. }
  104. if (!fRet)
  105. Shutdown(NULL);
  106. return fRet;
  107. }
  108. bool AppInit2(int argc, char* argv[])
  109. {
  110. #ifdef _MSC_VER
  111. // Turn off microsoft heap dump noise
  112. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
  113. _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
  114. #endif
  115. #if _MSC_VER >= 1400
  116. // Disable confusing "helpful" text message on abort, ctrl-c
  117. _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
  118. #endif
  119. #ifndef WIN32
  120. umask(077);
  121. #endif
  122. #ifndef WIN32
  123. // Clean shutdown on SIGTERM
  124. struct sigaction sa;
  125. sa.sa_handler = HandleSIGTERM;
  126. sigemptyset(&sa.sa_mask);
  127. sa.sa_flags = 0;
  128. sigaction(SIGTERM, &sa, NULL);
  129. sigaction(SIGINT, &sa, NULL);
  130. sigaction(SIGHUP, &sa, NULL);
  131. #endif
  132. //
  133. // Parameters
  134. //
  135. // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
  136. #if !defined(QT_GUI)
  137. ParseParameters(argc, argv);
  138. if (!ReadConfigFile(mapArgs, mapMultiArgs))
  139. {
  140. fprintf(stderr, "Error: Specified directory does not exist\n");
  141. Shutdown(NULL);
  142. }
  143. #endif
  144. if (mapArgs.count("-?") || mapArgs.count("--help"))
  145. {
  146. string strUsage = string() +
  147. _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
  148. _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
  149. " bitcoind [options] \t " + "\n" +
  150. " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind") + "\n" +
  151. " bitcoind [options] help \t\t " + _("List commands") + "\n" +
  152. " bitcoind [options] help <command> \t\t " + _("Get help for a command") + "\n" +
  153. _("Options:") + "\n" +
  154. " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
  155. " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
  156. " -gen \t\t " + _("Generate coins") + "\n" +
  157. " -gen=0 \t\t " + _("Don't generate coins") + "\n" +
  158. " -min \t\t " + _("Start minimized") + "\n" +
  159. " -splash \t\t " + _("Show splash screen on startup (default: 1)") + "\n" +
  160. " -datadir=<dir> \t\t " + _("Specify data directory") + "\n" +
  161. " -dbcache=<n> \t\t " + _("Set database cache size in megabytes (default: 25)") + "\n" +
  162. " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)") + "\n" +
  163. " -proxy=<ip:port> \t " + _("Connect through socks4 proxy") + "\n" +
  164. " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" +
  165. " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
  166. " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
  167. " -addnode=<ip> \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
  168. " -connect=<ip> \t\t " + _("Connect only to the specified node") + "\n" +
  169. " -irc \t " + _("Find peers using internet relay chat (default: 0)") + "\n" +
  170. " -listen \t " + _("Accept connections from outside (default: 1)") + "\n" +
  171. #ifdef QT_GUI
  172. " -lang=<lang> \t\t " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
  173. #endif
  174. " -dnsseed \t " + _("Find peers using DNS lookup (default: 1)") + "\n" +
  175. " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
  176. " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
  177. " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
  178. " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
  179. #ifdef USE_UPNP
  180. #if USE_UPNP
  181. " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
  182. #else
  183. " -upnp \t " + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
  184. #endif
  185. #endif
  186. " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send") + "\n" +
  187. #ifdef QT_GUI
  188. " -server \t\t " + _("Accept command line and JSON-RPC commands") + "\n" +
  189. #endif
  190. #if !defined(WIN32) && !defined(QT_GUI)
  191. " -daemon \t\t " + _("Run in the background as a daemon and accept commands") + "\n" +
  192. #endif
  193. " -testnet \t\t " + _("Use the test network") + "\n" +
  194. " -debug \t\t " + _("Output extra debugging information") + "\n" +
  195. " -logtimestamps \t " + _("Prepend debug output with timestamp") + "\n" +
  196. " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
  197. #ifdef WIN32
  198. " -printtodebugger \t " + _("Send trace/debug info to debugger") + "\n" +
  199. #endif
  200. " -rpcuser=<user> \t " + _("Username for JSON-RPC connections") + "\n" +
  201. " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections") + "\n" +
  202. " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
  203. " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
  204. " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
  205. " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
  206. " -upgradewallet \t " + _("Upgrade wallet to latest format") + "\n" +
  207. " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)") + "\n" +
  208. " -rescan \t " + _("Rescan the block chain for missing wallet transactions") + "\n" +
  209. " -checkblocks=<n> \t\t " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
  210. " -checklevel=<n> \t\t " + _("How thorough the block verification is (0-6, default: 1)") + "\n";
  211. #ifdef USE_SSL
  212. strUsage += string() +
  213. _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
  214. " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
  215. " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)") + "\n" +
  216. " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)") + "\n" +
  217. " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
  218. #endif
  219. strUsage += string() +
  220. " -? \t\t " + _("This help message") + "\n";
  221. // Remove tabs
  222. strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
  223. #if defined(QT_GUI) && defined(WIN32)
  224. // On windows, show a message box, as there is no stderr
  225. wxMessageBox(strUsage, "Usage");
  226. #else
  227. fprintf(stderr, "%s", strUsage.c_str());
  228. #endif
  229. return false;
  230. }
  231. fTestNet = GetBoolArg("-testnet");
  232. if (fTestNet)
  233. {
  234. SoftSetBoolArg("-irc", true);
  235. }
  236. fDebug = GetBoolArg("-debug");
  237. #if !defined(WIN32) && !defined(QT_GUI)
  238. fDaemon = GetBoolArg("-daemon");
  239. #else
  240. fDaemon = false;
  241. #endif
  242. if (fDaemon)
  243. fServer = true;
  244. else
  245. fServer = GetBoolArg("-server");
  246. /* force fServer when running without GUI */
  247. #if !defined(QT_GUI)
  248. fServer = true;
  249. #endif
  250. fPrintToConsole = GetBoolArg("-printtoconsole");
  251. fPrintToDebugger = GetBoolArg("-printtodebugger");
  252. fLogTimestamps = GetBoolArg("-logtimestamps");
  253. #ifndef QT_GUI
  254. for (int i = 1; i < argc; i++)
  255. if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
  256. fCommandLine = true;
  257. if (fCommandLine)
  258. {
  259. int ret = CommandLineRPC(argc, argv);
  260. exit(ret);
  261. }
  262. #endif
  263. #if !defined(WIN32) && !defined(QT_GUI)
  264. if (fDaemon)
  265. {
  266. // Daemonize
  267. pid_t pid = fork();
  268. if (pid < 0)
  269. {
  270. fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
  271. return false;
  272. }
  273. if (pid > 0)
  274. {
  275. CreatePidFile(GetPidFile(), pid);
  276. return true;
  277. }
  278. pid_t sid = setsid();
  279. if (sid < 0)
  280. fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
  281. }
  282. #endif
  283. if (!fDebug && !pszSetDataDir[0])
  284. ShrinkDebugFile();
  285. printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
  286. printf("Bitcoin version %s\n", FormatFullVersion().c_str());
  287. printf("Default data directory %s\n", GetDefaultDataDir().c_str());
  288. if (GetBoolArg("-loadblockindextest"))
  289. {
  290. CTxDB txdb("r");
  291. txdb.LoadBlockIndex();
  292. PrintBlockTree();
  293. return false;
  294. }
  295. // Make sure only a single bitcoin process is using the data directory.
  296. string strLockFile = GetDataDir() + "/.lock";
  297. FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
  298. if (file) fclose(file);
  299. static boost::interprocess::file_lock lock(strLockFile.c_str());
  300. if (!lock.try_lock())
  301. {
  302. wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
  303. return false;
  304. }
  305. std::ostringstream strErrors;
  306. //
  307. // Load data files
  308. //
  309. if (fDaemon)
  310. fprintf(stdout, "bitcoin server starting\n");
  311. int64 nStart;
  312. InitMessage(_("Loading addresses..."));
  313. printf("Loading addresses...\n");
  314. nStart = GetTimeMillis();
  315. if (!LoadAddresses())
  316. strErrors << _("Error loading addr.dat") << "\n";
  317. printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
  318. InitMessage(_("Loading block index..."));
  319. printf("Loading block index...\n");
  320. nStart = GetTimeMillis();
  321. if (!LoadBlockIndex())
  322. strErrors << _("Error loading blkindex.dat") << "\n";
  323. printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
  324. InitMessage(_("Loading wallet..."));
  325. printf("Loading wallet...\n");
  326. nStart = GetTimeMillis();
  327. bool fFirstRun;
  328. pwalletMain = new CWallet("wallet.dat");
  329. int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
  330. if (nLoadWalletRet != DB_LOAD_OK)
  331. {
  332. if (nLoadWalletRet == DB_CORRUPT)
  333. strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
  334. else if (nLoadWalletRet == DB_TOO_NEW)
  335. strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
  336. else if (nLoadWalletRet == DB_NEED_REWRITE)
  337. {
  338. strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
  339. printf("%s", strErrors.str().c_str());
  340. wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
  341. return false;
  342. }
  343. else
  344. strErrors << _("Error loading wallet.dat") << "\n";
  345. }
  346. if (GetBoolArg("-upgradewallet", fFirstRun))
  347. {
  348. int nMaxVersion = GetArg("-upgradewallet", 0);
  349. if (nMaxVersion == 0) // the -walletupgrade without argument case
  350. {
  351. printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
  352. nMaxVersion = CLIENT_VERSION;
  353. pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
  354. }
  355. else
  356. printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
  357. if (nMaxVersion < pwalletMain->GetVersion())
  358. strErrors << _("Cannot downgrade wallet") << "\n";
  359. pwalletMain->SetMaxVersion(nMaxVersion);
  360. }
  361. if (fFirstRun)
  362. {
  363. // Create new keyUser and set as default key
  364. RandAddSeedPerfmon();
  365. std::vector<unsigned char> newDefaultKey;
  366. if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
  367. strErrors << _("Cannot initialize keypool") << "\n";
  368. pwalletMain->SetDefaultKey(newDefaultKey);
  369. if (!pwalletMain->SetAddressBookName(CBitcoinAddress(pwalletMain->vchDefaultKey), ""))
  370. strErrors << _("Cannot write default address") << "\n";
  371. }
  372. printf("%s", strErrors.str().c_str());
  373. printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
  374. RegisterWallet(pwalletMain);
  375. CBlockIndex *pindexRescan = pindexBest;
  376. if (GetBoolArg("-rescan"))
  377. pindexRescan = pindexGenesisBlock;
  378. else
  379. {
  380. CWalletDB walletdb("wallet.dat");
  381. CBlockLocator locator;
  382. if (walletdb.ReadBestBlock(locator))
  383. pindexRescan = locator.GetBlockIndex();
  384. }
  385. if (pindexBest != pindexRescan)
  386. {
  387. InitMessage(_("Rescanning..."));
  388. printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
  389. nStart = GetTimeMillis();
  390. pwalletMain->ScanForWalletTransactions(pindexRescan, true);
  391. printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
  392. }
  393. InitMessage(_("Done loading"));
  394. printf("Done loading\n");
  395. //// debug print
  396. printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
  397. printf("nBestHeight = %d\n", nBestHeight);
  398. printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
  399. printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
  400. printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
  401. if (!strErrors.str().empty())
  402. {
  403. wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
  404. return false;
  405. }
  406. // Add wallet transactions that aren't already in a block to mapTransactions
  407. pwalletMain->ReacceptWalletTransactions();
  408. // Note: Bitcoin-QT stores several settings in the wallet, so we want
  409. // to load the wallet BEFORE parsing command-line arguments, so
  410. // the command-line/bitcoin.conf settings override GUI setting.
  411. //
  412. // Parameters
  413. //
  414. if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
  415. {
  416. PrintBlockTree();
  417. return false;
  418. }
  419. if (mapArgs.count("-timeout"))
  420. {
  421. int nNewTimeout = GetArg("-timeout", 5000);
  422. if (nNewTimeout > 0 && nNewTimeout < 600000)
  423. nConnectTimeout = nNewTimeout;
  424. }
  425. if (mapArgs.count("-printblock"))
  426. {
  427. string strMatch = mapArgs["-printblock"];
  428. int nFound = 0;
  429. for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
  430. {
  431. uint256 hash = (*mi).first;
  432. if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
  433. {
  434. CBlockIndex* pindex = (*mi).second;
  435. CBlock block;
  436. block.ReadFromDisk(pindex);
  437. block.BuildMerkleTree();
  438. block.print();
  439. printf("\n");
  440. nFound++;
  441. }
  442. }
  443. if (nFound == 0)
  444. printf("No blocks matching %s were found\n", strMatch.c_str());
  445. return false;
  446. }
  447. if (mapArgs.count("-proxy"))
  448. {
  449. fUseProxy = true;
  450. addrProxy = CService(mapArgs["-proxy"], 9050);
  451. if (!addrProxy.IsValid())
  452. {
  453. wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
  454. return false;
  455. }
  456. }
  457. bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
  458. if (fTor)
  459. {
  460. // Use SoftSetBoolArg here so user can override any of these if they wish.
  461. // Note: the GetBoolArg() calls for all of these must happen later.
  462. SoftSetBoolArg("-listen", false);
  463. SoftSetBoolArg("-irc", false);
  464. SoftSetBoolArg("-dnsseed", false);
  465. SoftSetBoolArg("-upnp", false);
  466. SoftSetBoolArg("-dns", false);
  467. }
  468. fAllowDNS = GetBoolArg("-dns");
  469. fNoListen = !GetBoolArg("-listen", true);
  470. // Continue to put "/P2SH/" in the coinbase to monitor
  471. // BIP16 support.
  472. // This can be removed eventually...
  473. const char* pszP2SH = "/P2SH/";
  474. COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
  475. if (!fNoListen)
  476. {
  477. std::string strError;
  478. if (!BindListenPort(strError))
  479. {
  480. wxMessageBox(strError, "Bitcoin");
  481. return false;
  482. }
  483. }
  484. if (mapArgs.count("-addnode"))
  485. {
  486. BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
  487. {
  488. CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
  489. addr.nTime = 0; // so it won't relay unless successfully connected
  490. if (addr.IsValid())
  491. addrman.Add(addr, CNetAddr("127.0.0.1"));
  492. }
  493. }
  494. if (mapArgs.count("-paytxfee"))
  495. {
  496. if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
  497. {
  498. wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
  499. return false;
  500. }
  501. if (nTransactionFee > 0.25 * COIN)
  502. wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
  503. }
  504. //
  505. // Start the node
  506. //
  507. if (!CheckDiskSpace())
  508. return false;
  509. RandAddSeedPerfmon();
  510. if (!CreateThread(StartNode, NULL))
  511. wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
  512. if (fServer)
  513. CreateThread(ThreadRPCServer, NULL);
  514. #ifdef QT_GUI
  515. if(GetStartOnSystemStartup())
  516. SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
  517. #endif
  518. #if !defined(QT_GUI)
  519. while (1)
  520. Sleep(5000);
  521. #endif
  522. return true;
  523. }
  524. #ifdef WIN32
  525. string StartupShortcutPath()
  526. {
  527. return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
  528. }
  529. bool GetStartOnSystemStartup()
  530. {
  531. return filesystem::exists(StartupShortcutPath().c_str());
  532. }
  533. bool SetStartOnSystemStartup(bool fAutoStart)
  534. {
  535. // If the shortcut exists already, remove it for updating
  536. remove(StartupShortcutPath().c_str());
  537. if (fAutoStart)
  538. {
  539. CoInitialize(NULL);
  540. // Get a pointer to the IShellLink interface.
  541. IShellLink* psl = NULL;
  542. HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
  543. CLSCTX_INPROC_SERVER, IID_IShellLink,
  544. reinterpret_cast<void**>(&psl));
  545. if (SUCCEEDED(hres))
  546. {
  547. // Get the current executable path
  548. TCHAR pszExePath[MAX_PATH];
  549. GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
  550. TCHAR pszArgs[5] = TEXT("-min");
  551. // Set the path to the shortcut target
  552. psl->SetPath(pszExePath);
  553. PathRemoveFileSpec(pszExePath);
  554. psl->SetWorkingDirectory(pszExePath);
  555. psl->SetShowCmd(SW_SHOWMINNOACTIVE);
  556. psl->SetArguments(pszArgs);
  557. // Query IShellLink for the IPersistFile interface for
  558. // saving the shortcut in persistent storage.
  559. IPersistFile* ppf = NULL;
  560. hres = psl->QueryInterface(IID_IPersistFile,
  561. reinterpret_cast<void**>(&ppf));
  562. if (SUCCEEDED(hres))
  563. {
  564. WCHAR pwsz[MAX_PATH];
  565. // Ensure that the string is ANSI.
  566. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
  567. // Save the link by calling IPersistFile::Save.
  568. hres = ppf->Save(pwsz, TRUE);
  569. ppf->Release();
  570. psl->Release();
  571. CoUninitialize();
  572. return true;
  573. }
  574. psl->Release();
  575. }
  576. CoUninitialize();
  577. return false;
  578. }
  579. return true;
  580. }
  581. #elif defined(LINUX)
  582. // Follow the Desktop Application Autostart Spec:
  583. // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
  584. boost::filesystem::path GetAutostartDir()
  585. {
  586. namespace fs = boost::filesystem;
  587. char* pszConfigHome = getenv("XDG_CONFIG_HOME");
  588. if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
  589. char* pszHome = getenv("HOME");
  590. if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
  591. return fs::path();
  592. }
  593. boost::filesystem::path GetAutostartFilePath()
  594. {
  595. return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
  596. }
  597. bool GetStartOnSystemStartup()
  598. {
  599. boost::filesystem::ifstream optionFile(GetAutostartFilePath());
  600. if (!optionFile.good())
  601. return false;
  602. // Scan through file for "Hidden=true":
  603. string line;
  604. while (!optionFile.eof())
  605. {
  606. getline(optionFile, line);
  607. if (line.find("Hidden") != string::npos &&
  608. line.find("true") != string::npos)
  609. return false;
  610. }
  611. optionFile.close();
  612. return true;
  613. }
  614. bool SetStartOnSystemStartup(bool fAutoStart)
  615. {
  616. if (!fAutoStart)
  617. {
  618. #if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION >= 3
  619. unlink(GetAutostartFilePath().string().c_str());
  620. #else
  621. unlink(GetAutostartFilePath().native_file_string().c_str());
  622. #endif
  623. }
  624. else
  625. {
  626. char pszExePath[MAX_PATH+1];
  627. memset(pszExePath, 0, sizeof(pszExePath));
  628. if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
  629. return false;
  630. boost::filesystem::create_directories(GetAutostartDir());
  631. boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
  632. if (!optionFile.good())
  633. return false;
  634. // Write a bitcoin.desktop file to the autostart directory:
  635. optionFile << "[Desktop Entry]\n";
  636. optionFile << "Type=Application\n";
  637. optionFile << "Name=Bitcoin\n";
  638. optionFile << "Exec=" << pszExePath << " -min\n";
  639. optionFile << "Terminal=false\n";
  640. optionFile << "Hidden=false\n";
  641. optionFile.close();
  642. }
  643. return true;
  644. }
  645. #else
  646. // TODO: OSX startup stuff; see:
  647. // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
  648. bool GetStartOnSystemStartup() { return false; }
  649. bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
  650. #endif