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 " -port=<port> \t\t " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)\n") +
genesis 164 " -maxconnections=<n>\t " + _("Maintain at most <n> connections to peers (default: 125)\n") +
asciilifeform_ver... 165 " -myip=<ip> \t " + _("Set this node's external IP address.\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 " -nolisten \t " + _("Don't accept connections from outside\n") +
genesis 169 " -banscore=<n> \t " + _("Threshold for disconnecting misbehaving peers (default: 100)\n") +
genesis 170 " -bantime=<n> \t " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)\n") +
genesis 171 " -maxreceivebuffer=<n>\t " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)\n") +
genesis 172 " -maxsendbuffer=<n>\t " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)\n") +
genesis 173 " -paytxfee=<amt> \t " + _("Fee per kB to add to transactions you send\n") +
genesis 174 " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") +
genesis 175 " -testnet \t\t " + _("Use the test network\n") +
genesis 176 " -debug \t\t " + _("Output extra debugging information\n") +
asciilifeform_and... 177 " -caneat \t\t " + _("Permit the use of 'eatblock'\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");
asciilifeform_and... 200 fCanEat = GetBoolArg("-caneat");
genesis 201
genesis 202 if (fDaemon)
genesis 203 fServer = true;
genesis 204 else
genesis 205 fServer = GetBoolArg("-server");
genesis 206
genesis 207 /* force fServer when running without GUI */
genesis 208 fServer = true;
genesis 209 fPrintToConsole = GetBoolArg("-printtoconsole");
genesis 210 fPrintToDebugger = GetBoolArg("-printtodebugger");
genesis 211 fLogTimestamps = GetBoolArg("-logtimestamps");
genesis 212
genesis 213 for (int i = 1; i < argc; i++)
genesis 214 if (!IsSwitchChar(argv[i][0]))
genesis 215 fCommandLine = true;
genesis 216
genesis 217 if (fCommandLine)
genesis 218 {
genesis 219 int ret = CommandLineRPC(argc, argv);
genesis 220 exit(ret);
genesis 221 }
genesis 222
genesis 223 if (fDaemon)
genesis 224 {
genesis 225 // Daemonize
genesis 226 pid_t pid = fork();
genesis 227 if (pid < 0)
genesis 228 {
genesis 229 fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
genesis 230 return false;
genesis 231 }
genesis 232 if (pid > 0)
genesis 233 {
genesis 234 CreatePidFile(GetPidFile(), pid);
genesis 235 return true;
genesis 236 }
genesis 237
genesis 238 pid_t sid = setsid();
genesis 239 if (sid < 0)
genesis 240 fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
genesis 241 }
genesis 242
genesis 243 if (!fDebug && !pszSetDataDir[0])
genesis 244 ShrinkDebugFile();
genesis 245 printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
genesis 246 printf("Bitcoin version %s\n", FormatFullVersion().c_str());
genesis 247 printf("Default data directory %s\n", GetDefaultDataDir().c_str());
genesis 248
genesis 249 if (GetBoolArg("-loadblockindextest"))
genesis 250 {
genesis 251 CTxDB txdb("r");
genesis 252 txdb.LoadBlockIndex();
genesis 253 PrintBlockTree();
genesis 254 return false;
genesis 255 }
genesis 256
genesis 257 // Make sure only a single bitcoin process is using the data directory.
genesis 258 string strLockFile = GetDataDir() + "/.lock";
genesis 259 FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
genesis 260 if (file) fclose(file);
genesis 261 static boost::interprocess::file_lock lock(strLockFile.c_str());
genesis 262 if (!lock.try_lock())
genesis 263 {
genesis 264 wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
genesis 265 return false;
genesis 266 }
genesis 267
genesis 268 string strErrors;
genesis 269
genesis 270 //
genesis 271 // Load data files
genesis 272 //
genesis 273 if (fDaemon)
genesis 274 fprintf(stdout, "bitcoin server starting\n");
genesis 275 strErrors = "";
genesis 276 int64 nStart;
genesis 277
genesis 278 InitMessage(_("Loading addresses..."));
genesis 279 printf("Loading addresses...\n");
genesis 280 nStart = GetTimeMillis();
genesis 281 if (!LoadAddresses())
genesis 282 strErrors += _("Error loading addr.dat \n");
genesis 283 printf(" addresses %15"PRI64d"ms\n", GetTimeMillis() - nStart);
genesis 284
genesis 285 InitMessage(_("Loading block index..."));
genesis 286 printf("Loading block index...\n");
genesis 287 nStart = GetTimeMillis();
genesis 288 if (!LoadBlockIndex())
genesis 289 strErrors += _("Error loading blkindex.dat \n");
genesis 290 printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
genesis 291
genesis 292 InitMessage(_("Loading wallet..."));
genesis 293 printf("Loading wallet...\n");
genesis 294 nStart = GetTimeMillis();
genesis 295 bool fFirstRun;
genesis 296 pwalletMain = new CWallet("wallet.dat");
genesis 297 int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
genesis 298 if (nLoadWalletRet != DB_LOAD_OK)
genesis 299 {
genesis 300 if (nLoadWalletRet == DB_CORRUPT)
genesis 301 strErrors += _("Error loading wallet.dat: Wallet corrupted \n");
genesis 302 else if (nLoadWalletRet == DB_TOO_NEW)
genesis 303 strErrors += _("Error loading wallet.dat: Wallet requires newer version of Bitcoin \n");
genesis 304 else if (nLoadWalletRet == DB_NEED_REWRITE)
genesis 305 {
genesis 306 strErrors += _("Wallet needed to be rewritten: restart Bitcoin to complete \n");
genesis 307 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
genesis 308 return false;
genesis 309 }
genesis 310 else
genesis 311 strErrors += _("Error loading wallet.dat \n");
genesis 312 }
genesis 313 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
genesis 314
genesis 315 RegisterWallet(pwalletMain);
genesis 316
genesis 317 CBlockIndex *pindexRescan = pindexBest;
genesis 318 if (GetBoolArg("-rescan"))
genesis 319 pindexRescan = pindexGenesisBlock;
genesis 320 else
genesis 321 {
genesis 322 CWalletDB walletdb("wallet.dat");
genesis 323 CBlockLocator locator;
genesis 324 if (walletdb.ReadBestBlock(locator))
genesis 325 pindexRescan = locator.GetBlockIndex();
genesis 326 }
genesis 327 if (pindexBest != pindexRescan)
genesis 328 {
genesis 329 InitMessage(_("Rescanning..."));
genesis 330 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
genesis 331 nStart = GetTimeMillis();
genesis 332 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
genesis 333 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
genesis 334 }
genesis 335
genesis 336 InitMessage(_("Done loading"));
genesis 337 printf("Done loading\n");
genesis 338
genesis 339 //// debug print
genesis 340 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
genesis 341 printf("nBestHeight = %d\n", nBestHeight);
genesis 342 printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
genesis 343 printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
genesis 344 printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
genesis 345
genesis 346 if (!strErrors.empty())
genesis 347 {
genesis 348 wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);
genesis 349 return false;
genesis 350 }
genesis 351
genesis 352 // Add wallet transactions that aren't already in a block to mapTransactions
genesis 353 pwalletMain->ReacceptWalletTransactions();
genesis 354
genesis 355 // Note: Bitcoin-QT stores several settings in the wallet, so we want
genesis 356 // to load the wallet BEFORE parsing command-line arguments, so
genesis 357 // the command-line/bitcoin.conf settings override GUI setting.
genesis 358
genesis 359 //
genesis 360 // Parameters
genesis 361 //
genesis 362 if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
genesis 363 {
genesis 364 PrintBlockTree();
genesis 365 return false;
genesis 366 }
genesis 367
genesis 368 if (mapArgs.count("-timeout"))
genesis 369 {
genesis 370 int nNewTimeout = GetArg("-timeout", 5000);
genesis 371 if (nNewTimeout > 0 && nNewTimeout < 600000)
genesis 372 nConnectTimeout = nNewTimeout;
genesis 373 }
genesis 374
genesis 375 if (mapArgs.count("-printblock"))
genesis 376 {
genesis 377 string strMatch = mapArgs["-printblock"];
genesis 378 int nFound = 0;
genesis 379 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
genesis 380 {
genesis 381 uint256 hash = (*mi).first;
genesis 382 if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
genesis 383 {
genesis 384 CBlockIndex* pindex = (*mi).second;
genesis 385 CBlock block;
genesis 386 block.ReadFromDisk(pindex);
genesis 387 block.BuildMerkleTree();
genesis 388 block.print();
genesis 389 printf("\n");
genesis 390 nFound++;
genesis 391 }
genesis 392 }
genesis 393 if (nFound == 0)
genesis 394 printf("No blocks matching %s were found\n", strMatch.c_str());
genesis 395 return false;
genesis 396 }
genesis 397
genesis 398 fGenerateBitcoins = GetBoolArg("-gen");
genesis 399
genesis 400 if (mapArgs.count("-proxy"))
genesis 401 {
genesis 402 fUseProxy = true;
genesis 403 addrProxy = CAddress(mapArgs["-proxy"]);
genesis 404 if (!addrProxy.IsValid())
genesis 405 {
genesis 406 wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
genesis 407 return false;
genesis 408 }
genesis 409 }
genesis 410
genesis 411 bool fTor = (fUseProxy && addrProxy.port == htons(9050));
genesis 412 if (fTor)
genesis 413 {
genesis 414 // Use SoftSetArg here so user can override any of these if they wish.
genesis 415 // Note: the GetBoolArg() calls for all of these must happen later.
genesis 416 SoftSetArg("-nolisten", true);
genesis 417 }
genesis 418
genesis 419 fNoListen = GetBoolArg("-nolisten");
genesis 420
genesis 421 // Command-line args override in-wallet settings:
genesis 422
genesis 423 if (!fNoListen)
genesis 424 {
genesis 425 if (!BindListenPort(strErrors))
genesis 426 {
genesis 427 wxMessageBox(strErrors, "Bitcoin");
genesis 428 return false;
genesis 429 }
genesis 430 }
genesis 431
genesis 432 if (mapArgs.count("-addnode"))
genesis 433 {
genesis 434 BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
genesis 435 {
asciilifeform_dns... 436 CAddress addr(strAddr);
genesis 437 addr.nTime = 0; // so it won't relay unless successfully connected
genesis 438 if (addr.IsValid())
genesis 439 AddAddress(addr);
genesis 440 }
genesis 441 }
genesis 442
genesis 443 if (mapArgs.count("-paytxfee"))
genesis 444 {
genesis 445 if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
genesis 446 {
genesis 447 wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
genesis 448 return false;
genesis 449 }
genesis 450 if (nTransactionFee > 0.25 * COIN)
genesis 451 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 452 }
genesis 453
genesis 454 //
genesis 455 // Start the node
genesis 456 //
genesis 457 if (!CheckDiskSpace())
genesis 458 return false;
genesis 459
genesis 460 RandAddSeedPerfmon();
genesis 461
genesis 462 if (!CreateThread(StartNode, NULL))
genesis 463 wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
genesis 464
genesis 465 if (fServer)
genesis 466 CreateThread(ThreadRPCServer, NULL);
genesis 467
genesis 468 while (1)
genesis 469 Sleep(5000);
genesis 470
genesis 471 return true;
genesis 472 }