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