Fabcoin Core  0.16.2
P2P Digital Currency
main.cpp
Go to the documentation of this file.
1 /*
2  This file is part of cpp-ethereum.
3 
4  cpp-ethereum is free software: you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation, either version 3 of the License, or
7  (at your option) any later version.
8 
9  cpp-ethereum is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  GNU General Public License for more details.
13 
14  You should have received a copy of the GNU General Public License
15  along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
16 */
25 #include <thread>
26 #include <fstream>
27 #include <iostream>
28 #include <signal.h>
29 
30 #include <boost/algorithm/string.hpp>
31 #include <boost/algorithm/string/trim_all.hpp>
32 #include <boost/filesystem.hpp>
33 
34 #include <libdevcore/FileSystem.h>
36 #include <libevm/VM.h>
37 #include <libevm/VMFactory.h>
38 #include <libethcore/KeyManager.h>
39 #include <libethcore/ICAP.h>
40 #include <libethereum/Defaults.h>
44 #include <libwebthree/WebThree.h>
45 
47 #include <libweb3jsonrpc/Eth.h>
49 #include <jsonrpccpp/client/connectors/httpclient.h>
52 #include <libweb3jsonrpc/LevelDB.h>
53 #include <libweb3jsonrpc/Whisper.h>
54 #include <libweb3jsonrpc/Net.h>
55 #include <libweb3jsonrpc/Web3.h>
60 #include <libweb3jsonrpc/Debug.h>
61 #include <libweb3jsonrpc/Test.h>
62 
63 #include <ethminer/MinerAux.h>
64 #include "BuildInfo.h"
65 #include "AccountManager.h"
66 
67 using namespace std;
68 using namespace dev;
69 using namespace dev::p2p;
70 using namespace dev::eth;
71 using namespace boost::algorithm;
72 
73 static std::atomic<bool> g_silence = {false};
74 
75 void help()
76 {
77  cout
78  << "Usage eth [OPTIONS]" << endl
79  << "Options:" << endl << endl
80  << "Wallet usage:" << endl;
83  cout
84  << endl;
85  cout
86  << "Client mode (default):" << endl
87  << " --mainnet Use the main network protocol." << endl
88  << " --ropsten Use the Ropsten testnet." << endl
89  << " --private <name> Use a private chain." << endl
90  << " --test Testing mode: Disable PoW and provide test rpc interface." << endl
91  << " --config <file> Configure specialised blockchain using given JSON information." << endl
92  << " --oppose-dao-fork Ignore DAO hard fork (default is to participate)." << endl
93  << endl
94  << " -o,--mode <full/peer> Start a full node or a peer node (default: full)." << endl
95  << endl
96  << " -j,--json-rpc Enable JSON-RPC server (default: off)." << endl
97  << " --ipc Enable IPC server (default: on)." << endl
98  << " --ipcpath Set .ipc socket path (default: data directory)" << endl
99  << " --admin-via-http Expose admin interface via http - UNSAFE! (default: off)." << endl
100  << " --no-ipc Disable IPC server." << endl
101  << " --json-rpc-port <n> Specify JSON-RPC server port (implies '-j', default: " << SensibleHttpPort << ")." << endl
102  << " --rpccorsdomain <domain> Domain on which to send Access-Control-Allow-Origin header." << endl
103  << " --admin <password> Specify admin session key for JSON-RPC (default: auto-generated and printed at start-up)." << endl
104  << " -K,--kill Kill the blockchain first." << endl
105  << " -R,--rebuild Rebuild the blockchain from the existing database." << endl
106  << " --rescue Attempt to rescue a corrupt database." << endl
107  << endl
108  << " --import-presale <file> Import a pre-sale key; you'll need to specify the password to this key." << endl
109  << " -s,--import-secret <secret> Import a secret key into the key store." << endl
110  << " --master <password> Give the master password for the key store. Use --master \"\" to show a prompt." << endl
111  << " --password <password> Give a password for a private key." << endl
112  << endl
113  << "Client transacting:" << endl
114  /*<< " -B,--block-fees <n> Set the block fee profit in the reference unit, e.g. ¢ (default: 15)." << endl
115  << " -e,--ether-price <n> Set the ether price in the reference unit, e.g. ¢ (default: 30.679)." << endl
116  << " -P,--priority <0 - 100> Set the default priority percentage (%) of a transaction (default: 50)." << endl*/
117  << " --ask <wei> Set the minimum ask gas price under which no transaction will be mined (default " << toString(DefaultGasPrice) << " )." << endl
118  << " --bid <wei> Set the bid gas price to pay for transactions (default " << toString(DefaultGasPrice) << " )." << endl
119  << " --unsafe-transactions Allow all transactions to proceed without verification. EXTREMELY UNSAFE."
120  << endl
121  << "Client mining:" << endl
122  << " -a,--address <addr> Set the author (mining payout) address to given address (default: auto)." << endl
123  << " -m,--mining <on/off/number> Enable mining, optionally for a specified number of blocks (default: off)." << endl
124  << " -f,--force-mining Mine even when there are no transactions to mine (default: off)." << endl
125  << " -C,--cpu When mining, use the CPU." << endl
126  << " -t, --mining-threads <n> Limit number of CPU/GPU miners to n (default: use everything available on selected platform)." << endl
127  << endl
128  << "Client networking:" << endl
129  << " --client-name <name> Add a name to your client's version string (default: blank)." << endl
130  << " --bootstrap Connect to the default Ethereum peer servers (default unless --no-discovery used)." << endl
131  << " --no-bootstrap Do not connect to the default Ethereum peer servers (default only when --no-discovery is used)." << endl
132  << " -x,--peers <number> Attempt to connect to a given number of peers (default: 11)." << endl
133  << " --peer-stretch <number> Give the accepted connection multiplier (default: 7)." << endl
134 
135  << " --public-ip <ip> Force advertised public IP to the given IP (default: auto)." << endl
136  << " --listen-ip <ip>(:<port>) Listen on the given IP for incoming connections (default: 0.0.0.0)." << endl
137  << " --listen <port> Listen on the given port for incoming connections (default: 30303)." << endl
138  << " -r,--remote <host>(:<port>) Connect to the given remote host (default: none)." << endl
139  << " --port <port> Connect to the given remote port (default: 30303)." << endl
140  << " --network-id <n> Only connect to other hosts with this network id." << endl
141  << " --upnp <on/off> Use UPnP for NAT (default: on)." << endl
142 
143  << " --peerset <list> Space delimited list of peers; element format: type:publickey@ipAddress[:port]." << endl
144  << " Types:" << endl
145  << " default Attempt connection when no other peers are available and pinning is disabled." << endl
146  << " required Keep connected at all times." << endl
147 // TODO:
148 // << " --trust-peers <filename> Space delimited list of publickeys." << endl
149 
150  << " --no-discovery Disable node discovery, implies --no-bootstrap." << endl
151  << " --pin Only accept or connect to trusted peers." << endl
152  << " --hermit Equivalent to --no-discovery --pin." << endl
153  << " --sociable Force discovery and no pinning." << endl
154  << endl;
155  MinerCLI::streamHelp(cout);
156  cout
157  << "Import/export modes:" << endl
158  << " --from <n> Export only from block n; n may be a decimal, a '0x' prefixed hash, or 'latest'." << endl
159  << " --to <n> Export only to block n (inclusive); n may be a decimal, a '0x' prefixed hash, or 'latest'." << endl
160  << " --only <n> Equivalent to --export-from n --export-to n." << endl
161  << " --dont-check Prevent checking some block aspects. Faster importing, but to apply only when the data is known to be valid." << endl
162  << endl
163  << "General Options:" << endl
164  << " -d,--db-path,--datadir <path> Load database from path (default: " << getDataDir() << ")." << endl
165 #if ETH_EVMJIT
166  << " --vm <vm-kind> Select VM; options are: interpreter, jit or smart (default: interpreter)." << endl
167 #endif // ETH_EVMJIT
168  << " -v,--verbosity <0 - 9> Set the log verbosity from 0 to 9 (default: 8)." << endl
169  << " -V,--version Show the version and exit." << endl
170  << " -h,--help Show this help message and exit." << endl
171  << endl
172  << "Experimental / Proof of Concept:" << endl
173  << " --shh Enable Whisper." << endl
174  << endl
175  ;
176  exit(0);
177 }
178 
179 string ethCredits(bool _interactive = false)
180 {
181  std::ostringstream cout;
182  if (_interactive)
183  cout
184  << "Type 'exit' to quit" << endl << endl;
185  return credits() + cout.str();
186 }
187 
188 void version()
189 {
190  cout << "eth version " << dev::Version << endl;
191  cout << "eth network protocol version: " << dev::eth::c_protocolVersion << endl;
192  cout << "Client database version: " << dev::eth::c_databaseVersion << endl;
193  cout << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
194  exit(0);
195 }
196 
197 /*
198 The equivalent of setlocale(LC_ALL, “C”) is called before any user code is run.
199 If the user has an invalid environment setting then it is possible for the call
200 to set locale to fail, so there are only two possible actions, the first is to
201 throw a runtime exception and cause the program to quit (default behaviour),
202 or the second is to modify the environment to something sensible (least
203 surprising behaviour).
204 
205 The follow code produces the least surprising behaviour. It will use the user
206 specified default locale if it is valid, and if not then it will modify the
207 environment the process is running in to use a sensible default. This also means
208 that users do not need to install language packs for their OS.
209 */
211 {
212 #if __unix__
213  if (!std::setlocale(LC_ALL, ""))
214  {
215  setenv("LC_ALL", "C", 1);
216  }
217 #endif
218 }
219 
220 void importPresale(KeyManager& _km, string const& _file, function<string()> _pass)
221 {
222  KeyPair k = _km.presaleSecret(contentsString(_file), [&](bool){ return _pass(); });
223  _km.import(k.secret(), "Presale wallet" + _file + " (insecure)");
224 }
225 
226 Address c_config = Address("ccdeac59d35627b7de09332e819d5159e7bb7250");
227 string pretty(h160 _a, dev::eth::State const& _st)
228 {
229  string ns;
230  h256 n;
231  if (h160 nameReg = (u160)_st.storage(c_config, 0))
232  n = _st.storage(nameReg, (u160)(_a));
233  if (n)
234  {
235  std::string s((char const*)n.data(), 32);
236  if (s.find_first_of('\0') != string::npos)
237  s.resize(s.find_first_of('\0'));
238  ns = " " + s;
239  }
240  return ns;
241 }
242 
243 inline bool isPrime(unsigned _number)
244 {
245  if (((!(_number & 1)) && _number != 2 ) || (_number < 2) || (_number % 3 == 0 && _number != 3))
246  return false;
247  for(unsigned k = 1; 36 * k * k - 12 * k < _number; ++k)
248  if ((_number % (6 * k + 1) == 0) || (_number % (6 * k - 1) == 0))
249  return false;
250  return true;
251 }
252 
253 enum class NodeMode
254 {
255  PeerServer,
256  Full
257 };
258 
259 enum class OperationMode
260 {
261  Node,
262  Import,
263  Export
264 };
265 
266 enum class Format
267 {
268  Binary,
269  Hex,
270  Human
271 };
272 
273 void stopSealingAfterXBlocks(eth::Client* _c, unsigned _start, unsigned& io_mining)
274 {
275  try
276  {
277  if (io_mining != ~(unsigned)0 && io_mining && asEthashClient(_c)->isMining() && _c->blockChain().details().number - _start == io_mining)
278  {
279  _c->stopSealing();
280  io_mining = ~(unsigned)0;
281  }
282  }
283  catch (InvalidSealEngine&)
284  {
285  }
286 
287  this_thread::sleep_for(chrono::milliseconds(100));
288 }
289 
291 {
292 public:
293  void exit() { exitHandler(0); }
294  static void exitHandler(int) { s_shouldExit = true; }
295  bool shouldExit() const { return s_shouldExit; }
296 
297 private:
298  static bool s_shouldExit;
299 };
300 
301 bool ExitHandler::s_shouldExit = false;
302 
303 int main(int argc, char** argv)
304 {
306 
307  // Init secp256k1 context by calling one of the functions.
308  toPublic({});
309 
310  // Init defaults
311  Defaults::get();
312  Ethash::init();
313  NoProof::init();
314 
315 #if ETH_DEBUG
316  g_logVerbosity = 4;
317 #else
318  g_logVerbosity = 1;
319 #endif
320 
323 // unsigned prime = 0;
324 // bool yesIReallyKnowWhatImDoing = false;
325  strings scripts;
326 
328  string filename;
329  bool safeImport = false;
330 
332  string exportFrom = "1";
333  string exportTo = "latest";
334  Format exportFormat = Format::Binary;
335 
337  NodeMode nodeMode = NodeMode::Full;
338  bool interactive = false;
339 
340  int jsonRPCURL = -1;
341  bool adminViaHttp = false;
342  bool ipc = true;
343  std::string rpcCorsDomain = "";
344 
345  string jsonAdmin;
346  ChainParams chainParams(genesisInfo(eth::Network::MainNetwork), genesisStateRoot(eth::Network::MainNetwork));
347  u256 gasFloor = Invalid256;
348  string privateChain;
349 
350  bool upnp = true;
351  WithExisting withExisting = WithExisting::Trust;
352 
354  string clientName;
355  string listenIP;
356  unsigned short listenPort = 30303;
357  string publicIP;
358  string remoteHost;
359  unsigned short remotePort = 30303;
360 
361  unsigned peers = 11;
362  unsigned peerStretch = 7;
363  std::map<NodeID, pair<NodeIPEndpoint,bool>> preferredNodes;
364  bool bootstrap = true;
365  bool disableDiscovery = false;
366  bool pinning = false;
367  bool enableDiscovery = false;
368  bool noPinning = false;
369  static const unsigned NoNetworkID = (unsigned)-1;
370  unsigned networkID = NoNetworkID;
371 
373  unsigned mining = 0;
374  Address author;
375  strings presaleImports;
376  bytes extraData;
377 
379 // TransactionPriority priority = TransactionPriority::Medium;
380 // double etherPrice = 30.679;
381 // double blockFees = 15.0;
382  u256 askPrice = DefaultGasPrice;
383  u256 bidPrice = DefaultGasPrice;
384  bool alwaysConfirm = true;
385 
387  string masterPassword;
388  bool masterSet = false;
389 
391  bool useWhisper = false;
392  bool testingMode = false;
393 
394  string configFile = getDataDir() + "/config.rlp";
395  bytes b = contents(configFile);
396 
397  strings passwordsToNote;
398  Secrets toImport;
399  if (b.size())
400  {
401  try
402  {
403  RLP config(b);
404  author = config[1].toHash<Address>();
405  }
406  catch (...) {}
407  }
408 
409  if (argc > 1 && (string(argv[1]) == "wallet" || string(argv[1]) == "account"))
410  {
411  AccountManager accountm;
412  return !accountm.execute(argc, argv);
413  }
414 
415 
417 
418  bool listenSet = false;
419  string configJSON;
420  string genesisJSON;
421  for (int i = 1; i < argc; ++i)
422  {
423  string arg = argv[i];
424  if (m.interpretOption(i, argc, argv))
425  {
426  }
427  else if (arg == "--listen-ip" && i + 1 < argc)
428  {
429  listenIP = argv[++i];
430  listenSet = true;
431  }
432  else if ((arg == "--listen" || arg == "--listen-port") && i + 1 < argc)
433  {
434  listenPort = (short)atoi(argv[++i]);
435  listenSet = true;
436  }
437  else if ((arg == "--public-ip" || arg == "--public") && i + 1 < argc)
438  {
439  publicIP = argv[++i];
440  }
441  else if ((arg == "-r" || arg == "--remote") && i + 1 < argc)
442  {
443  string host = argv[++i];
444  string::size_type found = host.find_first_of(':');
445  if (found != std::string::npos)
446  {
447  remoteHost = host.substr(0, found);
448  remotePort = (short)atoi(host.substr(found + 1, host.length()).c_str());
449  }
450  else
451  remoteHost = host;
452  }
453  else if (arg == "--port" && i + 1 < argc)
454  {
455  remotePort = (short)atoi(argv[++i]);
456  }
457  else if (arg == "--password" && i + 1 < argc)
458  passwordsToNote.push_back(argv[++i]);
459  else if (arg == "--master" && i + 1 < argc)
460  {
461  masterPassword = argv[++i];
462  masterSet = true;
463  }
464  else if ((arg == "-I" || arg == "--import" || arg == "import") && i + 1 < argc)
465  {
466  mode = OperationMode::Import;
467  filename = argv[++i];
468  }
469  else if (arg == "--dont-check")
470  safeImport = true;
471  else if ((arg == "-E" || arg == "--export" || arg == "export") && i + 1 < argc)
472  {
473  mode = OperationMode::Export;
474  filename = argv[++i];
475  }
476  else if (arg == "--script" && i + 1 < argc)
477  scripts.push_back(argv[++i]);
478  else if (arg == "--format" && i + 1 < argc)
479  {
480  string m = argv[++i];
481  if (m == "binary")
482  exportFormat = Format::Binary;
483  else if (m == "hex")
484  exportFormat = Format::Hex;
485  else if (m == "human")
486  exportFormat = Format::Human;
487  else
488  {
489  cerr << "Bad " << arg << " option: " << m << endl;
490  return -1;
491  }
492  }
493  else if (arg == "--to" && i + 1 < argc)
494  exportTo = argv[++i];
495  else if (arg == "--from" && i + 1 < argc)
496  exportFrom = argv[++i];
497  else if (arg == "--only" && i + 1 < argc)
498  exportTo = exportFrom = argv[++i];
499  else if (arg == "--upnp" && i + 1 < argc)
500  {
501  string m = argv[++i];
502  if (isTrue(m))
503  upnp = true;
504  else if (isFalse(m))
505  upnp = false;
506  else
507  {
508  cerr << "Bad " << arg << " option: " << m << endl;
509  return -1;
510  }
511  }
512  else if (arg == "--network-id" && i + 1 < argc)
513  try {
514  networkID = stol(argv[++i]);
515  }
516  catch (...)
517  {
518  cerr << "Bad " << arg << " option: " << argv[i] << endl;
519  return -1;
520  }
521  else if (arg == "--private" && i + 1 < argc)
522  try {
523  privateChain = argv[++i];
524  }
525  catch (...)
526  {
527  cerr << "Bad " << arg << " option: " << argv[i] << endl;
528  return -1;
529  }
530  else if (arg == "--independent" && i + 1 < argc)
531  try {
532  privateChain = argv[++i];
533  noPinning = enableDiscovery = true;
534  }
535  catch (...)
536  {
537  cerr << "Bad " << arg << " option: " << argv[i] << endl;
538  return -1;
539  }
540  else if (arg == "-K" || arg == "--kill-blockchain" || arg == "--kill")
541  withExisting = WithExisting::Kill;
542  else if (arg == "-R" || arg == "--rebuild")
543  withExisting = WithExisting::Verify;
544  else if (arg == "-R" || arg == "--rescue")
545  withExisting = WithExisting::Rescue;
546  else if (arg == "--client-name" && i + 1 < argc)
547  clientName = argv[++i];
548  else if ((arg == "-a" || arg == "--address" || arg == "--author") && i + 1 < argc)
549  try {
550  author = h160(fromHex(argv[++i], WhenError::Throw));
551  }
552  catch (BadHexCharacter&)
553  {
554  cerr << "Bad hex in " << arg << " option: " << argv[i] << endl;
555  return -1;
556  }
557  catch (...)
558  {
559  cerr << "Bad " << arg << " option: " << argv[i] << endl;
560  return -1;
561  }
562  else if ((arg == "-s" || arg == "--import-secret") && i + 1 < argc)
563  {
564  Secret s(fromHex(argv[++i]));
565  toImport.emplace_back(s);
566  }
567  else if ((arg == "-S" || arg == "--import-session-secret") && i + 1 < argc)
568  {
569  Secret s(fromHex(argv[++i]));
570  toImport.emplace_back(s);
571  }
572  else if ((arg == "-d" || arg == "--path" || arg == "--db-path" || arg == "--datadir") && i + 1 < argc)
573  setDataDir(argv[++i]);
574  else if (arg == "--ipcpath" && i + 1 < argc )
575  setIpcPath(argv[++i]);
576  else if ((arg == "--genesis-json" || arg == "--genesis") && i + 1 < argc)
577  {
578  try
579  {
580  genesisJSON = contentsString(argv[++i]);
581  }
582  catch (...)
583  {
584  cerr << "Bad " << arg << " option: " << argv[i] << endl;
585  return -1;
586  }
587  }
588  else if (arg == "--config" && i + 1 < argc)
589  {
590  try
591  {
592  configJSON = contentsString(argv[++i]);
593  }
594  catch (...)
595  {
596  cerr << "Bad " << arg << " option: " << argv[i] << endl;
597  return -1;
598  }
599  }
600  else if (arg == "--extra-data" && i + 1 < argc)
601  {
602  try
603  {
604  extraData = fromHex(argv[++i]);
605  }
606  catch (...)
607  {
608  cerr << "Bad " << arg << " option: " << argv[i] << endl;
609  return -1;
610  }
611  }
612  else if (arg == "--gas-floor" && i + 1 < argc)
613  gasFloor = u256(argv[++i]);
614  else if (arg == "--mainnet")
615  chainParams = ChainParams(genesisInfo(eth::Network::MainNetwork), genesisStateRoot(eth::Network::MainNetwork));
616  else if (arg == "--ropsten" || arg == "--testnet")
617  chainParams = ChainParams(genesisInfo(eth::Network::Ropsten), genesisStateRoot(eth::Network::Ropsten));
618  else if (arg == "--oppose-dao-fork")
619  {
620  chainParams = ChainParams(genesisInfo(eth::Network::MainNetwork), genesisStateRoot(eth::Network::MainNetwork));
621  chainParams.otherParams["daoHardforkBlock"] = toHex(u256(-1) - 10, HexPrefix::Add);
622  }
623  else if (arg == "--support-dao-fork")
624  {
625  // default
626  }
627  else if (arg == "--bob")
628  {
629  cout << "Asking Bob for blocks (this should work in theoreum)..." << endl;
630  while (true)
631  {
632  u256 x(h256::random());
633  u256 c;
634  for (; x != 1; ++c)
635  {
636  x = (x & 1) == 0 ? x / 2 : 3 * x + 1;
637  cout << toHex(x) << endl;
638  this_thread::sleep_for(chrono::seconds(1));
639  }
640  cout << "Block number: " << hex << c << endl;
641  exit(0);
642  }
643  }
644 /* else if ((arg == "-B" || arg == "--block-fees") && i + 1 < argc)
645  {
646  try
647  {
648  blockFees = stof(argv[++i]);
649  }
650  catch (...)
651  {
652  cerr << "Bad " << arg << " option: " << argv[i] << endl;
653  return -1;
654  }
655  }
656  else if ((arg == "-e" || arg == "--ether-price") && i + 1 < argc)
657  {
658  try
659  {
660  etherPrice = stof(argv[++i]);
661  }
662  catch (...)
663  {
664  cerr << "Bad " << arg << " option: " << argv[i] << endl;
665  return -1;
666  }
667  }*/
668  else if (arg == "--ask" && i + 1 < argc)
669  {
670  try
671  {
672  askPrice = u256(argv[++i]);
673  }
674  catch (...)
675  {
676  cerr << "Bad " << arg << " option: " << argv[i] << endl;
677  return -1;
678  }
679  }
680  else if (arg == "--bid" && i + 1 < argc)
681  {
682  try
683  {
684  bidPrice = u256(argv[++i]);
685  }
686  catch (...)
687  {
688  cerr << "Bad " << arg << " option: " << argv[i] << endl;
689  return -1;
690  }
691  }
692 /* else if ((arg == "-P" || arg == "--priority") && i + 1 < argc)
693  {
694  string m = boost::to_lower_copy(string(argv[++i]));
695  if (m == "lowest")
696  priority = TransactionPriority::Lowest;
697  else if (m == "low")
698  priority = TransactionPriority::Low;
699  else if (m == "medium" || m == "mid" || m == "default" || m == "normal")
700  priority = TransactionPriority::Medium;
701  else if (m == "high")
702  priority = TransactionPriority::High;
703  else if (m == "highest")
704  priority = TransactionPriority::Highest;
705  else
706  try {
707  priority = (TransactionPriority)(max(0, min(100, stoi(m))) * 8 / 100);
708  }
709  catch (...) {
710  cerr << "Unknown " << arg << " option: " << m << endl;
711  return -1;
712  }
713  }*/
714  else if ((arg == "-m" || arg == "--mining") && i + 1 < argc)
715  {
716  string m = argv[++i];
717  if (isTrue(m))
718  mining = ~(unsigned)0;
719  else if (isFalse(m))
720  mining = 0;
721  else
722  try {
723  mining = stoi(m);
724  }
725  catch (...) {
726  cerr << "Unknown " << arg << " option: " << m << endl;
727  return -1;
728  }
729  }
730  else if (arg == "-b" || arg == "--bootstrap")
731  bootstrap = true;
732  else if (arg == "--no-bootstrap")
733  bootstrap = false;
734  else if (arg == "--no-discovery")
735  {
736  disableDiscovery = true;
737  bootstrap = false;
738  }
739  else if (arg == "--pin")
740  pinning = true;
741  else if (arg == "--hermit")
742  pinning = disableDiscovery = true;
743  else if (arg == "--sociable")
744  noPinning = enableDiscovery = true;
745  else if (arg == "--unsafe-transactions")
746  alwaysConfirm = false;
747  else if (arg == "--import-presale" && i + 1 < argc)
748  presaleImports.push_back(argv[++i]);
749  else if (arg == "--old-interactive")
750  interactive = true;
751 
752  else if ((arg == "-j" || arg == "--json-rpc"))
753  jsonRPCURL = jsonRPCURL == -1 ? SensibleHttpPort : jsonRPCURL;
754  else if (arg == "--admin-via-http")
755  adminViaHttp = true;
756  else if (arg == "--json-rpc-port" && i + 1 < argc)
757  jsonRPCURL = atoi(argv[++i]);
758  else if (arg == "--rpccorsdomain" && i + 1 < argc)
759  rpcCorsDomain = argv[++i];
760  else if (arg == "--json-admin" && i + 1 < argc)
761  jsonAdmin = argv[++i];
762  else if (arg == "--ipc")
763  ipc = true;
764  else if (arg == "--no-ipc")
765  ipc = false;
766 
767  else if ((arg == "-v" || arg == "--verbosity") && i + 1 < argc)
768  g_logVerbosity = atoi(argv[++i]);
769  else if ((arg == "-x" || arg == "--peers") && i + 1 < argc)
770  peers = atoi(argv[++i]);
771  else if (arg == "--peer-stretch" && i + 1 < argc)
772  peerStretch = atoi(argv[++i]);
773  else if (arg == "--peerset" && i + 1 < argc)
774  {
775  string peerset = argv[++i];
776  if (peerset.empty())
777  {
778  cerr << "--peerset argument must not be empty";
779  return -1;
780  }
781 
782  vector<string> each;
783  boost::split(each, peerset, boost::is_any_of("\t "));
784  for (auto const& p: each)
785  {
786  string type;
787  string pubk;
788  string hostIP;
789  unsigned short port = c_defaultListenPort;
790 
791  // type:key@ip[:port]
792  vector<string> typeAndKeyAtHostAndPort;
793  boost::split(typeAndKeyAtHostAndPort, p, boost::is_any_of(":"));
794  if (typeAndKeyAtHostAndPort.size() < 2 || typeAndKeyAtHostAndPort.size() > 3)
795  continue;
796 
797  type = typeAndKeyAtHostAndPort[0];
798  if (typeAndKeyAtHostAndPort.size() == 3)
799  port = (uint16_t)atoi(typeAndKeyAtHostAndPort[2].c_str());
800 
801  vector<string> keyAndHost;
802  boost::split(keyAndHost, typeAndKeyAtHostAndPort[1], boost::is_any_of("@"));
803  if (keyAndHost.size() != 2)
804  continue;
805  pubk = keyAndHost[0];
806  if (pubk.size() != 128)
807  continue;
808  hostIP = keyAndHost[1];
809 
810  // todo: use Network::resolveHost()
811  if (hostIP.size() < 4 /* g.it */)
812  continue;
813 
814  bool required = type == "required";
815  if (!required && type != "default")
816  continue;
817 
818  Public publicKey(fromHex(pubk));
819  try
820  {
821  preferredNodes[publicKey] = make_pair(NodeIPEndpoint(bi::address::from_string(hostIP), port, port), required);
822  }
823  catch (...)
824  {
825  cerr << "Unrecognized peerset: " << peerset << endl;
826  return -1;
827  }
828  }
829  }
830  else if ((arg == "-o" || arg == "--mode") && i + 1 < argc)
831  {
832  string m = argv[++i];
833  if (m == "full")
834  nodeMode = NodeMode::Full;
835  else if (m == "peer")
836  nodeMode = NodeMode::PeerServer;
837  else
838  {
839  cerr << "Unknown mode: " << m << endl;
840  return -1;
841  }
842  }
843 #if ETH_EVMJIT
844  else if (arg == "--vm" && i + 1 < argc)
845  {
846  string vmKind = argv[++i];
847  if (vmKind == "interpreter")
848  VMFactory::setKind(VMKind::Interpreter);
849  else if (vmKind == "jit")
850  VMFactory::setKind(VMKind::JIT);
851  else if (vmKind == "smart")
852  VMFactory::setKind(VMKind::Smart);
853  else
854  {
855  cerr << "Unknown VM kind: " << vmKind << endl;
856  return -1;
857  }
858  }
859 #endif
860  else if (arg == "--shh")
861  useWhisper = true;
862  else if (arg == "-h" || arg == "--help")
863  help();
864  else if (arg == "-V" || arg == "--version")
865  version();
866  else if (arg == "--test")
867  {
868  testingMode = true;
869  enableDiscovery = false;
870  disableDiscovery = true;
871  noPinning = true;
872  bootstrap = false;
873  }
874  else
875  {
876  cerr << "Invalid argument: " << arg << endl;
877  exit(-1);
878  }
879  }
880 
881  if (!configJSON.empty())
882  {
883  try
884  {
885  chainParams = chainParams.loadConfig(configJSON);
886  }
887  catch (...)
888  {
889  cerr << "provided configuration is not well formatted" << endl;
890  cerr << "sample: " << endl << genesisInfo(eth::Network::MainNetworkTest) << endl;
891  return 0;
892  }
893  }
894 
895 
896  if (!genesisJSON.empty())
897  {
898  try
899  {
900  chainParams = chainParams.loadGenesis(genesisJSON);
901  }
902  catch (...)
903  {
904  cerr << "provided genesis block description is not well formatted" << endl;
905  string genesisSample =
906  R"E(
907  {
908  "nonce": "0x0000000000000042",
909  "difficulty": "0x400000000",
910  "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
911  "author": "0x0000000000000000000000000000000000000000",
912  "timestamp": "0x00",
913  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
914  "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
915  "gasLimit": "0x1388"
916  }
917  )E";
918  cerr << "sample: " << endl << genesisSample << endl;
919  return 0;
920  }
921  }
922 
923 
924  if (!privateChain.empty())
925  {
926  chainParams.extraData = sha3(privateChain).asBytes();
927  chainParams.difficulty = chainParams.u256Param("minimumDifficulty");
928  chainParams.gasLimit = u256(1) << 32;
929  }
930  // TODO: Open some other API path
931 // if (gasFloor != Invalid256)
932 // c_gasFloorTarget = gasFloor;
933 
934  if (g_logVerbosity > 0)
935  cout << EthGrayBold "cpp-ethereum, a C++ Ethereum client" EthReset << endl;
936 
937  m.execute();
938 
939  std::string secretsPath;
940  if (testingMode)
941  secretsPath = (boost::filesystem::path(getDataDir()) / "keystore").string();
942  else
943  secretsPath = SecretStore::defaultPath();
944  KeyManager keyManager(KeyManager::defaultPath(), secretsPath);
945  for (auto const& s: passwordsToNote)
946  keyManager.notePassword(s);
947 
948  // the first value is deprecated (never used)
949  writeFile(configFile, rlpList(author, author));
950 
951  if (!clientName.empty())
952  clientName += "/";
953 
954  string logbuf;
955  std::string additional;
956  if (interactive)
957  g_logPost = [&](std::string const& a, char const*){
958  static SpinLock s_lock;
959  SpinGuard l(s_lock);
960 
961  if (g_silence)
962  logbuf += a + "\n";
963  else
964  cout << "\r \r" << a << endl << additional << flush;
965 
966  // helpful to use OutputDebugString on windows
967  #if defined(_WIN32)
968  {
969  OutputDebugStringA(a.data());
970  OutputDebugStringA("\n");
971  }
972  #endif
973  };
974 
975  auto getPassword = [&](string const& prompt) {
976  bool s = g_silence;
977  g_silence = true;
978  cout << endl;
979  string ret = dev::getPassword(prompt);
980  g_silence = s;
981  return ret;
982  };
983  auto getResponse = [&](string const& prompt, unordered_set<string> const& acceptable) {
984  bool s = g_silence;
985  g_silence = true;
986  cout << endl;
987  string ret;
988  while (true)
989  {
990  cout << prompt;
991  getline(cin, ret);
992  if (acceptable.count(ret))
993  break;
994  cout << "Invalid response: " << ret << endl;
995  }
996  g_silence = s;
997  return ret;
998  };
999  auto getAccountPassword = [&](Address const& a){
1000  return getPassword("Enter password for address " + keyManager.accountName(a) + " (" + a.abridged() + "; hint:" + keyManager.passwordHint(a) + "): ");
1001  };
1002 
1003  auto netPrefs = publicIP.empty() ? NetworkPreferences(listenIP, listenPort, upnp) : NetworkPreferences(publicIP, listenIP ,listenPort, upnp);
1004  netPrefs.discovery = (privateChain.empty() && !disableDiscovery) || enableDiscovery;
1005  netPrefs.pin = (pinning || !privateChain.empty()) && !noPinning;
1006 
1007  auto nodesState = contents(getDataDir() + "/network.rlp");
1008  auto caps = useWhisper ? set<string>{"eth", "shh"} : set<string>{"eth"};
1009 
1010  if (testingMode)
1011  {
1012  chainParams.sealEngineName = "NoProof";
1013  chainParams.otherParams["allowFutureBlocks"] = "1";
1014  }
1015 
1017  WebThreeDirect::composeClientVersion("eth"),
1018  getDataDir(),
1019  chainParams,
1020  withExisting,
1021  nodeMode == NodeMode::Full ? caps : set<string>(),
1022  netPrefs,
1023  &nodesState,
1024  testingMode
1025  );
1026 
1027  if (!extraData.empty())
1028  web3.ethereum()->setExtraData(extraData);
1029 
1030  auto toNumber = [&](string const& s) -> unsigned {
1031  if (s == "latest")
1032  return web3.ethereum()->number();
1033  if (s.size() == 64 || (s.size() == 66 && s.substr(0, 2) == "0x"))
1034  return web3.ethereum()->blockChain().number(h256(s));
1035  try {
1036  return stol(s);
1037  }
1038  catch (...)
1039  {
1040  cerr << "Bad block number/hash option: " << s << endl;
1041  exit(-1);
1042  }
1043  };
1044 
1045  if (mode == OperationMode::Export)
1046  {
1047  ofstream fout(filename, std::ofstream::binary);
1048  ostream& out = (filename.empty() || filename == "--") ? cout : fout;
1049 
1050  unsigned last = toNumber(exportTo);
1051  for (unsigned i = toNumber(exportFrom); i <= last; ++i)
1052  {
1053  bytes block = web3.ethereum()->blockChain().block(web3.ethereum()->blockChain().numberHash(i));
1054  switch (exportFormat)
1055  {
1056  case Format::Binary: out.write((char const*)block.data(), block.size()); break;
1057  case Format::Hex: out << toHex(block) << endl; break;
1058  case Format::Human: out << RLP(block) << endl; break;
1059  default:;
1060  }
1061  }
1062  return 0;
1063  }
1064 
1065  if (mode == OperationMode::Import)
1066  {
1067  ifstream fin(filename, std::ifstream::binary);
1068  istream& in = (filename.empty() || filename == "--") ? cin : fin;
1069  unsigned alreadyHave = 0;
1070  unsigned good = 0;
1071  unsigned futureTime = 0;
1072  unsigned unknownParent = 0;
1073  unsigned bad = 0;
1074  chrono::steady_clock::time_point t = chrono::steady_clock::now();
1075  double last = 0;
1076  unsigned lastImported = 0;
1077  unsigned imported = 0;
1078  while (in.peek() != -1)
1079  {
1080  bytes block(8);
1081  in.read((char*)block.data(), 8);
1082  block.resize(RLP(block, RLP::LaissezFaire).actualSize());
1083  in.read((char*)block.data() + 8, block.size() - 8);
1084 
1085  switch (web3.ethereum()->queueBlock(block, safeImport))
1086  {
1087  case ImportResult::Success: good++; break;
1088  case ImportResult::AlreadyKnown: alreadyHave++; break;
1089  case ImportResult::UnknownParent: unknownParent++; break;
1090  case ImportResult::FutureTimeUnknown: unknownParent++; futureTime++; break;
1091  case ImportResult::FutureTimeKnown: futureTime++; break;
1092  default: bad++; break;
1093  }
1094 
1095  // sync chain with queue
1096  tuple<ImportRoute, bool, unsigned> r = web3.ethereum()->syncQueue(10);
1097  imported += get<2>(r);
1098 
1099  double e = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - t).count() / 1000.0;
1100  if ((unsigned)e >= last + 10)
1101  {
1102  auto i = imported - lastImported;
1103  auto d = e - last;
1104  cout << i << " more imported at " << (round(i * 10 / d) / 10) << " blocks/s. " << imported << " imported in " << e << " seconds at " << (round(imported * 10 / e) / 10) << " blocks/s (#" << web3.ethereum()->number() << ")" << endl;
1105  last = (unsigned)e;
1106  lastImported = imported;
1107 // cout << web3.ethereum()->blockQueueStatus() << endl;
1108  }
1109  }
1110 
1111  bool moreToImport = true;
1112  while (moreToImport)
1113  {
1114  this_thread::sleep_for(chrono::seconds(1));
1115  tie(ignore, moreToImport, ignore) = web3.ethereum()->syncQueue(100000);
1116  }
1117  double e = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - t).count() / 1000.0;
1118  cout << imported << " imported in " << e << " seconds at " << (round(imported * 10 / e) / 10) << " blocks/s (#" << web3.ethereum()->number() << ")" << endl;
1119  return 0;
1120  }
1121 
1122  try
1123  {
1124  if (keyManager.exists())
1125  {
1126  if (!keyManager.load(masterPassword) && masterSet)
1127  {
1128  while (true)
1129  {
1130  masterPassword = getPassword("Please enter your MASTER password: ");
1131  if (keyManager.load(masterPassword))
1132  break;
1133  cout << "The password you entered is incorrect. If you have forgotten your password, and you wish to start afresh, manually remove the file: " + getDataDir("ethereum") + "/keys.info" << endl;
1134  }
1135  }
1136  }
1137  else
1138  {
1139  if (masterSet)
1140  keyManager.create(masterPassword);
1141  else
1142  keyManager.create(std::string());
1143  }
1144  }
1145  catch(...)
1146  {
1147  cerr << "Error initializing key manager: " << boost::current_exception_diagnostic_information() << endl;
1148  return -1;
1149  }
1150 
1151  for (auto const& presale: presaleImports)
1152  importPresale(keyManager, presale, [&](){ return getPassword("Enter your wallet password for " + presale + ": "); });
1153 
1154  for (auto const& s: toImport)
1155  {
1156  keyManager.import(s, "Imported key (UNSAFE)");
1157  }
1158 
1159  cout << ethCredits();
1160  web3.setIdealPeerCount(peers);
1161  web3.setPeerStretch(peerStretch);
1162 // std::shared_ptr<eth::BasicGasPricer> gasPricer = make_shared<eth::BasicGasPricer>(u256(double(ether / 1000) / etherPrice), u256(blockFees * 1000));
1163  std::shared_ptr<eth::TrivialGasPricer> gasPricer = make_shared<eth::TrivialGasPricer>(askPrice, bidPrice);
1164  eth::Client* c = nodeMode == NodeMode::Full ? web3.ethereum() : nullptr;
1165  if (c)
1166  {
1167  c->setGasPricer(gasPricer);
1168  DEV_IGNORE_EXCEPTIONS(asEthashClient(c)->setShouldPrecomputeDAG(m.shouldPrecompute()));
1169  c->setSealer(m.minerType());
1170  c->setAuthor(author);
1171  if (networkID != NoNetworkID)
1172  c->setNetworkId(networkID);
1173  }
1174 
1175  auto renderFullAddress = [&](Address const& _a) -> std::string
1176  {
1177  return ICAP(_a).encoded() + " (" + toUUID(keyManager.uuid(_a)) + " - " + toHex(_a.ref().cropped(0, 4)) + ")";
1178  };
1179 
1180  if (author)
1181  cout << "Mining Beneficiary: " << renderFullAddress(author) << endl;
1182 
1183  if (bootstrap || !remoteHost.empty() || enableDiscovery || listenSet)
1184  {
1185  web3.startNetwork();
1186  cout << "Node ID: " << web3.enode() << endl;
1187  }
1188  else
1189  cout << "Networking disabled. To start, use netstart or pass --bootstrap or a remote host." << endl;
1190 
1191  unique_ptr<ModularServer<>> jsonrpcHttpServer;
1192  unique_ptr<ModularServer<>> jsonrpcIpcServer;
1193  unique_ptr<rpc::SessionManager> sessionManager;
1194  unique_ptr<SimpleAccountHolder> accountHolder;
1195 
1196  AddressHash allowedDestinations;
1197 
1198  std::function<bool(TransactionSkeleton const&, bool)> authenticator;
1199  if (testingMode)
1200  authenticator = [](TransactionSkeleton const&, bool) -> bool { return true; };
1201  else
1202  authenticator = [&](TransactionSkeleton const& _t, bool isProxy) -> bool {
1203  // "unlockAccount" functionality is done in the AccountHolder.
1204  if (!alwaysConfirm || allowedDestinations.count(_t.to))
1205  return true;
1206 
1207  string r = getResponse(_t.userReadable(isProxy,
1208  [&](TransactionSkeleton const& _t) -> pair<bool, string>
1209  {
1210  h256 contractCodeHash = web3.ethereum()->postState().codeHash(_t.to);
1211  if (contractCodeHash == EmptySHA3)
1212  return std::make_pair(false, std::string());
1213  // TODO: actually figure out the natspec. we'll need the natspec database here though.
1214  return std::make_pair(true, std::string());
1215  }, [&](Address const& _a) { return ICAP(_a).encoded() + " (" + _a.abridged() + ")"; }
1216  ) + "\nEnter yes/no/always (always to this address): ", {"yes", "n", "N", "no", "NO", "always"});
1217  if (r == "always")
1218  allowedDestinations.insert(_t.to);
1219  return r == "yes" || r == "always";
1220  };
1221 
1222  ExitHandler exitHandler;
1223 
1224  if (jsonRPCURL > -1 || ipc)
1225  {
1226  using FullServer = ModularServer<
1231  >;
1232 
1233  sessionManager.reset(new rpc::SessionManager());
1234  accountHolder.reset(new SimpleAccountHolder([&](){ return web3.ethereum(); }, getAccountPassword, keyManager, authenticator));
1235  auto ethFace = new rpc::Eth(*web3.ethereum(), *accountHolder.get());
1236  rpc::TestFace* testEth = nullptr;
1237  if (testingMode)
1238  testEth = new rpc::Test(*web3.ethereum());
1239 
1240  if (jsonRPCURL >= 0)
1241  {
1242  rpc::AdminEth* adminEth = nullptr;
1243  rpc::PersonalFace* personal = nullptr;
1244  rpc::AdminNet* adminNet = nullptr;
1245  rpc::AdminUtils* adminUtils = nullptr;
1246  if (adminViaHttp)
1247  {
1248  personal = new rpc::Personal(keyManager, *accountHolder, *web3.ethereum());
1249  adminEth = new rpc::AdminEth(*web3.ethereum(), *gasPricer.get(), keyManager, *sessionManager.get());
1250  adminNet = new rpc::AdminNet(web3, *sessionManager.get());
1251  adminUtils = new rpc::AdminUtils(*sessionManager.get());
1252  }
1253 
1254  jsonrpcHttpServer.reset(new FullServer(
1255  ethFace, new rpc::LevelDB(), new rpc::Whisper(web3, {}),
1256  new rpc::Net(web3), new rpc::Web3(web3.clientVersion()), personal,
1257  adminEth, adminNet, adminUtils,
1258  new rpc::Debug(*web3.ethereum()),
1259  testEth
1260  ));
1261  auto httpConnector = new SafeHttpServer(jsonRPCURL, "", "", SensibleHttpThreads);
1262  httpConnector->setAllowedOrigin(rpcCorsDomain);
1263  jsonrpcHttpServer->addConnector(httpConnector);
1264  jsonrpcHttpServer->StartListening();
1265  }
1266  if (ipc)
1267  {
1268  jsonrpcIpcServer.reset(new FullServer(
1269  ethFace, new rpc::LevelDB(), new rpc::Whisper(web3, {}), new rpc::Net(web3),
1270  new rpc::Web3(web3.clientVersion()), new rpc::Personal(keyManager, *accountHolder, *web3.ethereum()),
1271  new rpc::AdminEth(*web3.ethereum(), *gasPricer.get(), keyManager, *sessionManager.get()),
1272  new rpc::AdminNet(web3, *sessionManager.get()),
1273  new rpc::AdminUtils(*sessionManager.get()),
1274  new rpc::Debug(*web3.ethereum()),
1275  testEth
1276  ));
1277  auto ipcConnector = new IpcServer("geth");
1278  jsonrpcIpcServer->addConnector(ipcConnector);
1279  ipcConnector->StartListening();
1280  }
1281 
1282  if (jsonAdmin.empty())
1283  jsonAdmin = sessionManager->newSession(rpc::SessionPermissions{{rpc::Privilege::Admin}});
1284  else
1285  sessionManager->addSession(jsonAdmin, rpc::SessionPermissions{{rpc::Privilege::Admin}});
1286 
1287  cout << "JSONRPC Admin Session Key: " << jsonAdmin << endl;
1288  writeFile(getDataDir("web3") + "/session.key", jsonAdmin);
1289  writeFile(getDataDir("web3") + "/session.url", "http://localhost:" + toString(jsonRPCURL));
1290  }
1291 
1292  for (auto const& p: preferredNodes)
1293  if (p.second.second)
1294  web3.requirePeer(p.first, p.second.first);
1295  else
1296  web3.addNode(p.first, p.second.first);
1297 
1298  if (bootstrap && privateChain.empty())
1299  for (auto const& i: Host::pocHosts())
1300  web3.requirePeer(i.first, i.second);
1301  if (!remoteHost.empty())
1302  web3.addNode(p2p::NodeID(), remoteHost + ":" + toString(remotePort));
1303 
1304  signal(SIGABRT, &ExitHandler::exitHandler);
1305  signal(SIGTERM, &ExitHandler::exitHandler);
1306  signal(SIGINT, &ExitHandler::exitHandler);
1307 
1308  if (c)
1309  {
1310  unsigned n = c->blockChain().details().number;
1311  if (mining)
1312  c->startSealing();
1313 
1314  while (!exitHandler.shouldExit())
1315  stopSealingAfterXBlocks(c, n, mining);
1316  }
1317  else
1318  while (!exitHandler.shouldExit())
1319  this_thread::sleep_for(chrono::milliseconds(1000));
1320 
1321  if (jsonrpcHttpServer.get())
1322  jsonrpcHttpServer->StopListening();
1323  if (jsonrpcIpcServer.get())
1324  jsonrpcIpcServer->StopListening();
1325 
1326  auto netData = web3.saveNetwork();
1327  if (!netData.empty())
1328  writeFile(getDataDir() + "/network.rlp", netData);
1329  return 0;
1330 }
std::string encoded() const
Definition: ICAP.cpp:110
void stopSealing() override
Stop sealing.
Definition: Client.h:161
rpc::EthFace * ethFace
Definition: shhrpc.cpp:61
Adapted from code found on http://stackoverflow.com/questions/180947/base64-decode-snippet-in-c Origi...
Definition: Arith256.cpp:15
void help()
Definition: main.cpp:39
std::string toHex(T const &_data, int _w=2, HexPrefix _prefix=HexPrefix::DontAdd)
Definition: CommonData.h:54
OperationMode
Definition: main.cpp:259
const unsigned c_protocolVersion
Current protocol version.
Definition: Common.cpp:43
BlockDetails details(h256 const &_hash) const
Get the familial details concerning a block (or the most recent mined if none given). Thread-safe.
Definition: BlockChain.h:156
std::string const & clientVersion() const
Definition: WebThree.h:146
static KeyPair presaleSecret(std::string const &_json, std::function< std::string(bool)> const &_password)
Extracts the secret key from the presale wallet.
Definition: KeyManager.cpp:298
byte * data()
Definition: FixedHash.h:139
string getAccountPassword(KeyManager &keyManager, Address const &a)
Definition: KeyAux.h:46
std::string const & accountName(Address const &_address) const
Definition: KeyManager.cpp:351
unique_ptr< AccountHolder > accountHolder
Definition: shhrpc.cpp:64
static bool s_shouldExit
Definition: main.cpp:298
EthashClient & asEthashClient(Interface &_c)
static void streamWalletHelp(std::ostream &_out)
stream wallet help section
eth::Client * ethereum() const
Definition: WebThree.h:140
void writeFile(std::string const &_file, bytesConstRef _data, bool _writeDeleteRename=false)
Write the given binary data into the given file, replacing the file if it pre-exists.
Definition: CommonIO.cpp:107
std::unordered_map< std::string, std::string > otherParams
Additional parameters.
h128 uuid(Address const &_a) const
Definition: KeyManager.cpp:197
void notePassword(std::string const &_pass)
Definition: KeyManager.h:89
Simple class that represents a "key pair".
Definition: Common.h:150
size_t count
Definition: ExecStats.cpp:37
h160 Address
An Ethereum address: 20 bytes.
Definition: Common.h:62
evm_mode mode
Definition: SmartVM.cpp:47
void setExtraData(bytes const &_extraData)
Set the extra data that goes into sealed blocks.
Definition: Client.h:193
std::vector< Secret > Secrets
A vector of secrets.
Definition: Common.h:74
#define c(i)
std::vector< std::string > strings
Definition: Common.h:147
h256 const & genesisStateRoot(Network _n)
Definition: GenesisInfo.cpp:57
std::hash for asio::adress
Definition: Common.h:323
std::string contentsString(std::string const &_file)
Retrieve and returns the contents of the given file as a std::string.
static void streamHelp(ostream &_out)
Definition: MinerAux.h:242
Main API hub for interfacing with Web 3 components.
Definition: WebThree.h:119
#define DEV_QUOTED(s)
Definition: Common.h:61
int Add(word *C, const word *A, const word *B, size_t N)
Definition: integer.cpp:2143
std::string getDataDir(std::string _prefix="ethereum")
Secret const & secret() const
Definition: Common.h:167
std::string toString(string32 const &_s)
Make normal string from fixed-length string.
Definition: CommonData.cpp:141
IPv4,UDP/TCP endpoints.
Definition: Common.h:175
Simple lock that waits for release without making context switch.
Definition: Guards.h:73
void exit()
Definition: main.cpp:293
Model of an Ethereum state, essentially a facade for the trie.
Definition: State.h:161
void setIpcPath(std::string const &_ipcPath)
Sets the ipc socket dir.
ChainParams loadConfig(std::string const &_json, h256 const &_stateRoot=h256()) const
load config/genesis
Definition: ChainParams.cpp:54
string pretty(h160 _a, dev::eth::State const &_st)
Definition: main.cpp:227
void version()
Definition: main.cpp:53
std::string const & passwordHint(Address const &_address) const
Definition: KeyManager.cpp:373
std::string userReadable(bool _toProxy, std::function< std::pair< bool, std::string >(TransactionSkeleton const &)> const &_getNatSpec, std::function< std::string(Address const &)> const &_formatAddress) const
Definition: Common.cpp:154
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 160, 160, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u160
Definition: Common.h:127
h128 import(Secret const &_s, std::string const &_accountName, std::string const &_pass, std::string const &_passwordHint)
WithExisting
Definition: Common.h:310
Public toPublic(Secret const &_secret)
Convert a secret key into the public key equivalent.
Definition: Common.cpp:67
#define a(i)
#define x(i)
bytes fromHex(std::string const &_s, WhenError _throw=WhenError::DontThrow)
Definition: CommonData.cpp:99
_N toHash(int _flags=Strict) const
Definition: RLP.h:298
void setDefaultOrCLocale()
Definition: main.cpp:72
static void streamAccountHelp(std::ostream &_out)
stream account help section
std::tuple< ImportRoute, bool, unsigned > syncQueue(unsigned _max=1)
Freeze worker thread and sync some of the block queue.
Definition: Client.cpp:134
int main(int argc, char **argv)
Definition: main.cpp:149
ChainParams loadGenesis(std::string const &_json, h256 const &_stateRoot=h256()) const
Definition: ChainParams.cpp:88
High-level manager of password-encrypted keys for Ethereum.
Definition: KeyManager.h:72
void requirePeer(p2p::NodeID const &_node, bi::tcp::endpoint const &_endpoint) override
Require connection to peer.
Definition: WebThree.cpp:150
BlockChain const & blockChain() const
Get the object representing the current canonical blockchain.
Definition: Client.h:125
dev::bytes saveNetwork() override
Save peers.
Definition: WebThree.cpp:140
unsigned number(h256 const &_hash) const
Get a number for the given hash (or the most recent mined if none given). Thread-safe.
Definition: BlockChain.h:225
h256 numberHash(unsigned _i) const
Get the hash for a given block&#39;s number.
Definition: BlockChain.h:183
std::string minerType() const
Definition: MinerAux.h:266
void stopSealingAfterXBlocks(eth::Client *_c, unsigned _start, unsigned &io_mining)
Definition: main.cpp:273
std::function< void(std::string const &, char const *)> g_logPost
The current method that the logging system uses to output the log messages. Defaults to simpleDebugOu...
Definition: Log.cpp:215
void create(std::string const &_pass)
Definition: KeyManager.cpp:56
bool interpretOption(int &i, int argc, char **argv)
Definition: MinerAux.h:107
bool isPrime(unsigned _number)
Definition: main.cpp:243
void setDataDir(std::string const &_dir)
Sets the data dir for the default ("ethereum") prefix.
std::vector< byte > bytes
Definition: Common.h:75
Format
Definition: main.cpp:266
const u256 Invalid256
Definition: Common.cpp:38
u256 storage(Address const &_contract, u256 const &_memory) const
Get the value of a storage position of an account.
Definition: State.cpp:353
Fixed-size raw-byte array container type, with an API optimised for storing hashes.
Definition: FixedHash.h:47
static void exitHandler(int)
Definition: main.cpp:294
Main API hub for interfacing with Ethereum.
Definition: Client.h:75
bool execute(int argc, char **argv)
uses argc, argv provided by the CLI and executes implemented options.
FixedHash< 32 > h256
Definition: FixedHash.h:340
std::lock_guard< SpinLock > SpinGuard
Definition: Guards.h:82
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u256
Definition: Common.h:125
std::string credits()
Definition: MinerAux.h:70
const unsigned SensibleHttpPort
Definition: Eth.cpp:49
string ethCredits(bool _interactive=false)
Definition: main.cpp:179
bool shouldExit() const
Definition: main.cpp:295
#define b(i, j)
Address c_config
Definition: main.cpp:226
bytes rlpList()
Export a list of items in RLP format, returning a byte array.
Definition: RLP.h:470
int g_logVerbosity
The logging system&#39;s current verbosity.
Definition: Log.cpp:37
Add account management functionnalities to CLI.
void setPeerStretch(size_t _n)
Experimental. Sets ceiling for incoming connections to multiple of ideal peer count.
Definition: WebThree.cpp:135
u256 u256Param(std::string const &_name) const
Convenience method to get an otherParam as a u256 int.
JSON-RPC api implementation.
Definition: Eth.h:64
std::string const & genesisInfo(Network _n)
Definition: GenesisInfo.cpp:37
Encapsulation of an ICAP address.
Definition: ICAP.h:45
WebThreeDirect * web3
Definition: shhrpc.cpp:54
PlatformStyle::TableColorType type
Definition: rpcconsole.cpp:61
bool load(std::string const &_pass)
Definition: KeyManager.cpp:88
std::string enode() const override
Get enode string.
Definition: WebThree.h:198
std::string sealEngineName
The chain sealer name: e.g. Ethash, NoProof, BasicAuthority.
virtual void addNode(p2p::NodeID const &_node, bi::tcp::endpoint const &_hostEndpoint) override
Add node to connect to.
Definition: WebThree.cpp:145
#define round(a, b, c, x, mul)
NodeMode
Definition: main.cpp:253
clock::time_point time_point
Definition: bench.h:49
bool sha3(bytesConstRef _input, bytesRef o_output)
Calculate SHA3-256 hash of the given input and load it into the given output.
Definition: SHA3.cpp:214
#define EthGrayBold
Definition: Terminal.h:135
char const * Version
Definition: Common.cpp:36
bool exists() const
Definition: KeyManager.cpp:51
const unsigned SensibleHttpThreads
Definition: Eth.cpp:47
#define e(i)
Definition: sha.cpp:733
bool shouldPrecompute() const
Definition: MinerAux.h:267
FixedHash< 20 > h160
Definition: FixedHash.h:341
const unsigned c_databaseVersion
Current database version.
Definition: Common.cpp:54
virtual unsigned number() const override
Definition: ClientBase.cpp:481
void importPresale(KeyManager &_km, string const &_file, function< string()> _pass)
Definition: main.cpp:220
bytes block(h256 const &_hash) const
Get a block (RLP format) for the given hash (or the most recent mined if none given). Thread-safe.
std::string getPassword(std::string const &_prompt)
Requests the user to enter a password on the console.
Definition: CommonIO.cpp:135
#define d(i)
Definition: sha.cpp:732
UnixDomainSocketServer IpcServer
Definition: IpcServer.h:32
void setIdealPeerCount(size_t _n) override
Sets the ideal number of peers.
Definition: WebThree.cpp:130
bytes contents(std::string const &_file)
Retrieve and returns the contents of the given file.
void setGasPricer(std::shared_ptr< GasPricer > _gp)
Resets the gas pricer to some other object.
Definition: Client.h:94
Class for interpreting Recursive Linear-Prefix Data.
Definition: RLP.h:64
#define DEV_IGNORE_EXCEPTIONS(X)
Definition: Common.h:63
#define EthReset
Definition: Terminal.h:80
bool isFalse(std::string const &_m)
Definition: MinerAux.h:65
int atoi(const std::string &str)
std::string toUUID(h128 const &_uuid)
Definition: FixedHash.cpp:43
void execute()
Definition: MinerAux.h:230
void startNetwork() override
Start the network subsystem.
Definition: WebThree.h:204
bool isTrue(std::string const &_m)
Definition: MinerAux.h:60
ImportResult queueBlock(bytes const &_block, bool _isSafe=false)
Queues a block for import.
Definition: Client.cpp:127
std::unordered_set< h160 > AddressHash
A hash set of Ethereum addresses.
Definition: Common.h:71