Merge branch 'display-version-in-help' of https://github.com/mhanne/bitcoin
[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     for (int i = 1; i < argc; i++)
78         if (!IsSwitchChar(argv[i][0]))
79             fCommandLine = true;
80     fDaemon = !fCommandLine;
81
82 #ifdef __WXGTK__
83     if (!fCommandLine)
84     {
85         // Daemonize
86         pid_t pid = fork();
87         if (pid < 0)
88         {
89             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
90             return 1;
91         }
92         if (pid > 0)
93             pthread_exit((void*)0);
94     }
95 #endif
96
97     if (!AppInit(argc, argv))
98         return 1;
99
100     while (!fShutdown)
101         Sleep(1000000);
102     return 0;
103 }
104 #endif
105
106 bool AppInit(int argc, char* argv[])
107 {
108     bool fRet = false;
109     try
110     {
111         fRet = AppInit2(argc, argv);
112     }
113     catch (std::exception& e) {
114         PrintException(&e, "AppInit()");
115     } catch (...) {
116         PrintException(NULL, "AppInit()");
117     }
118     if (!fRet)
119         Shutdown(NULL);
120     return fRet;
121 }
122
123 bool AppInit2(int argc, char* argv[])
124 {
125 #ifdef _MSC_VER
126     // Turn off microsoft heap dump noise
127     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
128     _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
129 #endif
130 #if _MSC_VER >= 1400
131     // Disable confusing "helpful" text message on abort, ctrl-c
132     _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
133 #endif
134 #ifndef __WXMSW__
135     umask(077);
136 #endif
137 #ifndef __WXMSW__
138     // Clean shutdown on SIGTERM
139     struct sigaction sa;
140     sa.sa_handler = HandleSIGTERM;
141     sigemptyset(&sa.sa_mask);
142     sa.sa_flags = 0;
143     sigaction(SIGTERM, &sa, NULL);
144 #endif
145
146     //
147     // Parameters
148     //
149     ParseParameters(argc, argv);
150
151     if (mapArgs.count("-datadir"))
152     {
153         filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
154         strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
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 " + FormatVersion(VERSION).c_str() + " beta\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             "  -gen             \t\t  " + _("Generate coins\n") +
171             "  -gen=0           \t\t  " + _("Don't generate coins\n") +
172             "  -min             \t\t  " + _("Start minimized\n") +
173             "  -datadir=<dir>   \t\t  " + _("Specify data directory\n") +
174             "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy\n") +
175             "  -addnode=<ip>    \t  "   + _("Add a node to connect to\n") +
176             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node\n") +
177             "  -nolisten        \t  "   + _("Don't accept connections from outside") +
178             "  -paytxfee=<amt>  \t  "   + _("Fee per KB to add to transactions you send\n") +
179             "  -server          \t\t  " + _("Accept command line and JSON-RPC commands\n") +
180             "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands\n") +
181             "  -testnet         \t\t  " + _("Use the test network\n") +
182             "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections\n") +
183             "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections\n") +
184             "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
185             "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address\n") +
186             "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
187             "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)\n") +
188             "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions\n");
189
190 #ifdef USE_SSL
191         strUsage += string() +
192             _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
193             "  -rpcssl                                \t  " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
194             "  -rpcsslcertificatechainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)\n") +
195             "  -rpcsslprivatekeyfile=<file.pem>       \t  " + _("Server private key (default: server.pem)\n") +
196             "  -rpcsslciphers=<ciphers>               \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
197 #endif
198
199         strUsage += string() +
200             "  -?               \t\t  " + _("This help message\n");
201
202 #if defined(__WXMSW__) && defined(GUI)
203         // Tabs make the columns line up in the message box
204         wxMessageBox(strUsage, "Bitcoin", wxOK);
205 #else
206         // Remove tabs
207         strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
208         fprintf(stderr, "%s", strUsage.c_str());
209 #endif
210         return false;
211     }
212
213     fDebug = GetBoolArg("-debug");
214
215     fPrintToConsole = GetBoolArg("-printtoconsole");
216     fPrintToDebugger = GetBoolArg("-printtodebugger");
217
218     fTestNet = GetBoolArg("-testnet");
219     
220     fNoListen = GetBoolArg("-nolisten");
221
222     if (fCommandLine)
223     {
224         int ret = CommandLineRPC(argc, argv);
225         exit(ret);
226     }
227
228     if (!fDebug && !pszSetDataDir[0])
229         ShrinkDebugFile();
230     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
231     printf("Bitcoin version %s%s beta\n", FormatVersion(VERSION).c_str(), pszSubVer);
232 #ifdef GUI
233     printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
234     printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
235     printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
236 #endif
237     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
238
239     if (GetBoolArg("-loadblockindextest"))
240     {
241         CTxDB txdb("r");
242         txdb.LoadBlockIndex();
243         PrintBlockTree();
244         return false;
245     }
246
247     //
248     // Limit to single instance per user
249     // Required to protect the database files if we're going to keep deleting log.*
250     //
251 #if defined(__WXMSW__) && defined(GUI)
252     // wxSingleInstanceChecker doesn't work on Linux
253     wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
254     for (int i = 0; i < strMutexName.size(); i++)
255         if (!isalnum(strMutexName[i]))
256             strMutexName[i] = '.';
257     wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
258     if (psingleinstancechecker->IsAnotherRunning())
259     {
260         printf("Existing instance found\n");
261         unsigned int nStart = GetTime();
262         loop
263         {
264             // Show the previous instance and exit
265             HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
266             if (hwndPrev)
267             {
268                 if (IsIconic(hwndPrev))
269                     ShowWindow(hwndPrev, SW_RESTORE);
270                 SetForegroundWindow(hwndPrev);
271                 return false;
272             }
273
274             if (GetTime() > nStart + 60)
275                 return false;
276
277             // Resume this instance if the other exits
278             delete psingleinstancechecker;
279             Sleep(1000);
280             psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
281             if (!psingleinstancechecker->IsAnotherRunning())
282                 break;
283         }
284     }
285 #endif
286
287     // Make sure only a single bitcoin process is using the data directory.
288     string strLockFile = GetDataDir() + "/.lock";
289     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
290     fclose(file);
291     static boost::interprocess::file_lock lock(strLockFile.c_str());
292     if (!lock.try_lock())
293     {
294         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
295         return false;
296     }
297
298     // Bind to the port early so we can tell if another instance is already running.
299     string strErrors;
300     if (!fNoListen)
301     {
302         if (!BindListenPort(strErrors))
303         {
304             wxMessageBox(strErrors, "Bitcoin");
305             return false;
306         }
307     }
308
309     //
310     // Load data files
311     //
312     if (fDaemon)
313         fprintf(stdout, "bitcoin server starting\n");
314     strErrors = "";
315     int64 nStart;
316
317     printf("Loading addresses...\n");
318     nStart = GetTimeMillis();
319     if (!LoadAddresses())
320         strErrors += _("Error loading addr.dat      \n");
321     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
322
323     printf("Loading block index...\n");
324     nStart = GetTimeMillis();
325     if (!LoadBlockIndex())
326         strErrors += _("Error loading blkindex.dat      \n");
327     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
328
329     printf("Loading wallet...\n");
330     nStart = GetTimeMillis();
331     bool fFirstRun;
332     if (!LoadWallet(fFirstRun))
333         strErrors += _("Error loading wallet.dat      \n");
334     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
335
336     if (GetBoolArg("-rescan"))
337     {
338         nStart = GetTimeMillis();
339         ScanForWalletTransactions(pindexGenesisBlock);
340         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
341     }
342
343     printf("Done loading\n");
344
345         //// debug print
346         printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
347         printf("nBestHeight = %d\n",            nBestHeight);
348         printf("mapKeys.size() = %d\n",         mapKeys.size());
349         printf("mapPubKeys.size() = %d\n",      mapPubKeys.size());
350         printf("mapWallet.size() = %d\n",       mapWallet.size());
351         printf("mapAddressBook.size() = %d\n",  mapAddressBook.size());
352
353     if (!strErrors.empty())
354     {
355         wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
356         return false;
357     }
358
359     // Add wallet transactions that aren't already in a block to mapTransactions
360     ReacceptWalletTransactions();
361
362     //
363     // Parameters
364     //
365     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
366     {
367         PrintBlockTree();
368         return false;
369     }
370
371     if (mapArgs.count("-printblock"))
372     {
373         string strMatch = mapArgs["-printblock"];
374         int nFound = 0;
375         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
376         {
377             uint256 hash = (*mi).first;
378             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
379             {
380                 CBlockIndex* pindex = (*mi).second;
381                 CBlock block;
382                 block.ReadFromDisk(pindex);
383                 block.BuildMerkleTree();
384                 block.print();
385                 printf("\n");
386                 nFound++;
387             }
388         }
389         if (nFound == 0)
390             printf("No blocks matching %s were found\n", strMatch.c_str());
391         return false;
392     }
393
394     fGenerateBitcoins = GetBoolArg("-gen");
395
396     if (mapArgs.count("-proxy"))
397     {
398         fUseProxy = true;
399         addrProxy = CAddress(mapArgs["-proxy"]);
400         if (!addrProxy.IsValid())
401         {
402             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
403             return false;
404         }
405     }
406
407     if (mapArgs.count("-addnode"))
408     {
409         foreach(string strAddr, mapMultiArgs["-addnode"])
410         {
411             CAddress addr(strAddr, NODE_NETWORK);
412             addr.nTime = 0; // so it won't relay unless successfully connected
413             if (addr.IsValid())
414                 AddAddress(addr);
415         }
416     }
417
418     if (mapArgs.count("-paytxfee"))
419     {
420         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
421         {
422             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
423             return false;
424         }
425         if (nTransactionFee > 0.25 * COIN)
426             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
427     }
428
429     //
430     // Create the main window and start the node
431     //
432 #ifdef GUI
433     if (!fDaemon)
434         CreateMainWindow();
435 #endif
436
437     if (!CheckDiskSpace())
438         return false;
439
440     RandAddSeedPerfmon();
441
442     if (!CreateThread(StartNode, NULL))
443         wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
444
445     if (GetBoolArg("-server") || fDaemon)
446         CreateThread(ThreadRPCServer, NULL);
447
448 #if defined(__WXMSW__) && defined(GUI)
449     if (fFirstRun)
450         SetStartOnSystemStartup(true);
451 #endif
452
453     return true;
454 }