State.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. /*
  2. This file is part of cpp-ethereum.
  3. cpp-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. cpp-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /** @file State.cpp
  15. * @author Gav Wood <i@gavwood.com>
  16. * @date 2014
  17. */
  18. #include "State.h"
  19. #include <ctime>
  20. #include <boost/filesystem.hpp>
  21. #include <boost/timer.hpp>
  22. #include <libdevcore/CommonIO.h>
  23. #include <libdevcore/Assertions.h>
  24. #include <libdevcore/TrieHash.h>
  25. #include <libevmcore/Instruction.h>
  26. #include <libethcore/Exceptions.h>
  27. #include <libevm/VMFactory.h>
  28. #include "BlockChain.h"
  29. #include "CodeSizeCache.h"
  30. #include "Defaults.h"
  31. #include "ExtVM.h"
  32. #include "Executive.h"
  33. #include "BlockChain.h"
  34. #include "TransactionQueue.h"
  35. using namespace std;
  36. using namespace dev;
  37. using namespace dev::eth;
  38. namespace fs = boost::filesystem;
  39. const char* StateSafeExceptions::name() { return EthViolet "⚙" EthBlue " ℹ"; }
  40. const char* StateDetail::name() { return EthViolet "⚙" EthWhite " ◌"; }
  41. const char* StateTrace::name() { return EthViolet "⚙" EthGray " ◎"; }
  42. const char* StateChat::name() { return EthViolet "⚙" EthWhite " ◌"; }
  43. State::State(u256 const& _accountStartNonce, OverlayDB const& _db, BaseState _bs):
  44. m_db(_db),
  45. m_state(&m_db),
  46. m_accountStartNonce(_accountStartNonce)
  47. {
  48. if (_bs != BaseState::PreExisting)
  49. // Initialise to the state entailed by the genesis block; this guarantees the trie is built correctly.
  50. m_state.init();
  51. paranoia("end of normal construction.", true);
  52. }
  53. State::State(State const& _s):
  54. m_db(_s.m_db),
  55. m_state(&m_db, _s.m_state.root(), Verification::Skip),
  56. m_cache(_s.m_cache),
  57. m_unchangedCacheEntries(_s.m_unchangedCacheEntries),
  58. m_touched(_s.m_touched),
  59. m_accountStartNonce(_s.m_accountStartNonce)
  60. {
  61. paranoia("after state cloning (copy cons).", true);
  62. }
  63. OverlayDB State::openDB(std::string const& _basePath, h256 const& _genesisHash, WithExisting _we)
  64. {
  65. std::string path = _basePath.empty() ? Defaults::get()->m_dbPath : _basePath;
  66. if (_we == WithExisting::Kill)
  67. {
  68. cnote << "Killing state database (WithExisting::Kill).";
  69. boost::filesystem::remove_all(path + "/state");
  70. }
  71. path += "/" + toHex(_genesisHash.ref().cropped(0, 4)) + "/" + toString(c_databaseVersion);
  72. boost::filesystem::create_directories(path);
  73. DEV_IGNORE_EXCEPTIONS(fs::permissions(path, fs::owner_all));
  74. ldb::Options o;
  75. o.max_open_files = 256;
  76. o.create_if_missing = true;
  77. ldb::DB* db = nullptr;
  78. ldb::Status status = ldb::DB::Open(o, path + "/state", &db);
  79. if (!status.ok() || !db)
  80. {
  81. if (boost::filesystem::space(path + "/state").available < 1024)
  82. {
  83. cwarn << "Not enough available space found on hard drive. Please free some up and then re-run. Bailing.";
  84. BOOST_THROW_EXCEPTION(NotEnoughAvailableSpace());
  85. }
  86. else
  87. {
  88. cwarn << status.ToString();
  89. cwarn <<
  90. "Database " <<
  91. (path + "/state") <<
  92. "already open. You appear to have another instance of ethereum running. Bailing.";
  93. BOOST_THROW_EXCEPTION(DatabaseAlreadyOpen());
  94. }
  95. }
  96. ctrace << "Opened state DB.";
  97. return OverlayDB(db);
  98. }
  99. void State::populateFrom(AccountMap const& _map)
  100. {
  101. eth::commit(_map, m_state);
  102. commit(State::CommitBehaviour::KeepEmptyAccounts);
  103. }
  104. u256 const& State::requireAccountStartNonce() const
  105. {
  106. if (m_accountStartNonce == Invalid256)
  107. BOOST_THROW_EXCEPTION(InvalidAccountStartNonceInState());
  108. return m_accountStartNonce;
  109. }
  110. void State::noteAccountStartNonce(u256 const& _actual)
  111. {
  112. if (m_accountStartNonce == Invalid256)
  113. m_accountStartNonce = _actual;
  114. else if (m_accountStartNonce != _actual)
  115. BOOST_THROW_EXCEPTION(IncorrectAccountStartNonceInState());
  116. }
  117. void State::removeEmptyAccounts()
  118. {
  119. for (auto& i: m_cache)
  120. if (i.second.isDirty() && i.second.isEmpty())
  121. i.second.kill();
  122. }
  123. void State::paranoia(std::string const& _when, bool _enforceRefs) const
  124. {
  125. #if ETH_PARANOIA && !ETH_FATDB
  126. // TODO: variable on context; just need to work out when there should be no leftovers
  127. // [in general this is hard since contract alteration will result in nodes in the DB that are no directly part of the state DB].
  128. if (!isTrieGood(_enforceRefs, false))
  129. {
  130. cwarn << "BAD TRIE" << _when;
  131. BOOST_THROW_EXCEPTION(InvalidTrie());
  132. }
  133. #else
  134. (void)_when;
  135. (void)_enforceRefs;
  136. #endif
  137. }
  138. State& State::operator=(State const& _s)
  139. {
  140. if (&_s == this)
  141. return *this;
  142. m_db = _s.m_db;
  143. m_state.open(&m_db, _s.m_state.root(), Verification::Skip);
  144. m_cache = _s.m_cache;
  145. m_unchangedCacheEntries = _s.m_unchangedCacheEntries;
  146. m_touched = _s.m_touched;
  147. m_accountStartNonce = _s.m_accountStartNonce;
  148. paranoia("after state cloning (assignment op)", true);
  149. return *this;
  150. }
  151. Account const* State::account(Address const& _a, bool _requireCode) const
  152. {
  153. return const_cast<State*>(this)->account(_a, _requireCode);
  154. }
  155. Account* State::account(Address const& _a, bool _requireCode)
  156. {
  157. Account *a = nullptr;
  158. auto it = m_cache.find(_a);
  159. if (it != m_cache.end())
  160. a = &it->second;
  161. else
  162. {
  163. // populate basic info.
  164. string stateBack = m_state.at(_a);
  165. if (stateBack.empty())
  166. return nullptr;
  167. clearCacheIfTooLarge();
  168. RLP state(stateBack);
  169. m_cache[_a] = Account(state[0].toInt<u256>(), state[1].toInt<u256>(), state[2].toHash<h256>(), state[3].toHash<h256>(), Account::Unchanged);
  170. m_unchangedCacheEntries.push_back(_a);
  171. a = &m_cache[_a];
  172. }
  173. if (_requireCode && a && !a->isFreshCode() && !a->codeCacheValid())
  174. {
  175. a->noteCode(a->codeHash() == EmptySHA3 ? bytesConstRef() : bytesConstRef(m_db.lookup(a->codeHash())));
  176. CodeSizeCache::instance().store(a->codeHash(), a->code().size());
  177. }
  178. return a;
  179. }
  180. void State::clearCacheIfTooLarge() const
  181. {
  182. // TODO: Find a good magic number
  183. while (m_unchangedCacheEntries.size() > 1000)
  184. {
  185. // Remove a random element
  186. size_t const randomIndex = boost::random::uniform_int_distribution<size_t>(0, m_unchangedCacheEntries.size() - 1)(dev::s_fixedHashEngine);
  187. Address const addr = m_unchangedCacheEntries[randomIndex];
  188. swap(m_unchangedCacheEntries[randomIndex], m_unchangedCacheEntries.back());
  189. m_unchangedCacheEntries.pop_back();
  190. auto cacheEntry = m_cache.find(addr);
  191. if (cacheEntry != m_cache.end() && !cacheEntry->second.isDirty())
  192. m_cache.erase(cacheEntry);
  193. }
  194. }
  195. void State::commit(CommitBehaviour _commitBehaviour)
  196. {
  197. if (_commitBehaviour == CommitBehaviour::RemoveEmptyAccounts)
  198. removeEmptyAccounts();
  199. m_touched += dev::eth::commit(m_cache, m_state);
  200. m_cache.clear();
  201. m_unchangedCacheEntries.clear();
  202. }
  203. unordered_map<Address, u256> State::addresses() const
  204. {
  205. #if ETH_FATDB
  206. unordered_map<Address, u256> ret;
  207. for (auto i: m_cache)
  208. if (i.second.isAlive())
  209. ret[i.first] = i.second.balance();
  210. for (auto const& i: m_state)
  211. if (m_cache.find(i.first) == m_cache.end())
  212. ret[i.first] = RLP(i.second)[1].toInt<u256>();
  213. return ret;
  214. #else
  215. BOOST_THROW_EXCEPTION(InterfaceNotSupported("State::addresses()"));
  216. #endif
  217. }
  218. void State::setRoot(h256 const& _r)
  219. {
  220. m_cache.clear();
  221. m_unchangedCacheEntries.clear();
  222. // m_touched.clear();
  223. m_state.setRoot(_r);
  224. paranoia("begin setRoot", true);
  225. }
  226. bool State::addressInUse(Address const& _id) const
  227. {
  228. return !!account(_id);
  229. }
  230. bool State::accountNonemptyAndExisting(Address const& _address) const
  231. {
  232. if (Account const* a = account(_address))
  233. return !a->isEmpty();
  234. else
  235. return false;
  236. }
  237. bool State::addressHasCode(Address const& _id) const
  238. {
  239. if (auto a = account(_id))
  240. return a->isFreshCode() || a->codeHash() != EmptySHA3;
  241. else
  242. return false;
  243. }
  244. u256 State::balance(Address const& _id) const
  245. {
  246. if (auto a = account(_id))
  247. return a->balance();
  248. else
  249. return 0;
  250. }
  251. void State::incNonce(Address const& _addr)
  252. {
  253. if (Account* a = account(_addr))
  254. a->incNonce();
  255. else
  256. // This is possible if a transaction has gas price 0.
  257. m_cache[_addr] = Account(requireAccountStartNonce() + 1, 0);
  258. }
  259. void State::addBalance(Address const& _id, u256 const& _amount)
  260. {
  261. if (Account* a = account(_id))
  262. a->addBalance(_amount);
  263. else
  264. m_cache[_id] = Account(requireAccountStartNonce(), _amount, Account::NormalCreation);
  265. }
  266. void State::subBalance(Address const& _id, bigint const& _amount)
  267. {
  268. if (_amount == 0)
  269. return;
  270. Account* a = account(_id);
  271. if (!a || a->balance() < _amount)
  272. BOOST_THROW_EXCEPTION(NotEnoughCash());
  273. else
  274. a->addBalance(-_amount);
  275. }
  276. void State::createContract(Address const& _address, bool _incrementNonce)
  277. {
  278. m_cache[_address] = Account(
  279. requireAccountStartNonce() + (_incrementNonce ? 1 : 0),
  280. balance(_address),
  281. Account::ContractConception
  282. );
  283. }
  284. void State::ensureAccountExists(const Address& _address)
  285. {
  286. if (!addressInUse(_address))
  287. m_cache[_address] = Account(requireAccountStartNonce(), 0, Account::NormalCreation);
  288. }
  289. void State::kill(Address _addr)
  290. {
  291. if (auto a = account(_addr))
  292. a->kill();
  293. // If the account is not in the db, nothing to kill.
  294. }
  295. u256 State::getNonce(Address const& _addr) const
  296. {
  297. if (auto a = account(_addr))
  298. return a->nonce();
  299. else
  300. return m_accountStartNonce;
  301. }
  302. u256 State::storage(Address const& _id, u256 const& _key) const
  303. {
  304. if (Account const* a = account(_id))
  305. {
  306. auto mit = a->storageOverlay().find(_key);
  307. if (mit != a->storageOverlay().end())
  308. return mit->second;
  309. // Not in the storage cache - go to the DB.
  310. SecureTrieDB<h256, OverlayDB> memdb(const_cast<OverlayDB*>(&m_db), a->baseRoot()); // promise we won't change the overlay! :)
  311. string payload = memdb.at(_key);
  312. u256 ret = payload.size() ? RLP(payload).toInt<u256>() : 0;
  313. a->setStorageCache(_key, ret);
  314. return ret;
  315. }
  316. else
  317. return 0;
  318. }
  319. map<u256, u256> State::storage(Address const& _id) const
  320. {
  321. map<u256, u256> ret;
  322. if (Account const* a = account(_id))
  323. {
  324. // Pull out all values from trie storage.
  325. if (h256 root = a->baseRoot())
  326. {
  327. SecureTrieDB<h256, OverlayDB> memdb(const_cast<OverlayDB*>(&m_db), root); // promise we won't alter the overlay! :)
  328. for (auto const& i: memdb)
  329. ret[i.first] = RLP(i.second).toInt<u256>();
  330. }
  331. // Then merge cached storage over the top.
  332. for (auto const& i: a->storageOverlay())
  333. if (i.second)
  334. ret[i.first] = i.second;
  335. else
  336. ret.erase(i.first);
  337. }
  338. return ret;
  339. }
  340. h256 State::storageRoot(Address const& _id) const
  341. {
  342. string s = m_state.at(_id);
  343. if (s.size())
  344. {
  345. RLP r(s);
  346. return r[2].toHash<h256>();
  347. }
  348. return EmptyTrie;
  349. }
  350. bytes const& State::code(Address const& _a) const
  351. {
  352. if (!addressHasCode(_a))
  353. return NullBytes;
  354. return account(_a, true)->code();
  355. }
  356. h256 State::codeHash(Address const& _a) const
  357. {
  358. if (Account const* a = account(_a))
  359. {
  360. if (a->isFreshCode())
  361. return sha3(a->code());
  362. else
  363. return a->codeHash();
  364. }
  365. else
  366. return EmptySHA3;
  367. }
  368. size_t State::codeSize(Address const& _a) const
  369. {
  370. if (Account const* a = account(_a))
  371. {
  372. if (a->isFreshCode())
  373. return code(_a).size();
  374. auto& codeSizeCache = CodeSizeCache::instance();
  375. h256 codeHash = a->codeHash();
  376. if (codeSizeCache.contains(codeHash))
  377. return codeSizeCache.get(codeHash);
  378. else
  379. {
  380. size_t size = code(_a).size();
  381. codeSizeCache.store(codeHash, size);
  382. return size;
  383. }
  384. }
  385. else
  386. return 0;
  387. }
  388. bool State::isTrieGood(bool _enforceRefs, bool _requireNoLeftOvers) const
  389. {
  390. for (int e = 0; e < (_enforceRefs ? 2 : 1); ++e)
  391. try
  392. {
  393. EnforceRefs r(m_db, !!e);
  394. auto lo = m_state.leftOvers();
  395. if (!lo.empty() && _requireNoLeftOvers)
  396. {
  397. cwarn << "LEFTOVERS" << (e ? "[enforced" : "[unenforced") << "refs]";
  398. cnote << "Left:" << lo;
  399. cnote << "Keys:" << m_db.keys();
  400. m_state.debugStructure(cerr);
  401. return false;
  402. }
  403. // TODO: Enable once fixed.
  404. /* for (auto const& i: m_state)
  405. {
  406. RLP r(i.second);
  407. SecureTrieDB<h256, OverlayDB> storageDB(const_cast<OverlayDB*>(&m_db), r[2].toHash<h256>()); // promise not to alter OverlayDB.
  408. for (auto const& j: storageDB) { (void)j; }
  409. if (!e && r[3].toHash<h256>() != EmptySHA3 && m_db.lookup(r[3].toHash<h256>()).empty())
  410. return false;
  411. }*/
  412. }
  413. catch (InvalidTrie const&)
  414. {
  415. cwarn << "BAD TRIE" << (e ? "[enforced" : "[unenforced") << "refs]";
  416. cnote << m_db.keys();
  417. m_state.debugStructure(cerr);
  418. return false;
  419. }
  420. return true;
  421. }
  422. std::pair<ExecutionResult, TransactionReceipt> State::execute(EnvInfo const& _envInfo, SealEngineFace const& _sealEngine, Transaction const& _t, Permanence _p, OnOpFunc const& _onOp)
  423. {
  424. auto onOp = _onOp;
  425. #if ETH_VMTRACE
  426. if (isChannelVisible<VMTraceChannel>())
  427. onOp = Executive::simpleTrace(); // override tracer
  428. #endif
  429. #if ETH_PARANOIA
  430. paranoia("start of execution.", true);
  431. State old(*this);
  432. auto h = rootHash();
  433. #endif
  434. // Create and initialize the executive. This will throw fairly cheaply and quickly if the
  435. // transaction is bad in any way.
  436. Executive e(*this, _envInfo, _sealEngine);
  437. ExecutionResult res;
  438. e.setResultRecipient(res);
  439. e.initialize(_t);
  440. // OK - transaction looks valid - execute.
  441. u256 startGasUsed = _envInfo.gasUsed();
  442. #if ETH_PARANOIA
  443. ctrace << "Executing" << e.t() << "on" << h;
  444. ctrace << toHex(e.t().rlp());
  445. #endif
  446. if (!e.execute())
  447. e.go(onOp);
  448. e.finalize();
  449. #if ETH_PARANOIA
  450. ctrace << "Ready for commit;";
  451. ctrace << old.diff(*this);
  452. #endif
  453. if (_p == Permanence::Reverted)
  454. m_cache.clear();
  455. else
  456. {
  457. bool removeEmptyAccounts = _envInfo.number() >= _sealEngine.chainParams().u256Param("EIP158ForkBlock");
  458. commit(removeEmptyAccounts ? State::CommitBehaviour::RemoveEmptyAccounts : State::CommitBehaviour::KeepEmptyAccounts);
  459. #if ETH_PARANOIA && !ETH_FATDB
  460. ctrace << "Executed; now" << rootHash();
  461. ctrace << old.diff(*this);
  462. paranoia("after execution commit.", true);
  463. if (e.t().receiveAddress())
  464. {
  465. EnforceRefs r(m_db, true);
  466. if (storageRoot(e.t().receiveAddress()) && m_db.lookup(storageRoot(e.t().receiveAddress())).empty())
  467. {
  468. cwarn << "TRIE immediately after execution; no node for receiveAddress";
  469. BOOST_THROW_EXCEPTION(InvalidTrie());
  470. }
  471. }
  472. #endif
  473. // TODO: CHECK TRIE after level DB flush to make sure exactly the same.
  474. }
  475. return make_pair(res, TransactionReceipt(rootHash(), startGasUsed + e.gasUsed(), e.logs()));
  476. }
  477. std::ostream& dev::eth::operator<<(std::ostream& _out, State const& _s)
  478. {
  479. _out << "--- " << _s.rootHash() << std::endl;
  480. std::set<Address> d;
  481. std::set<Address> dtr;
  482. auto trie = SecureTrieDB<Address, OverlayDB>(const_cast<OverlayDB*>(&_s.m_db), _s.rootHash());
  483. for (auto i: trie)
  484. d.insert(i.first), dtr.insert(i.first);
  485. for (auto i: _s.m_cache)
  486. d.insert(i.first);
  487. for (auto i: d)
  488. {
  489. auto it = _s.m_cache.find(i);
  490. Account* cache = it != _s.m_cache.end() ? &it->second : nullptr;
  491. string rlpString = dtr.count(i) ? trie.at(i) : "";
  492. RLP r(rlpString);
  493. assert(cache || r);
  494. if (cache && !cache->isAlive())
  495. _out << "XXX " << i << std::endl;
  496. else
  497. {
  498. string lead = (cache ? r ? " * " : " + " : " ");
  499. if (cache && r && cache->nonce() == r[0].toInt<u256>() && cache->balance() == r[1].toInt<u256>())
  500. lead = " . ";
  501. stringstream contout;
  502. if ((cache && cache->codeBearing()) || (!cache && r && (h256)r[3] != EmptySHA3))
  503. {
  504. std::map<u256, u256> mem;
  505. std::set<u256> back;
  506. std::set<u256> delta;
  507. std::set<u256> cached;
  508. if (r)
  509. {
  510. SecureTrieDB<h256, OverlayDB> memdb(const_cast<OverlayDB*>(&_s.m_db), r[2].toHash<h256>()); // promise we won't alter the overlay! :)
  511. for (auto const& j: memdb)
  512. mem[j.first] = RLP(j.second).toInt<u256>(), back.insert(j.first);
  513. }
  514. if (cache)
  515. for (auto const& j: cache->storageOverlay())
  516. {
  517. if ((!mem.count(j.first) && j.second) || (mem.count(j.first) && mem.at(j.first) != j.second))
  518. mem[j.first] = j.second, delta.insert(j.first);
  519. else if (j.second)
  520. cached.insert(j.first);
  521. }
  522. if (!delta.empty())
  523. lead = (lead == " . ") ? "*.* " : "*** ";
  524. contout << " @:";
  525. if (!delta.empty())
  526. contout << "???";
  527. else
  528. contout << r[2].toHash<h256>();
  529. if (cache && cache->isFreshCode())
  530. contout << " $" << toHex(cache->code());
  531. else
  532. contout << " $" << (cache ? cache->codeHash() : r[3].toHash<h256>());
  533. for (auto const& j: mem)
  534. if (j.second)
  535. contout << std::endl << (delta.count(j.first) ? back.count(j.first) ? " * " : " + " : cached.count(j.first) ? " . " : " ") << std::hex << nouppercase << std::setw(64) << j.first << ": " << std::setw(0) << j.second ;
  536. else
  537. contout << std::endl << "XXX " << std::hex << nouppercase << std::setw(64) << j.first << "";
  538. }
  539. else
  540. contout << " [SIMPLE]";
  541. _out << lead << i << ": " << std::dec << (cache ? cache->nonce() : r[0].toInt<u256>()) << " #:" << (cache ? cache->balance() : r[1].toInt<u256>()) << contout.str() << std::endl;
  542. }
  543. }
  544. return _out;
  545. }