init.cpp 31 KB

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