PPCoin: RPC 'makekeypair' limits loop to avoid hang
[novacoin.git] / src / init.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #include "headers.h"
7 #include "db.h"
8 #include "bitcoinrpc.h"
9 #include "net.h"
10 #include "init.h"
11 #include "strlcpy.h"
12 #include <boost/filesystem.hpp>
13 #include <boost/filesystem/fstream.hpp>
14 #include <boost/interprocess/sync/file_lock.hpp>
15
16 #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
17 #define _BITCOIN_QT_PLUGINS_INCLUDED
18 #define __INSURE__
19 #include <QtPlugin>
20 Q_IMPORT_PLUGIN(qcncodecs)
21 Q_IMPORT_PLUGIN(qjpcodecs)
22 Q_IMPORT_PLUGIN(qtwcodecs)
23 Q_IMPORT_PLUGIN(qkrcodecs)
24 #endif
25
26 using namespace std;
27 using namespace boost;
28
29 CWallet* pwalletMain;
30
31 //////////////////////////////////////////////////////////////////////////////
32 //
33 // Shutdown
34 //
35
36 void ExitTimeout(void* parg)
37 {
38 #ifdef WIN32
39     Sleep(5000);
40     ExitProcess(0);
41 #endif
42 }
43
44 void Shutdown(void* parg)
45 {
46     static CCriticalSection cs_Shutdown;
47     static bool fTaken;
48     bool fFirstThread = false;
49     TRY_CRITICAL_BLOCK(cs_Shutdown)
50     {
51         fFirstThread = !fTaken;
52         fTaken = true;
53     }
54     static bool fExit;
55     if (fFirstThread)
56     {
57         fShutdown = true;
58         nTransactionsUpdated++;
59         DBFlush(false);
60         StopNode();
61         DBFlush(true);
62         boost::filesystem::remove(GetPidFile());
63         UnregisterWallet(pwalletMain);
64         delete pwalletMain;
65         CreateThread(ExitTimeout, NULL);
66         Sleep(50);
67         printf("PPCoin exiting\n\n");
68         fExit = true;
69         exit(0);
70     }
71     else
72     {
73         while (!fExit)
74             Sleep(500);
75         Sleep(100);
76         ExitThread(0);
77     }
78 }
79
80 void HandleSIGTERM(int)
81 {
82     fRequestShutdown = true;
83 }
84
85
86
87
88
89
90 //////////////////////////////////////////////////////////////////////////////
91 //
92 // Start
93 //
94 #if !defined(QT_GUI)
95 #if !defined(PPCOIN_GENESIS)
96 int main(int argc, char* argv[])
97 {
98     bool fRet = false;
99     fRet = AppInit(argc, argv);
100
101     if (fRet && fDaemon)
102         return 0;
103
104     return 1;
105 }
106 #endif
107 #endif
108
109 bool AppInit(int argc, char* argv[])
110 {
111     bool fRet = false;
112     try
113     {
114         fRet = AppInit2(argc, argv);
115     }
116     catch (std::exception& e) {
117         PrintException(&e, "AppInit()");
118     } catch (...) {
119         PrintException(NULL, "AppInit()");
120     }
121     if (!fRet)
122         Shutdown(NULL);
123     return fRet;
124 }
125
126 bool AppInit2(int argc, char* argv[])
127 {
128 #ifdef _MSC_VER
129     // Turn off microsoft heap dump noise
130     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
131     _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
132 #endif
133 #if _MSC_VER >= 1400
134     // Disable confusing "helpful" text message on abort, ctrl-c
135     _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
136 #endif
137 #ifndef WIN32
138     umask(077);
139 #endif
140 #ifndef WIN32
141     // Clean shutdown on SIGTERM
142     struct sigaction sa;
143     sa.sa_handler = HandleSIGTERM;
144     sigemptyset(&sa.sa_mask);
145     sa.sa_flags = 0;
146     sigaction(SIGTERM, &sa, NULL);
147     sigaction(SIGINT, &sa, NULL);
148     sigaction(SIGHUP, &sa, NULL);
149 #endif
150
151     //
152     // Parameters
153     //
154     ParseParameters(argc, argv);
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           _("PPCoin version") + " " + FormatFullVersion() + "\n\n" +
177           _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
178             "  ppcoind [options]                   \t  " + "\n" +
179             "  ppcoind [options] <command> [params]\t  " + _("Send command to -server or ppcoind\n") +
180             "  ppcoind [options] help              \t\t  " + _("List commands\n") +
181             "  ppcoind [options] help <command>    \t\t  " + _("Get help for a command\n") +
182           _("Options:\n") +
183             "  -conf=<file>     \t\t  " + _("Specify configuration file (default: ppcoin.conf)\n") +
184             "  -pid=<file>      \t\t  " + _("Specify pid file (default: ppcoind.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: 9901 or testnet: 9903)\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: 9902)\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("PPCoin 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.  PPCoin is probably already running."), GetDataDir().c_str()), "PPCoin");
331         return false;
332     }
333
334     // Bind to the port early so we can tell if another instance is already running.
335     string strErrors;
336     if (!fNoListen)
337     {
338         if (!BindListenPort(strErrors))
339         {
340             wxMessageBox(strErrors, "PPCoin");
341             return false;
342         }
343     }
344
345     //
346     // Load data files
347     //
348     if (fDaemon)
349         fprintf(stdout, "ppcoin server starting\n");
350     strErrors = "";
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 PPCoin      \n");
379         else if (nLoadWalletRet == DB_NEED_REWRITE)
380         {
381             strErrors += _("Wallet needed to be rewritten: restart PPCoin to complete    \n");
382             wxMessageBox(strErrors, "PPCoin", 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.empty())
422     {
423         wxMessageBox(strErrors, "PPCoin", 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"), "PPCoin");
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) || nTransactionFee < MIN_TX_FEE)
496         {
497             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "PPCoin");
498             return false;
499         }
500         nTransactionFee = (nTransactionFee / CENT) * CENT;  // round to cent
501         if (nTransactionFee >= 0.25 * COIN)
502             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "PPCoin", wxOK | wxICON_EXCLAMATION);
503     }
504
505     if (fHaveUPnP)
506     {
507 #if USE_UPNP
508     if (GetBoolArg("-noupnp"))
509         fUseUPnP = false;
510 #else
511     if (GetBoolArg("-upnp"))
512         fUseUPnP = true;
513 #endif
514     }
515
516     //
517     // Start the node
518     //
519     if (!CheckDiskSpace())
520         return false;
521
522     RandAddSeedPerfmon();
523
524     if (!CreateThread(StartNode, NULL))
525         wxMessageBox(_("Error: CreateThread(StartNode) failed"), "PPCoin");
526
527     if (fServer)
528         CreateThread(ThreadRPCServer, NULL);
529
530 #if !defined(QT_GUI)
531     while (1)
532         Sleep(5000);
533 #endif
534
535     return true;
536 }