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