Update License in File Headers
[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         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 QT_GUI
210             "  -server          \t\t  " + _("Accept command line and JSON-RPC commands\n") +
211 #endif
212 #if !defined(WIN32) && !defined(QT_GUI)
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 #if defined(QT_GUI) && defined(WIN32)
245         // On windows, show a message box, as there is no stderr
246         wxMessageBox(strUsage, "Usage");
247 #else
248         fprintf(stderr, "%s", strUsage.c_str());
249 #endif
250         return false;
251     }
252
253     fTestNet = GetBoolArg("-testnet");
254     fDebug = GetBoolArg("-debug");
255
256 #if !defined(WIN32) && !defined(QT_GUI)
257     fDaemon = GetBoolArg("-daemon");
258 #else
259     fDaemon = false;
260 #endif
261
262     if (fDaemon)
263         fServer = true;
264     else
265         fServer = GetBoolArg("-server");
266
267     /* force fServer when running without GUI */
268 #if !defined(QT_GUI)
269     fServer = true;
270 #endif
271     fPrintToConsole = GetBoolArg("-printtoconsole");
272     fPrintToDebugger = GetBoolArg("-printtodebugger");
273     fLogTimestamps = GetBoolArg("-logtimestamps");
274
275 #ifndef QT_GUI
276     for (int i = 1; i < argc; i++)
277         if (!IsSwitchChar(argv[i][0]))
278             fCommandLine = true;
279
280     if (fCommandLine)
281     {
282         int ret = CommandLineRPC(argc, argv);
283         exit(ret);
284     }
285 #endif
286
287 #if !defined(WIN32) && !defined(QT_GUI)
288     if (fDaemon)
289     {
290         // Daemonize
291         pid_t pid = fork();
292         if (pid < 0)
293         {
294             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
295             return false;
296         }
297         if (pid > 0)
298         {
299             CreatePidFile(GetPidFile(), pid);
300             return true;
301         }
302
303         pid_t sid = setsid();
304         if (sid < 0)
305             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
306     }
307 #endif
308
309     if (!fDebug && !pszSetDataDir[0])
310         ShrinkDebugFile();
311     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
312     printf("Bitcoin version %s\n", FormatFullVersion().c_str());
313     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
314
315     if (GetBoolArg("-loadblockindextest"))
316     {
317         CTxDB txdb("r");
318         txdb.LoadBlockIndex();
319         PrintBlockTree();
320         return false;
321     }
322
323     // Make sure only a single bitcoin process is using the data directory.
324     string strLockFile = GetDataDir() + "/.lock";
325     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
326     if (file) fclose(file);
327     static boost::interprocess::file_lock lock(strLockFile.c_str());
328     if (!lock.try_lock())
329     {
330         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
331         return false;
332     }
333
334     string strErrors;
335
336     //
337     // Load data files
338     //
339     if (fDaemon)
340         fprintf(stdout, "bitcoin server starting\n");
341     strErrors = "";
342     int64 nStart;
343
344     InitMessage(_("Loading addresses..."));
345     printf("Loading addresses...\n");
346     nStart = GetTimeMillis();
347     if (!LoadAddresses())
348         strErrors += _("Error loading addr.dat      \n");
349     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
350
351     InitMessage(_("Loading block index..."));
352     printf("Loading block index...\n");
353     nStart = GetTimeMillis();
354     if (!LoadBlockIndex())
355         strErrors += _("Error loading blkindex.dat      \n");
356     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
357
358     InitMessage(_("Loading wallet..."));
359     printf("Loading wallet...\n");
360     nStart = GetTimeMillis();
361     bool fFirstRun;
362     pwalletMain = new CWallet("wallet.dat");
363     int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
364     if (nLoadWalletRet != DB_LOAD_OK)
365     {
366         if (nLoadWalletRet == DB_CORRUPT)
367             strErrors += _("Error loading wallet.dat: Wallet corrupted      \n");
368         else if (nLoadWalletRet == DB_TOO_NEW)
369             strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin      \n");
370         else if (nLoadWalletRet == DB_NEED_REWRITE)
371         {
372             strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete    \n");
373             printf("%s", strErrors.c_str());
374             wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
375             return false;
376         }
377         else
378             strErrors += _("Error loading wallet.dat      \n");
379     }
380     printf("%s", strErrors.c_str());
381     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
382
383     RegisterWallet(pwalletMain);
384
385     CBlockIndex *pindexRescan = pindexBest;
386     if (GetBoolArg("-rescan"))
387         pindexRescan = pindexGenesisBlock;
388     else
389     {
390         CWalletDB walletdb("wallet.dat");
391         CBlockLocator locator;
392         if (walletdb.ReadBestBlock(locator))
393             pindexRescan = locator.GetBlockIndex();
394     }
395     if (pindexBest != pindexRescan)
396     {
397         InitMessage(_("Rescanning..."));
398         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
399         nStart = GetTimeMillis();
400         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
401         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
402     }
403
404     InitMessage(_("Done loading"));
405     printf("Done loading\n");
406
407         //// debug print
408         printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
409         printf("nBestHeight = %d\n",            nBestHeight);
410         printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
411         printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
412         printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
413
414     if (!strErrors.empty())
415     {
416         wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
417         return false;
418     }
419
420     // Add wallet transactions that aren't already in a block to mapTransactions
421     pwalletMain->ReacceptWalletTransactions();
422
423     // Note: Bitcoin-QT stores several settings in the wallet, so we want
424     // to load the wallet BEFORE parsing command-line arguments, so
425     // the command-line/bitcoin.conf settings override GUI setting.
426
427     //
428     // Parameters
429     //
430     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
431     {
432         PrintBlockTree();
433         return false;
434     }
435
436     if (mapArgs.count("-timeout"))
437     {
438         int nNewTimeout = GetArg("-timeout", 5000);
439         if (nNewTimeout > 0 && nNewTimeout < 600000)
440             nConnectTimeout = nNewTimeout;
441     }
442
443     if (mapArgs.count("-printblock"))
444     {
445         string strMatch = mapArgs["-printblock"];
446         int nFound = 0;
447         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
448         {
449             uint256 hash = (*mi).first;
450             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
451             {
452                 CBlockIndex* pindex = (*mi).second;
453                 CBlock block;
454                 block.ReadFromDisk(pindex);
455                 block.BuildMerkleTree();
456                 block.print();
457                 printf("\n");
458                 nFound++;
459             }
460         }
461         if (nFound == 0)
462             printf("No blocks matching %s were found\n", strMatch.c_str());
463         return false;
464     }
465
466     fGenerateBitcoins = GetBoolArg("-gen");
467
468     if (mapArgs.count("-proxy"))
469     {
470         fUseProxy = true;
471         addrProxy = CAddress(mapArgs["-proxy"]);
472         if (!addrProxy.IsValid())
473         {
474             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
475             return false;
476         }
477     }
478
479     bool fTor = (fUseProxy && addrProxy.port == htons(9050));
480     if (fTor)
481     {
482         // Use SoftSetArg here so user can override any of these if they wish.
483         // Note: the GetBoolArg() calls for all of these must happen later.
484         SoftSetArg("-nolisten", true);
485         SoftSetArg("-noirc", true);
486         SoftSetArg("-nodnsseed", true);
487         SoftSetArg("-noupnp", true);
488         SoftSetArg("-upnp", false);
489         SoftSetArg("-dns", false);
490     }
491
492     fAllowDNS = GetBoolArg("-dns");
493     fNoListen = GetBoolArg("-nolisten");
494
495     // Command-line args override in-wallet settings:
496     if (mapArgs.count("-upnp"))
497         fUseUPnP = GetBoolArg("-upnp");
498     else if (mapArgs.count("-noupnp"))
499         fUseUPnP = !GetBoolArg("-noupnp");
500
501     if (!fNoListen)
502     {
503         if (!BindListenPort(strErrors))
504         {
505             wxMessageBox(strErrors, "Bitcoin");
506             return false;
507         }
508     }
509
510     if (mapArgs.count("-addnode"))
511     {
512         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
513         {
514             CAddress addr(strAddr, fAllowDNS);
515             addr.nTime = 0; // so it won't relay unless successfully connected
516             if (addr.IsValid())
517                 AddAddress(addr);
518         }
519     }
520
521     if (mapArgs.count("-paytxfee"))
522     {
523         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
524         {
525             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
526             return false;
527         }
528         if (nTransactionFee > 0.25 * COIN)
529             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
530     }
531
532     //
533     // Start the node
534     //
535     if (!CheckDiskSpace())
536         return false;
537
538     RandAddSeedPerfmon();
539
540     if (!CreateThread(StartNode, NULL))
541         wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
542
543     if (fServer)
544         CreateThread(ThreadRPCServer, NULL);
545
546 #if !defined(QT_GUI)
547     while (1)
548         Sleep(5000);
549 #endif
550
551     return true;
552 }