directory re-organization (keeps the old build system)
[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             "  -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
212 #ifndef __WXMSW__
213     fDaemon = GetBoolArg("-daemon");
214 #else
215     fDaemon = false;
216 #endif
217
218     if (fDaemon)
219         fServer = true;
220     else
221         fServer = GetBoolArg("-server");
222
223     /* force fServer when running without GUI */
224 #ifndef GUI
225     fServer = true;
226 #endif
227
228     fPrintToConsole = GetBoolArg("-printtoconsole");
229     fPrintToDebugger = GetBoolArg("-printtodebugger");
230
231     fTestNet = GetBoolArg("-testnet");
232     fNoListen = GetBoolArg("-nolisten");
233     fLogTimestamps = GetBoolArg("-logtimestamps");
234
235     for (int i = 1; i < argc; i++)
236         if (!IsSwitchChar(argv[i][0]))
237             fCommandLine = true;
238
239     if (fCommandLine)
240     {
241         int ret = CommandLineRPC(argc, argv);
242         exit(ret);
243     }
244
245 #ifndef __WXMSW__
246     if (fDaemon)
247     {
248         // Daemonize
249         pid_t pid = fork();
250         if (pid < 0)
251         {
252             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
253             return false;
254         }
255         if (pid > 0)
256         {
257             CreatePidFile(GetPidFile(), pid);
258             return true;
259         }
260
261         pid_t sid = setsid();
262         if (sid < 0)
263             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
264     }
265 #endif
266
267     if (!fDebug && !pszSetDataDir[0])
268         ShrinkDebugFile();
269     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
270     printf("Bitcoin version %s\n", FormatFullVersion().c_str());
271 #ifdef GUI
272     printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
273     printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
274     printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
275 #endif
276     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
277
278     if (GetBoolArg("-loadblockindextest"))
279     {
280         CTxDB txdb("r");
281         txdb.LoadBlockIndex();
282         PrintBlockTree();
283         return false;
284     }
285
286     //
287     // Limit to single instance per user
288     // Required to protect the database files if we're going to keep deleting log.*
289     //
290 #if defined(__WXMSW__) && defined(GUI)
291     // wxSingleInstanceChecker doesn't work on Linux
292     wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
293     for (int i = 0; i < strMutexName.size(); i++)
294         if (!isalnum(strMutexName[i]))
295             strMutexName[i] = '.';
296     wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
297     if (psingleinstancechecker->IsAnotherRunning())
298     {
299         printf("Existing instance found\n");
300         unsigned int nStart = GetTime();
301         loop
302         {
303             // Show the previous instance and exit
304             HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
305             if (hwndPrev)
306             {
307                 if (IsIconic(hwndPrev))
308                     ShowWindow(hwndPrev, SW_RESTORE);
309                 SetForegroundWindow(hwndPrev);
310                 return false;
311             }
312
313             if (GetTime() > nStart + 60)
314                 return false;
315
316             // Resume this instance if the other exits
317             delete psingleinstancechecker;
318             Sleep(1000);
319             psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
320             if (!psingleinstancechecker->IsAnotherRunning())
321                 break;
322         }
323     }
324 #endif
325
326     // Make sure only a single bitcoin process is using the data directory.
327     string strLockFile = GetDataDir() + "/.lock";
328     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
329     fclose(file);
330     static boost::interprocess::file_lock lock(strLockFile.c_str());
331     if (!lock.try_lock())
332     {
333         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
334         return false;
335     }
336
337     // Bind to the port early so we can tell if another instance is already running.
338     string strErrors;
339     if (!fNoListen)
340     {
341         if (!BindListenPort(strErrors))
342         {
343             wxMessageBox(strErrors, "Bitcoin");
344             return false;
345         }
346     }
347
348     //
349     // Load data files
350     //
351     if (fDaemon)
352         fprintf(stdout, "bitcoin server starting\n");
353     strErrors = "";
354     int64 nStart;
355
356     printf("Loading addresses...\n");
357     nStart = GetTimeMillis();
358     if (!LoadAddresses())
359         strErrors += _("Error loading addr.dat      \n");
360     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
361
362     printf("Loading block index...\n");
363     nStart = GetTimeMillis();
364     if (!LoadBlockIndex())
365         strErrors += _("Error loading blkindex.dat      \n");
366     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
367
368     printf("Loading wallet...\n");
369     nStart = GetTimeMillis();
370     bool fFirstRun;
371     if (!LoadWallet(fFirstRun))
372         strErrors += _("Error loading wallet.dat      \n");
373     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
374
375     CBlockIndex *pindexRescan = pindexBest;
376     if (GetBoolArg("-rescan"))
377         pindexRescan = pindexGenesisBlock;
378     else
379     {
380         CWalletDB walletdb;
381         CBlockLocator locator;
382         if (walletdb.ReadBestBlock(locator))
383             pindexRescan = locator.GetBlockIndex();
384     }
385     if (pindexBest != pindexRescan)
386     {
387         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
388         nStart = GetTimeMillis();
389         ScanForWalletTransactions(pindexRescan);
390         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
391     }
392
393     printf("Done loading\n");
394
395         //// debug print
396         printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
397         printf("nBestHeight = %d\n",            nBestHeight);
398         printf("mapKeys.size() = %d\n",         mapKeys.size());
399         printf("mapPubKeys.size() = %d\n",      mapPubKeys.size());
400         printf("mapWallet.size() = %d\n",       mapWallet.size());
401         printf("mapAddressBook.size() = %d\n",  mapAddressBook.size());
402
403     if (!strErrors.empty())
404     {
405         wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
406         return false;
407     }
408
409     // Add wallet transactions that aren't already in a block to mapTransactions
410     ReacceptWalletTransactions();
411
412     //
413     // Parameters
414     //
415     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
416     {
417         PrintBlockTree();
418         return false;
419     }
420
421     if (mapArgs.count("-printblock"))
422     {
423         string strMatch = mapArgs["-printblock"];
424         int nFound = 0;
425         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
426         {
427             uint256 hash = (*mi).first;
428             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
429             {
430                 CBlockIndex* pindex = (*mi).second;
431                 CBlock block;
432                 block.ReadFromDisk(pindex);
433                 block.BuildMerkleTree();
434                 block.print();
435                 printf("\n");
436                 nFound++;
437             }
438         }
439         if (nFound == 0)
440             printf("No blocks matching %s were found\n", strMatch.c_str());
441         return false;
442     }
443
444     fGenerateBitcoins = GetBoolArg("-gen");
445
446     if (mapArgs.count("-proxy"))
447     {
448         fUseProxy = true;
449         addrProxy = CAddress(mapArgs["-proxy"]);
450         if (!addrProxy.IsValid())
451         {
452             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
453             return false;
454         }
455     }
456
457     if (mapArgs.count("-addnode"))
458     {
459         foreach(string strAddr, mapMultiArgs["-addnode"])
460         {
461             CAddress addr(strAddr, NODE_NETWORK);
462             addr.nTime = 0; // so it won't relay unless successfully connected
463             if (addr.IsValid())
464                 AddAddress(addr);
465         }
466     }
467
468     if (mapArgs.count("-dnsseed"))
469         DNSAddressSeed();
470
471     if (mapArgs.count("-paytxfee"))
472     {
473         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
474         {
475             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
476             return false;
477         }
478         if (nTransactionFee > 0.25 * COIN)
479             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
480     }
481
482     if (fHaveUPnP)
483     {
484 #if USE_UPNP
485     if (GetBoolArg("-noupnp"))
486         fUseUPnP = false;
487 #else
488     if (GetBoolArg("-upnp"))
489         fUseUPnP = true;
490 #endif
491     }
492
493     //
494     // Create the main window and start the node
495     //
496 #ifdef GUI
497     if (!fDaemon)
498         CreateMainWindow();
499 #endif
500
501     if (!CheckDiskSpace())
502         return false;
503
504     RandAddSeedPerfmon();
505
506     if (!CreateThread(StartNode, NULL))
507         wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
508
509     if (fServer)
510         CreateThread(ThreadRPCServer, NULL);
511
512 #if defined(__WXMSW__) && defined(GUI)
513     if (fFirstRun)
514         SetStartOnSystemStartup(true);
515 #endif
516
517 #ifndef GUI
518     while (1)
519         Sleep(5000);
520 #endif
521
522     return true;
523 }