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