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