/
state.go
597 lines (504 loc) · 17 KB
/
state.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
package state
import (
"bytes"
"fmt"
"math/big"
"sync"
"syscall"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/core"
ethState "github.com/ethereum/go-ethereum/core/state"
ethTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp"
"github.com/sirupsen/logrus"
bcommon "github.com/Fantom-foundation/go-evm/src/common"
"github.com/Fantom-foundation/go-lachesis/src/poset"
)
var (
chainID = big.NewInt(1)
gasLimit = big.NewInt(1000000000000000000)
txMetaSuffix = []byte{0x01}
receiptsPrefix = []byte("receipts-")
errorPrefix = []byte("errors-")
MIPMapLevels = []uint64{1000000, 500000, 100000, 50000, 1000}
headTxKey = []byte("LastTx")
rootKey = []byte("root")
)
var (
participantPrefix = "participant"
rootSuffix = "root"
roundPrefix = "round"
topoPrefix = "topo"
blockPrefix = "block"
framePrefix = "frame"
)
func blockKey(index int64) []byte {
return []byte(fmt.Sprintf("%s_%09d", blockPrefix, index))
}
type State struct {
db ethdb.Database
commitMutex sync.Mutex
ethState *ethState.StateDB
was *WriteAheadState
txPool *TxPool
blockIndex int64
signer ethTypes.Signer
chainConfig params.ChainConfig //vm.env is still tightly coupled with chainConfig
vmConfig vm.Config
logger *logrus.Logger
}
func NewState(logger *logrus.Logger, dbFile string, dbCache int) (*State, error) {
handles, err := getFdLimit()
if err != nil {
return nil, err
}
db, err := ethdb.NewLDBDatabase(dbFile, dbCache, handles)
if err != nil {
return nil, err
}
s := &State{
db: db,
signer: ethTypes.NewEIP155Signer(chainID),
chainConfig: params.ChainConfig{ChainID: chainID},
vmConfig: vm.Config{Tracer: vm.NewStructLogger(nil)},
logger: logger,
}
if err := s.InitState(); err != nil {
return nil, err
}
s.resetWAS()
return s, nil
}
// getFdLimit retrieves the number of file descriptors allowed to be opened by this
// process.
func getFdLimit() (int, error) {
var limit syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
return 0, err
}
return int(limit.Cur), nil
}
//------------------------------------------------------------------------------
func (s *State) Call(callMsg ethTypes.Message) ([]byte, error) {
s.logger.Debug("Call")
s.commitMutex.Lock()
defer s.commitMutex.Unlock()
context := vm.Context{
CanTransfer: core.CanTransfer,
Transfer: core.Transfer,
GetHash: func(uint64) common.Hash { return common.Hash{} },
// Message information
Origin: callMsg.From(),
GasLimit: callMsg.Gas(),
GasPrice: callMsg.GasPrice(),
BlockNumber: big.NewInt(0), //the vm has a dependency on this..
}
s.logger.WithField("From", callMsg.From().Hex()).Debug("Call(callMsg ethTypes.Message)")
s.logger.WithField("To", callMsg.To().Hex()).Debug("Call(callMsg ethTypes.Message)")
s.logger.WithField("Data", hexutil.Encode(callMsg.Data())).Debug("Call(callMsg ethTypes.Message)")
// The EVM should never be reused and is not thread safe.
// Call is done on a copy of the state...we don't want any changes to be persisted
// Call is a readonly operation
vmenv := vm.NewEVM(context, s.was.ethState.Copy(), &s.chainConfig, s.vmConfig)
// Apply the transaction to the current state (included in the env)
res, gas, failed, err := core.ApplyMessage(vmenv, callMsg, new(core.GasPool).AddGas(gasLimit.Uint64()))
if err != nil {
s.logger.WithError(err).Error("Executing Call on WAS")
return nil, err
}
s.logger.WithField("Failed", failed).Debug("Call(callMsg ethTypes.Message)")
s.logger.WithField("Res", res).Debug("Call(callMsg ethTypes.Message)")
s.logger.WithField("Gas", gas).Debug("Call(callMsg ethTypes.Message)")
return res, err
}
func (s *State) GetBlockIndex() int64 {
return s.blockIndex
}
func (s *State) ProcessBlock(block poset.Block) (common.Hash, error) {
s.logger.Debug("Process Block")
s.commitMutex.Lock()
defer s.commitMutex.Unlock()
blockIndex := block.Index()
hash, _ := block.BlockHash()
blockHash := common.BytesToHash(hash)
if block.GetCreatedTime() == 0 {
block.CreatedTime = time.Now().Unix()
}
blockMarshal, _ := block.ProtoMarshal()
s.logger.WithField("block.GetCreatedTime", block.GetCreatedTime()).Debug("ProcessBlock(block poset.Block)")
s.logger.WithField("blockIndex", blockIndex).Debug("ProcessBlock(block poset.Block)")
s.logger.WithField("blockHash", block.BlockHex()).Debug("ProcessBlock(block poset.Block)")
s.blockIndex = blockIndex
if err := s.db.Put(hash, blockMarshal); err != nil {
return common.Hash{}, err
}
if err := s.db.Put(blockKey(blockIndex), blockMarshal); err != nil {
return common.Hash{}, err
}
for txIndex, txBytes := range block.Transactions() {
// Block is valid, don't exit just because of transactions
if err := s.applyTransaction(txBytes, txIndex, blockHash); err != nil {
s.logger.WithError(err).Error("s.applyTransaction(txBytes, txIndex, blockHash);")
}
}
return s.Commit()
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
func isProtectedV(V *big.Int) bool {
if V.BitLen() <= 8 {
v := V.Uint64()
return v != 27 && v != 28
}
// anything not 27 or 28 are considered unprotected
return true
}
// deriveChainId derives the chain id from the given v parameter
func deriveChainId(v *big.Int) *big.Int {
if v.BitLen() <= 64 {
v := v.Uint64()
if v == 27 || v == 28 {
return new(big.Int)
}
return new(big.Int).SetUint64((v - 35) / 2)
}
v = new(big.Int).Sub(v, big.NewInt(35))
return v.Div(v, big.NewInt(2))
}
// deriveSigner makes a *best* guess about which signer to use.
func deriveSigner(V *big.Int) ethTypes.Signer {
if V.Sign() != 0 && isProtectedV(V) {
return ethTypes.NewEIP155Signer(deriveChainId(V))
} else {
return ethTypes.HomesteadSigner{}
}
}
func (s *State) PrintTransaction(tx *ethTypes.Transaction) string {
var from, to string
//v, _, _ := tx.RawSignatureValues()
// make a best guess about the signer and use that to derive
// the sender.
//signer := deriveSigner(v)
if f, err := ethTypes.Sender(s.signer, tx); err != nil { // derive but don't cache
from = "[invalid sender: invalid sig]"
} else {
from = fmt.Sprintf("%x", f[:])
}
if tx.To() == nil {
to = "[contract creation]"
} else {
to = fmt.Sprintf("%x", tx.To()[:])
}
return fmt.Sprintf(`
TX(%x)
Contract: %v
From: %s
To: %s
Nonce: %v
GasPrice: %#x
GasLimit %#x
Value: %#x
Data: 0x%x
`,
tx.Hash(),
tx.To() == nil,
from,
to,
tx.Nonce(),
tx.GasPrice(),
tx.Gas(),
tx.Value(),
tx.Data(),
)
}
//applyTransaction applies a transaction to the WAS
func (s *State) applyTransaction(txBytes []byte, txIndex int, blockHash common.Hash) error {
var t ethTypes.Transaction
if err := rlp.Decode(bytes.NewReader(txBytes), &t); err != nil {
s.logger.WithError(err).Error("Decoding Transaction")
return err
}
s.logger.WithField("hash", t.Hash().Hex()).Debug("Decoded tx")
s.logger.WithField("tx", s.PrintTransaction(&t)).Debug("Decoded tx")
msg, err := t.AsMessage(s.signer)
if err != nil {
s.logger.WithError(err).Error("Converting Transaction to Message")
return err
}
context := vm.Context{
CanTransfer: core.CanTransfer,
Transfer: core.Transfer,
GetHash: func(uint64) common.Hash { return blockHash },
// Message information
Origin: msg.From(),
GasLimit: msg.Gas(),
GasPrice: msg.GasPrice(),
BlockNumber: big.NewInt(0), //the vm has a dependency on this..
}
s.logger.WithFields(logrus.Fields{
"GasLimit": msg.Gas(),
"s.was.gp": s.was.gp,
}).Debug("state.ApplyTransaction")
//Prepare the ethState with transaction Hash so that it can be used in emitted
//logs
s.was.ethState.Prepare(t.Hash(), blockHash, txIndex)
// The EVM should never be reused and is not thread safe.
vmenv := vm.NewEVM(context, s.was.ethState, &s.chainConfig, s.vmConfig)
// Apply the transaction to the current state (included in the env)
_, gas, failed, err := core.ApplyMessage(vmenv, msg, s.was.gp)
if err != nil {
txError := TxError{
Tx: t,
Error: err.Error(),
}
txHash := t.Hash()
txErrorMarshal, _ := txError.Marshal()
if err := s.db.Put(append(errorPrefix, txHash[:]...), txErrorMarshal); err != nil {
s.logger.WithError(err).Error("s.db.Put")
}
s.logger.WithError(err).Error("Applying transaction to State")
return err
}
s.was.totalUsedGas.Add(s.was.totalUsedGas, big.NewInt(0).SetUint64(gas))
// Create a new receipt for the transaction, storing the intermediate root and gas used by the tx
// based on the eip phase, we're passing whether the root touch-delete accounts.
root := s.was.ethState.IntermediateRoot(true) //this has side effects. It updates StateObjects (SmartContract memory)
receipt := ethTypes.NewReceipt(root.Bytes(), failed, bcommon.BigintToUInt64(s.was.totalUsedGas))
receipt.TxHash = t.Hash()
receipt.GasUsed = gas
// if the transaction created a contract, store the creation address in the receipt.
if msg.To() == nil {
receipt.ContractAddress = crypto.CreateAddress(vmenv.Context.Origin, t.Nonce())
}
// Set the receipt logs and create a bloom for filtering
receipt.Logs = s.was.ethState.GetLogs(t.Hash())
//receipt.Logs = s.was.state.Logs()
receipt.Bloom = ethTypes.CreateBloom(ethTypes.Receipts{receipt})
s.was.txIndex++
s.was.transactions = append(s.was.transactions, &t)
s.was.receipts = append(s.was.receipts, receipt)
s.was.allLogs = append(s.was.allLogs, receipt.Logs...)
s.logger.WithField("hash", t.Hash().Hex()).Debug("Applied tx to WAS")
return nil
}
//Commit persists all pending state changes (in the WAS) to the DB, and resets
//the WAS and TxPool
func (s *State) Commit() (common.Hash, error) {
//commit all state changes to the database
root, err := s.was.Commit()
if err != nil {
s.logger.WithError(err).Error("Committing WAS")
return root, err
}
// reset the write ahead state for the next block
// with the latest eth state
/*s.ethState = s.was.ethState
s.logger.WithField("root", root.Hex()).Debug("Committed")
s.resetWAS()*/
if err := s.ethState.Reset(root); err != nil {
s.logger.WithError(err).Error("Resetting main StateDB")
return root, err
}
s.logger.WithField("root", root.Hex()).Debug("Committed")
//Reset WAS
if err := s.was.Reset(root); err != nil {
s.logger.WithError(err).Error("Resetting WAS")
return root, err
}
s.logger.Debug("Reset WAS")
//Reset TxPool
if err := s.txPool.Reset(root); err != nil {
s.logger.WithError(err).Error("Resetting TxPool")
return root, err
}
s.logger.Debug("Reset TxPool")
return root, nil
}
func (s *State) resetWAS() {
state := s.ethState.Copy()
s.was = &WriteAheadState{
db: s.db,
ethState: state,
txIndex: 0,
totalUsedGas: big.NewInt(0),
gp: new(core.GasPool).AddGas(gasLimit.Uint64()),
logger: s.logger,
gasLimit: gasLimit.Uint64(),
}
s.logger.WithFields(logrus.Fields{
"gasLimit": gasLimit.Uint64(),
"s.was.gp": s.was.gp,
}).Debug("Reset Write Ahead State")
}
//------------------------------------------------------------------------------
//InitState initializes the statedb object. It checks if there was already a
//root hash in the underlying database, in which case it initializes the statedb
//from that root.
func (s *State) InitState() error {
rootHash := common.Hash{}
/*//get head transaction hash
headTxHash := common.Hash{}
data, _ := s.db.Get(headTxKey)
if len(data) != 0 {
headTxHash = common.BytesToHash(data)
s.logger.WithField("head_tx", headTxHash.Hex()).Debug("Loading state from existing head")
//get head tx receipt
headTxReceipt, err := s.GetReceipt(headTxHash)
if err != nil {
s.logger.WithError(err).Error("Head transaction receipt missing")
return err
}
//extract root from receipt
if len(headTxReceipt.PostState) != 0 {
rootHash = common.BytesToHash(headTxReceipt.PostState)
s.logger.WithField("root", rootHash.Hex()).Debug("Head transaction root")
}
}
//use root to initialise the state
var err error
s.ethState, err = ethState.New(rootHash, ethState.NewDatabase(s.db))
return err*/
// Use root instead
//get root hash
data, _ := s.db.Get(rootKey)
if len(data) != 0 {
rootHash = common.BytesToHash(data)
s.logger.WithField("root", rootHash.Hex()).Debug("Existing State Root")
}
//use root to initialise the state
var err error
s.ethState, err = ethState.New(rootHash, ethState.NewDatabase(s.db))
if err != nil {
return err
}
s.was, err = NewWriteAheadState(s.db, rootHash, s.signer, s.chainConfig, s.vmConfig, gasLimit.Uint64(), s.logger)
if err != nil {
return err
}
s.txPool = NewTxPool(s.ethState.Copy(), s.signer, s.chainConfig, s.vmConfig, gasLimit.Uint64(), s.logger)
return err
}
//CheckTx attempt to apply a transaction to the TxPool's statedb. It is called
//by the Service handlers to check if a transaction is valid before submitting
//it to the consensus system. This also updates the sender's Nonce in the
//TxPool's statedb.
func (s *State) CheckTx(tx *ethTypes.Transaction) error {
return s.txPool.CheckTx(tx)
}
//ApplyTransaction decodes a transaction and applies it to the WAS. It is meant
//to be called by the consensus system to apply transactions sequentially.
func (s *State) ApplyTransaction(txBytes []byte, txIndex int, blockHash common.Hash) error {
var t ethTypes.Transaction
if err := rlp.Decode(bytes.NewReader(txBytes), &t); err != nil {
s.logger.WithError(err).Error("Decoding Transaction")
return err
}
s.logger.WithField("hash", t.Hash().Hex()).Debug("Decoded tx")
return s.was.ApplyTransaction(t, txIndex, blockHash)
}
func (s *State) CreateAccounts(accounts bcommon.AccountMap) error {
s.commitMutex.Lock()
defer s.commitMutex.Unlock()
for addr, account := range accounts {
address := common.HexToAddress(addr)
if !s.Exist(address) {
s.was.ethState.AddBalance(address, math.MustParseBig256(account.Balance))
s.was.ethState.SetCode(address, common.Hex2Bytes(account.Code))
for key, value := range account.Storage {
s.was.ethState.SetState(address, common.HexToHash(key), common.HexToHash(value))
}
s.logger.WithField("address", addr).Debug("Adding account")
}
}
_, err := s.Commit()
return err
}
//Exist reports whether the given account address exists in the state.
func (s *State) Exist(addr common.Address) bool {
return s.ethState.Exist(addr)
}
func (s *State) GetBalance(addr common.Address) *big.Int {
return s.ethState.GetBalance(addr)
}
func (s *State) GetNonce(addr common.Address) uint64 {
return s.was.ethState.GetNonce(addr)
}
//GetPoolNonce returns an account's nonce from the txpool's ethState
func (s *State) GetPoolNonce(addr common.Address) uint64 {
return s.txPool.ethState.GetNonce(addr)
}
func (s *State) GetBlock(hash common.Hash) (*poset.Block, error) {
// Retrieve the block itself from the database
data, err := s.db.Get(hash.Bytes())
if err != nil {
s.logger.WithError(err).Error("GetBlock")
return nil, err
}
newBlock := new(poset.Block)
if err := newBlock.ProtoUnmarshal(data); err != nil {
s.logger.WithError(err).Error("GetBlock.newBlock := new(poset.Block)")
return nil, err
}
return newBlock, nil
}
func (s *State) GetBlockById(id int64) (*poset.Block, error) {
// Retrieve the block itself from the database
key := blockKey(id)
data, err := s.db.Get(key)
if err != nil {
s.logger.WithError(err).Error("GetBlockById")
return nil, err
}
newBlock := new(poset.Block)
if err := newBlock.ProtoUnmarshal(data); err != nil {
s.logger.WithError(err).Error("GetBlockById.newBlock := new(poset.Block)")
return nil, err
}
return newBlock, nil
}
func (s *State) GetTransaction(hash common.Hash) (*ethTypes.Transaction, error) {
// Retrieve the transaction itself from the database
data, err := s.db.Get(hash.Bytes())
if err != nil {
s.logger.WithError(err).Error("GetTransaction")
return nil, err
}
var tx ethTypes.Transaction
if err := rlp.DecodeBytes(data, &tx); err != nil {
s.logger.WithError(err).Error("Decoding Transaction")
return nil, err
}
return &tx, nil
}
func (s *State) GetReceipt(txHash common.Hash) (*ethTypes.Receipt, error) {
data, err := s.db.Get(append(receiptsPrefix, txHash[:]...))
if err != nil {
s.logger.WithError(err).Error("GetReceipt")
return nil, err
}
var receipt ethTypes.ReceiptForStorage
if err := rlp.DecodeBytes(data, &receipt); err != nil {
s.logger.WithError(err).Error("Decoding Receipt")
return nil, err
}
return (*ethTypes.Receipt)(&receipt), nil
}
func (s *State) GetFailedTx(txHash common.Hash) (*TxError, error) {
data, err := s.db.Get(append(errorPrefix, txHash[:]...))
if err != nil {
s.logger.WithError(err).Error("GetFailedTx")
return nil, err
}
newTx := new(TxError)
if err := newTx.Unmarshal(data); err != nil {
s.logger.WithError(err).Error("GetFailedTx.newTx := new(TxError)")
return nil, err
}
return newTx, nil
}