/
state_object.go
388 lines (309 loc) · 10.4 KB
/
state_object.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package types
import (
"fmt"
"math/big"
"github.com/tendermint/tendermint/crypto"
authexported "github.com/Dipper-Labs/Dipper-Protocol/app/v0/auth/exported"
"github.com/Dipper-Labs/Dipper-Protocol/app/v0/auth/types"
"github.com/Dipper-Labs/Dipper-Protocol/store/prefix"
sdk "github.com/Dipper-Labs/Dipper-Protocol/types"
)
var (
_ StateObject = (*stateObject)(nil)
)
type (
// StateObject interface for interacting with state object
StateObject interface {
GetCommittedState(key sdk.Hash) sdk.Hash
GetState(key sdk.Hash) sdk.Hash
SetState(key, value sdk.Hash)
Code() []byte
SetCode(codeHash sdk.Hash, code []byte)
CodeHash() []byte
AddBalance(amount *big.Int)
SubBalance(amount *big.Int)
SetBalance(amount *big.Int)
Balance() *big.Int
ReturnGas(gas *big.Int)
Address() sdk.Address
SetNonce(nonce uint64)
Nonce() uint64
}
// stateObject represents an Ethereum account which is being modified.
//
// The usage pattern is as follows:
// First you need to obtain a state object.
// Account values can be accessed and modified through the object.
// Finally, call CommitTrie to write the modified storage trie into a database.
stateObject struct {
address sdk.AccAddress
stateDB *CommitStateDB
account *types.BaseAccount
// DB error.
// State objects are used by the consensus core and VM which are
// unable to deal with database-level errors. Any error that occurs
// during a database read is memoized here and will eventually be returned
// by StateDB.Commit.
dbErr error
code sdk.Code // contract bytecode, which gets set when code is loaded
originStorage sdk.Storage // Storage cache of original entries to dedup rewrites
dirtyStorage sdk.Storage // Storage entries that need to be flushed to disk
// cache flags
//
// When an object is marked suicided it will be delete from the trie during
// the "update" phase of the state transition.
dirtyCode bool
suicided bool
deleted bool
}
)
func newObject(db *CommitStateDB, accProto authexported.Account) *stateObject {
acc, ok := accProto.(*types.BaseAccount)
if !ok {
panic(fmt.Sprintf("invalid account type for state object: %T", accProto))
}
return &stateObject{
stateDB: db,
account: acc,
address: acc.Address,
originStorage: make(sdk.Storage),
dirtyStorage: make(sdk.Storage),
}
}
// ----------------------------------------------------------------------------
// Setters
// ----------------------------------------------------------------------------
// SetState updates a value in account storage. Note, the key will be prefixed
// with the address of the state object.
func (so *stateObject) SetState(key, value sdk.Hash) {
// if the new value is the same as old, don't set
prev := so.GetState(key)
if prev == value {
return
}
prefixKey := so.GetStorageByAddressKey(key.Bytes())
// since the new value is different, update and journal the change
so.stateDB.journal.append(storageChange{
account: &so.address,
key: prefixKey,
prevValue: prev,
})
so.setState(prefixKey, value)
}
func (so *stateObject) setState(key, value sdk.Hash) {
so.dirtyStorage[key] = value
}
// SetCode sets the state object's code.
func (so *stateObject) SetCode(codeHash sdk.Hash, code []byte) {
prevCode := so.Code()
so.stateDB.journal.append(codeChange{
account: &so.address,
prevHash: so.CodeHash(),
prevCode: prevCode,
})
so.setCode(codeHash, code)
}
func (so *stateObject) setCode(codeHash sdk.Hash, code []byte) {
so.code = code
so.account.CodeHash = codeHash.Bytes()
so.dirtyCode = true
}
// AddBalance adds an amount to a state object's balance. It is used to add
// funds to the destination account of a transfer.
func (so *stateObject) AddBalance(amount *big.Int) {
amt := sdk.NewIntFromBigInt(amount)
// EIP158: We must check emptiness for the objects such that the account
// clearing (0,0,0 objects) can take effect.
if amt.Sign() == 0 {
if so.empty() {
so.touch()
}
return
}
newBalance := so.account.Balance().Add(amt)
so.SetBalance(newBalance.BigInt())
}
// SubBalance removes an amount from the stateObject's balance. It is used to
// remove funds from the origin account of a transfer.
func (so *stateObject) SubBalance(amount *big.Int) {
amt := sdk.NewIntFromBigInt(amount)
if amt.Sign() == 0 {
return
}
newBalance := so.account.Balance().Sub(amt)
so.SetBalance(newBalance.BigInt())
}
// SetBalance sets the state object's balance.
func (so *stateObject) SetBalance(amount *big.Int) {
amt := sdk.NewIntFromBigInt(amount)
so.stateDB.journal.append(balanceChange{
account: &so.address,
prev: so.account.Balance(),
})
so.setBalance(amt)
}
func (so *stateObject) setBalance(amount sdk.Int) {
so.account.SetBalance(amount)
}
// SetNonce sets the state object's nonce (sequence number).
func (so *stateObject) SetNonce(nonce uint64) {
so.stateDB.journal.append(nonceChange{
account: &so.address,
prev: so.account.Sequence,
})
so.setNonce(nonce)
}
func (so *stateObject) setNonce(nonce uint64) {
so.account.Sequence = nonce
}
// setError remembers the first non-nil error it is called with.
func (so *stateObject) setError(err error) {
if so.dbErr == nil {
so.dbErr = err
}
}
func (so *stateObject) markSuicided() {
so.suicided = true
}
// commitState commits all dirty storage to a KVStore.
func (so *stateObject) commitState() {
ctx := so.stateDB.ctx
store := prefix.NewStore(ctx.KVStore(so.stateDB.storageKey), AddressStoragePrefix(so.address))
for key, value := range so.dirtyStorage {
delete(so.dirtyStorage, key)
if value == so.originStorage[key] {
continue
}
so.originStorage[key] = value
if (value == sdk.Hash{}) {
store.Delete(key.Bytes())
continue
}
store.Set(key.Bytes(), value.Bytes())
}
}
// commitCode persists the state object's code to the KVStore.
func (so *stateObject) commitCode() {
ctx := so.stateDB.ctx
store := prefix.NewStore(ctx.KVStore(so.stateDB.storageKey), KeyPrefixCode)
store.Set(so.CodeHash(), so.code)
}
// ----------------------------------------------------------------------------
// Getters
// ----------------------------------------------------------------------------
// Address returns the address of the state object.
func (so stateObject) Address() sdk.Address {
return so.address
}
// Balance returns the state object's current balance.
func (so *stateObject) Balance() *big.Int {
return so.account.Balance().BigInt()
}
// CodeHash returns the state object's code hash.
func (so *stateObject) CodeHash() []byte {
return so.account.CodeHash
}
// Nonce returns the state object's current nonce (sequence number).
func (so *stateObject) Nonce() uint64 {
return so.account.Sequence
}
// Code returns the contract code associated with this object, if any.
func (so *stateObject) Code() []byte {
if so.code != nil {
return so.code
}
if so.CodeHash() == nil {
return nil
}
ctx := so.stateDB.ctx
store := prefix.NewStore(ctx.KVStore(so.stateDB.storageKey), KeyPrefixCode)
code := store.Get(so.CodeHash())
if len(code) == 0 {
so.setError(fmt.Errorf("failed to get code hash %x for address: %x", so.CodeHash(), so.Address()))
}
so.code = code
return code
}
// GetState retrieves a value from the account storage trie. Note, the key will
// be prefixed with the address of the state object.
func (so *stateObject) GetState(key sdk.Hash) sdk.Hash {
prefixKey := so.GetStorageByAddressKey(key.Bytes())
// if we have a dirty value for this state entry, return it
value, dirty := so.dirtyStorage[prefixKey]
if dirty {
return value
}
// otherwise return the entry's original value
return so.GetCommittedState(key)
}
// GetCommittedState retrieves a value from the committed account storage trie.
// Note, the key will be prefixed with the address of the state object.
func (so *stateObject) GetCommittedState(key sdk.Hash) sdk.Hash {
prefixKey := so.GetStorageByAddressKey(key.Bytes())
// if we have the original value cached, return that
value, cached := so.originStorage[prefixKey]
if cached {
return value
}
// otherwise load the value from the KVStore
ctx := so.stateDB.ctx
store := prefix.NewStore(ctx.KVStore(so.stateDB.storageKey), AddressStoragePrefix(so.address))
rawValue := store.Get(prefixKey.Bytes())
if len(rawValue) > 0 {
value.SetBytes(rawValue)
}
so.originStorage[prefixKey] = value
return value
}
// ----------------------------------------------------------------------------
// Auxiliary
// ----------------------------------------------------------------------------
// ReturnGas returns the gas back to the origin. Used by the Virtual machine or
// Closures. It performs a no-op.
func (so *stateObject) ReturnGas(gas *big.Int) {}
func (so *stateObject) deepCopy(db *CommitStateDB) *stateObject {
newStateObj := newObject(db, so.account)
newStateObj.code = so.code
newStateObj.dirtyStorage = so.dirtyStorage.Copy()
newStateObj.originStorage = so.originStorage.Copy()
newStateObj.suicided = so.suicided
newStateObj.dirtyCode = so.dirtyCode
newStateObj.deleted = so.deleted
return newStateObj
}
// empty returns whether the account is considered empty.
func (so *stateObject) empty() bool {
return so.account.Sequence == 0 &&
so.account.Balance().Sign() == 0 &&
len(so.account.CodeHash) == 0
}
func (so *stateObject) touch() {
so.stateDB.journal.append(touchChange{
account: &so.address,
})
//if so.address == ripemd {//TODO check
// // Explicitly put it in the dirty-cache, which is otherwise generated from
// // flattened journals.
// so.stateDB.journal.dirty(so.address)
//}
}
// GetStorageByAddressKey returns a hash of the composite key for a state
// object's storage prefixed with it's address.
func (so stateObject) GetStorageByAddressKey(key []byte) sdk.Hash {
prefix := so.Address().Bytes()
compositeKey := make([]byte, len(prefix)+len(key))
copy(compositeKey, prefix)
copy(compositeKey[len(prefix):], key)
return sdk.BytesToHash(crypto.Sha256(compositeKey))
}
type SO struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
BaseAccount types.BaseAccount `json:"base_account" yaml:"base_account"`
OriginStorage sdk.Storage `json:"origin_storage" yaml:"origin_storage"`
DirtyStorage sdk.Storage `json:"dirty_storage" yaml:"dirty_storage"`
DirtyCode bool `json:"dirty_code" yaml:"dirty_code"`
Suicided bool `json:"suicided" yaml:"suicided"`
Deleted bool `json:"deleted" yaml:"deleted"`
Code sdk.Code `json:"code" yaml:"code"`
}
type SOs []SO