cbd9fc02191ae5161abcd088b984e1f5e64e31ed
[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/operations.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 //////////////////////////////////////////////////////////////////////////////
18 //
19 // Shutdown
20 //
21
22 void ExitTimeout(void* parg)
23 {
24 #ifdef __WXMSW__
25     Sleep(5000);
26     ExitProcess(0);
27 #endif
28 }
29
30 void Shutdown(void* parg)
31 {
32     static CCriticalSection cs_Shutdown;
33     static bool fTaken;
34     bool fFirstThread;
35     CRITICAL_BLOCK(cs_Shutdown)
36     {
37         fFirstThread = !fTaken;
38         fTaken = true;
39     }
40     static bool fExit;
41     if (fFirstThread)
42     {
43         fShutdown = true;
44         nTransactionsUpdated++;
45         DBFlush(false);
46         StopNode();
47         DBFlush(true);
48         boost::filesystem::remove(GetPidFile());
49         CreateThread(ExitTimeout, NULL);
50         Sleep(50);
51         printf("Bitcoin exiting\n\n");
52         fExit = true;
53         exit(0);
54     }
55     else
56     {
57         while (!fExit)
58             Sleep(500);
59         Sleep(100);
60         ExitThread(0);
61     }
62 }
63
64 void HandleSIGTERM(int)
65 {
66     fRequestShutdown = true;
67 }
68
69
70
71
72
73
74 //////////////////////////////////////////////////////////////////////////////
75 //
76 // Start
77 //
78 #if !defined(QT_GUI) && !defined(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
91 bool AppInit(int argc, char* argv[])
92 {
93     bool fRet = false;
94     try
95     {
96         fRet = AppInit2(argc, argv);
97     }
98     catch (std::exception& e) {
99         PrintException(&e, "AppInit()");
100     } catch (...) {
101         PrintException(NULL, "AppInit()");
102     }
103     if (!fRet)
104         Shutdown(NULL);
105     return fRet;
106 }
107
108 bool AppInit2(int argc, char* argv[])
109 {
110 #ifdef _MSC_VER
111     // Turn off microsoft heap dump noise
112     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
113     _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
114 #endif
115 #if _MSC_VER >= 1400
116     // Disable confusing "helpful" text message on abort, ctrl-c
117     _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
118 #endif
119 #ifndef __WXMSW__
120     umask(077);
121 #endif
122 #ifndef __WXMSW__
123     // Clean shutdown on SIGTERM
124     struct sigaction sa;
125     sa.sa_handler = HandleSIGTERM;
126     sigemptyset(&sa.sa_mask);
127     sa.sa_flags = 0;
128     sigaction(SIGTERM, &sa, NULL);
129     sigaction(SIGINT, &sa, NULL);
130     sigaction(SIGHUP, &sa, NULL);
131 #endif
132
133     //
134     // Parameters
135     //
136     ParseParameters(argc, argv);
137
138     if (mapArgs.count("-datadir"))
139     {
140         filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
141         strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
142     }
143
144     ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
145
146     if (mapArgs.count("-?") || mapArgs.count("--help"))
147     {
148         string strUsage = string() +
149           _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
150           _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
151             "  bitcoin [options]                   \t  " + "\n" +
152             "  bitcoin [options] <command> [params]\t  " + _("Send command to -server or bitcoind\n") +
153             "  bitcoin [options] help              \t\t  " + _("List commands\n") +
154             "  bitcoin [options] help <command>    \t\t  " + _("Get help for a command\n") +
155           _("Options:\n") +
156             "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)\n") +
157             "  -pid=<file>      \t\t  " + _("Specify pid file (default: bitcoind.pid)\n") +
158             "  -gen             \t\t  " + _("Generate coins\n") +
159             "  -gen=0           \t\t  " + _("Don't generate coins\n") +
160             "  -min             \t\t  " + _("Start minimized\n") +
161             "  -datadir=<dir>   \t\t  " + _("Specify data directory\n") +
162             "  -timeout=<n>     \t  "   + _("Specify connection timeout (in milliseconds)\n") +
163             "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy\n") +
164             "  -dns             \t  "   + _("Allow DNS lookups for addnode and connect\n") +
165             "  -addnode=<ip>    \t  "   + _("Add a node to connect to\n") +
166             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node\n") +
167             "  -nolisten        \t  "   + _("Don't accept connections from outside\n") +
168 #ifdef USE_UPNP
169 #if USE_UPNP
170             "  -noupnp          \t  "   + _("Don't attempt to use UPnP to map the listening port\n") +
171 #else
172             "  -upnp            \t  "   + _("Attempt to use UPnP to map the listening port\n") +
173 #endif
174 #endif
175             "  -paytxfee=<amt>  \t  "   + _("Fee per KB to add to transactions you send\n") +
176 #ifdef GUI
177             "  -server          \t\t  " + _("Accept command line and JSON-RPC commands\n") +
178 #endif
179 #ifndef __WXMSW__
180             "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands\n") +
181 #endif
182             "  -testnet         \t\t  " + _("Use the test network\n") +
183             "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections\n") +
184             "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections\n") +
185             "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
186             "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address\n") +
187             "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
188             "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)\n") +
189             "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions\n");
190
191 #ifdef USE_SSL
192         strUsage += string() +
193             _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
194             "  -rpcssl                                \t  " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
195             "  -rpcsslcertificatechainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)\n") +
196             "  -rpcsslprivatekeyfile=<file.pem>       \t  " + _("Server private key (default: server.pem)\n") +
197             "  -rpcsslciphers=<ciphers>               \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
198 #endif
199
200         strUsage += string() +
201             "  -?               \t\t  " + _("This help message\n");
202
203 #if defined(__WXMSW__) && defined(GUI)
204         // Tabs make the columns line up in the message box
205         wxMessageBox(strUsage, "Bitcoin", wxOK);
206 #else
207         // Remove tabs
208         strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
209         fprintf(stderr, "%s", strUsage.c_str());
210 #endif
211         return false;
212     }
213
214     fDebug = GetBoolArg("-debug");
215     fAllowDNS = GetBoolArg("-dns");
216
217 #ifndef __WXMSW__
218     fDaemon = GetBoolArg("-daemon");
219 #else
220     fDaemon = false;
221 #endif
222
223     if (fDaemon)
224         fServer = true;
225     else
226         fServer = GetBoolArg("-server");
227
228     /* force fServer when running without GUI */
229 #if !defined(QT_GUI) && !defined(GUI)
230     fServer = true;
231 #endif
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 #if !defined(QT_GUI) && !defined(GUI)
529     while (1)
530         Sleep(5000);
531 #endif
532
533     return true;
534 }