Don't call exit() in Shutdown() for Bitcoin-Qt (fixes a tray-icon issue)
[novacoin.git] / src / init.cpp
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 "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/interprocess/sync/file_lock.hpp>
14
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
26 using namespace std;
27 using namespace boost;
28
29 CWallet* pwalletMain;
30
31 //////////////////////////////////////////////////////////////////////////////
32 //
33 // Shutdown
34 //
35
36 void ExitTimeout(void* parg)
37 {
38 #ifdef WIN32
39     Sleep(5000);
40     ExitProcess(0);
41 #endif
42 }
43
44 void Shutdown(void* parg)
45 {
46     static CCriticalSection cs_Shutdown;
47     static bool fTaken;
48     bool fFirstThread = false;
49     TRY_CRITICAL_BLOCK(cs_Shutdown)
50     {
51         fFirstThread = !fTaken;
52         fTaken = true;
53     }
54     static bool fExit;
55     if (fFirstThread)
56     {
57         fShutdown = true;
58         nTransactionsUpdated++;
59         DBFlush(false);
60         StopNode();
61         DBFlush(true);
62         boost::filesystem::remove(GetPidFile());
63         UnregisterWallet(pwalletMain);
64         delete pwalletMain;
65         CreateThread(ExitTimeout, NULL);
66         Sleep(50);
67         printf("Bitcoin exiting\n\n");
68         fExit = true;
69 #ifndef QT_GUI
70         // ensure non UI client get's exited here, but let Bitcoin-Qt reach return 0; in bitcoin.cpp
71         exit(0);
72 #endif
73     }
74     else
75     {
76         while (!fExit)
77             Sleep(500);
78         Sleep(100);
79         ExitThread(0);
80     }
81 }
82
83 void HandleSIGTERM(int)
84 {
85     fRequestShutdown = true;
86 }
87
88
89
90
91
92
93 //////////////////////////////////////////////////////////////////////////////
94 //
95 // Start
96 //
97 #if !defined(QT_GUI)
98 int main(int argc, char* argv[])
99 {
100     bool fRet = false;
101     fRet = AppInit(argc, argv);
102
103     if (fRet && fDaemon)
104         return 0;
105
106     return 1;
107 }
108 #endif
109
110 bool AppInit(int argc, char* argv[])
111 {
112     bool fRet = false;
113     try
114     {
115         fRet = AppInit2(argc, argv);
116     }
117     catch (std::exception& e) {
118         PrintException(&e, "AppInit()");
119     } catch (...) {
120         PrintException(NULL, "AppInit()");
121     }
122     if (!fRet)
123         Shutdown(NULL);
124     return fRet;
125 }
126
127 bool AppInit2(int argc, char* argv[])
128 {
129 #ifdef _MSC_VER
130     // Turn off microsoft heap dump noise
131     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
132     _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
133 #endif
134 #if _MSC_VER >= 1400
135     // Disable confusing "helpful" text message on abort, ctrl-c
136     _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
137 #endif
138 #ifndef WIN32
139     umask(077);
140 #endif
141 #ifndef WIN32
142     // Clean shutdown on SIGTERM
143     struct sigaction sa;
144     sa.sa_handler = HandleSIGTERM;
145     sigemptyset(&sa.sa_mask);
146     sa.sa_flags = 0;
147     sigaction(SIGTERM, &sa, NULL);
148     sigaction(SIGINT, &sa, NULL);
149     sigaction(SIGHUP, &sa, NULL);
150 #endif
151
152     //
153     // Parameters
154     //
155     ParseParameters(argc, argv);
156
157     if (mapArgs.count("-datadir"))
158     {
159         if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
160         {
161             filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
162             strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
163         }
164         else
165         {
166             fprintf(stderr, "Error: Specified directory does not exist\n");
167             Shutdown(NULL);
168         }
169     }
170
171
172     ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
173
174     if (mapArgs.count("-?") || mapArgs.count("--help"))
175     {
176         string strUsage = string() +
177           _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
178           _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
179             "  bitcoind [options]                   \t  " + "\n" +
180             "  bitcoind [options] <command> [params]\t  " + _("Send command to -server or bitcoind\n") +
181             "  bitcoind [options] help              \t\t  " + _("List commands\n") +
182             "  bitcoind [options] help <command>    \t\t  " + _("Get help for a command\n") +
183           _("Options:\n") +
184             "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)\n") +
185             "  -pid=<file>      \t\t  " + _("Specify pid file (default: bitcoind.pid)\n") +
186             "  -gen             \t\t  " + _("Generate coins\n") +
187             "  -gen=0           \t\t  " + _("Don't generate coins\n") +
188             "  -min             \t\t  " + _("Start minimized\n") +
189             "  -datadir=<dir>   \t\t  " + _("Specify data directory\n") +
190             "  -timeout=<n>     \t  "   + _("Specify connection timeout (in milliseconds)\n") +
191             "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy\n") +
192             "  -dns             \t  "   + _("Allow DNS lookups for addnode and connect\n") +
193             "  -port=<port>     \t\t  " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)\n") +
194             "  -maxconnections=<n>\t  " + _("Maintain at most <n> connections to peers (default: 125)\n") +
195             "  -addnode=<ip>    \t  "   + _("Add a node to connect to\n") +
196             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node\n") +
197             "  -noirc           \t  "   + _("Don't find peers using internet relay chat\n") +
198             "  -nolisten        \t  "   + _("Don't accept connections from outside\n") +
199             "  -nodnsseed       \t  "   + _("Don't bootstrap list of peers using DNS\n") +
200             "  -banscore=<n>    \t  "   + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
201             "  -bantime=<n>     \t  "   + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\n") +
202             "  -maxreceivebuffer=<n>\t  " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)\n") +
203             "  -maxsendbuffer=<n>\t  "   + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)\n") +
204 #ifdef USE_UPNP
205 #if USE_UPNP
206             "  -noupnp          \t  "   + _("Don't attempt to use UPnP to map the listening port\n") +
207 #else
208             "  -upnp            \t  "   + _("Attempt to use UPnP to map the listening port\n") +
209 #endif
210 #endif
211             "  -paytxfee=<amt>  \t  "   + _("Fee per kB to add to transactions you send\n") +
212 #ifdef QT_GUI
213             "  -server          \t\t  " + _("Accept command line and JSON-RPC commands\n") +
214 #endif
215 #if !defined(WIN32) && !defined(QT_GUI)
216             "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands\n") +
217 #endif
218             "  -testnet         \t\t  " + _("Use the test network\n") +
219             "  -debug           \t\t  " + _("Output extra debugging information\n") +
220             "  -logtimestamps   \t  "   + _("Prepend debug output with timestamp\n") +
221             "  -printtoconsole  \t  "   + _("Send trace/debug info to console instead of debug.log file\n") +
222 #ifdef WIN32
223             "  -printtodebugger \t  "   + _("Send trace/debug info to debugger\n") +
224 #endif
225             "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections\n") +
226             "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections\n") +
227             "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
228             "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address\n") +
229             "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
230             "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)\n") +
231             "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions\n");
232
233 #ifdef USE_SSL
234         strUsage += string() +
235             _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
236             "  -rpcssl                                \t  " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
237             "  -rpcsslcertificatechainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)\n") +
238             "  -rpcsslprivatekeyfile=<file.pem>       \t  " + _("Server private key (default: server.pem)\n") +
239             "  -rpcsslciphers=<ciphers>               \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
240 #endif
241
242         strUsage += string() +
243             "  -?               \t\t  " + _("This help message\n");
244
245         // Remove tabs
246         strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
247 #if defined(QT_GUI) && defined(WIN32)
248         // On windows, show a message box, as there is no stderr
249         wxMessageBox(strUsage, "Usage");
250 #else
251         fprintf(stderr, "%s", strUsage.c_str());
252 #endif
253         return false;
254     }
255
256     fTestNet = GetBoolArg("-testnet");
257     fDebug = GetBoolArg("-debug");
258
259 #if !defined(WIN32) && !defined(QT_GUI)
260     fDaemon = GetBoolArg("-daemon");
261 #else
262     fDaemon = false;
263 #endif
264
265     if (fDaemon)
266         fServer = true;
267     else
268         fServer = GetBoolArg("-server");
269
270     /* force fServer when running without GUI */
271 #if !defined(QT_GUI)
272     fServer = true;
273 #endif
274     fPrintToConsole = GetBoolArg("-printtoconsole");
275     fPrintToDebugger = GetBoolArg("-printtodebugger");
276     fLogTimestamps = GetBoolArg("-logtimestamps");
277
278 #ifndef QT_GUI
279     for (int i = 1; i < argc; i++)
280         if (!IsSwitchChar(argv[i][0]))
281             fCommandLine = true;
282
283     if (fCommandLine)
284     {
285         int ret = CommandLineRPC(argc, argv);
286         exit(ret);
287     }
288 #endif
289
290 #if !defined(WIN32) && !defined(QT_GUI)
291     if (fDaemon)
292     {
293         // Daemonize
294         pid_t pid = fork();
295         if (pid < 0)
296         {
297             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
298             return false;
299         }
300         if (pid > 0)
301         {
302             CreatePidFile(GetPidFile(), pid);
303             return true;
304         }
305
306         pid_t sid = setsid();
307         if (sid < 0)
308             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
309     }
310 #endif
311
312     if (!fDebug && !pszSetDataDir[0])
313         ShrinkDebugFile();
314     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
315     printf("Bitcoin version %s\n", FormatFullVersion().c_str());
316     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
317
318     if (GetBoolArg("-loadblockindextest"))
319     {
320         CTxDB txdb("r");
321         txdb.LoadBlockIndex();
322         PrintBlockTree();
323         return false;
324     }
325
326     // Make sure only a single bitcoin process is using the data directory.
327     string strLockFile = GetDataDir() + "/.lock";
328     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
329     if (file) fclose(file);
330     static boost::interprocess::file_lock lock(strLockFile.c_str());
331     if (!lock.try_lock())
332     {
333         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
334         return false;
335     }
336
337     string strErrors;
338
339     //
340     // Load data files
341     //
342     if (fDaemon)
343         fprintf(stdout, "bitcoin server starting\n");
344     strErrors = "";
345     int64 nStart;
346
347     InitMessage(_("Loading addresses..."));
348     printf("Loading addresses...\n");
349     nStart = GetTimeMillis();
350     if (!LoadAddresses())
351         strErrors += _("Error loading addr.dat      \n");
352     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
353
354     InitMessage(_("Loading block index..."));
355     printf("Loading block index...\n");
356     nStart = GetTimeMillis();
357     if (!LoadBlockIndex())
358         strErrors += _("Error loading blkindex.dat      \n");
359     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
360
361     InitMessage(_("Loading wallet..."));
362     printf("Loading wallet...\n");
363     nStart = GetTimeMillis();
364     bool fFirstRun;
365     pwalletMain = new CWallet("wallet.dat");
366     int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
367     if (nLoadWalletRet != DB_LOAD_OK)
368     {
369         if (nLoadWalletRet == DB_CORRUPT)
370             strErrors += _("Error loading wallet.dat: Wallet corrupted      \n");
371         else if (nLoadWalletRet == DB_TOO_NEW)
372             strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin      \n");
373         else if (nLoadWalletRet == DB_NEED_REWRITE)
374         {
375             strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete    \n");
376             printf("%s", strErrors.c_str());
377             wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
378             return false;
379         }
380         else
381             strErrors += _("Error loading wallet.dat      \n");
382     }
383     printf("%s", strErrors.c_str());
384     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
385
386     RegisterWallet(pwalletMain);
387
388     CBlockIndex *pindexRescan = pindexBest;
389     if (GetBoolArg("-rescan"))
390         pindexRescan = pindexGenesisBlock;
391     else
392     {
393         CWalletDB walletdb("wallet.dat");
394         CBlockLocator locator;
395         if (walletdb.ReadBestBlock(locator))
396             pindexRescan = locator.GetBlockIndex();
397     }
398     if (pindexBest != pindexRescan)
399     {
400         InitMessage(_("Rescanning..."));
401         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
402         nStart = GetTimeMillis();
403         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
404         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
405     }
406
407     InitMessage(_("Done loading"));
408     printf("Done loading\n");
409
410         //// debug print
411         printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
412         printf("nBestHeight = %d\n",            nBestHeight);
413         printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
414         printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
415         printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
416
417     if (!strErrors.empty())
418     {
419         wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
420         return false;
421     }
422
423     // Add wallet transactions that aren't already in a block to mapTransactions
424     pwalletMain->ReacceptWalletTransactions();
425
426     // Note: Bitcoin-QT stores several settings in the wallet, so we want
427     // to load the wallet BEFORE parsing command-line arguments, so
428     // the command-line/bitcoin.conf settings override GUI setting.
429
430     //
431     // Parameters
432     //
433     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
434     {
435         PrintBlockTree();
436         return false;
437     }
438
439     if (mapArgs.count("-timeout"))
440     {
441         int nNewTimeout = GetArg("-timeout", 5000);
442         if (nNewTimeout > 0 && nNewTimeout < 600000)
443             nConnectTimeout = nNewTimeout;
444     }
445
446     if (mapArgs.count("-printblock"))
447     {
448         string strMatch = mapArgs["-printblock"];
449         int nFound = 0;
450         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
451         {
452             uint256 hash = (*mi).first;
453             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
454             {
455                 CBlockIndex* pindex = (*mi).second;
456                 CBlock block;
457                 block.ReadFromDisk(pindex);
458                 block.BuildMerkleTree();
459                 block.print();
460                 printf("\n");
461                 nFound++;
462             }
463         }
464         if (nFound == 0)
465             printf("No blocks matching %s were found\n", strMatch.c_str());
466         return false;
467     }
468
469     fGenerateBitcoins = GetBoolArg("-gen");
470
471     if (mapArgs.count("-proxy"))
472     {
473         fUseProxy = true;
474         addrProxy = CAddress(mapArgs["-proxy"]);
475         if (!addrProxy.IsValid())
476         {
477             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
478             return false;
479         }
480     }
481
482     bool fTor = (fUseProxy && addrProxy.port == htons(9050));
483     if (fTor)
484     {
485         // Use SoftSetArg here so user can override any of these if they wish.
486         // Note: the GetBoolArg() calls for all of these must happen later.
487         SoftSetArg("-nolisten", true);
488         SoftSetArg("-noirc", true);
489         SoftSetArg("-nodnsseed", true);
490         SoftSetArg("-noupnp", true);
491         SoftSetArg("-upnp", false);
492         SoftSetArg("-dns", false);
493     }
494
495     fAllowDNS = GetBoolArg("-dns");
496     fNoListen = GetBoolArg("-nolisten");
497
498     // Command-line args override in-wallet settings:
499     if (mapArgs.count("-upnp"))
500         fUseUPnP = GetBoolArg("-upnp");
501     else if (mapArgs.count("-noupnp"))
502         fUseUPnP = !GetBoolArg("-noupnp");
503
504     if (!fNoListen)
505     {
506         if (!BindListenPort(strErrors))
507         {
508             wxMessageBox(strErrors, "Bitcoin");
509             return false;
510         }
511     }
512
513     if (mapArgs.count("-addnode"))
514     {
515         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
516         {
517             CAddress addr(strAddr, fAllowDNS);
518             addr.nTime = 0; // so it won't relay unless successfully connected
519             if (addr.IsValid())
520                 AddAddress(addr);
521         }
522     }
523
524     if (mapArgs.count("-paytxfee"))
525     {
526         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
527         {
528             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
529             return false;
530         }
531         if (nTransactionFee > 0.25 * COIN)
532             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
533     }
534
535     //
536     // Start the node
537     //
538     if (!CheckDiskSpace())
539         return false;
540
541     RandAddSeedPerfmon();
542
543     if (!CreateThread(StartNode, NULL))
544         wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
545
546     if (fServer)
547         CreateThread(ThreadRPCServer, NULL);
548
549 #if !defined(QT_GUI)
550     while (1)
551         Sleep(5000);
552 #endif
553
554     return true;
555 }