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