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