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