Research
Timechain
Search Donate
Sponsors
Cake Wallet, private Bitcoin and Monero walletSideShift.ai, no-signup crypto exchangeOrangeRock, non-custodial bitcoin spot and perps tradingBraiins Hashpower, buy and sell Bitcoin hashrateeCash.com
Bitcoin v0.3.19 · 2010-12-13

init.cpp

437 lines · plain text · GitHub · MIT license (license.txt)
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"678910111213//////////////////////////////////////////////////////////////////////////////14//15// Shutdown16//1718void ExitTimeout(void* parg)19{20#ifdef __WXMSW__21    Sleep(5000);22    ExitProcess(0);23#endif24}2526void 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    else51    {52        while (!fExit)53            Sleep(500);54        Sleep(100);55        ExitThread(0);56    }57}5859void HandleSIGTERM(int)60{61    fRequestShutdown = true;62}63646566676869//////////////////////////////////////////////////////////////////////////////70//71// Start72//7374#ifndef GUI75int 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;8182#ifdef __WXGTK__83    if (!fCommandLine)84    {85        // Daemonize86        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#endif9697    if (!AppInit(argc, argv))98        return 1;99100    while (!fShutdown)101        Sleep(1000000);102    return 0;103}104#endif105106bool AppInit(int argc, char* argv[])107{108    bool fRet = false;109    try110    {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}122123bool AppInit2(int argc, char* argv[])124{125#ifdef _MSC_VER126    // Turn off microsoft heap dump noise127    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);128    _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));129#endif130#if _MSC_VER >= 1400131    // Disable confusing "helpful" text message on abort, ctrl-c132    _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);133#endif134#ifndef __WXMSW__135    umask(077);136#endif137#ifndef __WXMSW__138    // Clean shutdown on SIGTERM139    struct sigaction sa;140    sa.sa_handler = HandleSIGTERM;141    sigemptyset(&sa.sa_mask);142    sa.sa_flags = 0;143    sigaction(SIGTERM, &sa, NULL);144#endif145146    //147    // Parameters148    //149    ParseParameters(argc, argv);150151    if (mapArgs.count("-datadir"))152    {153        filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);154        strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));155    }156157    ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir158159    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");185186#ifdef USE_SSL187        strUsage += string() +188            _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +189            "  -rpcssl=1                             \t  " + _("Use OpenSSL (https) for JSON-RPC connections\n") +190            "  -rpcsslcertificatchainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)\n") +191            "  -rpcsslprivatekeyfile=<file.pem>      \t  " + _("Server private key (default: server.pem)\n") +192            "  -rpcsslciphers=<ciphers>              \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");193#endif194195        strUsage += string() +196            "  -?               \t\t  " + _("This help message\n");197198#if defined(__WXMSW__) && defined(GUI)199        // Tabs make the columns line up in the message box200        wxMessageBox(strUsage, "Bitcoin", wxOK);201#else202        // Remove tabs203        strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());204        fprintf(stderr, "%s", strUsage.c_str());205#endif206        return false;207    }208209    fDebug = GetBoolArg("-debug");210211    fPrintToDebugger = GetBoolArg("-printtodebugger");212213    fTestNet = GetBoolArg("-testnet");214215    if (fCommandLine)216    {217        int ret = CommandLineRPC(argc, argv);218        exit(ret);219    }220221    if (!fDebug && !pszSetDataDir[0])222        ShrinkDebugFile();223    printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");224    printf("Bitcoin version %s%s beta\n", FormatVersion(VERSION).c_str(), pszSubVer);225#ifdef GUI226    printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());227    printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());228    printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());229#endif230    printf("Default data directory %s\n", GetDefaultDataDir().c_str());231232    if (GetBoolArg("-loadblockindextest"))233    {234        CTxDB txdb("r");235        txdb.LoadBlockIndex();236        PrintBlockTree();237        return false;238    }239240    //241    // Limit to single instance per user242    // Required to protect the database files if we're going to keep deleting log.*243    //244#if defined(__WXMSW__) && defined(GUI)245    // wxSingleInstanceChecker doesn't work on Linux246    wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");247    for (int i = 0; i < strMutexName.size(); i++)248        if (!isalnum(strMutexName[i]))249            strMutexName[i] = '.';250    wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);251    if (psingleinstancechecker->IsAnotherRunning())252    {253        printf("Existing instance found\n");254        unsigned int nStart = GetTime();255        loop256        {257            // Show the previous instance and exit258            HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");259            if (hwndPrev)260            {261                if (IsIconic(hwndPrev))262                    ShowWindow(hwndPrev, SW_RESTORE);263                SetForegroundWindow(hwndPrev);264                return false;265            }266267            if (GetTime() > nStart + 60)268                return false;269270            // Resume this instance if the other exits271            delete psingleinstancechecker;272            Sleep(1000);273            psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);274            if (!psingleinstancechecker->IsAnotherRunning())275                break;276        }277    }278#endif279280    // Make sure only a single bitcoin process is using the data directory.281    string strLockFile = GetDataDir() + "/.lock";282    FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.283    fclose(file);284    static boost::interprocess::file_lock lock(strLockFile.c_str());285    if (!lock.try_lock())286    {287        wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");288        return false;289    }290291    // Bind to the port early so we can tell if another instance is already running.292    string strErrors;293    if (!BindListenPort(strErrors))294    {295        wxMessageBox(strErrors, "Bitcoin");296        return false;297    }298299    //300    // Load data files301    //302    if (fDaemon)303        fprintf(stdout, "bitcoin server starting\n");304    strErrors = "";305    int64 nStart;306307    printf("Loading addresses...\n");308    nStart = GetTimeMillis();309    if (!LoadAddresses())310        strErrors += _("Error loading addr.dat      \n");311    printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);312313    printf("Loading block index...\n");314    nStart = GetTimeMillis();315    if (!LoadBlockIndex())316        strErrors += _("Error loading blkindex.dat      \n");317    printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);318319    printf("Loading wallet...\n");320    nStart = GetTimeMillis();321    bool fFirstRun;322    if (!LoadWallet(fFirstRun))323        strErrors += _("Error loading wallet.dat      \n");324    printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);325326    printf("Done loading\n");327328        //// debug print329        printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());330        printf("nBestHeight = %d\n",            nBestHeight);331        printf("mapKeys.size() = %d\n",         mapKeys.size());332        printf("mapPubKeys.size() = %d\n",      mapPubKeys.size());333        printf("mapWallet.size() = %d\n",       mapWallet.size());334        printf("mapAddressBook.size() = %d\n",  mapAddressBook.size());335336    if (!strErrors.empty())337    {338        wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);339        return false;340    }341342    // Add wallet transactions that aren't already in a block to mapTransactions343    ReacceptWalletTransactions();344345    //346    // Parameters347    //348    if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))349    {350        PrintBlockTree();351        return false;352    }353354    if (mapArgs.count("-printblock"))355    {356        string strMatch = mapArgs["-printblock"];357        int nFound = 0;358        for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)359        {360            uint256 hash = (*mi).first;361            if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)362            {363                CBlockIndex* pindex = (*mi).second;364                CBlock block;365                block.ReadFromDisk(pindex);366                block.BuildMerkleTree();367                block.print();368                printf("\n");369                nFound++;370            }371        }372        if (nFound == 0)373            printf("No blocks matching %s were found\n", strMatch.c_str());374        return false;375    }376377    fGenerateBitcoins = GetBoolArg("-gen");378379    if (mapArgs.count("-proxy"))380    {381        fUseProxy = true;382        addrProxy = CAddress(mapArgs["-proxy"]);383        if (!addrProxy.IsValid())384        {385            wxMessageBox(_("Invalid -proxy address"), "Bitcoin");386            return false;387        }388    }389390    if (mapArgs.count("-addnode"))391    {392        foreach(string strAddr, mapMultiArgs["-addnode"])393        {394            CAddress addr(strAddr, NODE_NETWORK);395            addr.nTime = 0; // so it won't relay unless successfully connected396            if (addr.IsValid())397                AddAddress(addr);398        }399    }400401    if (mapArgs.count("-paytxfee"))402    {403        if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))404        {405            wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");406            return false;407        }408        if (nTransactionFee > 0.25 * COIN)409            wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);410    }411412    //413    // Create the main window and start the node414    //415#ifdef GUI416    if (!fDaemon)417        CreateMainWindow();418#endif419420    if (!CheckDiskSpace())421        return false;422423    RandAddSeedPerfmon();424425    if (!CreateThread(StartNode, NULL))426        wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");427428    if (GetBoolArg("-server") || fDaemon)429        CreateThread(ThreadRPCServer, NULL);430431#if defined(__WXMSW__) && defined(GUI)432    if (fFirstRun)433        SetStartOnSystemStartup(true);434#endif435436    return true;437}

Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.

0:000:00