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