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