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