Framework for banning mis-behaving peers
[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 "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 int main(int argc, char* argv[])
85 {
86     bool fRet = false;
87     fRet = AppInit(argc, argv);
88
89     if (fRet && fDaemon)
90         return 0;
91
92     return 1;
93 }
94 #endif
95
96 bool AppInit(int argc, char* argv[])
97 {
98     bool fRet = false;
99     try
100     {
101         fRet = AppInit2(argc, argv);
102     }
103     catch (std::exception& e) {
104         PrintException(&e, "AppInit()");
105     } catch (...) {
106         PrintException(NULL, "AppInit()");
107     }
108     if (!fRet)
109         Shutdown(NULL);
110     return fRet;
111 }
112
113 bool AppInit2(int argc, char* argv[])
114 {
115 #ifdef _MSC_VER
116     // Turn off microsoft heap dump noise
117     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
118     _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
119 #endif
120 #if _MSC_VER >= 1400
121     // Disable confusing "helpful" text message on abort, ctrl-c
122     _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
123 #endif
124 #ifndef __WXMSW__
125     umask(077);
126 #endif
127 #ifndef __WXMSW__
128     // Clean shutdown on SIGTERM
129     struct sigaction sa;
130     sa.sa_handler = HandleSIGTERM;
131     sigemptyset(&sa.sa_mask);
132     sa.sa_flags = 0;
133     sigaction(SIGTERM, &sa, NULL);
134     sigaction(SIGINT, &sa, NULL);
135     sigaction(SIGHUP, &sa, NULL);
136 #endif
137
138     //
139     // Parameters
140     //
141     ParseParameters(argc, argv);
142
143     if (mapArgs.count("-datadir"))
144     {
145         if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
146         {
147             filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
148             strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
149         }
150         else
151         {
152             fprintf(stderr, "Error: Specified directory does not exist\n");
153             Shutdown(NULL);
154         }
155     }
156
157
158     ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
159
160     if (mapArgs.count("-?") || mapArgs.count("--help"))
161     {
162         string strUsage = string() +
163           _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
164           _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
165             "  bitcoin [options]                   \t  " + "\n" +
166             "  bitcoin [options] <command> [params]\t  " + _("Send command to -server or bitcoind\n") +
167             "  bitcoin [options] help              \t\t  " + _("List commands\n") +
168             "  bitcoin [options] help <command>    \t\t  " + _("Get help for a command\n") +
169           _("Options:\n") +
170             "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)\n") +
171             "  -pid=<file>      \t\t  " + _("Specify pid file (default: bitcoind.pid)\n") +
172             "  -gen             \t\t  " + _("Generate coins\n") +
173             "  -gen=0           \t\t  " + _("Don't generate coins\n") +
174             "  -min             \t\t  " + _("Start minimized\n") +
175             "  -datadir=<dir>   \t\t  " + _("Specify data directory\n") +
176             "  -timeout=<n>     \t  "   + _("Specify connection timeout (in milliseconds)\n") +
177             "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy\n") +
178             "  -dns             \t  "   + _("Allow DNS lookups for addnode and connect\n") +
179             "  -addnode=<ip>    \t  "   + _("Add a node to connect to\n") +
180             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node\n") +
181             "  -nolisten        \t  "   + _("Don't accept connections from outside\n") +
182             "  -banscore=<n>    \t  "   + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
183             "  -bantime=<n>     \t  "   + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\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     bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
254     fNoListen = GetBoolArg("-nolisten") || fTOR;
255     fLogTimestamps = GetBoolArg("-logtimestamps");
256
257     for (int i = 1; i < argc; i++)
258         if (!IsSwitchChar(argv[i][0]))
259             fCommandLine = true;
260
261     if (fCommandLine)
262     {
263         int ret = CommandLineRPC(argc, argv);
264         exit(ret);
265     }
266
267 #ifndef __WXMSW__
268     if (fDaemon)
269     {
270         // Daemonize
271         pid_t pid = fork();
272         if (pid < 0)
273         {
274             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
275             return false;
276         }
277         if (pid > 0)
278         {
279             CreatePidFile(GetPidFile(), pid);
280             return true;
281         }
282
283         pid_t sid = setsid();
284         if (sid < 0)
285             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
286     }
287 #endif
288
289     if (!fDebug && !pszSetDataDir[0])
290         ShrinkDebugFile();
291     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
292     printf("Bitcoin version %s\n", FormatFullVersion().c_str());
293 #ifdef GUI
294     printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
295     printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
296     printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
297 #endif
298     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
299
300     if (GetBoolArg("-loadblockindextest"))
301     {
302         CTxDB txdb("r");
303         txdb.LoadBlockIndex();
304         PrintBlockTree();
305         return false;
306     }
307
308     //
309     // Limit to single instance per user
310     // Required to protect the database files if we're going to keep deleting log.*
311     //
312 #if defined(__WXMSW__) && defined(GUI)
313     // wxSingleInstanceChecker doesn't work on Linux
314     wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
315     for (int i = 0; i < strMutexName.size(); i++)
316         if (!isalnum(strMutexName[i]))
317             strMutexName[i] = '.';
318     wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
319     if (psingleinstancechecker->IsAnotherRunning())
320     {
321         printf("Existing instance found\n");
322         unsigned int nStart = GetTime();
323         loop
324         {
325             // Show the previous instance and exit
326             HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
327             if (hwndPrev)
328             {
329                 if (IsIconic(hwndPrev))
330                     ShowWindow(hwndPrev, SW_RESTORE);
331                 SetForegroundWindow(hwndPrev);
332                 return false;
333             }
334
335             if (GetTime() > nStart + 60)
336                 return false;
337
338             // Resume this instance if the other exits
339             delete psingleinstancechecker;
340             Sleep(1000);
341             psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
342             if (!psingleinstancechecker->IsAnotherRunning())
343                 break;
344         }
345     }
346 #endif
347
348     // Make sure only a single bitcoin process is using the data directory.
349     string strLockFile = GetDataDir() + "/.lock";
350     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
351     if (file) fclose(file);
352     static boost::interprocess::file_lock lock(strLockFile.c_str());
353     if (!lock.try_lock())
354     {
355         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
356         return false;
357     }
358
359     // Bind to the port early so we can tell if another instance is already running.
360     string strErrors;
361     if (!fNoListen)
362     {
363         if (!BindListenPort(strErrors))
364         {
365             wxMessageBox(strErrors, "Bitcoin");
366             return false;
367         }
368     }
369
370     //
371     // Load data files
372     //
373     if (fDaemon)
374         fprintf(stdout, "bitcoin server starting\n");
375     strErrors = "";
376     int64 nStart;
377
378     printf("Loading addresses...\n");
379     nStart = GetTimeMillis();
380     if (!LoadAddresses())
381         strErrors += _("Error loading addr.dat      \n");
382     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
383
384     printf("Loading block index...\n");
385     nStart = GetTimeMillis();
386     if (!LoadBlockIndex())
387         strErrors += _("Error loading blkindex.dat      \n");
388     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
389
390     printf("Loading wallet...\n");
391     nStart = GetTimeMillis();
392     bool fFirstRun;
393     pwalletMain = new CWallet("wallet.dat");
394     int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
395     if (nLoadWalletRet != DB_LOAD_OK)
396     {
397         if (nLoadWalletRet == DB_CORRUPT)
398             strErrors += _("Error loading wallet.dat: Wallet corrupted      \n");
399         else if (nLoadWalletRet == DB_TOO_NEW)
400             strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin      \n");
401         else
402             strErrors += _("Error loading wallet.dat      \n");
403     }
404     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
405
406     RegisterWallet(pwalletMain);
407
408     CBlockIndex *pindexRescan = pindexBest;
409     if (GetBoolArg("-rescan"))
410         pindexRescan = pindexGenesisBlock;
411     else
412     {
413         CWalletDB walletdb("wallet.dat");
414         CBlockLocator locator;
415         if (walletdb.ReadBestBlock(locator))
416             pindexRescan = locator.GetBlockIndex();
417     }
418     if (pindexBest != pindexRescan)
419     {
420         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
421         nStart = GetTimeMillis();
422         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
423         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
424     }
425
426     printf("Done loading\n");
427
428         //// debug print
429         printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
430         printf("nBestHeight = %d\n",            nBestHeight);
431         printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
432         printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
433         printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
434
435     if (!strErrors.empty())
436     {
437         wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
438         return false;
439     }
440
441     // Add wallet transactions that aren't already in a block to mapTransactions
442     pwalletMain->ReacceptWalletTransactions();
443
444     //
445     // Parameters
446     //
447     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
448     {
449         PrintBlockTree();
450         return false;
451     }
452
453     if (mapArgs.count("-timeout"))
454     {
455         int nNewTimeout = GetArg("-timeout", 5000);
456         if (nNewTimeout > 0 && nNewTimeout < 600000)
457             nConnectTimeout = nNewTimeout;
458     }
459
460     if (mapArgs.count("-printblock"))
461     {
462         string strMatch = mapArgs["-printblock"];
463         int nFound = 0;
464         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
465         {
466             uint256 hash = (*mi).first;
467             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
468             {
469                 CBlockIndex* pindex = (*mi).second;
470                 CBlock block;
471                 block.ReadFromDisk(pindex);
472                 block.BuildMerkleTree();
473                 block.print();
474                 printf("\n");
475                 nFound++;
476             }
477         }
478         if (nFound == 0)
479             printf("No blocks matching %s were found\n", strMatch.c_str());
480         return false;
481     }
482
483     fGenerateBitcoins = GetBoolArg("-gen");
484
485     if (mapArgs.count("-proxy"))
486     {
487         fUseProxy = true;
488         addrProxy = CAddress(mapArgs["-proxy"]);
489         if (!addrProxy.IsValid())
490         {
491             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
492             return false;
493         }
494     }
495
496     if (mapArgs.count("-addnode"))
497     {
498         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
499         {
500             CAddress addr(strAddr, fAllowDNS);
501             addr.nTime = 0; // so it won't relay unless successfully connected
502             if (addr.IsValid())
503                 AddAddress(addr);
504         }
505     }
506
507     if (GetBoolArg("-nodnsseed"))
508         printf("DNS seeding disabled\n");
509     else
510         DNSAddressSeed();
511
512     if (mapArgs.count("-paytxfee"))
513     {
514         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
515         {
516             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
517             return false;
518         }
519         if (nTransactionFee > 0.25 * COIN)
520             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
521     }
522
523     if (fHaveUPnP)
524     {
525 #if USE_UPNP
526     if (GetBoolArg("-noupnp"))
527         fUseUPnP = false;
528 #else
529     if (GetBoolArg("-upnp"))
530         fUseUPnP = true;
531 #endif
532     }
533
534     //
535     // Create the main window and start the node
536     //
537 #ifdef GUI
538     if (!fDaemon)
539         CreateMainWindow();
540 #endif
541
542     if (!CheckDiskSpace())
543         return false;
544
545     RandAddSeedPerfmon();
546
547     if (!CreateThread(StartNode, NULL))
548         wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
549
550     if (fServer)
551         CreateThread(ThreadRPCServer, NULL);
552
553 #if defined(__WXMSW__) && defined(GUI)
554     if (fFirstRun)
555         SetStartOnSystemStartup(true);
556 #endif
557
558 #ifndef GUI
559     while (1)
560         Sleep(5000);
561 #endif
562
563     return true;
564 }