Obsolete keypool and make sure database removes log files on shutdown.
[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, false);
59         StopNode();
60         DBFlush(true, 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             "  bitcoin [options]                   \t  " + "\n" +
176             "  bitcoin [options] <command> [params]\t  " + _("Send command to -server or bitcoind\n") +
177             "  bitcoin [options] help              \t\t  " + _("List commands\n") +
178             "  bitcoin [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             "  -addnode=<ip>    \t  "   + _("Add a node to connect to\n") +
190             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node\n") +
191             "  -nolisten        \t  "   + _("Don't accept connections from outside\n") +
192             "  -banscore=<n>    \t  "   + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
193             "  -bantime=<n>     \t  "   + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\n") +
194 #ifdef USE_UPNP
195 #if USE_UPNP
196             "  -noupnp          \t  "   + _("Don't attempt to use UPnP to map the listening port\n") +
197 #else
198             "  -upnp            \t  "   + _("Attempt to use UPnP to map the listening port\n") +
199 #endif
200 #endif
201             "  -paytxfee=<amt>  \t  "   + _("Fee per KB to add to transactions you send\n") +
202 #ifdef GUI
203             "  -server          \t\t  " + _("Accept command line and JSON-RPC commands\n") +
204 #endif
205 #ifndef WIN32
206             "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands\n") +
207 #endif
208             "  -testnet         \t\t  " + _("Use the test network\n") +
209             "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections\n") +
210             "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections\n") +
211             "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
212             "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address\n") +
213             "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
214             "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)\n") +
215             "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions\n");
216
217 #ifdef USE_SSL
218         strUsage += string() +
219             _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
220             "  -rpcssl                                \t  " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
221             "  -rpcsslcertificatechainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)\n") +
222             "  -rpcsslprivatekeyfile=<file.pem>       \t  " + _("Server private key (default: server.pem)\n") +
223             "  -rpcsslciphers=<ciphers>               \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
224 #endif
225
226         strUsage += string() +
227             "  -?               \t\t  " + _("This help message\n");
228
229         // Remove tabs
230         strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
231         fprintf(stderr, "%s", strUsage.c_str());
232         return false;
233     }
234
235     fDebug = GetBoolArg("-debug");
236     fAllowDNS = GetBoolArg("-dns");
237
238 #ifndef WIN32
239     fDaemon = GetBoolArg("-daemon");
240 #else
241     fDaemon = false;
242 #endif
243
244     if (fDaemon)
245         fServer = true;
246     else
247         fServer = GetBoolArg("-server");
248
249     /* force fServer when running without GUI */
250 #if !defined(QT_GUI)
251     fServer = true;
252 #endif
253     fPrintToConsole = GetBoolArg("-printtoconsole");
254     fPrintToDebugger = GetBoolArg("-printtodebugger");
255
256     fTestNet = GetBoolArg("-testnet");
257     bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
258     fNoListen = GetBoolArg("-nolisten") || fTOR;
259     fLogTimestamps = GetBoolArg("-logtimestamps");
260
261 #ifndef QT_GUI
262     for (int i = 1; i < argc; i++)
263         if (!IsSwitchChar(argv[i][0]))
264             fCommandLine = true;
265
266     if (fCommandLine)
267     {
268         int ret = CommandLineRPC(argc, argv);
269         exit(ret);
270     }
271 #endif
272
273 #ifndef WIN32
274     if (fDaemon)
275     {
276         // Daemonize
277         pid_t pid = fork();
278         if (pid < 0)
279         {
280             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
281             return false;
282         }
283         if (pid > 0)
284         {
285             CreatePidFile(GetPidFile(), pid);
286             return true;
287         }
288
289         pid_t sid = setsid();
290         if (sid < 0)
291             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
292     }
293 #endif
294
295     if (!fDebug && !pszSetDataDir[0])
296         ShrinkDebugFile();
297     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
298     printf("Bitcoin version %s\n", FormatFullVersion().c_str());
299     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
300
301     if (GetBoolArg("-loadblockindextest"))
302     {
303         CTxDB txdb("r");
304         txdb.LoadBlockIndex();
305         PrintBlockTree();
306         return false;
307     }
308
309     // Make sure only a single bitcoin process is using the data directory.
310     string strLockFile = GetDataDir() + "/.lock";
311     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
312     if (file) fclose(file);
313     static boost::interprocess::file_lock lock(strLockFile.c_str());
314     if (!lock.try_lock())
315     {
316         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
317         return false;
318     }
319
320     // Bind to the port early so we can tell if another instance is already running.
321     string strErrors;
322     if (!fNoListen)
323     {
324         if (!BindListenPort(strErrors))
325         {
326             wxMessageBox(strErrors, "Bitcoin");
327             return false;
328         }
329     }
330
331     //
332     // Load data files
333     //
334     if (fDaemon)
335         fprintf(stdout, "bitcoin server starting\n");
336     strErrors = "";
337     int64 nStart;
338
339     InitMessage(_("Loading addresses..."));
340     printf("Loading addresses...\n");
341     nStart = GetTimeMillis();
342     if (!LoadAddresses())
343         strErrors += _("Error loading addr.dat      \n");
344     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
345
346     InitMessage(_("Loading block index..."));
347     printf("Loading block index...\n");
348     nStart = GetTimeMillis();
349     if (!LoadBlockIndex())
350         strErrors += _("Error loading blkindex.dat      \n");
351     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
352
353     InitMessage(_("Loading wallet..."));
354     printf("Loading wallet...\n");
355     nStart = GetTimeMillis();
356     bool fFirstRun;
357     pwalletMain = new CWallet("wallet.dat");
358     int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
359     if (nLoadWalletRet != DB_LOAD_OK)
360     {
361         if (nLoadWalletRet == DB_CORRUPT)
362             strErrors += _("Error loading wallet.dat: Wallet corrupted      \n");
363         else if (nLoadWalletRet == DB_TOO_NEW)
364             strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin      \n");
365         else if (nLoadWalletRet == DB_NEED_REWRITE)
366         {
367             strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete    \n");
368             wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
369             return false;
370         }
371         else
372             strErrors += _("Error loading wallet.dat      \n");
373     }
374     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
375
376     RegisterWallet(pwalletMain);
377
378     CBlockIndex *pindexRescan = pindexBest;
379     if (GetBoolArg("-rescan"))
380         pindexRescan = pindexGenesisBlock;
381     else
382     {
383         CWalletDB walletdb("wallet.dat");
384         CBlockLocator locator;
385         if (walletdb.ReadBestBlock(locator))
386             pindexRescan = locator.GetBlockIndex();
387     }
388     if (pindexBest != pindexRescan)
389     {
390         InitMessage(_("Rescanning..."));
391         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
392         nStart = GetTimeMillis();
393         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
394         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
395     }
396
397     InitMessage(_("Done loading"));
398     printf("Done loading\n");
399
400         //// debug print
401         printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
402         printf("nBestHeight = %d\n",            nBestHeight);
403         printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
404         printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
405         printf("mapAddressBook.size() = %d\n",  pwalletMain->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     pwalletMain->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 (GetBoolArg("-nodnsseed"))
480         printf("DNS seeding disabled\n");
481     else
482         DNSAddressSeed();
483
484     if (mapArgs.count("-paytxfee"))
485     {
486         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
487         {
488             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
489             return false;
490         }
491         if (nTransactionFee > 0.25 * COIN)
492             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
493     }
494
495     if (fHaveUPnP)
496     {
497 #if USE_UPNP
498     if (GetBoolArg("-noupnp"))
499         fUseUPnP = false;
500 #else
501     if (GetBoolArg("-upnp"))
502         fUseUPnP = true;
503 #endif
504     }
505
506     //
507     // Start the node
508     //
509     if (!CheckDiskSpace())
510         return false;
511
512     RandAddSeedPerfmon();
513
514     if (!CreateThread(StartNode, NULL))
515         wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
516
517     if (fServer)
518         CreateThread(ThreadRPCServer, NULL);
519
520 #if !defined(QT_GUI)
521     while (1)
522         Sleep(5000);
523 #endif
524
525     return true;
526 }