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