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