Add branch README.md
[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  " + _("Specify configuration file (default: bitcoin.conf)\n") +
169             "  -gen            \t  " + _("Generate coins\n") +
170             "  -gen=0          \t  " + _("Don't generate coins\n") +
171             "  -min            \t  " + _("Start minimized\n") +
172             "  -datadir=<dir>  \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  " + _("Connect only to the specified node\n") +
176             "  -server         \t  " + _("Accept command line and JSON-RPC commands\n") +
177             "  -daemon         \t  " + _("Run in the background as a daemon and accept commands\n") +
178             "  -?              \t  " + _("This help message\n");
179
180 #if defined(__WXMSW__) && defined(GUI)
181         // Tabs make the columns line up in the message box
182         wxMessageBox(strUsage, "Bitcoin", wxOK);
183 #else
184         // Remove tabs
185         strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
186         fprintf(stderr, "%s", strUsage.c_str());
187 #endif
188         return false;
189     }
190
191     if (mapArgs.count("-debug"))
192         fDebug = true;
193
194     if (mapArgs.count("-printtodebugger"))
195         fPrintToDebugger = true;
196
197     if (fCommandLine)
198     {
199         int ret = CommandLineRPC(argc, argv);
200         exit(ret);
201     }
202
203     if (!fDebug && !pszSetDataDir[0])
204         ShrinkDebugFile();
205     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
206     printf("Bitcoin version %d.%d.%d%s beta\n", VERSION/10000, (VERSION/100)%100, VERSION%100, pszSubVer);
207 #ifdef GUI
208     printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
209     printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
210     printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
211 #endif
212     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
213
214     if (mapArgs.count("-loadblockindextest"))
215     {
216         CTxDB txdb("r");
217         txdb.LoadBlockIndex();
218         PrintBlockTree();
219         return false;
220     }
221
222     //
223     // Limit to single instance per user
224     // Required to protect the database files if we're going to keep deleting log.*
225     //
226 #if defined(__WXMSW__) && defined(GUI)
227     // todo: wxSingleInstanceChecker wasn't working on Linux, never deleted its lock file
228     //  maybe should go by whether successfully bind port 8333 instead
229     wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
230     for (int i = 0; i < strMutexName.size(); i++)
231         if (!isalnum(strMutexName[i]))
232             strMutexName[i] = '.';
233     wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
234     if (psingleinstancechecker->IsAnotherRunning())
235     {
236         printf("Existing instance found\n");
237         unsigned int nStart = GetTime();
238         loop
239         {
240             // TODO: find out how to do this in Linux, or replace with wxWidgets commands
241             // Show the previous instance and exit
242             HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
243             if (hwndPrev)
244             {
245                 if (IsIconic(hwndPrev))
246                     ShowWindow(hwndPrev, SW_RESTORE);
247                 SetForegroundWindow(hwndPrev);
248                 return false;
249             }
250
251             if (GetTime() > nStart + 60)
252                 return false;
253
254             // Resume this instance if the other exits
255             delete psingleinstancechecker;
256             Sleep(1000);
257             psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
258             if (!psingleinstancechecker->IsAnotherRunning())
259                 break;
260         }
261     }
262 #endif
263
264     // Bind to the port early so we can tell if another instance is already running.
265     // This is a backup to wxSingleInstanceChecker, which doesn't work on Linux.
266     string strErrors;
267     if (!BindListenPort(strErrors))
268     {
269         wxMessageBox(strErrors, "Bitcoin");
270         return false;
271     }
272
273     //
274     // Load data files
275     //
276     if (fDaemon)
277         fprintf(stdout, "bitcoin server starting\n");
278     strErrors = "";
279     int64 nStart;
280
281     printf("Loading addresses...\n");
282     nStart = GetTimeMillis();
283     if (!LoadAddresses())
284         strErrors += _("Error loading addr.dat      \n");
285     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
286
287     printf("Loading block index...\n");
288     nStart = GetTimeMillis();
289     if (!LoadBlockIndex())
290         strErrors += _("Error loading blkindex.dat      \n");
291     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
292
293     printf("Loading wallet...\n");
294     nStart = GetTimeMillis();
295     bool fFirstRun;
296     if (!LoadWallet(fFirstRun))
297         strErrors += _("Error loading wallet.dat      \n");
298     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
299
300     printf("Done loading\n");
301
302         //// debug print
303         printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
304         printf("nBestHeight = %d\n",            nBestHeight);
305         printf("mapKeys.size() = %d\n",         mapKeys.size());
306         printf("mapPubKeys.size() = %d\n",      mapPubKeys.size());
307         printf("mapWallet.size() = %d\n",       mapWallet.size());
308         printf("mapAddressBook.size() = %d\n",  mapAddressBook.size());
309
310     if (!strErrors.empty())
311     {
312         wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
313         return false;
314     }
315
316     // Add wallet transactions that aren't already in a block to mapTransactions
317     ReacceptWalletTransactions();
318
319     //
320     // Parameters
321     //
322     if (mapArgs.count("-printblockindex") || mapArgs.count("-printblocktree"))
323     {
324         PrintBlockTree();
325         return false;
326     }
327
328     if (mapArgs.count("-printblock"))
329     {
330         string strMatch = mapArgs["-printblock"];
331         int nFound = 0;
332         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
333         {
334             uint256 hash = (*mi).first;
335             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
336             {
337                 CBlockIndex* pindex = (*mi).second;
338                 CBlock block;
339                 block.ReadFromDisk(pindex);
340                 block.BuildMerkleTree();
341                 block.print();
342                 printf("\n");
343                 nFound++;
344             }
345         }
346         if (nFound == 0)
347             printf("No blocks matching %s were found\n", strMatch.c_str());
348         return false;
349     }
350
351     if (mapArgs.count("-gen"))
352     {
353         if (mapArgs["-gen"].empty())
354             fGenerateBitcoins = true;
355         else
356             fGenerateBitcoins = (atoi(mapArgs["-gen"].c_str()) != 0);
357     }
358
359     if (mapArgs.count("-proxy"))
360     {
361         fUseProxy = true;
362         addrProxy = CAddress(mapArgs["-proxy"]);
363         if (!addrProxy.IsValid())
364         {
365             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
366             return false;
367         }
368     }
369
370     if (mapArgs.count("-addnode"))
371     {
372         foreach(string strAddr, mapMultiArgs["-addnode"])
373         {
374             CAddress addr(strAddr, NODE_NETWORK);
375             addr.nTime = 0; // so it won't relay unless successfully connected
376             if (addr.IsValid())
377                 AddAddress(addr);
378         }
379     }
380
381     if (mapArgs.count("-paytxfee"))
382     {
383         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
384         {
385             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
386             return false;
387         }
388         if (nTransactionFee > 1 * COIN)
389             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
390     }
391
392     //
393     // Create the main window and start the node
394     //
395 #ifdef GUI
396     if (!fDaemon)
397         CreateMainWindow();
398 #endif
399
400     if (!CheckDiskSpace())
401         return false;
402
403     RandAddSeedPerfmon();
404
405     if (!CreateThread(StartNode, NULL))
406         wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
407
408     if (mapArgs.count("-server") || fDaemon)
409         CreateThread(ThreadRPCServer, NULL);
410
411 #if defined(__WXMSW__) && defined(GUI)
412     if (fFirstRun)
413         SetStartOnSystemStartup(true);
414 #endif
415
416     return true;
417 }