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