raw
genesis                 1 // Copyright (c) 2009-2010 Satoshi Nakamoto
genesis 2 // Copyright (c) 2009-2012 The Bitcoin developers
genesis 3 // Distributed under the MIT/X11 software license, see the accompanying
genesis 4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
genesis 5 #include "headers.h"
genesis 6 #include "db.h"
genesis 7 #include "bitcoinrpc.h"
genesis 8 #include "net.h"
genesis 9 #include "init.h"
genesis 10 #include "strlcpy.h"
genesis 11 #include <boost/filesystem.hpp>
genesis 12 #include <boost/filesystem/fstream.hpp>
genesis 13 #include <boost/interprocess/sync/file_lock.hpp>
genesis 14
genesis 15
genesis 16 using namespace std;
genesis 17 using namespace boost;
genesis 18
genesis 19 CWallet* pwalletMain;
genesis 20
genesis 21 //////////////////////////////////////////////////////////////////////////////
genesis 22 //
genesis 23 // Shutdown
genesis 24 //
genesis 25
genesis 26 void ExitTimeout(void* parg)
genesis 27 {
genesis 28 }
genesis 29
genesis 30 void Shutdown(void* parg)
genesis 31 {
genesis 32 static CCriticalSection cs_Shutdown;
genesis 33 static bool fTaken;
genesis 34 bool fFirstThread = false;
genesis 35 TRY_CRITICAL_BLOCK(cs_Shutdown)
genesis 36 {
genesis 37 fFirstThread = !fTaken;
genesis 38 fTaken = true;
genesis 39 }
genesis 40 static bool fExit;
genesis 41 if (fFirstThread)
genesis 42 {
genesis 43 fShutdown = true;
genesis 44 nTransactionsUpdated++;
genesis 45 DBFlush(false);
genesis 46 StopNode();
genesis 47 DBFlush(true);
genesis 48 boost::filesystem::remove(GetPidFile());
genesis 49 UnregisterWallet(pwalletMain);
genesis 50 delete pwalletMain;
genesis 51 CreateThread(ExitTimeout, NULL);
genesis 52 Sleep(50);
genesis 53 printf("Bitcoin exiting\n\n");
genesis 54 fExit = true;
genesis 55 exit(0);
genesis 56 }
genesis 57 else
genesis 58 {
genesis 59 while (!fExit)
genesis 60 Sleep(500);
genesis 61 Sleep(100);
genesis 62 ExitThread(0);
genesis 63 }
genesis 64 }
genesis 65
genesis 66 void HandleSIGTERM(int)
genesis 67 {
genesis 68 fRequestShutdown = true;
genesis 69 }
genesis 70
genesis 71
genesis 72
genesis 73
genesis 74
genesis 75
genesis 76 //////////////////////////////////////////////////////////////////////////////
genesis 77 //
genesis 78 // Start
genesis 79 //
bitcoin-asciilife... 80
genesis 81 int main(int argc, char* argv[])
genesis 82 {
genesis 83 bool fRet = false;
genesis 84 fRet = AppInit(argc, argv);
genesis 85
genesis 86 if (fRet && fDaemon)
genesis 87 return 0;
genesis 88
genesis 89 return 1;
genesis 90 }
bitcoin-asciilife... 91
genesis 92
genesis 93 bool AppInit(int argc, char* argv[])
genesis 94 {
genesis 95 bool fRet = false;
genesis 96 try
genesis 97 {
genesis 98 fRet = AppInit2(argc, argv);
genesis 99 }
genesis 100 catch (std::exception& e) {
genesis 101 PrintException(&e, "AppInit()");
genesis 102 } catch (...) {
genesis 103 PrintException(NULL, "AppInit()");
genesis 104 }
genesis 105 if (!fRet)
genesis 106 Shutdown(NULL);
genesis 107 return fRet;
genesis 108 }
genesis 109
genesis 110 bool AppInit2(int argc, char* argv[])
genesis 111 {
genesis 112 umask(077);
bitcoin-asciilife... 113
genesis 114 // Clean shutdown on SIGTERM
genesis 115 struct sigaction sa;
genesis 116 sa.sa_handler = HandleSIGTERM;
genesis 117 sigemptyset(&sa.sa_mask);
genesis 118 sa.sa_flags = 0;
genesis 119 sigaction(SIGTERM, &sa, NULL);
genesis 120 sigaction(SIGINT, &sa, NULL);
genesis 121 sigaction(SIGHUP, &sa, NULL);
genesis 122
genesis 123 //
genesis 124 // Parameters
genesis 125 //
genesis 126 ParseParameters(argc, argv);
genesis 127
genesis 128 if (mapArgs.count("-datadir"))
genesis 129 {
genesis 130 if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
genesis 131 {
genesis 132 filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
genesis 133 strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
genesis 134 }
genesis 135 else
genesis 136 {
genesis 137 fprintf(stderr, "Error: Specified directory does not exist\n");
genesis 138 Shutdown(NULL);
genesis 139 }
genesis 140 }
genesis 141
genesis 142
genesis 143 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
genesis 144
genesis 145 if (mapArgs.count("-?") || mapArgs.count("--help"))
genesis 146 {
genesis 147 string strUsage = string() +
genesis 148 _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
genesis 149 _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
genesis 150 " bitcoind [options] \t " + "\n" +
genesis 151 " bitcoind [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") +
genesis 152 " bitcoind [options] help \t\t " + _("List commands\n") +
genesis 153 " bitcoind [options] help <command> \t\t " + _("Get help for a command\n") +
genesis 154 _("Options:\n") +
genesis 155 " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") +
genesis 156 " -pid=<file> \t\t " + _("Specify pid file (default: bitcoind.pid)\n") +
genesis 157 " -gen \t\t " + _("Generate coins\n") +
genesis 158 " -gen=0 \t\t " + _("Don't generate coins\n") +
genesis 159 " -min \t\t " + _("Start minimized\n") +
genesis 160 " -datadir=<dir> \t\t " + _("Specify data directory\n") +
genesis 161 " -timeout=<n> \t " + _("Specify connection timeout (in milliseconds)\n") +
genesis 162 " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") +
genesis 163 " -dns \t " + _("Allow DNS lookups for addnode and connect\n") +
genesis 164 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)\n") +
genesis 165 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)\n") +
genesis 166 " -addnode=<ip> \t " + _("Add a node to connect to\n") +
genesis 167 " -connect=<ip> \t\t " + _("Connect only to the specified node\n") +
genesis 168 " -noirc \t " + _("Don't find peers using internet relay chat\n") +
genesis 169 " -nolisten \t " + _("Don't accept connections from outside\n") +
genesis 170 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
genesis 171 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\n") +
genesis 172 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)\n") +
genesis 173 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)\n") +
genesis 174 " -paytxfee=<amt> \t " + _("Fee per kB to add to transactions you send\n") +
genesis 175 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
genesis 176 " -testnet \t\t " + _("Use the test network\n") +
genesis 177 " -debug \t\t " + _("Output extra debugging information\n") +
genesis 178 " -logtimestamps \t " + _("Prepend debug output with timestamp\n") +
genesis 179 " -printtoconsole \t " + _("Send trace/debug info to console instead of debug.log file\n") +
genesis 180 " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") +
genesis 181 " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") +
genesis 182 " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
genesis 183 " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") +
genesis 184 " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
genesis 185 " -keypool=<n> \t " + _("Set key pool size to <n> (default: 100)\n") +
genesis 186 " -rescan \t " + _("Rescan the block chain for missing wallet transactions\n");
genesis 187
genesis 188 strUsage += string() +
genesis 189 " -? \t\t " + _("This help message\n");
genesis 190
genesis 191 // Remove tabs
genesis 192 strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
genesis 193 fprintf(stderr, "%s", strUsage.c_str());
genesis 194 return false;
genesis 195 }
genesis 196
genesis 197 fTestNet = GetBoolArg("-testnet");
genesis 198 fDebug = GetBoolArg("-debug");
genesis 199 fDaemon = GetBoolArg("-daemon");
genesis 200
genesis 201 if (fDaemon)
genesis 202 fServer = true;
genesis 203 else
genesis 204 fServer = GetBoolArg("-server");
genesis 205
genesis 206 /* force fServer when running without GUI */
genesis 207 fServer = true;
genesis 208 fPrintToConsole = GetBoolArg("-printtoconsole");
genesis 209 fPrintToDebugger = GetBoolArg("-printtodebugger");
genesis 210 fLogTimestamps = GetBoolArg("-logtimestamps");
genesis 211
genesis 212 for (int i = 1; i < argc; i++)
genesis 213 if (!IsSwitchChar(argv[i][0]))
genesis 214 fCommandLine = true;
genesis 215
genesis 216 if (fCommandLine)
genesis 217 {
genesis 218 int ret = CommandLineRPC(argc, argv);
genesis 219 exit(ret);
genesis 220 }
genesis 221
genesis 222 if (fDaemon)
genesis 223 {
genesis 224 // Daemonize
genesis 225 pid_t pid = fork();
genesis 226 if (pid < 0)
genesis 227 {
genesis 228 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
genesis 229 return false;
genesis 230 }
genesis 231 if (pid > 0)
genesis 232 {
genesis 233 CreatePidFile(GetPidFile(), pid);
genesis 234 return true;
genesis 235 }
genesis 236
genesis 237 pid_t sid = setsid();
genesis 238 if (sid < 0)
genesis 239 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
genesis 240 }
genesis 241
genesis 242 if (!fDebug && !pszSetDataDir[0])
genesis 243 ShrinkDebugFile();
genesis 244 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
genesis 245 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
genesis 246 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
genesis 247
genesis 248 if (GetBoolArg("-loadblockindextest"))
genesis 249 {
genesis 250 CTxDB txdb("r");
genesis 251 txdb.LoadBlockIndex();
genesis 252 PrintBlockTree();
genesis 253 return false;
genesis 254 }
genesis 255
genesis 256 // Make sure only a single bitcoin process is using the data directory.
genesis 257 string strLockFile = GetDataDir() + "/.lock";
genesis 258 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
genesis 259 if (file) fclose(file);
genesis 260 static boost::interprocess::file_lock lock(strLockFile.c_str());
genesis 261 if (!lock.try_lock())
genesis 262 {
genesis 263 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
genesis 264 return false;
genesis 265 }
genesis 266
genesis 267 string strErrors;
genesis 268
genesis 269 //
genesis 270 // Load data files
genesis 271 //
genesis 272 if (fDaemon)
genesis 273 fprintf(stdout, "bitcoin server starting\n");
genesis 274 strErrors = "";
genesis 275 int64 nStart;
genesis 276
genesis 277 InitMessage(_("Loading addresses..."));
genesis 278 printf("Loading addresses...\n");
genesis 279 nStart = GetTimeMillis();
genesis 280 if (!LoadAddresses())
genesis 281 strErrors += _("Error loading addr.dat \n");
genesis 282 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
genesis 283
genesis 284 InitMessage(_("Loading block index..."));
genesis 285 printf("Loading block index...\n");
genesis 286 nStart = GetTimeMillis();
genesis 287 if (!LoadBlockIndex())
genesis 288 strErrors += _("Error loading blkindex.dat \n");
genesis 289 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
genesis 290
genesis 291 InitMessage(_("Loading wallet..."));
genesis 292 printf("Loading wallet...\n");
genesis 293 nStart = GetTimeMillis();
genesis 294 bool fFirstRun;
genesis 295 pwalletMain = new CWallet("wallet.dat");
genesis 296 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
genesis 297 if (nLoadWalletRet != DB_LOAD_OK)
genesis 298 {
genesis 299 if (nLoadWalletRet == DB_CORRUPT)
genesis 300 strErrors += _("Error loading wallet.dat: Wallet corrupted \n");
genesis 301 else if (nLoadWalletRet == DB_TOO_NEW)
genesis 302 strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin \n");
genesis 303 else if (nLoadWalletRet == DB_NEED_REWRITE)
genesis 304 {
genesis 305 strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete \n");
genesis 306 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
genesis 307 return false;
genesis 308 }
genesis 309 else
genesis 310 strErrors += _("Error loading wallet.dat \n");
genesis 311 }
genesis 312 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
genesis 313
genesis 314 RegisterWallet(pwalletMain);
genesis 315
genesis 316 CBlockIndex *pindexRescan = pindexBest;
genesis 317 if (GetBoolArg("-rescan"))
genesis 318 pindexRescan = pindexGenesisBlock;
genesis 319 else
genesis 320 {
genesis 321 CWalletDB walletdb("wallet.dat");
genesis 322 CBlockLocator locator;
genesis 323 if (walletdb.ReadBestBlock(locator))
genesis 324 pindexRescan = locator.GetBlockIndex();
genesis 325 }
genesis 326 if (pindexBest != pindexRescan)
genesis 327 {
genesis 328 InitMessage(_("Rescanning..."));
genesis 329 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
genesis 330 nStart = GetTimeMillis();
genesis 331 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
genesis 332 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
genesis 333 }
genesis 334
genesis 335 InitMessage(_("Done loading"));
genesis 336 printf("Done loading\n");
genesis 337
genesis 338 //// debug print
genesis 339 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
genesis 340 printf("nBestHeight = %d\n", nBestHeight);
genesis 341 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
genesis 342 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
genesis 343 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
genesis 344
genesis 345 if (!strErrors.empty())
genesis 346 {
genesis 347 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
genesis 348 return false;
genesis 349 }
genesis 350
genesis 351 // Add wallet transactions that aren't already in a block to mapTransactions
genesis 352 pwalletMain->ReacceptWalletTransactions();
genesis 353
genesis 354 // Note: Bitcoin-QT stores several settings in the wallet, so we want
genesis 355 // to load the wallet BEFORE parsing command-line arguments, so
genesis 356 // the command-line/bitcoin.conf settings override GUI setting.
genesis 357
genesis 358 //
genesis 359 // Parameters
genesis 360 //
genesis 361 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
genesis 362 {
genesis 363 PrintBlockTree();
genesis 364 return false;
genesis 365 }
genesis 366
genesis 367 if (mapArgs.count("-timeout"))
genesis 368 {
genesis 369 int nNewTimeout = GetArg("-timeout", 5000);
genesis 370 if (nNewTimeout > 0 && nNewTimeout < 600000)
genesis 371 nConnectTimeout = nNewTimeout;
genesis 372 }
genesis 373
genesis 374 if (mapArgs.count("-printblock"))
genesis 375 {
genesis 376 string strMatch = mapArgs["-printblock"];
genesis 377 int nFound = 0;
genesis 378 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
genesis 379 {
genesis 380 uint256 hash = (*mi).first;
genesis 381 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
genesis 382 {
genesis 383 CBlockIndex* pindex = (*mi).second;
genesis 384 CBlock block;
genesis 385 block.ReadFromDisk(pindex);
genesis 386 block.BuildMerkleTree();
genesis 387 block.print();
genesis 388 printf("\n");
genesis 389 nFound++;
genesis 390 }
genesis 391 }
genesis 392 if (nFound == 0)
genesis 393 printf("No blocks matching %s were found\n", strMatch.c_str());
genesis 394 return false;
genesis 395 }
genesis 396
genesis 397 fGenerateBitcoins = GetBoolArg("-gen");
genesis 398
genesis 399 if (mapArgs.count("-proxy"))
genesis 400 {
genesis 401 fUseProxy = true;
genesis 402 addrProxy = CAddress(mapArgs["-proxy"]);
genesis 403 if (!addrProxy.IsValid())
genesis 404 {
genesis 405 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
genesis 406 return false;
genesis 407 }
genesis 408 }
genesis 409
genesis 410 bool fTor = (fUseProxy && addrProxy.port == htons(9050));
genesis 411 if (fTor)
genesis 412 {
genesis 413 // Use SoftSetArg here so user can override any of these if they wish.
genesis 414 // Note: the GetBoolArg() calls for all of these must happen later.
genesis 415 SoftSetArg("-nolisten", true);
genesis 416 SoftSetArg("-noirc", true);
genesis 417 SoftSetArg("-dns", false);
genesis 418 }
genesis 419
genesis 420 fAllowDNS = GetBoolArg("-dns");
genesis 421 fNoListen = GetBoolArg("-nolisten");
genesis 422
genesis 423 // Command-line args override in-wallet settings:
genesis 424
genesis 425 if (!fNoListen)
genesis 426 {
genesis 427 if (!BindListenPort(strErrors))
genesis 428 {
genesis 429 wxMessageBox(strErrors, "Bitcoin");
genesis 430 return false;
genesis 431 }
genesis 432 }
genesis 433
genesis 434 if (mapArgs.count("-addnode"))
genesis 435 {
genesis 436 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
genesis 437 {
genesis 438 CAddress addr(strAddr, fAllowDNS);
genesis 439 addr.nTime = 0; // so it won't relay unless successfully connected
genesis 440 if (addr.IsValid())
genesis 441 AddAddress(addr);
genesis 442 }
genesis 443 }
genesis 444
genesis 445 if (mapArgs.count("-paytxfee"))
genesis 446 {
genesis 447 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
genesis 448 {
genesis 449 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
genesis 450 return false;
genesis 451 }
genesis 452 if (nTransactionFee > 0.25 * COIN)
genesis 453 wxMessageBox(_("Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
genesis 454 }
genesis 455
genesis 456 //
genesis 457 // Start the node
genesis 458 //
genesis 459 if (!CheckDiskSpace())
genesis 460 return false;
genesis 461
genesis 462 RandAddSeedPerfmon();
genesis 463
genesis 464 if (!CreateThread(StartNode, NULL))
genesis 465 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
genesis 466
genesis 467 if (fServer)
genesis 468 CreateThread(ThreadRPCServer, NULL);
genesis 469
genesis 470 while (1)
genesis 471 Sleep(5000);
genesis 472
genesis 473 return true;
genesis 474 }