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 
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>
379 AddressHash commit(AccountMap const& _cache, SecureTrieDB<Address, DB>& _state);
380 
381 }
382 }
383 
u256 getNonce(Address const &_addr) const
Definition: State.cpp:414
State(u256 const &_accountStartNonce)
Default constructor; creates with a blank database prepopulated with the genesis block.
Definition: State.h:176
u256 originalStorageValue(Address const &_contract, u256 const &_key) const
Definition: State.cpp:436
std::unordered_map< Address, u256 > addresses() const
Definition: State.cpp:210
Definition: Address.cpp:20
boost::error_info< struct tag_block, bytes > errinfo_block
Definition: State.h:48
bytes const & code(Address const &_addr) const
Definition: State.cpp:503
boost::error_info< struct tag_unclesExcluded, h256Hash > errinfo_unclesExcluded
Definition: State.h:47
u256 storage(Address const &_contract, u256 const &_memory) const
Definition: State.cpp:422
std::function< void(uint64_t, uint64_t, Instruction, bigint, bigint, bigint, VMFace const *, ExtVMFace const *)> OnOpFunc
Definition: ExtVMFace.h:115
void commit(CommitBehaviour _commitBehaviour)
Definition: State.cpp:200
A queue of Transactions, each stored as RLP. Maintains a transaction queue sorted by nonce diff and g...
std::unordered_map< Address, Account > AccountMap
Definition: Account.h:267
Address address
Changed account address.
Definition: State.h:116
boost::error_info< struct tag_uncleIndex, unsigned > errinfo_uncleIndex
Definition: State.h:44
Implements the blockchain database. All data this gives is disk-backed. .
Definition: BlockChain.h:104
void noteAccountStartNonce(u256 const &_actual)
Definition: State.cpp:117
std::ostream & operator<<(std::ostream &_out, BlockHeader const &_bi)
Definition: BlockHeader.h:217
void rollback(size_t _savepoint)
Revert all recent changes up to the given _savepoint savepoint.
Definition: State.cpp:560
boost::error_info< struct tag_transaction, bytes > errinfo_transaction
Definition: State.h:55
ChangeLog const & changeLog() const
Definition: State.h:331
void clearStorage(Address const &_contract)
Clear the storage root hash of an account to the hash of the empty trie.
Definition: State.cpp:444
boost::error_info< struct tag_currentNumber, u256 > errinfo_currentNumber
Definition: State.h:45
friend class dev::test::StateLoader
Definition: State.h:163
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
std::vector< Change > ChangeLog
Definition: State.h:144
Interface for getting a list of recent block hashes .
Change(Address const &_addr, u256 const &_value)
Helper constructor for nonce change log.
Definition: State.h:134
New code was added to an account (by "create" message execution).
Definition: State.h:109
Account was touched for the first time.
Definition: State.h:112
void populateFrom(AccountMap const &_map)
Populate the state from the given AccountMap. Just uses dev::eth::commit().
Definition: State.cpp:104
boost::error_info< struct tag_phase, unsigned > errinfo_phase
Definition: State.h:56
u256 value
Change value, e.g. balance, storage and nonce.
Definition: State.h:117
u256 const & accountStartNonce() const
Get the account start nonce. May be required.
Definition: State.h:320
WithExisting
Definition: Common.h:291
Active model of a block within the block chain. Keeps track of all transactions, receipts and state f...
Definition: Block.h:68
void kill(Address _a)
Delete an account (used for processing suicides).
Definition: State.cpp:407
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
Kind kind
The kind of the change.
Definition: State.h:115
void createContract(Address const &_address)
Create a contract at the given address (with unset code and unchanged balance).
Definition: State.cpp:394
bool addressInUse(Address const &_address) const
Check if the address is in use.
Definition: State.cpp:291
BaseState
Definition: State.h:66
u256 constexpr Invalid256
Definition: Common.h:147
Change(Address const &_addr, bytes const &_oldCode)
Helper constructor especially for new code change log.
Definition: State.h:139
void setBalance(Address const &_addr, u256 const &_value)
Definition: State.cpp:385
boost::error_info< struct tag_receipts, std::vector< bytes > > errinfo_receipts
Definition: State.h:54
std::vector< byte > bytes
Definition: Common.h:72
boost::error_info< struct tag_vmtrace, std::string > errinfo_vmtrace
Definition: State.h:53
h256 storageRoot(Address const &_contract) const
Get the root of the storage of an account.
Definition: State.cpp:492
friend std::ostream & operator<<(std::ostream &_out, State const &_s)
bool addressHasCode(Address const &_address) const
Check if the address contains executable code.
Definition: State.cpp:304
Message-call/contract-creation executor; useful for executing transactions.
Definition: Executive.h:103
Change(Kind _kind, Address const &_addr, u256 const &_value=0)
Helper constructor to make change log update more readable.
Definition: State.h:122
boost::error_info< struct tag_required_LogBloom, LogBloom > errinfo_required_LogBloom
Definition: State.h:57
u256 balance(Address const &_id) const
Definition: State.cpp:312
Encodes a transaction, ready to be exported to or freshly imported from RLP.
Definition: Transaction.h:85
Account nonce was changed.
Definition: State.h:103
void setRoot(h256 const &_root)
Resets any uncommitted changes to the cache.
Definition: State.cpp:282
std::map< h256, Address > AddressMap
Definition: State.h:173
OverlayDB & db()
Definition: State.h:196
size_t savepoint() const
Definition: State.cpp:555
State & operator=(State const &_s)
Copy state object.
Definition: State.cpp:132
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void > > u256
Definition: Common.h:121
u256 const & requireAccountStartNonce() const
Definition: State.cpp:110
State(NullType)
Definition: State.h:185
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
Change(Address const &_addr, u256 const &_key, u256 const &_value)
Helper constructor especially for storage change log.
Definition: State.h:129
u256 key
Storage key. Last because used only in one case.
Definition: State.h:118
Verified block info, does not hold block data, but a reference instead.
Definition: VerifiedBlock.h:36
void addBalance(Address const &_id, u256 const &_amount)
Definition: State.cpp:346
boost::error_info< struct tag_now, unsigned > errinfo_now
Definition: State.h:49
Externality interface for the Virtual Machine providing access to world state.
Definition: ExtVM.h:38
DEV_SIMPLE_EXCEPTION(NoHashRecorded)
Uncommitted state for change log readings in tests.
h256 rootHash() const
The hash of the root of our state tree.
Definition: State.h:310
void setNonce(Address const &_addr, u256 const &_newNonce)
Set the account nonce.
Definition: State.cpp:333
Permanence
Definition: State.h:72
void executeBlockTransactions(Block const &_block, unsigned _txCount, LastBlockHashesFace const &_lastHashes, SealEngineFace const &_sealEngine)
Definition: State.cpp:634
boost::error_info< struct tag_transactionIndex, unsigned > errinfo_transactionIndex
Definition: State.h:51
AddressHash commit(AccountMap const &_cache, SecureTrieDB< Address, DB > &_state)
Definition: State.cpp:759
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
void transferBalance(Address const &_from, Address const &_to, u256 const &_value)
Transfers "the balance _value between two accounts.
Definition: State.h:251
boost::error_info< struct tag_uncleNumber, u256 > errinfo_uncleNumber
Definition: State.h:46
friend class dev::test::ImportTest
Definition: State.h:162
An atomic state changelog entry.
Definition: State.h:86
void subBalance(Address const &_addr, u256 const &_value)
Definition: State.cpp:371
bytes oldCode
Code overwritten by CREATE, empty except in case of address collision.
Definition: State.h:119
boost::error_info< struct tag_get_LogBloom, LogBloom > errinfo_got_LogBloom
Definition: State.h:58
size_t codeSize(Address const &_contract) const
Definition: State.cpp:534
State & createIntermediateState(State &o_s, Block const &_block, unsigned _txIndex, BlockChain const &_bc)
Definition: State.cpp:744
OverlayDB const & db() const
Definition: State.h:195
Account was created (it was not existing before).
Definition: State.h:106
bool accountNonemptyAndExisting(Address const &_address) const
Definition: State.cpp:296
void incNonce(Address const &_id)
Increament the account nonce.
Definition: State.cpp:320
h256 codeHash(Address const &_contract) const
Definition: State.cpp:526
boost::tuple< errinfo_required_LogBloom, errinfo_got_LogBloom > LogBloomRequirementError
Definition: State.h:59
std::unordered_set< h160 > AddressHash
A hash set of Ethereum addresses.
Definition: Address.h:36