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