Bitcoin v0.3.0 · 2010-07-06
init.cpp
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include "headers.h"678910void ExitTimeout(void* parg)11{12#ifdef __WXMSW__13 Sleep(5000);14 ExitProcess(0);15#endif16}1718void Shutdown(void* parg)19{20 static CCriticalSection cs_Shutdown;21 static bool fTaken;22 bool fFirstThread;23 CRITICAL_BLOCK(cs_Shutdown)24 {25 fFirstThread = !fTaken;26 fTaken = true;27 }28 static bool fExit;29 if (fFirstThread)30 {31 fShutdown = true;32 nTransactionsUpdated++;33 DBFlush(false);34 StopNode();35 DBFlush(true);36 CreateThread(ExitTimeout, NULL);37 Sleep(50);38 printf("Bitcoin exiting\n\n");39 fExit = true;40 exit(0);41 }42 else43 {44 while (!fExit)45 Sleep(500);46 Sleep(100);47 ExitThread(0);48 }49}50515253545556//////////////////////////////////////////////////////////////////////////////57//58// Startup folder59//6061#ifdef __WXMSW__62typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);6364string MyGetSpecialFolderPath(int nFolder, bool fCreate)65{66 char pszPath[MAX_PATH+100] = "";6768 // SHGetSpecialFolderPath is not usually available on NT 4.069 HMODULE hShell32 = LoadLibraryA("shell32.dll");70 if (hShell32)71 {72 PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =73 (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");74 if (pSHGetSpecialFolderPath)75 (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);76 FreeModule(hShell32);77 }7879 // Backup option80 if (pszPath[0] == '\0')81 {82 if (nFolder == CSIDL_STARTUP)83 {84 strcpy(pszPath, getenv("USERPROFILE"));85 strcat(pszPath, "\\Start Menu\\Programs\\Startup");86 }87 else if (nFolder == CSIDL_APPDATA)88 {89 strcpy(pszPath, getenv("APPDATA"));90 }91 }9293 return pszPath;94}9596string StartupShortcutPath()97{98 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";99}100101bool GetStartOnSystemStartup()102{103 return wxFileExists(StartupShortcutPath());104}105106void SetStartOnSystemStartup(bool fAutoStart)107{108 // If the shortcut exists already, remove it for updating109 remove(StartupShortcutPath().c_str());110111 if (fAutoStart)112 {113 CoInitialize(NULL);114115 // Get a pointer to the IShellLink interface.116 IShellLink* psl = NULL;117 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,118 CLSCTX_INPROC_SERVER, IID_IShellLink,119 reinterpret_cast<void**>(&psl));120121 if (SUCCEEDED(hres))122 {123 // Get the current executable path124 TCHAR pszExePath[MAX_PATH];125 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));126127 // Set the path to the shortcut target128 psl->SetPath(pszExePath);129 PathRemoveFileSpec(pszExePath);130 psl->SetWorkingDirectory(pszExePath);131 psl->SetShowCmd(SW_SHOWMINNOACTIVE);132133 // Query IShellLink for the IPersistFile interface for134 // saving the shortcut in persistent storage.135 IPersistFile* ppf = NULL;136 hres = psl->QueryInterface(IID_IPersistFile,137 reinterpret_cast<void**>(&ppf));138 if (SUCCEEDED(hres))139 {140 WCHAR pwsz[MAX_PATH];141 // Ensure that the string is ANSI.142 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);143 // Save the link by calling IPersistFile::Save.144 hres = ppf->Save(pwsz, TRUE);145 ppf->Release();146 }147 psl->Release();148 }149 CoUninitialize();150 }151}152#else153bool GetStartOnSystemStartup() { return false; }154void SetStartOnSystemStartup(bool fAutoStart) { }155#endif156157158159160161162163//////////////////////////////////////////////////////////////////////////////164//165// CMyApp166//167168// Define a new application169class CMyApp: public wxApp170{171public:172 wxLocale m_locale;173174 CMyApp(){};175 ~CMyApp(){};176 bool OnInit();177 bool OnInit2();178 int OnExit();179180 // Hook Initialize so we can start without GUI181 virtual bool Initialize(int& argc, wxChar** argv);182183 // 2nd-level exception handling: we get all the exceptions occurring in any184 // event handler here185 virtual bool OnExceptionInMainLoop();186187 // 3rd, and final, level exception handling: whenever an unhandled188 // exception is caught, this function is called189 virtual void OnUnhandledException();190191 // and now for something different: this function is called in case of a192 // crash (e.g. dereferencing null pointer, division by 0, ...)193 virtual void OnFatalException();194};195196IMPLEMENT_APP(CMyApp)197198bool CMyApp::Initialize(int& argc, wxChar** argv)199{200 if (argc > 1 && argv[1][0] != '-' && (!fWindows || argv[1][0] != '/') &&201 wxString(argv[1]) != "start")202 {203 fCommandLine = true;204 }205 else if (!fGUI)206 {207 fDaemon = true;208 }209 else210 {211 // wxApp::Initialize will remove environment-specific parameters,212 // so it's too early to call ParseParameters yet213 for (int i = 1; i < argc; i++)214 {215 wxString str = argv[i];216 #ifdef __WXMSW__217 if (str.size() >= 1 && str[0] == '/')218 str[0] = '-';219 str = str.MakeLower();220 #endif221 // haven't decided which argument to use for this yet222 if (str == "-daemon" || str == "-d" || str == "start")223 fDaemon = true;224 }225 }226227#ifdef __WXGTK__228 if (fDaemon || fCommandLine)229 {230 // Call the original Initialize while suppressing error messages231 // and ignoring failure. If unable to initialize GTK, it fails232 // near the end so hopefully the last few things don't matter.233 {234 wxLogNull logNo;235 wxApp::Initialize(argc, argv);236 }237238 if (fDaemon)239 {240 // Daemonize241 pid_t pid = fork();242 if (pid < 0)243 {244 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);245 return false;246 }247 if (pid > 0)248 pthread_exit((void*)0);249 }250251 return true;252 }253#endif254255 return wxApp::Initialize(argc, argv);256}257258bool CMyApp::OnInit()259{260 bool fRet = false;261 try262 {263 fRet = OnInit2();264 }265 catch (std::exception& e) {266 PrintException(&e, "OnInit()");267 } catch (...) {268 PrintException(NULL, "OnInit()");269 }270 if (!fRet)271 Shutdown(NULL);272 return fRet;273}274275extern int g_isPainting;276277bool CMyApp::OnInit2()278{279#ifdef _MSC_VER280 // Turn off microsoft heap dump noise281 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);282 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));283#endif284#if _MSC_VER >= 1400285 // Disable confusing "helpful" text message on abort, ctrl-c286 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);287#endif288#if defined(__WXMSW__) && defined(__WXDEBUG__) && wxUSE_GUI289 // Disable malfunctioning wxWidgets debug assertion290 g_isPainting = 10000;291#endif292#if wxUSE_GUI293 wxImage::AddHandler(new wxPNGHandler);294#endif295#if defined(__WXMSW__ ) || defined(__WXMAC__)296 SetAppName("Bitcoin");297#else298 SetAppName("bitcoin");299#endif300#ifndef __WXMSW__301 umask(077);302#endif303#ifdef __WXMSW__304#if wxUSE_UNICODE305 // Hack to set wxConvLibc codepage to UTF-8 on Windows,306 // may break if wxMBConv_win32 implementation in strconv.cpp changes.307 class wxMBConv_win32 : public wxMBConv308 {309 public:310 long m_CodePage;311 size_t m_minMBCharWidth;312 };313 if (((wxMBConv_win32*)&wxConvLibc)->m_CodePage == CP_ACP)314 ((wxMBConv_win32*)&wxConvLibc)->m_CodePage = CP_UTF8;315#endif316#endif317318 // Load locale/<lang>/LC_MESSAGES/bitcoin.mo language file319 m_locale.Init(wxLANGUAGE_DEFAULT, 0);320 m_locale.AddCatalogLookupPathPrefix("locale");321 if (!fWindows)322 {323 m_locale.AddCatalogLookupPathPrefix("/usr/share/locale");324 m_locale.AddCatalogLookupPathPrefix("/usr/local/share/locale");325 }326 m_locale.AddCatalog("wxstd"); // wxWidgets standard translations, if any327 m_locale.AddCatalog("bitcoin");328329 //330 // Parameters331 //332 if (fCommandLine)333 {334 int ret = CommandLineRPC(argc, argv);335 exit(ret);336 }337338 ParseParameters(argc, argv);339 if (mapArgs.count("-?") || mapArgs.count("--help"))340 {341 wxString strUsage = string() +342 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +343 " bitcoin [options] \t" + "\n" +344 " bitcoin [command] \t" + _("Send command to bitcoin running with -server or -daemon\n") +345 " bitcoin [command] -? \t" + _("Get help for a command\n") +346 " bitcoin help \t" + _("List commands\n") +347 _("Options:\n") +348 " -gen \t " + _("Generate coins\n") +349 " -gen=0 \t " + _("Don't generate coins\n") +350 " -min \t " + _("Start minimized\n") +351 " -datadir=<dir> \t " + _("Specify data directory\n") +352 " -proxy=<ip:port>\t " + _("Connect through socks4 proxy\n") +353 " -addnode=<ip> \t " + _("Add a node to connect to\n") +354 " -connect=<ip> \t " + _("Connect only to the specified node\n") +355 " -server \t " + _("Accept command line and JSON-RPC commands\n") +356 " -daemon \t " + _("Run in the background as a daemon and accept commands\n") +357 " -? \t " + _("This help message\n");358359360 if (fWindows && fGUI)361 {362 // Tabs make the columns line up in the message box363 wxMessageBox(strUsage, "Bitcoin", wxOK);364 }365 else366 {367 // Remove tabs368 strUsage.Replace("\t", "");369 fprintf(stderr, "%s", ((string)strUsage).c_str());370 }371 return false;372 }373374 if (mapArgs.count("-datadir"))375 strlcpy(pszSetDataDir, mapArgs["-datadir"].c_str(), sizeof(pszSetDataDir));376377 if (mapArgs.count("-debug"))378 fDebug = true;379380 if (mapArgs.count("-printtodebugger"))381 fPrintToDebugger = true;382383 if (!fDebug && !pszSetDataDir[0])384 ShrinkDebugFile();385 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");386 printf("Bitcoin version %d.%d.%d%s beta, OS version %s\n", VERSION/10000, (VERSION/100)%100, VERSION%100, pszSubVer, ((string)wxGetOsDescription()).c_str());387 printf("System default language is %d %s\n", m_locale.GetSystemLanguage(), ((string)m_locale.GetSysName()).c_str());388 printf("Language file %s (%s)\n", (string("locale/") + (string)m_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)m_locale.GetLocale()).c_str());389390 if (mapArgs.count("-loadblockindextest"))391 {392 CTxDB txdb("r");393 txdb.LoadBlockIndex();394 PrintBlockTree();395 return false;396 }397398 //399 // Limit to single instance per user400 // Required to protect the database files if we're going to keep deleting log.*401 //402#ifdef __WXMSW__403 // todo: wxSingleInstanceChecker wasn't working on Linux, never deleted its lock file404 // maybe should go by whether successfully bind port 8333 instead405 wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");406 for (int i = 0; i < strMutexName.size(); i++)407 if (!isalnum(strMutexName[i]))408 strMutexName[i] = '.';409 wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);410 if (psingleinstancechecker->IsAnotherRunning())411 {412 printf("Existing instance found\n");413 unsigned int nStart = GetTime();414 loop415 {416 // TODO: find out how to do this in Linux, or replace with wxWidgets commands417 // Show the previous instance and exit418 HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");419 if (hwndPrev)420 {421 if (IsIconic(hwndPrev))422 ShowWindow(hwndPrev, SW_RESTORE);423 SetForegroundWindow(hwndPrev);424 return false;425 }426427 if (GetTime() > nStart + 60)428 return false;429430 // Resume this instance if the other exits431 delete psingleinstancechecker;432 Sleep(1000);433 psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);434 if (!psingleinstancechecker->IsAnotherRunning())435 break;436 }437 }438#endif439440 // Bind to the port early so we can tell if another instance is already running.441 // This is a backup to wxSingleInstanceChecker, which doesn't work on Linux.442 string strErrors;443 if (!BindListenPort(strErrors))444 {445 wxMessageBox(strErrors, "Bitcoin");446 return false;447 }448449 //450 // Load data files451 //452 if (fDaemon)453 fprintf(stdout, "bitcoin server starting\n");454 strErrors = "";455 int64 nStart;456457 printf("Loading addresses...\n");458 nStart = GetTimeMillis();459 if (!LoadAddresses())460 strErrors += _("Error loading addr.dat \n");461 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);462463 printf("Loading block index...\n");464 nStart = GetTimeMillis();465 if (!LoadBlockIndex())466 strErrors += _("Error loading blkindex.dat \n");467 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);468469 printf("Loading wallet...\n");470 nStart = GetTimeMillis();471 bool fFirstRun;472 if (!LoadWallet(fFirstRun))473 strErrors += _("Error loading wallet.dat \n");474 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);475476 printf("Done loading\n");477478 //// debug print479 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());480 printf("nBestHeight = %d\n", nBestHeight);481 printf("mapKeys.size() = %d\n", mapKeys.size());482 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());483 printf("mapWallet.size() = %d\n", mapWallet.size());484 printf("mapAddressBook.size() = %d\n", mapAddressBook.size());485486 if (!strErrors.empty())487 {488 wxMessageBox(strErrors, "Bitcoin");489 return false;490 }491492 // Add wallet transactions that aren't already in a block to mapTransactions493 ReacceptWalletTransactions();494495 //496 // Parameters497 //498 if (mapArgs.count("-printblockindex") || mapArgs.count("-printblocktree"))499 {500 PrintBlockTree();501 return false;502 }503504 if (mapArgs.count("-printblock"))505 {506 string strMatch = mapArgs["-printblock"];507 int nFound = 0;508 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)509 {510 uint256 hash = (*mi).first;511 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)512 {513 CBlockIndex* pindex = (*mi).second;514 CBlock block;515 block.ReadFromDisk(pindex);516 block.BuildMerkleTree();517 block.print();518 printf("\n");519 nFound++;520 }521 }522 if (nFound == 0)523 printf("No blocks matching %s were found\n", strMatch.c_str());524 return false;525 }526527 if (mapArgs.count("-gen"))528 {529 if (mapArgs["-gen"].empty())530 fGenerateBitcoins = true;531 else532 fGenerateBitcoins = (atoi(mapArgs["-gen"].c_str()) != 0);533 }534535 if (mapArgs.count("-proxy"))536 {537 fUseProxy = true;538 addrProxy = CAddress(mapArgs["-proxy"]);539 if (!addrProxy.IsValid())540 {541 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");542 return false;543 }544 }545546 if (mapArgs.count("-addnode"))547 {548 foreach(string strAddr, mapMultiArgs["-addnode"])549 {550 CAddress addr(strAddr, NODE_NETWORK);551 addr.nTime = 0; // so it won't relay unless successfully connected552 if (addr.IsValid())553 AddAddress(addr);554 }555 }556557 //558 // Create the main window and start the node559 //560 if (!fDaemon)561 CreateMainWindow();562563 if (!CheckDiskSpace())564 return false;565566 RandAddSeedPerfmon();567568 if (!CreateThread(StartNode, NULL))569 wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");570571 if (mapArgs.count("-server") || fDaemon)572 CreateThread(ThreadRPCServer, NULL);573574 if (fFirstRun)575 SetStartOnSystemStartup(true);576577 return true;578}579580int CMyApp::OnExit()581{582 Shutdown(NULL);583 return wxApp::OnExit();584}585586bool CMyApp::OnExceptionInMainLoop()587{588 try589 {590 throw;591 }592 catch (std::exception& e)593 {594 PrintException(&e, "CMyApp::OnExceptionInMainLoop()");595 wxLogWarning("Exception %s %s", typeid(e).name(), e.what());596 Sleep(1000);597 throw;598 }599 catch (...)600 {601 PrintException(NULL, "CMyApp::OnExceptionInMainLoop()");602 wxLogWarning("Unknown exception");603 Sleep(1000);604 throw;605 }606 return true;607}608609void CMyApp::OnUnhandledException()610{611 // this shows how we may let some exception propagate uncaught612 try613 {614 throw;615 }616 catch (std::exception& e)617 {618 PrintException(&e, "CMyApp::OnUnhandledException()");619 wxLogWarning("Exception %s %s", typeid(e).name(), e.what());620 Sleep(1000);621 throw;622 }623 catch (...)624 {625 PrintException(NULL, "CMyApp::OnUnhandledException()");626 wxLogWarning("Unknown exception");627 Sleep(1000);628 throw;629 }630}631632void CMyApp::OnFatalException()633{634 wxMessageBox(_("Program has crashed and will terminate. "), "Bitcoin", wxOK | wxICON_ERROR);635}
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
