Ethereum  PoC-8
The C++ Implementation of Ethereum
State.h
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 */
17 
18 #pragma once
19 
20 #include "Account.h"
21 #include "GasPricer.h"
22 #include "SecureTrieDB.h"
23 #include "Transaction.h"
24 #include "TransactionReceipt.h"
25 #include <libdevcore/Common.h>
26 #include <libdevcore/OverlayDB.h>
27 #include <libdevcore/RLP.h>
28 #include <libethcore/BlockHeader.h>
29 #include <libethcore/Exceptions.h>
31 #include <libevm/ExtVMFace.h>
32 #include <array>
33 #include <unordered_map>
34 
35 namespace dev
36 {
37 
38 namespace test { class ImportTest; class StateLoader; }
39 
40 namespace eth
41 {
42 
43 // Import-specific errinfos
44 using errinfo_uncleIndex = boost::error_info<struct tag_uncleIndex, unsigned>;
45 using errinfo_currentNumber = boost::error_info<struct tag_currentNumber, u256>;
46 using errinfo_uncleNumber = boost::error_info<struct tag_uncleNumber, u256>;
47 using errinfo_unclesExcluded = boost::error_info<struct tag_unclesExcluded, h256Hash>;
48 using errinfo_block = boost::error_info<struct tag_block, bytes>;
49 using errinfo_now = boost::error_info<struct tag_now, unsigned>;
50 
51 using errinfo_transactionIndex = boost::error_info<struct tag_transactionIndex, unsigned>;
52 
53 using errinfo_vmtrace = boost::error_info<struct tag_vmtrace, std::string>;
54 using errinfo_receipts = boost::error_info<struct tag_receipts, std::vector<bytes>>;
55 using errinfo_transaction = boost::error_info<struct tag_transaction, bytes>;
56 using errinfo_phase = boost::error_info<struct tag_phase, unsigned>;
57 using errinfo_required_LogBloom = boost::error_info<struct tag_required_LogBloom, LogBloom>;
58 using errinfo_got_LogBloom = boost::error_info<struct tag_get_LogBloom, LogBloom>;
59 using LogBloomRequirementError = boost::tuple<errinfo_required_LogBloom, errinfo_got_LogBloom>;
60 
61 class BlockChain;
62 class State;
63 class TransactionQueue;
64 struct VerifiedBlockRef;
65 
66 enum class BaseState
67 {
69  Empty
70 };
71 
72 enum class Permanence
73 {
74  Reverted,
75  Committed,
77 };
78 
79 DEV_SIMPLE_EXCEPTION(InvalidAccountStartNonceInState);
80 DEV_SIMPLE_EXCEPTION(IncorrectAccountStartNonceInState);
81 
82 class SealEngineFace;
83 class Executive;
84 
86 struct Change
87 {
88  enum Kind: int
89  {
93 
97 
101 
104 
107 
110 
112  Touch
113  };
114 
120 
122  Change(Kind _kind, Address const& _addr, u256 const& _value = 0):
123  kind(_kind), address(_addr), value(_value)
124  {
125  assert(_kind != Code); // For this the special constructor needs to be used.
126  }
127 
129  Change(Address const& _addr, u256 const& _key, u256 const& _value):
130  kind(Storage), address(_addr), value(_value), key(_key)
131  {}
132 
134  Change(Address const& _addr, u256 const& _value):
135  kind(Nonce), address(_addr), value(_value)
136  {}
137 
139  Change(Address const& _addr, bytes const& _oldCode):
140  kind(Code), address(_addr), oldCode(_oldCode)
141  {}
142 };
143 
144 using ChangeLog = std::vector<Change>;
145 
159 class State
160 {
161  friend class ExtVM;
162  friend class dev::test::ImportTest;
164  friend class BlockChain;
165 
166 public:
167  enum class CommitBehaviour
168  {
171  };
172 
173  using AddressMap = std::map<h256, Address>;
174 
176  explicit State(u256 const& _accountStartNonce): State(_accountStartNonce, OverlayDB(), BaseState::Empty) {}
177 
182  explicit State(u256 const& _accountStartNonce, OverlayDB const& _db, BaseState _bs = BaseState::PreExisting);
183 
184  enum NullType { Null };
186 
188  State(State const& _s);
189 
191  State& operator=(State const& _s);
192 
194  static OverlayDB openDB(boost::filesystem::path const& _path, h256 const& _genesisHash, WithExisting _we = WithExisting::Trust);
195  OverlayDB const& db() const { return m_db; }
196  OverlayDB& db() { return m_db; }
197 
199  void populateFrom(AccountMap const& _map);
200 
204  std::unordered_map<Address, u256> addresses() const;
205 
208  std::pair<AddressMap, h256> addresses(h256 const& _begin, size_t _maxResults) const;
209 
212  std::pair<ExecutionResult, TransactionReceipt> execute(EnvInfo const& _envInfo, SealEngineFace const& _sealEngine, Transaction const& _t, Permanence _p = Permanence::Committed, OnOpFunc const& _onOp = OnOpFunc());
213 
216  void executeBlockTransactions(Block const& _block, unsigned _txCount, LastBlockHashesFace const& _lastHashes, SealEngineFace const& _sealEngine);
217 
219  bool addressInUse(Address const& _address) const;
220 
223  bool accountNonemptyAndExisting(Address const& _address) const;
224 
226  bool addressHasCode(Address const& _address) const;
227 
230  u256 balance(Address const& _id) const;
231 
234  void addBalance(Address const& _id, u256 const& _amount);
235 
239  void subBalance(Address const& _addr, u256 const& _value);
240 
243  void setBalance(Address const& _addr, u256 const& _value);
244 
251  void transferBalance(Address const& _from, Address const& _to, u256 const& _value) { subBalance(_from, _value); addBalance(_to, _value); }
252 
254  h256 storageRoot(Address const& _contract) const;
255 
258  u256 storage(Address const& _contract, u256 const& _memory) const;
259 
261  void setStorage(Address const& _contract, u256 const& _location, u256 const& _value);
262 
266  u256 originalStorageValue(Address const& _contract, u256 const& _key) const;
267 
269  void clearStorage(Address const& _contract);
270 
272  void createContract(Address const& _address);
273 
275  void setCode(Address const& _address, bytes&& _code);
276 
278  void kill(Address _a);
279 
283  std::map<h256, std::pair<u256, u256>> storage(Address const& _contract) const;
284 
289  bytes const& code(Address const& _addr) const;
290 
293  h256 codeHash(Address const& _contract) const;
294 
297  size_t codeSize(Address const& _contract) const;
298 
300  void incNonce(Address const& _id);
301 
303  void setNonce(Address const& _addr, u256 const& _newNonce);
304 
307  u256 getNonce(Address const& _addr) const;
308 
310  h256 rootHash() const { return m_state.root(); }
311 
314  void commit(CommitBehaviour _commitBehaviour);
315 
317  void setRoot(h256 const& _root);
318 
320  u256 const& accountStartNonce() const { return m_accountStartNonce; }
321  u256 const& requireAccountStartNonce() const;
322  void noteAccountStartNonce(u256 const& _actual);
323 
326  size_t savepoint() const;
327 
329  void rollback(size_t _savepoint);
330 
331  ChangeLog const& changeLog() const { return m_changeLog; }
332 
333 private:
335  void removeEmptyAccounts();
336 
339  Account const* account(Address const& _addr) const;
340 
343  Account* account(Address const& _addr);
344 
346  void clearCacheIfTooLarge() const;
347 
348  void createAccount(Address const& _address, Account const&& _account);
349 
352  bool executeTransaction(Executive& _e, Transaction const& _t, OnOpFunc const& _onOp);
353 
355  OverlayDB m_db;
360  mutable std::unordered_map<Address, Account> m_cache;
362  mutable std::vector<Address> m_unchangedCacheEntries;
364  mutable std::set<Address> m_nonExistingAccountsCache;
366  AddressHash m_touched;
367 
368  u256 m_accountStartNonce;
369 
370  friend std::ostream& operator<<(std::ostream& _out, State const& _s);
371  ChangeLog m_changeLog;
372 };
373 
374 std::ostream& operator<<(std::ostream& _out, State const& _s);
375 
376 State& createIntermediateState(State& o_s, Block const& _block, unsigned _txIndex, BlockChain const& _bc);
377 
378 template <class DB>
380 
381 }
382 }
383 
dev::eth::Change::oldCode
bytes oldCode
Code overwritten by CREATE, empty except in case of address collision.
Definition: State.h:119
dev::eth::errinfo_block
boost::error_info< struct tag_block, bytes > errinfo_block
Definition: State.h:48
dev::eth::OnOpFunc
std::function< void(uint64_t, uint64_t, Instruction, bigint, bigint, bigint, VMFace const *, ExtVMFace const *)> OnOpFunc
Definition: ExtVMFace.h:115
dev::eth::Change::address
Address address
Changed account address.
Definition: State.h:116
dev::eth::State::addressInUse
bool addressInUse(Address const &_address) const
Check if the address is in use.
Definition: State.cpp:291
dev::eth::State::rootHash
h256 rootHash() const
The hash of the root of our state tree.
Definition: State.h:310
dev::eth::State::CommitBehaviour::RemoveEmptyAccounts
@ RemoveEmptyAccounts
dev::eth::State::accountStartNonce
u256 const & accountStartNonce() const
Get the account start nonce. May be required.
Definition: State.h:320
dev::eth::Transaction
Encodes a transaction, ready to be exported to or freshly imported from RLP.
Definition: Transaction.h:86
dev::eth::State::subBalance
void subBalance(Address const &_addr, u256 const &_value)
Definition: State.cpp:371
dev::eth::SealEngineFace
Definition: SealEngine.h:46
dev::eth::Change::Change
Change(Address const &_addr, u256 const &_value)
Helper constructor for nonce change log.
Definition: State.h:134
dev::eth::State::setNonce
void setNonce(Address const &_addr, u256 const &_newNonce)
Set the account nonce.
Definition: State.cpp:333
dev::eth::State::openDB
static OverlayDB openDB(boost::filesystem::path const &_path, h256 const &_genesisHash, WithExisting _we=WithExisting::Trust)
Open a DB - useful for passing into the constructor & keeping for other states that are necessary.
Definition: State.cpp:60
dev::eth::State::kill
void kill(Address _a)
Delete an account (used for processing suicides).
Definition: State.cpp:407
dev::eth::Change::Balance
@ Balance
Definition: State.h:92
dev::eth::State::operator<<
friend std::ostream & operator<<(std::ostream &_out, State const &_s)
dev::eth::BaseState::Empty
@ Empty
dev::eth::State::code
bytes const & code(Address const &_addr) const
Definition: State.cpp:503
dev::eth::Permanence
Permanence
Definition: State.h:73
dev::eth::createIntermediateState
State & createIntermediateState(State &o_s, Block const &_block, unsigned _txIndex, BlockChain const &_bc)
Definition: State.cpp:744
dev::eth::ChangeLog
std::vector< Change > ChangeLog
Definition: State.h:144
CodeSizeCache.h
dev::eth::State::noteAccountStartNonce
void noteAccountStartNonce(u256 const &_actual)
Definition: State.cpp:117
Exceptions.h
dev::eth::AccountMap
std::unordered_map< Address, Account > AccountMap
Definition: Account.h:267
dev::eth::Change::Storage
@ Storage
Definition: State.h:96
dev::eth::State::getNonce
u256 getNonce(Address const &_addr) const
Definition: State.cpp:414
dev::eth::Change::value
u256 value
Change value, e.g. balance, storage and nonce.
Definition: State.h:117
dev::eth::commit
AddressHash commit(AccountMap const &_cache, SecureTrieDB< Address, DB > &_state)
Definition: State.cpp:759
dev::eth::State::commit
void commit(CommitBehaviour _commitBehaviour)
Definition: State.cpp:200
dev::eth::State::incNonce
void incNonce(Address const &_id)
Increament the account nonce.
Definition: State.cpp:320
dev::eth::State::codeSize
size_t codeSize(Address const &_contract) const
Definition: State.cpp:534
BlockHeader.h
dev::eth::Change::Touch
@ Touch
Account was touched for the first time.
Definition: State.h:112
dev::eth::State::ImportTest
friend class dev::test::ImportTest
Definition: State.h:162
dev::eth::State::setBalance
void setBalance(Address const &_addr, u256 const &_value)
Definition: State.cpp:385
dev::FixedHash< 20 >
dev::eth::Change::Change
Change(Address const &_addr, bytes const &_oldCode)
Helper constructor especially for new code change log.
Definition: State.h:139
dev::eth::Permanence::Reverted
@ Reverted
dev::eth::State::accountNonemptyAndExisting
bool accountNonemptyAndExisting(Address const &_address) const
Definition: State.cpp:296
dev::eth::State::changeLog
ChangeLog const & changeLog() const
Definition: State.h:331
dev::eth::State::addBalance
void addBalance(Address const &_id, u256 const &_amount)
Definition: State.cpp:346
dev::WithExisting
WithExisting
Definition: Common.h:292
dev::eth::State::clearStorage
void clearStorage(Address const &_contract)
Clear the storage root hash of an account to the hash of the empty trie.
Definition: State.cpp:444
dev::AddressHash
std::unordered_set< h160 > AddressHash
A hash set of Ethereum addresses.
Definition: Address.h:36
dev::WithExisting::Trust
@ Trust
ExtVMFace.h
dev::eth::Change::Create
@ Create
Account was created (it was not existing before).
Definition: State.h:106
dev::eth::State::operator=
State & operator=(State const &_s)
Copy state object.
Definition: State.cpp:132
dev::eth::State::State
State(NullType)
Definition: State.h:185
dev::eth::errinfo_phase
boost::error_info< struct tag_phase, unsigned > errinfo_phase
Definition: State.h:56
Common.h
dev::eth::Permanence::Uncommitted
@ Uncommitted
Uncommitted state for change log readings in tests.
dev::eth::State::executeBlockTransactions
void executeBlockTransactions(Block const &_block, unsigned _txCount, LastBlockHashesFace const &_lastHashes, SealEngineFace const &_sealEngine)
Definition: State.cpp:634
dev::eth::Change::Code
@ Code
New code was added to an account (by "create" message execution).
Definition: State.h:109
TransactionReceipt.h
dev::OnFailed::Empty
@ Empty
dev::eth::State::populateFrom
void populateFrom(AccountMap const &_map)
Populate the state from the given AccountMap. Just uses dev::eth::commit().
Definition: State.cpp:104
dev::eth::Change::kind
Kind kind
The kind of the change.
Definition: State.h:115
dev::eth::errinfo_vmtrace
boost::error_info< struct tag_vmtrace, std::string > errinfo_vmtrace
Definition: State.h:53
dev::eth::errinfo_got_LogBloom
boost::error_info< struct tag_get_LogBloom, LogBloom > errinfo_got_LogBloom
Definition: State.h:58
dev::eth::errinfo_transactionIndex
boost::error_info< struct tag_transactionIndex, unsigned > errinfo_transactionIndex
Definition: State.h:51
dev::bytes
std::vector< byte > bytes
Definition: Common.h:72
dev::eth::errinfo_uncleNumber
boost::error_info< struct tag_uncleNumber, u256 > errinfo_uncleNumber
Definition: State.h:46
Transaction.h
dev::eth::Change::Change
Change(Address const &_addr, u256 const &_key, u256 const &_value)
Helper constructor especially for storage change log.
Definition: State.h:129
GasPricer.h
dev::eth::Executive
Message-call/contract-creation executor; useful for executing transactions.
Definition: Executive.h:104
dev::eth::BlockChain
Implements the blockchain database. All data this gives is disk-backed. @threadsafe.
Definition: BlockChain.h:105
dev::eth::State::CommitBehaviour::KeepEmptyAccounts
@ KeepEmptyAccounts
dev::eth::ExtVM
Externality interface for the Virtual Machine providing access to world state.
Definition: ExtVM.h:39
dev::OverlayDB
Definition: OverlayDB.h:34
dev::eth::State::State
State(u256 const &_accountStartNonce)
Default constructor; creates with a blank database prepopulated with the genesis block.
Definition: State.h:176
SecureTrieDB.h
dev::eth::State::addressHasCode
bool addressHasCode(Address const &_address) const
Check if the address contains executable code.
Definition: State.cpp:304
dev::Invalid256
constexpr u256 Invalid256
Definition: Common.h:147
dev::eth::errinfo_uncleIndex
boost::error_info< struct tag_uncleIndex, unsigned > errinfo_uncleIndex
Definition: State.h:44
dev::eth::TransactionQueue
A queue of Transactions, each stored as RLP. Maintains a transaction queue sorted by nonce diff and g...
Definition: TransactionQueue.h:45
dev::eth::Change::Kind
Kind
Definition: State.h:89
dev::eth::Change::Nonce
@ Nonce
Account nonce was changed.
Definition: State.h:103
dev::eth::Change::Change
Change(Kind _kind, Address const &_addr, u256 const &_value=0)
Helper constructor to make change log update more readable.
Definition: State.h:122
dev::eth::Change
An atomic state changelog entry.
Definition: State.h:87
dev::eth::BaseState
BaseState
Definition: State.h:67
dev::eth::State::db
OverlayDB const & db() const
Definition: State.h:195
dev::eth::State::AddressMap
std::map< h256, Address > AddressMap
Definition: State.h:173
dev::eth::State::NullType
NullType
Definition: State.h:184
dev::eth::State::transferBalance
void transferBalance(Address const &_from, Address const &_to, u256 const &_value)
Transfers "the balance _value between two accounts.
Definition: State.h:251
dev::eth::State::requireAccountStartNonce
u256 const & requireAccountStartNonce() const
Definition: State.cpp:110
dev::eth::State::Null
@ Null
Definition: State.h:184
dev::eth::errinfo_unclesExcluded
boost::error_info< struct tag_unclesExcluded, h256Hash > errinfo_unclesExcluded
Definition: State.h:47
dev::eth::State::setStorage
void setStorage(Address const &_contract, u256 const &_location, u256 const &_value)
Set the value of a storage position of an account.
Definition: State.cpp:430
OverlayDB.h
dev::eth::Permanence::Committed
@ Committed
dev::eth::State
Definition: State.h:160
dev::u256
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void > > u256
Definition: Common.h:121
dev::eth::State::savepoint
size_t savepoint() const
Definition: State.cpp:555
dev::eth::errinfo_transaction
boost::error_info< struct tag_transaction, bytes > errinfo_transaction
Definition: State.h:55
dev::eth::Change::StorageRoot
@ StorageRoot
Definition: State.h:100
dev::eth::State::storageRoot
h256 storageRoot(Address const &_contract) const
Get the root of the storage of an account.
Definition: State.cpp:492
dev::eth::errinfo_receipts
boost::error_info< struct tag_receipts, std::vector< bytes > > errinfo_receipts
Definition: State.h:54
dev::eth::operator<<
std::ostream & operator<<(std::ostream &_out, BlockHeader const &_bi)
Definition: BlockHeader.h:217
dev::eth::State::originalStorageValue
u256 originalStorageValue(Address const &_contract, u256 const &_key) const
Definition: State.cpp:436
dev::eth::errinfo_currentNumber
boost::error_info< struct tag_currentNumber, u256 > errinfo_currentNumber
Definition: State.h:45
dev::eth::VerifiedBlockRef
Verified block info, does not hold block data, but a reference instead.
Definition: VerifiedBlock.h:37
dev::eth::Change::key
u256 key
Storage key. Last because used only in one case.
Definition: State.h:118
dev::eth::State::setRoot
void setRoot(h256 const &_root)
Resets any uncommitted changes to the cache.
Definition: State.cpp:282
dev::eth::DEV_SIMPLE_EXCEPTION
DEV_SIMPLE_EXCEPTION(NoHashRecorded)
dev::eth::State::addresses
std::unordered_map< Address, u256 > addresses() const
Definition: State.cpp:210
dev
Definition: Address.cpp:21
dev::eth::State::setCode
void setCode(Address const &_address, bytes &&_code)
Sets the code of the account. Must only be called during / after contract creation.
Definition: State.cpp:520
dev::eth::State::StateLoader
friend class dev::test::StateLoader
Definition: State.h:163
dev::eth::State::balance
u256 balance(Address const &_id) const
Definition: State.cpp:312
dev::eth::State::codeHash
h256 codeHash(Address const &_contract) const
Definition: State.cpp:526
dev::eth::BaseState::PreExisting
@ PreExisting
Account.h
dev::eth::State::rollback
void rollback(size_t _savepoint)
Revert all recent changes up to the given _savepoint savepoint.
Definition: State.cpp:560
dev::eth::errinfo_now
boost::error_info< struct tag_now, unsigned > errinfo_now
Definition: State.h:49
dev::eth::State::db
OverlayDB & db()
Definition: State.h:196
dev::eth::State::execute
std::pair< ExecutionResult, TransactionReceipt > execute(EnvInfo const &_envInfo, SealEngineFace const &_sealEngine, Transaction const &_t, Permanence _p=Permanence::Committed, OnOpFunc const &_onOp=OnOpFunc())
Definition: State.cpp:598
dev::eth::State::storage
u256 storage(Address const &_contract, u256 const &_memory) const
Definition: State.cpp:422
dev::eth::State::CommitBehaviour
CommitBehaviour
Definition: State.h:168
dev::eth::State::createContract
void createContract(Address const &_address)
Create a contract at the given address (with unset code and unchanged balance).
Definition: State.cpp:394
dev::eth::EnvInfo
Definition: ExtVMFace.h:143
dev::eth::LastBlockHashesFace
Interface for getting a list of recent block hashes @threadsafe.
Definition: LastBlockHashesFace.h:37
dev::eth::errinfo_required_LogBloom
boost::error_info< struct tag_required_LogBloom, LogBloom > errinfo_required_LogBloom
Definition: State.h:57
RLP.h
dev::SpecificTrieDB
Definition: TrieDB.h:318
dev::eth::Block
Active model of a block within the block chain. Keeps track of all transactions, receipts and state f...
Definition: Block.h:69
dev::eth::Account
Definition: Account.h:57
dev::eth::LogBloomRequirementError
boost::tuple< errinfo_required_LogBloom, errinfo_got_LogBloom > LogBloomRequirementError
Definition: State.h:59