Merge branch 'spentpertxout' of https://github.com/sipa/bitcoin
[novacoin.git] / 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         CreateThread(ExitTimeout, NULL);
45         Sleep(50);
46         printf("Bitcoin exiting\n\n");
47         fExit = true;
48         exit(0);
49     }
50     else
51     {
52         while (!fExit)
53             Sleep(500);
54         Sleep(100);
55         ExitThread(0);
56     }
57 }
58
59 void HandleSIGTERM(int)
60 {
61     fRequestShutdown = true;
62 }
63
64
65
66
67
68
69 //////////////////////////////////////////////////////////////////////////////
70 //
71 // Start
72 //
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") + " " + FormatVersion(VERSION) + pszSubVer + beta + "\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             "  -gen             \t\t  " + _("Generate coins\n") +
155             "  -gen=0           \t\t  " + _("Don't generate coins\n") +
156             "  -min             \t\t  " + _("Start minimized\n") +
157             "  -datadir=<dir>   \t\t  " + _("Specify data directory\n") +
158             "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy\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
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             return true;
255
256         pid_t sid = setsid();
257         if (sid < 0)
258             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
259     }
260 #endif
261
262     if (!fDebug && !pszSetDataDir[0])
263         ShrinkDebugFile();
264     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
265     printf("Bitcoin version %s%s%s\n", FormatVersion(VERSION).c_str(), pszSubVer, VERSION_IS_BETA ? _(" beta") : "");
266 #ifdef GUI
267     printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
268     printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
269     printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
270 #endif
271     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
272
273     if (GetBoolArg("-loadblockindextest"))
274     {
275         CTxDB txdb("r");
276         txdb.LoadBlockIndex();
277         PrintBlockTree();
278         return false;
279     }
280
281     //
282     // Limit to single instance per user
283     // Required to protect the database files if we're going to keep deleting log.*
284     //
285 #if defined(__WXMSW__) && defined(GUI)
286     // wxSingleInstanceChecker doesn't work on Linux
287     wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
288     for (int i = 0; i < strMutexName.size(); i++)
289         if (!isalnum(strMutexName[i]))
290             strMutexName[i] = '.';
291     wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
292     if (psingleinstancechecker->IsAnotherRunning())
293     {
294         printf("Existing instance found\n");
295         unsigned int nStart = GetTime();
296         loop
297         {
298             // Show the previous instance and exit
299             HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
300             if (hwndPrev)
301             {
302                 if (IsIconic(hwndPrev))
303                     ShowWindow(hwndPrev, SW_RESTORE);
304                 SetForegroundWindow(hwndPrev);
305                 return false;
306             }
307
308             if (GetTime() > nStart + 60)
309                 return false;
310
311             // Resume this instance if the other exits
312             delete psingleinstancechecker;
313             Sleep(1000);
314             psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
315             if (!psingleinstancechecker->IsAnotherRunning())
316                 break;
317         }
318     }
319 #endif
320
321     // Make sure only a single bitcoin process is using the data directory.
322     string strLockFile = GetDataDir() + "/.lock";
323     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
324     fclose(file);
325     static boost::interprocess::file_lock lock(strLockFile.c_str());
326     if (!lock.try_lock())
327     {
328         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
329         return false;
330     }
331
332     // Bind to the port early so we can tell if another instance is already running.
333     string strErrors;
334     if (!fNoListen)
335     {
336         if (!BindListenPort(strErrors))
337         {
338             wxMessageBox(strErrors, "Bitcoin");
339             return false;
340         }
341     }
342
343     //
344     // Load data files
345     //
346     if (fDaemon)
347         fprintf(stdout, "bitcoin server starting\n");
348     strErrors = "";
349     int64 nStart;
350
351     printf("Loading addresses...\n");
352     nStart = GetTimeMillis();
353     if (!LoadAddresses())
354         strErrors += _("Error loading addr.dat      \n");
355     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
356
357     printf("Loading block index...\n");
358     nStart = GetTimeMillis();
359     if (!LoadBlockIndex())
360         strErrors += _("Error loading blkindex.dat      \n");
361     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
362
363     printf("Loading wallet...\n");
364     nStart = GetTimeMillis();
365     bool fFirstRun;
366     if (!LoadWallet(fFirstRun))
367         strErrors += _("Error loading wallet.dat      \n");
368     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
369
370     if (GetBoolArg("-rescan"))
371     {
372         nStart = GetTimeMillis();
373         ScanForWalletTransactions(pindexGenesisBlock);
374         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
375     }
376
377     printf("Done loading\n");
378
379         //// debug print
380         printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
381         printf("nBestHeight = %d\n",            nBestHeight);
382         printf("mapKeys.size() = %d\n",         mapKeys.size());
383         printf("mapPubKeys.size() = %d\n",      mapPubKeys.size());
384         printf("mapWallet.size() = %d\n",       mapWallet.size());
385         printf("mapAddressBook.size() = %d\n",  mapAddressBook.size());
386
387     if (!strErrors.empty())
388     {
389         wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
390         return false;
391     }
392
393     // Add wallet transactions that aren't already in a block to mapTransactions
394     ReacceptWalletTransactions();
395
396     //
397     // Parameters
398     //
399     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
400     {
401         PrintBlockTree();
402         return false;
403     }
404
405     if (mapArgs.count("-printblock"))
406     {
407         string strMatch = mapArgs["-printblock"];
408         int nFound = 0;
409         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
410         {
411             uint256 hash = (*mi).first;
412             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
413             {
414                 CBlockIndex* pindex = (*mi).second;
415                 CBlock block;
416                 block.ReadFromDisk(pindex);
417                 block.BuildMerkleTree();
418                 block.print();
419                 printf("\n");
420                 nFound++;
421             }
422         }
423         if (nFound == 0)
424             printf("No blocks matching %s were found\n", strMatch.c_str());
425         return false;
426     }
427
428     fGenerateBitcoins = GetBoolArg("-gen");
429
430     if (mapArgs.count("-proxy"))
431     {
432         fUseProxy = true;
433         addrProxy = CAddress(mapArgs["-proxy"]);
434         if (!addrProxy.IsValid())
435         {
436             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
437             return false;
438         }
439     }
440
441     if (mapArgs.count("-addnode"))
442     {
443         foreach(string strAddr, mapMultiArgs["-addnode"])
444         {
445             CAddress addr(strAddr, NODE_NETWORK);
446             addr.nTime = 0; // so it won't relay unless successfully connected
447             if (addr.IsValid())
448                 AddAddress(addr);
449         }
450     }
451
452     if (mapArgs.count("-dnsseed"))
453         DNSAddressSeed();
454
455     if (mapArgs.count("-paytxfee"))
456     {
457         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
458         {
459             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
460             return false;
461         }
462         if (nTransactionFee > 0.25 * COIN)
463             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
464     }
465
466     if (fHaveUPnP)
467     {
468 #if USE_UPNP
469     if (GetBoolArg("-noupnp"))
470         fUseUPnP = false;
471 #else
472     if (GetBoolArg("-upnp"))
473         fUseUPnP = true;
474 #endif
475     }
476
477     //
478     // Create the main window and start the node
479     //
480 #ifdef GUI
481     if (!fDaemon)
482         CreateMainWindow();
483 #endif
484
485     if (!CheckDiskSpace())
486         return false;
487
488     RandAddSeedPerfmon();
489
490     if (!CreateThread(StartNode, NULL))
491         wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
492
493     if (fServer)
494         CreateThread(ThreadRPCServer, NULL);
495
496 #if defined(__WXMSW__) && defined(GUI)
497     if (fFirstRun)
498         SetStartOnSystemStartup(true);
499 #endif
500
501 #ifndef GUI
502     while (1)
503         Sleep(5000);
504 #endif
505
506     return true;
507 }