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