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