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