d6e153285edd437b2f1c77c5d88ca8295eeb504c
[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;
48     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             "  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
366             strErrors += _("Error loading wallet.dat      \n");
367     }
368     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
369
370     RegisterWallet(pwalletMain);
371
372     CBlockIndex *pindexRescan = pindexBest;
373     if (GetBoolArg("-rescan"))
374         pindexRescan = pindexGenesisBlock;
375     else
376     {
377         CWalletDB walletdb("wallet.dat");
378         CBlockLocator locator;
379         if (walletdb.ReadBestBlock(locator))
380             pindexRescan = locator.GetBlockIndex();
381     }
382     if (pindexBest != pindexRescan)
383     {
384         InitMessage(_("Rescanning..."));
385         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
386         nStart = GetTimeMillis();
387         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
388         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
389     }
390
391     InitMessage(_("Done loading"));
392     printf("Done loading\n");
393
394         //// debug print
395         printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
396         printf("nBestHeight = %d\n",            nBestHeight);
397         printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
398         printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
399         printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
400
401     if (!strErrors.empty())
402     {
403         wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
404         return false;
405     }
406
407     // Add wallet transactions that aren't already in a block to mapTransactions
408     pwalletMain->ReacceptWalletTransactions();
409
410     //
411     // Parameters
412     //
413     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
414     {
415         PrintBlockTree();
416         return false;
417     }
418
419     if (mapArgs.count("-timeout"))
420     {
421         int nNewTimeout = GetArg("-timeout", 5000);
422         if (nNewTimeout > 0 && nNewTimeout < 600000)
423             nConnectTimeout = nNewTimeout;
424     }
425
426     if (mapArgs.count("-printblock"))
427     {
428         string strMatch = mapArgs["-printblock"];
429         int nFound = 0;
430         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
431         {
432             uint256 hash = (*mi).first;
433             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
434             {
435                 CBlockIndex* pindex = (*mi).second;
436                 CBlock block;
437                 block.ReadFromDisk(pindex);
438                 block.BuildMerkleTree();
439                 block.print();
440                 printf("\n");
441                 nFound++;
442             }
443         }
444         if (nFound == 0)
445             printf("No blocks matching %s were found\n", strMatch.c_str());
446         return false;
447     }
448
449     fGenerateBitcoins = GetBoolArg("-gen");
450
451     if (mapArgs.count("-proxy"))
452     {
453         fUseProxy = true;
454         addrProxy = CAddress(mapArgs["-proxy"]);
455         if (!addrProxy.IsValid())
456         {
457             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
458             return false;
459         }
460     }
461
462     if (mapArgs.count("-addnode"))
463     {
464         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
465         {
466             CAddress addr(strAddr, fAllowDNS);
467             addr.nTime = 0; // so it won't relay unless successfully connected
468             if (addr.IsValid())
469                 AddAddress(addr);
470         }
471     }
472
473     if (GetBoolArg("-nodnsseed"))
474         printf("DNS seeding disabled\n");
475     else
476         DNSAddressSeed();
477
478     if (mapArgs.count("-paytxfee"))
479     {
480         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
481         {
482             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
483             return false;
484         }
485         if (nTransactionFee > 0.25 * COIN)
486             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
487     }
488
489     if (fHaveUPnP)
490     {
491 #if USE_UPNP
492     if (GetBoolArg("-noupnp"))
493         fUseUPnP = false;
494 #else
495     if (GetBoolArg("-upnp"))
496         fUseUPnP = true;
497 #endif
498     }
499
500     //
501     // Start the node
502     //
503     if (!CheckDiskSpace())
504         return false;
505
506     RandAddSeedPerfmon();
507
508     if (!CreateThread(StartNode, NULL))
509         wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
510
511     if (fServer)
512         CreateThread(ThreadRPCServer, NULL);
513
514 #if !defined(QT_GUI)
515     while (1)
516         Sleep(5000);
517 #endif
518
519     return true;
520 }