Fabcoin Core  0.16.2
P2P Digital Currency
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 */
22 #pragma once
23 
24 #include <array>
25 #include <unordered_map>
26 #include <libdevcore/Common.h>
27 #include <libdevcore/RLP.h>
28 #include <libdevcore/TrieDB.h>
29 #include <libdevcore/OverlayDB.h>
30 #include <libethcore/Exceptions.h>
31 #include <libethcore/BlockHeader.h>
34 #include <libevm/ExtVMFace.h>
35 #include "Account.h"
36 #include "Transaction.h"
37 #include "TransactionReceipt.h"
38 #include "GasPricer.h"
39 
40 namespace dev
41 {
42 
43 namespace test { class ImportTest; class StateLoader; }
44 
45 namespace eth
46 {
47 
48 // Import-specific errinfos
49 using errinfo_uncleIndex = boost::error_info<struct tag_uncleIndex, unsigned>;
50 using errinfo_currentNumber = boost::error_info<struct tag_currentNumber, u256>;
51 using errinfo_uncleNumber = boost::error_info<struct tag_uncleNumber, u256>;
52 using errinfo_unclesExcluded = boost::error_info<struct tag_unclesExcluded, h256Hash>;
53 using errinfo_block = boost::error_info<struct tag_block, bytes>;
54 using errinfo_now = boost::error_info<struct tag_now, unsigned>;
55 
56 using errinfo_transactionIndex = boost::error_info<struct tag_transactionIndex, unsigned>;
57 
58 using errinfo_vmtrace = boost::error_info<struct tag_vmtrace, std::string>;
59 using errinfo_receipts = boost::error_info<struct tag_receipts, std::vector<bytes>>;
60 using errinfo_transaction = boost::error_info<struct tag_transaction, bytes>;
61 using errinfo_phase = boost::error_info<struct tag_phase, unsigned>;
62 using errinfo_required_LogBloom = boost::error_info<struct tag_required_LogBloom, LogBloom>;
63 using errinfo_got_LogBloom = boost::error_info<struct tag_get_LogBloom, LogBloom>;
64 using LogBloomRequirementError = boost::tuple<errinfo_required_LogBloom, errinfo_got_LogBloom>;
65 
66 class BlockChain;
67 class State;
68 class TransactionQueue;
69 struct VerifiedBlockRef;
70 
71 struct StateChat: public LogChannel { static const char* name(); static const int verbosity = 4; };
72 struct StateTrace: public LogChannel { static const char* name(); static const int verbosity = 5; };
73 struct StateDetail: public LogChannel { static const char* name(); static const int verbosity = 14; };
74 struct StateSafeExceptions: public LogChannel { static const char* name(); static const int verbosity = 21; };
75 
76 enum class BaseState
77 {
79  Empty
80 };
81 
82 enum class Permanence
83 {
84  Reverted,
85  Committed
86 };
87 
88 #if ETH_FATDB
89 template <class KeyType, class DB> using SecureTrieDB = SpecificTrieDB<FatGenericTrieDB<DB>, KeyType>;
90 #else
91 template <class KeyType, class DB> using SecureTrieDB = SpecificTrieDB<HashedGenericTrieDB<DB>, KeyType>;
92 #endif
93 
94 DEV_SIMPLE_EXCEPTION(InvalidAccountStartNonceInState);
95 DEV_SIMPLE_EXCEPTION(IncorrectAccountStartNonceInState);
96 
97 class SealEngineFace;
98 
99 
100 namespace detail
101 {
102 
104 struct Change
105 {
106  enum Kind: int
107  {
111 
115 
118 
121 
124 
126  Touch
127  };
128 
133 
135  Change(Kind _kind, Address const& _addr, u256 const& _value = 0):
136  kind(_kind), address(_addr), value(_value)
137  {}
138 
140  Change(Address const& _addr, u256 const& _key, u256 const& _value):
141  kind(Storage), address(_addr), value(_value), key(_key)
142  {}
143 };
144 
145 }
146 
147 
161 class State
162 {
163  friend class ExtVM;
164  friend class dev::test::ImportTest;
165  friend class dev::test::StateLoader;
166  friend class BlockChain;
167 
168 public:
169  enum class CommitBehaviour
170  {
171  KeepEmptyAccounts,
172  RemoveEmptyAccounts
173  };
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(std::string 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<ExecutionResult, TransactionReceipt> execute(EnvInfo const& _envInfo, SealEngineFace const& _sealEngine, Transaction const& _t, Permanence _p = Permanence::Committed, OnOpFunc const& _onOp = OnOpFunc());
209 
211  bool addressInUse(Address const& _address) const;
212 
215  bool accountNonemptyAndExisting(Address const& _address) const;
216 
218  bool addressHasCode(Address const& _address) const;
219 
222  u256 balance(Address const& _id) const;
223 
226  // void addBalance(Address const& _id, u256 const& _amount);
227  virtual void addBalance(Address const& _id, u256 const& _amount); // fasc
228 
232  void subBalance(Address const& _addr, u256 const& _value);
233 
240  virtual void transferBalance(Address const& _from, Address const& _to, u256 const& _value) { subBalance(_from, _value); addBalance(_to, _value); }
241 
243  h256 storageRoot(Address const& _contract) const;
244 
247  u256 storage(Address const& _contract, u256 const& _memory) const;
248 
250  void setStorage(Address const& _contract, u256 const& _location, u256 const& _value);
251 
253  void createContract(Address const& _address);
254 
256  void setNewCode(Address const& _address, bytes&& _code);
257 
259  virtual void kill(Address _a);
260 
264  std::map<h256, std::pair<u256, u256>> storage(Address const& _contract) const;
265 
270  bytes const& code(Address const& _addr) const;
271 
274  h256 codeHash(Address const& _contract) const;
275 
278  size_t codeSize(Address const& _contract) const;
279 
281  void incNonce(Address const& _id);
282 
285  u256 getNonce(Address const& _addr) const;
286 
288  h256 rootHash() const { return m_state.root(); }
289 
292  void commit(CommitBehaviour _commitBehaviour);
293 
295  void setRoot(h256 const& _root);
296 
298  u256 const& accountStartNonce() const { return m_accountStartNonce; }
299  u256 const& requireAccountStartNonce() const;
300  void noteAccountStartNonce(u256 const& _actual);
301 
304  size_t savepoint() const;
305 
307  void rollback(size_t _savepoint);
308 
309  virtual ~State(){}
310 
311 // private:
312 protected: // fasc
314  void removeEmptyAccounts();
315 
318  Account const* account(Address const& _addr) const;
319 
322  Account* account(Address const& _addr);
323 
325  void clearCacheIfTooLarge() const;
326 
327  void createAccount(Address const& _address, Account const&& _account);
328 
331  mutable std::unordered_map<Address, Account> m_cache;
332  mutable std::vector<Address> m_unchangedCacheEntries;
333  mutable std::set<Address> m_nonExistingAccountsCache;
335 
337 
338  friend std::ostream& operator<<(std::ostream& _out, State const& _s);
339  std::vector<detail::Change> m_changeLog;
340 };
341 
342 std::ostream& operator<<(std::ostream& _out, State const& _s);
343 
344 template <class DB>
346 {
347  AddressHash ret;
348  for (auto const& i: _cache)
349  if (i.second.isDirty())
350  {
351  if (!i.second.isAlive())
352  _state.remove(i.first);
353  else
354  {
355  RLPStream s(4);
356  s << i.second.nonce() << i.second.balance();
357 
358  if (i.second.storageOverlay().empty())
359  {
360  assert(i.second.baseRoot());
361  s.append(i.second.baseRoot());
362  }
363  else
364  {
365  SecureTrieDB<h256, DB> storageDB(_state.db(), i.second.baseRoot());
366  for (auto const& j: i.second.storageOverlay())
367  if (j.second)
368  storageDB.insert(j.first, rlp(j.second));
369  else
370  storageDB.remove(j.first);
371  assert(storageDB.root());
372  s.append(storageDB.root());
373  }
374 
375  if (i.second.hasNewCode())
376  {
377  h256 ch = i.second.codeHash();
378  // Store the size of the code
379  CodeSizeCache::instance().store(ch, i.second.code().size());
380  _state.db()->insert(ch, &i.second.code());
381  s << ch;
382  }
383  else
384  s << i.second.codeHash();
385 
386  _state.insert(i.first, &s.out());
387  }
388  ret.insert(i.first);
389  }
390  return ret;
391 }
392 
393 }
394 }
395 
State(u256 const &_accountStartNonce)
Default constructor; creates with a blank database prepopulated with the genesis block.
Definition: State.h:176
Adapted from code found on http://stackoverflow.com/questions/180947/base64-decode-snippet-in-c Origi...
Definition: Arith256.cpp:15
boost::error_info< struct tag_block, bytes > errinfo_block
Definition: State.h:53
boost::error_info< struct tag_unclesExcluded, h256Hash > errinfo_unclesExcluded
Definition: State.h:52
void remove(KeyType _k)
Definition: TrieDB.h:335
std::function< void(uint64_t, uint64_t, dev::eth::Instruction, dev::bigint, dev::bigint, dev::bigint, dev::eth::VM *, dev::eth::ExtVMFace const *)> OnOpFunc
Definition: fascstate.h:15
A queue of Transactions, each stored as RLP.
boost::error_info< struct tag_receipts, std::vector< bytes >> errinfo_receipts
Definition: State.h:59
std::unordered_map< Address, Account > AccountMap
Definition: Account.h:239
struct evm_uint256be balance(struct evm_env *env, struct evm_uint160be address)
Definition: capi.c:7
boost::error_info< struct tag_uncleIndex, unsigned > errinfo_uncleIndex
Definition: State.h:49
Implements the blockchain database.
Definition: BlockChain.h:105
bytes rlp(_T _t)
Export a single item in RLP format, returning a byte array.
Definition: RLP.h:467
RLPStream & append(unsigned _s)
Append given datum to the byte stream.
Definition: RLP.h:395
Models the state of a single Ethereum account.
Definition: Account.h:67
bytes const & out() const
Read the byte stream.
Definition: RLP.h:433
u256 key
Storage key. Last because used only in one case.
Definition: State.h:132
boost::error_info< struct tag_transaction, bytes > errinfo_transaction
Definition: State.h:60
boost::error_info< struct tag_currentNumber, u256 > errinfo_currentNumber
Definition: State.h:50
u256 const & accountStartNonce() const
Get the account start nonce. May be required.
Definition: State.h:298
Change(Address const &_addr, u256 const &_key, u256 const &_value)
Helper constructor especially for storage change log.
Definition: State.h:140
assert(len-trim+(2 *lenIndices)<=WIDTH)
Different view on a GenericTrieDB that can use different key types.
Definition: TrieDB.h:320
AddressHash m_touched
Tracks all addresses touched so far.
Definition: State.h:334
bytes code
Definition: SmartVM.cpp:45
Model of an Ethereum state, essentially a facade for the trie.
Definition: State.h:161
OverlayDB const & db() const
Definition: State.h:195
u256 value
Change value, e.g. balance, storage.
Definition: State.h:131
boost::error_info< struct tag_phase, unsigned > errinfo_phase
Definition: State.h:61
WithExisting
Definition: Common.h:310
New code was added to an account (by "create" message execution).
Definition: State.h:123
Account nonce was increased by 1.
Definition: State.h:117
Kind kind
The kind of the change.
Definition: State.h:129
BaseState
Definition: State.h:76
const char * name
Definition: rest.cpp:36
Change(Kind _kind, Address const &_addr, u256 const &_value=0)
Helper constructor to make change log update more readable.
Definition: State.h:135
void insert(KeyType _k, bytesConstRef _value)
Definition: TrieDB.h:333
std::vector< detail::Change > m_changeLog
Definition: State.h:339
std::vector< byte > bytes
Definition: Common.h:75
boost::error_info< struct tag_vmtrace, std::string > errinfo_vmtrace
Definition: State.h:58
const u256 Invalid256
Definition: Common.cpp:38
Fixed-size raw-byte array container type, with an API optimised for storing hashes.
Definition: FixedHash.h:47
std::function< void(uint64_t, uint64_t, Instruction, bigint, bigint, bigint, VM *, ExtVMFace const *)> OnOpFunc
Definition: ExtVMFace.h:193
Account storage was modified.
Definition: State.h:114
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u256
Definition: Common.h:125
std::unordered_map< Address, Account > m_cache
Our address cache. This stores the states of each address that has (or at least might have) been chan...
Definition: State.h:331
boost::error_info< struct tag_required_LogBloom, LogBloom > errinfo_required_LogBloom
Definition: State.h:62
Encodes a transaction, ready to be exported to or freshly imported from RLP.
Definition: Transaction.h:84
h256 rootHash() const
The hash of the root of our state tree.
Definition: State.h:288
DEV_SIMPLE_EXCEPTION(BadHexCharacter)
OverlayDB & db()
Definition: State.h:196
SecureTrieDB< Address, OverlayDB > m_state
Our state tree, as an OverlayDB DB.
Definition: State.h:330
std::vector< Address > m_unchangedCacheEntries
Tracks entries in m_cache that can potentially be purged if it grows too large.
Definition: State.h:332
h256 codeHash
Definition: SmartVM.cpp:46
State(NullType)
Definition: State.h:185
u256 m_accountStartNonce
Definition: State.h:336
Verified block info, does not hold block data, but a reference instead.
Definition: VerifiedBlock.h:36
virtual void transferBalance(Address const &_from, Address const &_to, u256 const &_value)
Transfers "the balance _value between two accounts.
Definition: State.h:240
boost::error_info< struct tag_now, unsigned > errinfo_now
Definition: State.h:54
OverlayDB m_db
Our overlay for the state tree.
Definition: State.h:329
An Empty class.
Definition: misc.h:184
Externality interface for the Virtual Machine providing access to world state.
Definition: ExtVM.h:42
Account balance changed.
Definition: State.h:110
The default logging channels.
Definition: Log.h:130
Permanence
Definition: State.h:82
boost::error_info< struct tag_transactionIndex, unsigned > errinfo_transactionIndex
Definition: State.h:56
AddressHash commit(AccountMap const &_cache, SecureTrieDB< Address, DB > &_state)
Definition: State.h:345
An atomic state changelog entry.
Definition: State.h:104
boost::error_info< struct tag_uncleNumber, u256 > errinfo_uncleNumber
Definition: State.h:51
uint32_t ch(uint32_t x, uint32_t y, uint32_t z)
Definition: picosha2.h:73
Class for writing to an RLP bytestream.
Definition: RLP.h:383
std::set< Address > m_nonExistingAccountsCache
Tracks addresses that are known to not exist.
Definition: State.h:333
std::ostream & operator<<(std::ostream &out, Stats::clock::duration const &d)
Definition: Stats.cpp:51
boost::error_info< struct tag_get_LogBloom, LogBloom > errinfo_got_LogBloom
Definition: State.h:63
Account was created (it was not existing before).
Definition: State.h:120
virtual ~State()
Definition: State.h:309
Address address
Changed account address.
Definition: State.h:130
boost::tuple< errinfo_required_LogBloom, errinfo_got_LogBloom > LogBloomRequirementError
Definition: State.h:64
std::unordered_set< h160 > AddressHash
A hash set of Ethereum addresses.
Definition: Common.h:71