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