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