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.
14 //////////////////////////////////////////////////////////////////////////////
19 void ExitTimeout(void* parg)
27 void Shutdown(void* parg)
29 static CCriticalSection cs_Shutdown;
32 CRITICAL_BLOCK(cs_Shutdown)
34 fFirstThread = !fTaken;
41 nTransactionsUpdated++;
45 CreateThread(ExitTimeout, NULL);
47 printf("Bitcoin exiting\n\n");
65 //////////////////////////////////////////////////////////////////////////////
71 int main(int argc, char* argv[])
73 for (int i = 1; i < argc; i++)
74 if (!IsSwitchChar(argv[i][0]))
76 fDaemon = !fCommandLine;
85 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
89 pthread_exit((void*)0);
93 if (!AppInit(argc, argv))
102 bool AppInit(int argc, char* argv[])
107 fRet = AppInit2(argc, argv);
109 catch (std::exception& e) {
110 PrintException(&e, "AppInit()");
112 PrintException(NULL, "AppInit()");
119 bool AppInit2(int argc, char* argv[])
122 // Turn off microsoft heap dump noise
123 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
124 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
127 // Disable confusing "helpful" text message on abort, ctrl-c
128 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
137 ParseParameters(argc, argv);
139 if (mapArgs.count("-datadir"))
141 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
142 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
145 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
147 if (mapArgs.count("-?") || mapArgs.count("--help"))
149 string strUsage = string() +
150 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
151 " bitcoin [options] \t " + "\n" +
152 " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
153 " bitcoin [options] help \t\t " + _("List commands\n") +
154 " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") +
156 " -conf=<file> \t " + _("Specify configuration file (default: bitcoin.conf)\n") +
157 " -gen \t " + _("Generate coins\n") +
158 " -gen=0 \t " + _("Don't generate coins\n") +
159 " -min \t " + _("Start minimized\n") +
160 " -datadir=<dir> \t " + _("Specify data directory\n") +
161 " -proxy=<ip:port>\t " + _("Connect through socks4 proxy\n") +
162 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
163 " -connect=<ip> \t " + _("Connect only to the specified node\n") +
164 " -server \t " + _("Accept command line and JSON-RPC commands\n") +
165 " -daemon \t " + _("Run in the background as a daemon and accept commands\n") +
166 " -? \t " + _("This help message\n");
168 #if defined(__WXMSW__) && defined(GUI)
169 // Tabs make the columns line up in the message box
170 wxMessageBox(strUsage, "Bitcoin", wxOK);
173 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
174 fprintf(stderr, "%s", strUsage.c_str());
179 if (mapArgs.count("-debug"))
182 if (mapArgs.count("-printtodebugger"))
183 fPrintToDebugger = true;
187 int ret = CommandLineRPC(argc, argv);
191 if (!fDebug && !pszSetDataDir[0])
193 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
194 printf("Bitcoin version %d.%d.%d%s beta\n", VERSION/10000, (VERSION/100)%100, VERSION%100, pszSubVer);
196 printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
197 printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
198 printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
200 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
202 if (mapArgs.count("-loadblockindextest"))
205 txdb.LoadBlockIndex();
211 // Limit to single instance per user
212 // Required to protect the database files if we're going to keep deleting log.*
214 #if defined(__WXMSW__) && defined(GUI)
215 // todo: wxSingleInstanceChecker wasn't working on Linux, never deleted its lock file
216 // maybe should go by whether successfully bind port 8333 instead
217 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
218 for (int i = 0; i < strMutexName.size(); i++)
219 if (!isalnum(strMutexName[i]))
220 strMutexName[i] = '.';
221 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
222 if (psingleinstancechecker->IsAnotherRunning())
224 printf("Existing instance found\n");
225 unsigned int nStart = GetTime();
228 // TODO: find out how to do this in Linux, or replace with wxWidgets commands
229 // Show the previous instance and exit
230 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
233 if (IsIconic(hwndPrev))
234 ShowWindow(hwndPrev, SW_RESTORE);
235 SetForegroundWindow(hwndPrev);
239 if (GetTime() > nStart + 60)
242 // Resume this instance if the other exits
243 delete psingleinstancechecker;
245 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
246 if (!psingleinstancechecker->IsAnotherRunning())
252 // Bind to the port early so we can tell if another instance is already running.
253 // This is a backup to wxSingleInstanceChecker, which doesn't work on Linux.
255 if (!BindListenPort(strErrors))
257 wxMessageBox(strErrors, "Bitcoin");
265 fprintf(stdout, "bitcoin server starting\n");
269 printf("Loading addresses...\n");
270 nStart = GetTimeMillis();
271 if (!LoadAddresses())
272 strErrors += _("Error loading addr.dat \n");
273 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
275 printf("Loading block index...\n");
276 nStart = GetTimeMillis();
277 if (!LoadBlockIndex())
278 strErrors += _("Error loading blkindex.dat \n");
279 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
281 printf("Loading wallet...\n");
282 nStart = GetTimeMillis();
284 if (!LoadWallet(fFirstRun))
285 strErrors += _("Error loading wallet.dat \n");
286 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
288 printf("Done loading\n");
291 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
292 printf("nBestHeight = %d\n", nBestHeight);
293 printf("mapKeys.size() = %d\n", mapKeys.size());
294 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
295 printf("mapWallet.size() = %d\n", mapWallet.size());
296 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
298 if (!strErrors.empty())
300 wxMessageBox(strErrors, "Bitcoin");
304 // Add wallet transactions that aren't already in a block to mapTransactions
305 ReacceptWalletTransactions();
310 if (mapArgs.count("-printblockindex") || mapArgs.count("-printblocktree"))
316 if (mapArgs.count("-printblock"))
318 string strMatch = mapArgs["-printblock"];
320 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
322 uint256 hash = (*mi).first;
323 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
325 CBlockIndex* pindex = (*mi).second;
327 block.ReadFromDisk(pindex);
328 block.BuildMerkleTree();
335 printf("No blocks matching %s were found\n", strMatch.c_str());
339 if (mapArgs.count("-gen"))
341 if (mapArgs["-gen"].empty())
342 fGenerateBitcoins = true;
344 fGenerateBitcoins = (atoi(mapArgs["-gen"].c_str()) != 0);
347 if (mapArgs.count("-proxy"))
350 addrProxy = CAddress(mapArgs["-proxy"]);
351 if (!addrProxy.IsValid())
353 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
358 if (mapArgs.count("-addnode"))
360 foreach(string strAddr, mapMultiArgs["-addnode"])
362 CAddress addr(strAddr, NODE_NETWORK);
363 addr.nTime = 0; // so it won't relay unless successfully connected
369 if (mapArgs.count("-paytxfee"))
371 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
373 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
379 // Create the main window and start the node
386 if (!CheckDiskSpace())
389 RandAddSeedPerfmon();
391 if (!CreateThread(StartNode, NULL))
392 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");
394 if (mapArgs.count("-server") || fDaemon)
395 CreateThread(ThreadRPCServer, NULL);
397 #if defined(__WXMSW__) && defined(GUI)
399 SetStartOnSystemStartup(true);