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