cac921e2b26194eebfd890e0dc191d95611478e8
[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     fNoListen = GetBoolArg("-nolisten");
250     fLogTimestamps = GetBoolArg("-logtimestamps");
251
252     for (int i = 1; i < argc; i++)
253         if (!IsSwitchChar(argv[i][0]))
254             fCommandLine = true;
255
256     if (fCommandLine)
257     {
258         int ret = CommandLineRPC(argc, argv);
259         exit(ret);
260     }
261
262 #ifndef __WXMSW__
263     if (fDaemon)
264     {
265         // Daemonize
266         pid_t pid = fork();
267         if (pid < 0)
268         {
269             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
270             return false;
271         }
272         if (pid > 0)
273         {
274             CreatePidFile(GetPidFile(), pid);
275             return true;
276         }
277
278         pid_t sid = setsid();
279         if (sid < 0)
280             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
281     }
282 #endif
283
284     if (!fDebug && !pszSetDataDir[0])
285         ShrinkDebugFile();
286     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
287     printf("Bitcoin version %s\n", FormatFullVersion().c_str());
288 #ifdef GUI
289     printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
290     printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
291     printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
292 #endif
293     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
294
295     if (GetBoolArg("-loadblockindextest"))
296     {
297         CTxDB txdb("r");
298         txdb.LoadBlockIndex();
299         PrintBlockTree();
300         return false;
301     }
302
303     //
304     // Limit to single instance per user
305     // Required to protect the database files if we're going to keep deleting log.*
306     //
307 #if defined(__WXMSW__) && defined(GUI)
308     // wxSingleInstanceChecker doesn't work on Linux
309     wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
310     for (int i = 0; i < strMutexName.size(); i++)
311         if (!isalnum(strMutexName[i]))
312             strMutexName[i] = '.';
313     wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
314     if (psingleinstancechecker->IsAnotherRunning())
315     {
316         printf("Existing instance found\n");
317         unsigned int nStart = GetTime();
318         loop
319         {
320             // Show the previous instance and exit
321             HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
322             if (hwndPrev)
323             {
324                 if (IsIconic(hwndPrev))
325                     ShowWindow(hwndPrev, SW_RESTORE);
326                 SetForegroundWindow(hwndPrev);
327                 return false;
328             }
329
330             if (GetTime() > nStart + 60)
331                 return false;
332
333             // Resume this instance if the other exits
334             delete psingleinstancechecker;
335             Sleep(1000);
336             psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
337             if (!psingleinstancechecker->IsAnotherRunning())
338                 break;
339         }
340     }
341 #endif
342
343     // Make sure only a single bitcoin process is using the data directory.
344     string strLockFile = GetDataDir() + "/.lock";
345     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
346     if (file) fclose(file);
347     static boost::interprocess::file_lock lock(strLockFile.c_str());
348     if (!lock.try_lock())
349     {
350         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
351         return false;
352     }
353
354     // Bind to the port early so we can tell if another instance is already running.
355     string strErrors;
356     if (!fNoListen)
357     {
358         if (!BindListenPort(strErrors))
359         {
360             wxMessageBox(strErrors, "Bitcoin");
361             return false;
362         }
363     }
364
365     //
366     // Load data files
367     //
368     if (fDaemon)
369         fprintf(stdout, "bitcoin server starting\n");
370     strErrors = "";
371     int64 nStart;
372
373     printf("Loading addresses...\n");
374     nStart = GetTimeMillis();
375     if (!LoadAddresses())
376         strErrors += _("Error loading addr.dat      \n");
377     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
378
379     printf("Loading block index...\n");
380     nStart = GetTimeMillis();
381     if (!LoadBlockIndex())
382         strErrors += _("Error loading blkindex.dat      \n");
383     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
384
385     printf("Loading wallet...\n");
386     nStart = GetTimeMillis();
387     bool fFirstRun;
388     pwalletMain = new CWallet("wallet.dat");
389     if (!pwalletMain->LoadWallet(fFirstRun))
390         strErrors += _("Error loading wallet.dat      \n");
391     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
392
393     RegisterWallet(pwalletMain);
394
395     CBlockIndex *pindexRescan = pindexBest;
396     if (GetBoolArg("-rescan"))
397         pindexRescan = pindexGenesisBlock;
398     else
399     {
400         CWalletDB walletdb("wallet.dat");
401         CBlockLocator locator;
402         if (walletdb.ReadBestBlock(locator))
403             pindexRescan = locator.GetBlockIndex();
404     }
405     if (pindexBest != pindexRescan)
406     {
407         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
408         nStart = GetTimeMillis();
409         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
410         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
411     }
412
413     printf("Done loading\n");
414
415         //// debug print
416         printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
417         printf("nBestHeight = %d\n",            nBestHeight);
418         printf("mapKeys.size() = %d\n",         pwalletMain->mapKeys.size());
419         printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
420         printf("mapPubKeys.size() = %d\n",      mapPubKeys.size());
421         printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
422         printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
423
424     if (!strErrors.empty())
425     {
426         wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
427         return false;
428     }
429
430     // Add wallet transactions that aren't already in a block to mapTransactions
431     pwalletMain->ReacceptWalletTransactions();
432
433     //
434     // Parameters
435     //
436     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
437     {
438         PrintBlockTree();
439         return false;
440     }
441
442     if (mapArgs.count("-timeout"))
443     {
444         int nNewTimeout = GetArg("-timeout", 5000);
445         if (nNewTimeout > 0 && nNewTimeout < 600000)
446             nConnectTimeout = nNewTimeout;
447     }
448
449     if (mapArgs.count("-printblock"))
450     {
451         string strMatch = mapArgs["-printblock"];
452         int nFound = 0;
453         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
454         {
455             uint256 hash = (*mi).first;
456             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
457             {
458                 CBlockIndex* pindex = (*mi).second;
459                 CBlock block;
460                 block.ReadFromDisk(pindex);
461                 block.BuildMerkleTree();
462                 block.print();
463                 printf("\n");
464                 nFound++;
465             }
466         }
467         if (nFound == 0)
468             printf("No blocks matching %s were found\n", strMatch.c_str());
469         return false;
470     }
471
472     fGenerateBitcoins = GetBoolArg("-gen");
473
474     if (mapArgs.count("-proxy"))
475     {
476         fUseProxy = true;
477         addrProxy = CAddress(mapArgs["-proxy"]);
478         if (!addrProxy.IsValid())
479         {
480             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
481             return false;
482         }
483     }
484
485     if (mapArgs.count("-addnode"))
486     {
487         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
488         {
489             CAddress addr(strAddr, fAllowDNS);
490             addr.nTime = 0; // so it won't relay unless successfully connected
491             if (addr.IsValid())
492                 AddAddress(addr);
493         }
494     }
495
496     if (mapArgs.count("-dnsseed"))
497         DNSAddressSeed();
498
499     if (mapArgs.count("-paytxfee"))
500     {
501         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
502         {
503             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
504             return false;
505         }
506         if (nTransactionFee > 0.25 * COIN)
507             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
508     }
509
510     if (fHaveUPnP)
511     {
512 #if USE_UPNP
513     if (GetBoolArg("-noupnp"))
514         fUseUPnP = false;
515 #else
516     if (GetBoolArg("-upnp"))
517         fUseUPnP = true;
518 #endif
519     }
520
521     //
522     // Create the main window and start the node
523     //
524 #ifdef GUI
525     if (!fDaemon)
526         CreateMainWindow();
527 #endif
528
529     if (!CheckDiskSpace())
530         return false;
531
532     RandAddSeedPerfmon();
533
534     if (!CreateThread(StartNode, NULL))
535         wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
536
537     if (fServer)
538         CreateThread(ThreadRPCServer, NULL);
539
540 #if defined(__WXMSW__) && defined(GUI)
541     if (fFirstRun)
542         SetStartOnSystemStartup(true);
543 #endif
544
545 #if !defined(QT_GUI) && !defined(GUI)
546     while (1)
547         Sleep(5000);
548 #endif
549
550     return true;
551 }