init.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  1. // ECOin - Copyright (c) - 2014/2021 - GPLv3 - epsylon@riseup.net (https://03c8.net)
  2. #include "txdb.h"
  3. #include "walletdb.h"
  4. #include "ecoinrpc.h"
  5. #include "net.h"
  6. #include "init.h"
  7. #include "util.h"
  8. #include "ui_interface.h"
  9. #include "checkpoints.h"
  10. #include "zerocoin/ZeroTest.h"
  11. #include <boost/filesystem.hpp>
  12. #include <boost/filesystem/fstream.hpp>
  13. #include <boost/filesystem/convenience.hpp>
  14. #include <boost/interprocess/sync/file_lock.hpp>
  15. #include <boost/algorithm/string/predicate.hpp>
  16. #include <openssl/crypto.h>
  17. #ifndef WIN32
  18. #include <signal.h>
  19. #endif
  20. using namespace std;
  21. using namespace boost;
  22. CWallet* pwalletMain;
  23. CClientUIInterface uiInterface;
  24. std::string strWalletFileName;
  25. bool fConfChange;
  26. bool fEnforceCanonical;
  27. unsigned int nNodeLifespan;
  28. unsigned int nDerivationMethodIndex;
  29. unsigned int nMinerSleep;
  30. bool fUseFastIndex;
  31. bool fUseFastStakeMiner;
  32. enum Checkpoints::CPMode CheckpointsMode;
  33. void ExitTimeout(void* parg)
  34. {
  35. #ifdef WIN32
  36. Sleep(5000);
  37. ExitProcess(0);
  38. #endif
  39. }
  40. void StartShutdown()
  41. {
  42. #ifdef QT_GUI
  43. uiInterface.QueueShutdown();
  44. #else
  45. NewThread(Shutdown, NULL);
  46. #endif
  47. }
  48. void Shutdown(void* parg)
  49. {
  50. static CCriticalSection cs_Shutdown;
  51. static bool fTaken;
  52. RenameThread("ecoin-shutoff");
  53. bool fFirstThread = false;
  54. {
  55. TRY_LOCK(cs_Shutdown, lockShutdown);
  56. if (lockShutdown)
  57. {
  58. fFirstThread = !fTaken;
  59. fTaken = true;
  60. }
  61. }
  62. static bool fExit;
  63. if (fFirstThread)
  64. {
  65. fShutdown = true;
  66. nTransactionsUpdated++;
  67. bitdb.Flush(false);
  68. StopNode();
  69. bitdb.Flush(true);
  70. boost::filesystem::remove(GetPidFile());
  71. UnregisterWallet(pwalletMain);
  72. delete pwalletMain;
  73. NewThread(ExitTimeout, NULL);
  74. Sleep(50);
  75. printf("Ecoin exited\n\n");
  76. fExit = true;
  77. #ifndef QT_GUI
  78. exit(0);
  79. #endif
  80. }
  81. else
  82. {
  83. while (!fExit)
  84. Sleep(500);
  85. Sleep(100);
  86. ExitThread(0);
  87. }
  88. }
  89. void HandleSIGTERM(int)
  90. {
  91. fRequestShutdown = true;
  92. }
  93. void HandleSIGHUP(int)
  94. {
  95. fReopenDebugLog = true;
  96. }
  97. #if !defined(QT_GUI)
  98. bool AppInit(int argc, char* argv[])
  99. {
  100. bool fRet = false;
  101. try
  102. {
  103. ParseParameters(argc, argv);
  104. if (!boost::filesystem::is_directory(GetDataDir(false)))
  105. {
  106. fprintf(stderr, "Error: Specified directory does not exist\n");
  107. Shutdown(NULL);
  108. }
  109. ReadConfigFile(mapArgs, mapMultiArgs);
  110. if (mapArgs.count("-?") || mapArgs.count("--help"))
  111. {
  112. std::string strUsage = _("Ecoin version") + " " + FormatFullVersion() + "\n\n" +
  113. _("Usage:") + "\n" +
  114. " ecoind [options] " + "\n" +
  115. " ecoind [options] <command> [params] " + _("Send command to -server or ecoind") + "\n" +
  116. " ecoind [options] help " + _("List commands") + "\n" +
  117. " ecoind [options] help <command> " + _("Get help for a command") + "\n";
  118. strUsage += "\n" + HelpMessage();
  119. fprintf(stdout, "%s", strUsage.c_str());
  120. return false;
  121. }
  122. for (int i = 1; i < argc; i++)
  123. if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "ecoin:"))
  124. fCommandLine = true;
  125. if (fCommandLine)
  126. {
  127. int ret = CommandLineRPC(argc, argv);
  128. exit(ret);
  129. }
  130. fRet = AppInit2();
  131. }
  132. catch (std::exception& e) {
  133. PrintException(&e, "AppInit()");
  134. } catch (...) {
  135. PrintException(NULL, "AppInit()");
  136. }
  137. if (!fRet)
  138. Shutdown(NULL);
  139. return fRet;
  140. }
  141. extern void noui_connect();
  142. int main(int argc, char* argv[])
  143. {
  144. bool fRet = false;
  145. noui_connect();
  146. fRet = AppInit(argc, argv);
  147. if (fRet && fDaemon)
  148. return 0;
  149. return 1;
  150. }
  151. #endif
  152. bool static InitError(const std::string &str)
  153. {
  154. uiInterface.ThreadSafeMessageBox(str, _("Ecoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
  155. return false;
  156. }
  157. bool static InitWarning(const std::string &str)
  158. {
  159. uiInterface.ThreadSafeMessageBox(str, _("Ecoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
  160. return true;
  161. }
  162. bool static Bind(const CService &addr, bool fError = true) {
  163. if (IsLimited(addr))
  164. return false;
  165. std::string strError;
  166. if (!BindListenPort(addr, strError)) {
  167. if (fError)
  168. return InitError(strError);
  169. return false;
  170. }
  171. return true;
  172. }
  173. std::string HelpMessage()
  174. {
  175. string strUsage = _("Options:") + "\n" +
  176. " -? " + _("This help message") + "\n" +
  177. " -conf=<file> " + _("Specify configuration file (default: ecoin.conf)") + "\n" +
  178. " -pid=<file> " + _("Specify pid file (default: ecoind.pid)") + "\n" +
  179. " -datadir=<dir> " + _("Specify data directory") + "\n" +
  180. " -wallet=<dir> " + _("Specify wallet file (within data directory)") + "\n" +
  181. " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
  182. " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
  183. " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
  184. " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
  185. " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
  186. " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
  187. " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
  188. " -port=<port> " + _("Listen for connections on <port> (default: 7408 or testnet: 17408)") + "\n" +
  189. " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
  190. " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
  191. " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
  192. " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
  193. " -externalip=<ip> " + _("Specify your own public address") + "\n" +
  194. " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
  195. " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
  196. " -irc " + _("Find peers using internet relay chat (default: 1)") + "\n" +
  197. " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
  198. " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
  199. " -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
  200. " -staking " + _("Stake your coins to support network and gain reward (default: 1)") + "\n" +
  201. " -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" +
  202. " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
  203. " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
  204. " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
  205. " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
  206. #ifdef USE_UPNP
  207. #if USE_UPNP
  208. " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
  209. #else
  210. " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
  211. #endif
  212. #endif
  213. " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
  214. " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
  215. " -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.01)") + "\n" +
  216. #ifdef QT_GUI
  217. " -server " + _("Accept command line and JSON-RPC commands") + "\n" +
  218. #endif
  219. #if !defined(WIN32) && !defined(QT_GUI)
  220. " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
  221. #endif
  222. " -testnet " + _("Use the test network") + "\n" +
  223. " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
  224. " -debugnet " + _("Output extra network debugging information") + "\n" +
  225. " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
  226. " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
  227. " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
  228. #ifdef WIN32
  229. " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
  230. #endif
  231. " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
  232. " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
  233. " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 7474 or testnet: 17474)") + "\n" +
  234. " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
  235. " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
  236. " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
  237. " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
  238. " -confchange " + _("Require a confirmations for change (default: 0)") + "\n" +
  239. " -enforcecanonical " + _("Enforce transaction scripts to use canonical PUSH operators (default: 1)") + "\n" +
  240. " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
  241. " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
  242. " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
  243. " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
  244. " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
  245. " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
  246. " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
  247. "\n" + _("Block creation options:") + "\n" +
  248. " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
  249. " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
  250. " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
  251. "\n" + _("SSL options: (see the Ecoin Wiki for SSL setup instructions)") + "\n" +
  252. " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
  253. " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
  254. " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
  255. " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
  256. return strUsage;
  257. }
  258. bool AppInit2()
  259. {
  260. #ifdef _MSC_VER
  261. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
  262. _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
  263. #endif
  264. #if _MSC_VER >= 1400
  265. // Disable confusing "helpful" text message on abort, Ctrl-C
  266. _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
  267. #endif
  268. #ifdef WIN32
  269. #ifndef PROCESS_DEP_ENABLE
  270. #define PROCESS_DEP_ENABLE 0x00000001
  271. #endif
  272. typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
  273. PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
  274. if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
  275. #endif
  276. #ifndef WIN32
  277. umask(077);
  278. struct sigaction sa;
  279. sa.sa_handler = HandleSIGTERM;
  280. sigemptyset(&sa.sa_mask);
  281. sa.sa_flags = 0;
  282. sigaction(SIGTERM, &sa, NULL);
  283. sigaction(SIGINT, &sa, NULL);
  284. struct sigaction sa_hup;
  285. sa_hup.sa_handler = HandleSIGHUP;
  286. sigemptyset(&sa_hup.sa_mask);
  287. sa_hup.sa_flags = 0;
  288. sigaction(SIGHUP, &sa_hup, NULL);
  289. #endif
  290. nNodeLifespan = GetArg("-addrlifespan", 7);
  291. fUseFastIndex = GetBoolArg("-fastindex", true);
  292. nMinerSleep = GetArg("-minersleep", 500);
  293. CheckpointsMode = Checkpoints::STRICT;
  294. std::string strCpMode = GetArg("-cppolicy", "strict");
  295. if(strCpMode == "strict")
  296. CheckpointsMode = Checkpoints::STRICT;
  297. if(strCpMode == "advisory")
  298. CheckpointsMode = Checkpoints::ADVISORY;
  299. if(strCpMode == "permissive")
  300. CheckpointsMode = Checkpoints::PERMISSIVE;
  301. nDerivationMethodIndex = 0;
  302. fTestNet = GetBoolArg("-testnet");
  303. if (fTestNet) {
  304. SoftSetBoolArg("-irc", true);
  305. }
  306. if (mapArgs.count("-bind")) {
  307. SoftSetBoolArg("-listen", true);
  308. }
  309. if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
  310. SoftSetBoolArg("-dnsseed", false);
  311. SoftSetBoolArg("-listen", false);
  312. }
  313. if (mapArgs.count("-proxy")) {
  314. SoftSetBoolArg("-listen", false);
  315. }
  316. if (!GetBoolArg("-listen", true)) {
  317. SoftSetBoolArg("-upnp", false);
  318. SoftSetBoolArg("-discover", false);
  319. }
  320. if (mapArgs.count("-externalip")) {
  321. SoftSetBoolArg("-discover", false);
  322. }
  323. if (GetBoolArg("-salvagewallet")) {
  324. SoftSetBoolArg("-rescan", true);
  325. }
  326. fDebug = GetBoolArg("-debug");
  327. if (fDebug)
  328. fDebugNet = true;
  329. else
  330. fDebugNet = GetBoolArg("-debugnet");
  331. bitdb.SetDetach(GetBoolArg("-detachdb", false));
  332. #if !defined(WIN32) && !defined(QT_GUI)
  333. fDaemon = GetBoolArg("-daemon");
  334. #else
  335. fDaemon = false;
  336. #endif
  337. if (fDaemon)
  338. fServer = true;
  339. else
  340. fServer = GetBoolArg("-server");
  341. #if !defined(QT_GUI)
  342. fServer = true;
  343. #endif
  344. fPrintToConsole = GetBoolArg("-printtoconsole");
  345. fPrintToDebugger = GetBoolArg("-printtodebugger");
  346. fLogTimestamps = GetBoolArg("-logtimestamps");
  347. if (mapArgs.count("-timeout"))
  348. {
  349. int nNewTimeout = GetArg("-timeout", 5000);
  350. if (nNewTimeout > 0 && nNewTimeout < 600000)
  351. nConnectTimeout = nNewTimeout;
  352. }
  353. const char* pszP2SH = "/P2SH/";
  354. COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
  355. if (mapArgs.count("-paytxfee"))
  356. {
  357. if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
  358. return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
  359. if (nTransactionFee > 0.25 * COIN)
  360. InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
  361. }
  362. fConfChange = GetBoolArg("-confchange", false);
  363. fEnforceCanonical = GetBoolArg("-enforcecanonical", true);
  364. if (mapArgs.count("-mininput"))
  365. {
  366. if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
  367. return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
  368. }
  369. std::string strDataDir = GetDataDir().string();
  370. std::string strWalletFileName = GetArg("-wallet", "wallet.dat");
  371. if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
  372. return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
  373. boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
  374. FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
  375. if (file) fclose(file);
  376. static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
  377. if (!lock.try_lock())
  378. return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Ecoin is probably already running."), strDataDir.c_str()));
  379. #if !defined(WIN32) && !defined(QT_GUI)
  380. if (fDaemon)
  381. {
  382. // Daemonize
  383. pid_t pid = fork();
  384. if (pid < 0)
  385. {
  386. fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
  387. return false;
  388. }
  389. if (pid > 0)
  390. {
  391. CreatePidFile(GetPidFile(), pid);
  392. return true;
  393. }
  394. pid_t sid = setsid();
  395. if (sid < 0)
  396. fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
  397. }
  398. #endif
  399. if (GetBoolArg("-shrinkdebugfile", !fDebug))
  400. ShrinkDebugFile();
  401. printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
  402. printf("Ecoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
  403. printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
  404. if (!fLogTimestamps)
  405. printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
  406. printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
  407. printf("Used data directory %s\n", strDataDir.c_str());
  408. std::ostringstream strErrors;
  409. if (fDaemon)
  410. fprintf(stdout, "Ecoin server starting\n");
  411. int64 nStart;
  412. uiInterface.InitMessage(_("Verifying database integrity..."));
  413. if (!bitdb.Open(GetDataDir()))
  414. {
  415. string msg = strprintf(_("Error initializing database environment %s!"
  416. " To recover, BACKUP THAT DIRECTORY, then remove"
  417. " everything from it except for wallet.dat."), strDataDir.c_str());
  418. return InitError(msg);
  419. }
  420. if (GetBoolArg("-salvagewallet"))
  421. {
  422. // Recover readable keypairs:
  423. if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
  424. return false;
  425. }
  426. if (filesystem::exists(GetDataDir() / strWalletFileName))
  427. {
  428. CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
  429. if (r == CDBEnv::RECOVER_OK)
  430. {
  431. string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
  432. " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
  433. " your balance or transactions are incorrect you should"
  434. " restore from a backup."), strDataDir.c_str());
  435. uiInterface.ThreadSafeMessageBox(msg, _("Ecoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
  436. }
  437. if (r == CDBEnv::RECOVER_FAIL)
  438. return InitError(_("wallet.dat corrupt, salvage failed"));
  439. }
  440. int nSocksVersion = GetArg("-socks", 5);
  441. if (nSocksVersion != 4 && nSocksVersion != 5)
  442. return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
  443. if (mapArgs.count("-onlynet")) {
  444. std::set<enum Network> nets;
  445. BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
  446. enum Network net = ParseNetwork(snet);
  447. if (net == NET_UNROUTABLE)
  448. return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
  449. nets.insert(net);
  450. }
  451. for (int n = 0; n < NET_MAX; n++) {
  452. enum Network net = (enum Network)n;
  453. if (!nets.count(net))
  454. SetLimited(net);
  455. }
  456. }
  457. #if defined(USE_IPV6)
  458. #if ! USE_IPV6
  459. else
  460. SetLimited(NET_IPV6);
  461. #endif
  462. #endif
  463. CService addrProxy;
  464. bool fProxy = false;
  465. if (mapArgs.count("-proxy")) {
  466. addrProxy = CService(mapArgs["-proxy"], 9050);
  467. if (!addrProxy.IsValid())
  468. return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
  469. if (!IsLimited(NET_IPV4))
  470. SetProxy(NET_IPV4, addrProxy, nSocksVersion);
  471. if (nSocksVersion > 4) {
  472. #ifdef USE_IPV6
  473. if (!IsLimited(NET_IPV6))
  474. SetProxy(NET_IPV6, addrProxy, nSocksVersion);
  475. #endif
  476. SetNameProxy(addrProxy, nSocksVersion);
  477. }
  478. fProxy = true;
  479. }
  480. if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
  481. CService addrOnion;
  482. if (!mapArgs.count("-tor"))
  483. addrOnion = addrProxy;
  484. else
  485. addrOnion = CService(mapArgs["-tor"], 9050);
  486. if (!addrOnion.IsValid())
  487. return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
  488. SetProxy(NET_TOR, addrOnion, 5);
  489. SetReachable(NET_TOR);
  490. }
  491. fNoListen = !GetBoolArg("-listen", true);
  492. fDiscover = GetBoolArg("-discover", true);
  493. fNameLookup = GetBoolArg("-dns", true);
  494. #ifdef USE_UPNP
  495. fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
  496. #endif
  497. bool fBound = false;
  498. if (!fNoListen)
  499. {
  500. std::string strError;
  501. if (mapArgs.count("-bind")) {
  502. BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
  503. CService addrBind;
  504. if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
  505. return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
  506. fBound |= Bind(addrBind);
  507. }
  508. } else {
  509. struct in_addr inaddr_any;
  510. inaddr_any.s_addr = INADDR_ANY;
  511. #ifdef USE_IPV6
  512. if (!IsLimited(NET_IPV6))
  513. fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
  514. #endif
  515. if (!IsLimited(NET_IPV4))
  516. fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
  517. }
  518. if (!fBound)
  519. return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
  520. }
  521. if (mapArgs.count("-externalip"))
  522. {
  523. BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
  524. CService addrLocal(strAddr, GetListenPort(), fNameLookup);
  525. if (!addrLocal.IsValid())
  526. return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
  527. AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
  528. }
  529. }
  530. if (mapArgs.count("-reservebalance")) // ecoin: reserve balance amount
  531. {
  532. int64 nReserveBalance = 0;
  533. if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
  534. {
  535. InitError(_("Invalid amount for -reservebalance=<amount>"));
  536. return false;
  537. }
  538. }
  539. if (mapArgs.count("-checkpointkey")) // ecoin: checkpoint master priv key
  540. {
  541. if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
  542. InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
  543. }
  544. BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
  545. AddOneShot(strDest);
  546. if (!bitdb.Open(GetDataDir()))
  547. {
  548. string msg = strprintf(_("Error initializing database environment %s!"
  549. " To recover, BACKUP THAT DIRECTORY, then remove"
  550. " everything from it except for wallet.dat."), strDataDir.c_str());
  551. return InitError(msg);
  552. }
  553. if (GetBoolArg("-loadblockindextest"))
  554. {
  555. CTxDB txdb("r");
  556. txdb.LoadBlockIndex();
  557. PrintBlockTree();
  558. return false;
  559. }
  560. uiInterface.InitMessage(_("Loading block index..."));
  561. printf("Loading block index...\n");
  562. nStart = GetTimeMillis();
  563. if (!LoadBlockIndex())
  564. return InitError(_("Error loading blkindex.dat"));
  565. if (fRequestShutdown)
  566. {
  567. printf("Shutdown requested. Exiting.\n");
  568. return false;
  569. }
  570. printf(" block index %15" PRI64d"ms\n", GetTimeMillis() - nStart);
  571. if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
  572. {
  573. PrintBlockTree();
  574. return false;
  575. }
  576. if (mapArgs.count("-printblock"))
  577. {
  578. string strMatch = mapArgs["-printblock"];
  579. int nFound = 0;
  580. for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
  581. {
  582. uint256 hash = (*mi).first;
  583. if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
  584. {
  585. CBlockIndex* pindex = (*mi).second;
  586. CBlock block;
  587. block.ReadFromDisk(pindex);
  588. block.BuildMerkleTree();
  589. block.print();
  590. printf("\n");
  591. nFound++;
  592. }
  593. }
  594. if (nFound == 0)
  595. printf("No blocks matching %s were found\n", strMatch.c_str());
  596. return false;
  597. }
  598. if (GetBoolArg("-zerotest", false))
  599. {
  600. printf("\n=== ZeroCoin tests start ===\n");
  601. Test_RunAllTests();
  602. printf("=== ZeroCoin tests end ===\n\n");
  603. }
  604. uiInterface.InitMessage(_("Loading wallet..."));
  605. printf("Loading wallet...\n");
  606. nStart = GetTimeMillis();
  607. bool fFirstRun = true;
  608. pwalletMain = new CWallet(strWalletFileName);
  609. DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
  610. if (nLoadWalletRet != DB_LOAD_OK)
  611. {
  612. if (nLoadWalletRet == DB_CORRUPT)
  613. strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
  614. else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
  615. {
  616. string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
  617. " or address book entries might be missing or incorrect."));
  618. uiInterface.ThreadSafeMessageBox(msg, _("Ecoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
  619. }
  620. else if (nLoadWalletRet == DB_TOO_NEW)
  621. strErrors << _("Error loading wallet.dat: Wallet requires newer version of Ecoin") << "\n";
  622. else if (nLoadWalletRet == DB_NEED_REWRITE)
  623. {
  624. strErrors << _("Wallet needed to be rewritten: restart Ecoin to complete") << "\n";
  625. printf("%s", strErrors.str().c_str());
  626. return InitError(strErrors.str());
  627. }
  628. else
  629. strErrors << _("Error loading wallet.dat") << "\n";
  630. }
  631. if (GetBoolArg("-upgradewallet", fFirstRun))
  632. {
  633. int nMaxVersion = GetArg("-upgradewallet", 0);
  634. if (nMaxVersion == 0) // the -upgradewallet without argument case
  635. {
  636. printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
  637. nMaxVersion = CLIENT_VERSION;
  638. pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
  639. }
  640. else
  641. printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
  642. if (nMaxVersion < pwalletMain->GetVersion())
  643. strErrors << _("Cannot downgrade wallet") << "\n";
  644. pwalletMain->SetMaxVersion(nMaxVersion);
  645. }
  646. if (fFirstRun)
  647. {
  648. RandAddSeedPerfmon();
  649. CPubKey newDefaultKey;
  650. if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
  651. strErrors << _("Cannot initialize keypool") << "\n";
  652. pwalletMain->SetDefaultKey(newDefaultKey);
  653. if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
  654. strErrors << _("Cannot write default address") << "\n";
  655. }
  656. printf("%s", strErrors.str().c_str());
  657. printf(" wallet %15" PRI64d"ms\n", GetTimeMillis() - nStart);
  658. RegisterWallet(pwalletMain);
  659. CBlockIndex *pindexRescan = pindexBest;
  660. if (GetBoolArg("-rescan"))
  661. pindexRescan = pindexGenesisBlock;
  662. else
  663. {
  664. CWalletDB walletdb(strWalletFileName);
  665. CBlockLocator locator;
  666. if (walletdb.ReadBestBlock(locator))
  667. pindexRescan = locator.GetBlockIndex();
  668. }
  669. if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
  670. {
  671. uiInterface.InitMessage(_("Rescanning..."));
  672. printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
  673. nStart = GetTimeMillis();
  674. pwalletMain->ScanForWalletTransactions(pindexRescan, true);
  675. printf(" rescan %15" PRI64d"ms\n", GetTimeMillis() - nStart);
  676. }
  677. if (mapArgs.count("-loadblock"))
  678. {
  679. uiInterface.InitMessage(_("Importing blockchain data file."));
  680. BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
  681. {
  682. FILE *file = fopen(strFile.c_str(), "rb");
  683. if (file)
  684. LoadExternalBlockFile(file);
  685. }
  686. exit(0);
  687. }
  688. filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
  689. if (filesystem::exists(pathBootstrap)) {
  690. uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
  691. FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
  692. if (file) {
  693. filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
  694. LoadExternalBlockFile(file);
  695. RenameOver(pathBootstrap, pathBootstrapOld);
  696. }
  697. }
  698. uiInterface.InitMessage(_("Loading addresses..."));
  699. printf("Loading addresses...\n");
  700. nStart = GetTimeMillis();
  701. {
  702. CAddrDB adb;
  703. if (!adb.Read(addrman))
  704. printf("Invalid or missing peers.dat; recreating\n");
  705. }
  706. printf("Loaded %i addresses from peers.dat %" PRI64d"ms\n",
  707. addrman.size(), GetTimeMillis() - nStart);
  708. if (!CheckDiskSpace())
  709. return false;
  710. RandAddSeedPerfmon();
  711. printf("mapBlockIndex.size() = %" PRIszu"\n", mapBlockIndex.size());
  712. printf("nBestHeight = %d\n", nBestHeight);
  713. printf("setKeyPool.size() = %" PRIszu"\n", pwalletMain->setKeyPool.size());
  714. printf("mapWallet.size() = %" PRIszu"\n", pwalletMain->mapWallet.size());
  715. printf("mapAddressBook.size() = %" PRIszu"\n", pwalletMain->mapAddressBook.size());
  716. if (!NewThread(StartNode, NULL))
  717. InitError(_("Error: could not start node"));
  718. if (fServer)
  719. NewThread(ThreadRPCServer, NULL);
  720. uiInterface.InitMessage(_("Done loading"));
  721. printf("Done loading\n");
  722. if (!strErrors.str().empty())
  723. return InitError(strErrors.str());
  724. pwalletMain->ReacceptWalletTransactions();
  725. #if !defined(QT_GUI)
  726. while (1)
  727. Sleep(5000);
  728. #endif
  729. return true;
  730. }