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