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