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