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