Add new command line argument "-printtoconsole" to send debugging output to the conso...
[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           _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
163             "  bitcoin [options]                   \t  " + "\n" +
164             "  bitcoin [options] <command> [params]\t  " + _("Send command to -server or bitcoind\n") +
165             "  bitcoin [options] help              \t\t  " + _("List commands\n") +
166             "  bitcoin [options] help <command>    \t\t  " + _("Get help for a command\n") +
167           _("Options:\n") +
168             "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)\n") +
169             "  -gen             \t\t  " + _("Generate coins\n") +
170             "  -gen=0           \t\t  " + _("Don't generate coins\n") +
171             "  -min             \t\t  " + _("Start minimized\n") +
172             "  -datadir=<dir>   \t\t  " + _("Specify data directory\n") +
173             "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy\n") +
174             "  -addnode=<ip>    \t  "   + _("Add a node to connect to\n") +
175             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node\n") +
176             "  -paytxfee=<amt>  \t  "   + _("Fee per KB to add to transactions you send\n") +
177             "  -server          \t\t  " + _("Accept command line and JSON-RPC commands\n") +
178             "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands\n") +
179             "  -testnet         \t\t  " + _("Use the test network\n") +
180             "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections\n") +
181             "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections\n") +
182             "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port>\n") +
183             "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address\n") +
184             "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip>\n") +
185             "  -keypool=<n>     \t  "   + _("Set key pool size to <n>\n") +
186             "  -nolisten        \t  "   + _("Don't accept connections from outside");
187
188 #ifdef USE_SSL
189         strUsage += string() +
190             _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
191             "  -rpcssl=1                             \t  " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
192             "  -rpcsslcertificatchainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)\n") +
193             "  -rpcsslprivatekeyfile=<file.pem>      \t  " + _("Server private key (default: server.pem)\n") +
194             "  -rpcsslciphers=<ciphers>              \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
195 #endif
196
197         strUsage += string() +
198             "  -?               \t\t  " + _("This help message\n");
199
200 #if defined(__WXMSW__) && defined(GUI)
201         // Tabs make the columns line up in the message box
202         wxMessageBox(strUsage, "Bitcoin", wxOK);
203 #else
204         // Remove tabs
205         strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
206         fprintf(stderr, "%s", strUsage.c_str());
207 #endif
208         return false;
209     }
210
211     fDebug = GetBoolArg("-debug");
212
213     fPrintToConsole = GetBoolArg("-printtoconsole");
214     fPrintToDebugger = GetBoolArg("-printtodebugger");
215
216     fTestNet = GetBoolArg("-testnet");
217     
218     fNoListen = GetBoolArg("-nolisten");
219
220     if (fCommandLine)
221     {
222         int ret = CommandLineRPC(argc, argv);
223         exit(ret);
224     }
225
226     if (!fDebug && !pszSetDataDir[0])
227         ShrinkDebugFile();
228     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
229     printf("Bitcoin version %s%s beta\n", FormatVersion(VERSION).c_str(), pszSubVer);
230 #ifdef GUI
231     printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
232     printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
233     printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
234 #endif
235     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
236
237     if (GetBoolArg("-loadblockindextest"))
238     {
239         CTxDB txdb("r");
240         txdb.LoadBlockIndex();
241         PrintBlockTree();
242         return false;
243     }
244
245     //
246     // Limit to single instance per user
247     // Required to protect the database files if we're going to keep deleting log.*
248     //
249 #if defined(__WXMSW__) && defined(GUI)
250     // wxSingleInstanceChecker doesn't work on Linux
251     wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
252     for (int i = 0; i < strMutexName.size(); i++)
253         if (!isalnum(strMutexName[i]))
254             strMutexName[i] = '.';
255     wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
256     if (psingleinstancechecker->IsAnotherRunning())
257     {
258         printf("Existing instance found\n");
259         unsigned int nStart = GetTime();
260         loop
261         {
262             // Show the previous instance and exit
263             HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
264             if (hwndPrev)
265             {
266                 if (IsIconic(hwndPrev))
267                     ShowWindow(hwndPrev, SW_RESTORE);
268                 SetForegroundWindow(hwndPrev);
269                 return false;
270             }
271
272             if (GetTime() > nStart + 60)
273                 return false;
274
275             // Resume this instance if the other exits
276             delete psingleinstancechecker;
277             Sleep(1000);
278             psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
279             if (!psingleinstancechecker->IsAnotherRunning())
280                 break;
281         }
282     }
283 #endif
284
285     // Make sure only a single bitcoin process is using the data directory.
286     string strLockFile = GetDataDir() + "/.lock";
287     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
288     fclose(file);
289     static boost::interprocess::file_lock lock(strLockFile.c_str());
290     if (!lock.try_lock())
291     {
292         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
293         return false;
294     }
295
296     // Bind to the port early so we can tell if another instance is already running.
297     string strErrors;
298     if (!fNoListen)
299     {
300         if (!BindListenPort(strErrors))
301         {
302             wxMessageBox(strErrors, "Bitcoin");
303             return false;
304         }
305     }
306
307     //
308     // Load data files
309     //
310     if (fDaemon)
311         fprintf(stdout, "bitcoin server starting\n");
312     strErrors = "";
313     int64 nStart;
314
315     printf("Loading addresses...\n");
316     nStart = GetTimeMillis();
317     if (!LoadAddresses())
318         strErrors += _("Error loading addr.dat      \n");
319     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
320
321     printf("Loading block index...\n");
322     nStart = GetTimeMillis();
323     if (!LoadBlockIndex())
324         strErrors += _("Error loading blkindex.dat      \n");
325     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
326
327     printf("Loading wallet...\n");
328     nStart = GetTimeMillis();
329     bool fFirstRun;
330     if (!LoadWallet(fFirstRun))
331         strErrors += _("Error loading wallet.dat      \n");
332     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
333
334     printf("Done loading\n");
335
336         //// debug print
337         printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
338         printf("nBestHeight = %d\n",            nBestHeight);
339         printf("mapKeys.size() = %d\n",         mapKeys.size());
340         printf("mapPubKeys.size() = %d\n",      mapPubKeys.size());
341         printf("mapWallet.size() = %d\n",       mapWallet.size());
342         printf("mapAddressBook.size() = %d\n",  mapAddressBook.size());
343
344     if (!strErrors.empty())
345     {
346         wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
347         return false;
348     }
349
350     // Add wallet transactions that aren't already in a block to mapTransactions
351     ReacceptWalletTransactions();
352
353     //
354     // Parameters
355     //
356     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
357     {
358         PrintBlockTree();
359         return false;
360     }
361
362     if (mapArgs.count("-printblock"))
363     {
364         string strMatch = mapArgs["-printblock"];
365         int nFound = 0;
366         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
367         {
368             uint256 hash = (*mi).first;
369             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
370             {
371                 CBlockIndex* pindex = (*mi).second;
372                 CBlock block;
373                 block.ReadFromDisk(pindex);
374                 block.BuildMerkleTree();
375                 block.print();
376                 printf("\n");
377                 nFound++;
378             }
379         }
380         if (nFound == 0)
381             printf("No blocks matching %s were found\n", strMatch.c_str());
382         return false;
383     }
384
385     fGenerateBitcoins = GetBoolArg("-gen");
386
387     if (mapArgs.count("-proxy"))
388     {
389         fUseProxy = true;
390         addrProxy = CAddress(mapArgs["-proxy"]);
391         if (!addrProxy.IsValid())
392         {
393             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
394             return false;
395         }
396     }
397
398     if (mapArgs.count("-addnode"))
399     {
400         foreach(string strAddr, mapMultiArgs["-addnode"])
401         {
402             CAddress addr(strAddr, NODE_NETWORK);
403             addr.nTime = 0; // so it won't relay unless successfully connected
404             if (addr.IsValid())
405                 AddAddress(addr);
406         }
407     }
408
409     if (mapArgs.count("-paytxfee"))
410     {
411         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
412         {
413             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
414             return false;
415         }
416         if (nTransactionFee > 0.25 * COIN)
417             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
418     }
419
420     //
421     // Create the main window and start the node
422     //
423 #ifdef GUI
424     if (!fDaemon)
425         CreateMainWindow();
426 #endif
427
428     if (!CheckDiskSpace())
429         return false;
430
431     RandAddSeedPerfmon();
432
433     if (!CreateThread(StartNode, NULL))
434         wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
435
436     if (GetBoolArg("-server") || fDaemon)
437         CreateThread(ThreadRPCServer, NULL);
438
439 #if defined(__WXMSW__) && defined(GUI)
440     if (fFirstRun)
441         SetStartOnSystemStartup(true);
442 #endif
443
444     return true;
445 }