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