Bugfix: avoid sub-cent change (lost in fees) whenever possible
[bitcoin.git] / init.cpp
blob04bdd68cde47ee1a65251a6e4c75e81f631e6b95
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.
5 #include "headers.h"
13 //////////////////////////////////////////////////////////////////////////////
15 // Shutdown
18 void ExitTimeout(void* parg)
20 #ifdef __WXMSW__
21 Sleep(5000);
22 ExitProcess(0);
23 #endif
26 void Shutdown(void* parg)
28 static CCriticalSection cs_Shutdown;
29 static bool fTaken;
30 bool fFirstThread;
31 CRITICAL_BLOCK(cs_Shutdown)
33 fFirstThread = !fTaken;
34 fTaken = true;
36 static bool fExit;
37 if (fFirstThread)
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);
50 else
52 while (!fExit)
53 Sleep(500);
54 Sleep(100);
55 ExitThread(0);
59 void HandleSIGTERM(int)
61 fRequestShutdown = true;
69 //////////////////////////////////////////////////////////////////////////////
71 // Start
74 #ifndef GUI
75 int main(int argc, char* argv[])
77 for (int i = 1; i < argc; i++)
78 if (!IsSwitchChar(argv[i][0]))
79 fCommandLine = true;
80 fDaemon = !fCommandLine;
82 #ifdef __WXGTK__
83 if (!fCommandLine)
85 // Daemonize
86 pid_t pid = fork();
87 if (pid < 0)
89 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
90 return 1;
92 if (pid > 0)
93 pthread_exit((void*)0);
95 #endif
97 if (!AppInit(argc, argv))
98 return 1;
100 while (!fShutdown)
101 Sleep(1000000);
102 return 0;
104 #endif
106 bool AppInit(int argc, char* argv[])
108 bool fRet = false;
111 fRet = AppInit2(argc, argv);
113 catch (std::exception& e) {
114 PrintException(&e, "AppInit()");
115 } catch (...) {
116 PrintException(NULL, "AppInit()");
118 if (!fRet)
119 Shutdown(NULL);
120 return fRet;
123 bool AppInit2(int argc, char* argv[])
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
147 // Parameters
149 ParseParameters(argc, argv);
151 if (mapArgs.count("-datadir"))
153 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
154 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
157 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
159 if (mapArgs.count("-?") || mapArgs.count("--help"))
161 string beta = VERSION_IS_BETA ? _(" beta") : "";
162 string strUsage = string() +
163 _("Bitcoin version") + " " + FormatVersion(VERSION) + pszSubVer + beta + "\n\n" +
164 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
165 " bitcoin [options] \t " + "\n" +
166 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
167 " bitcoin [options] help \t\t " + _("List commands\n") +
168 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
169 _("Options:\n") +
170 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
171 " -gen \t\t " + _("Generate coins\n") +
172 " -gen=0 \t\t " + _("Don't generate coins\n") +
173 " -min \t\t " + _("Start minimized\n") +
174 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
175 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
176 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
177 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
178 " -nolisten \t " + _("Don't accept connections from outside") +
179 " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") +
180 " -server \t\t " + _("Accept command line and JSON-RPC commands\n") +
181 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
182 " -testnet \t\t " + _("Use the test network\n") +
183 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
184 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
185 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
186 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
187 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
188 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
189 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
191 #ifdef USE_SSL
192 strUsage += string() +
193 _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
194 " -rpcssl \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
195 " -rpcsslcertificatechainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") +
196 " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") +
197 " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
198 #endif
200 strUsage += string() +
201 " -? \t\t " + _("This help message\n");
203 #if defined(__WXMSW__) && defined(GUI)
204 // Tabs make the columns line up in the message box
205 wxMessageBox(strUsage, "Bitcoin", wxOK);
206 #else
207 // Remove tabs
208 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
209 fprintf(stderr, "%s", strUsage.c_str());
210 #endif
211 return false;
214 fDebug = GetBoolArg("-debug");
216 fPrintToConsole = GetBoolArg("-printtoconsole");
217 fPrintToDebugger = GetBoolArg("-printtodebugger");
219 fTestNet = GetBoolArg("-testnet");
221 fNoListen = GetBoolArg("-nolisten");
223 if (fCommandLine)
225 int ret = CommandLineRPC(argc, argv);
226 exit(ret);
229 if (!fDebug && !pszSetDataDir[0])
230 ShrinkDebugFile();
231 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
232 printf("Bitcoin version %s%s%s\n", FormatVersion(VERSION).c_str(), pszSubVer, VERSION_IS_BETA ? _(" beta") : "");
233 #ifdef GUI
234 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
235 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
236 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
237 #endif
238 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
240 if (GetBoolArg("-loadblockindextest"))
242 CTxDB txdb("r");
243 txdb.LoadBlockIndex();
244 PrintBlockTree();
245 return false;
249 // Limit to single instance per user
250 // Required to protect the database files if we're going to keep deleting log.*
252 #if defined(__WXMSW__) && defined(GUI)
253 // wxSingleInstanceChecker doesn't work on Linux
254 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
255 for (int i = 0; i < strMutexName.size(); i++)
256 if (!isalnum(strMutexName[i]))
257 strMutexName[i] = '.';
258 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
259 if (psingleinstancechecker->IsAnotherRunning())
261 printf("Existing instance found\n");
262 unsigned int nStart = GetTime();
263 loop
265 // Show the previous instance and exit
266 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
267 if (hwndPrev)
269 if (IsIconic(hwndPrev))
270 ShowWindow(hwndPrev, SW_RESTORE);
271 SetForegroundWindow(hwndPrev);
272 return false;
275 if (GetTime() > nStart + 60)
276 return false;
278 // Resume this instance if the other exits
279 delete psingleinstancechecker;
280 Sleep(1000);
281 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
282 if (!psingleinstancechecker->IsAnotherRunning())
283 break;
286 #endif
288 // Make sure only a single bitcoin process is using the data directory.
289 string strLockFile = GetDataDir() + "/.lock";
290 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
291 fclose(file);
292 static boost::interprocess::file_lock lock(strLockFile.c_str());
293 if (!lock.try_lock())
295 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
296 return false;
299 // Bind to the port early so we can tell if another instance is already running.
300 string strErrors;
301 if (!fNoListen)
303 if (!BindListenPort(strErrors))
305 wxMessageBox(strErrors, "Bitcoin");
306 return false;
311 // Load data files
313 if (fDaemon)
314 fprintf(stdout, "bitcoin server starting\n");
315 strErrors = "";
316 int64 nStart;
318 printf("Loading addresses...\n");
319 nStart = GetTimeMillis();
320 if (!LoadAddresses())
321 strErrors += _("Error loading addr.dat \n");
322 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
324 printf("Loading block index...\n");
325 nStart = GetTimeMillis();
326 if (!LoadBlockIndex())
327 strErrors += _("Error loading blkindex.dat \n");
328 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
330 printf("Loading wallet...\n");
331 nStart = GetTimeMillis();
332 bool fFirstRun;
333 if (!LoadWallet(fFirstRun))
334 strErrors += _("Error loading wallet.dat \n");
335 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
337 if (GetBoolArg("-rescan"))
339 nStart = GetTimeMillis();
340 ScanForWalletTransactions(pindexGenesisBlock);
341 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
344 printf("Done loading\n");
346 //// debug print
347 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
348 printf("nBestHeight = %d\n", nBestHeight);
349 printf("mapKeys.size() = %d\n", mapKeys.size());
350 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
351 printf("mapWallet.size() = %d\n", mapWallet.size());
352 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
354 if (!strErrors.empty())
356 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
357 return false;
360 // Add wallet transactions that aren't already in a block to mapTransactions
361 ReacceptWalletTransactions();
364 // Parameters
366 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
368 PrintBlockTree();
369 return false;
372 if (mapArgs.count("-printblock"))
374 string strMatch = mapArgs["-printblock"];
375 int nFound = 0;
376 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
378 uint256 hash = (*mi).first;
379 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
381 CBlockIndex* pindex = (*mi).second;
382 CBlock block;
383 block.ReadFromDisk(pindex);
384 block.BuildMerkleTree();
385 block.print();
386 printf("\n");
387 nFound++;
390 if (nFound == 0)
391 printf("No blocks matching %s were found\n", strMatch.c_str());
392 return false;
395 fGenerateBitcoins = GetBoolArg("-gen");
397 if (mapArgs.count("-proxy"))
399 fUseProxy = true;
400 addrProxy = CAddress(mapArgs["-proxy"]);
401 if (!addrProxy.IsValid())
403 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
404 return false;
408 if (mapArgs.count("-addnode"))
410 foreach(string strAddr, mapMultiArgs["-addnode"])
412 CAddress addr(strAddr, NODE_NETWORK);
413 addr.nTime = 0; // so it won't relay unless successfully connected
414 if (addr.IsValid())
415 AddAddress(addr);
419 if (mapArgs.count("-paytxfee"))
421 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
423 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
424 return false;
426 if (nTransactionFee > 0.25 * COIN)
427 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
431 // Create the main window and start the node
433 #ifdef GUI
434 if (!fDaemon)
435 CreateMainWindow();
436 #endif
438 if (!CheckDiskSpace())
439 return false;
441 RandAddSeedPerfmon();
443 if (!CreateThread(StartNode, NULL))
444 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
446 if (GetBoolArg("-server") || fDaemon)
447 CreateThread(ThreadRPCServer, NULL);
449 #if defined(__WXMSW__) && defined(GUI)
450 if (fFirstRun)
451 SetStartOnSystemStartup(true);
452 #endif
454 return true;