Skip to content

Commit 10a57fc

Browse files
committed
consensus, core/*, params: metropolis preparation refactor
This commit is a preparation for the upcoming metropolis hardfork. It prepares the state, core and vm packages such that integration with metropolis becomes less of a hassle. * Difficulty calculation requires header instead of individual parameters * statedb.StartRecord renamed to statedb.Prepare and added Finalise method required by metropolis, which removes unwanted accounts from the state (i.e. selfdestruct) * State keeps record of destructed objects (in addition to dirty objects) * core/vm pre-compiles may now return errors * core/vm pre-compiles gas check now take the full byte slice as argument instead of just the size * core/vm now keeps several hard-fork instruction tables instead of a single instruction table and removes the need for hard-fork checks in the instructions * core/vm contains a empty restruction function which is added in preparation of metropolis write-only mode operations * Adds the bn256 curve * Adds and sets the metropolis chain config block parameters (2^64-1)
1 parent a2f23ca commit 10a57fc

28 files changed

Lines changed: 2865 additions & 183 deletions

‎consensus/ethash/consensus.go‎

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent *
239239
return errZeroBlockTime
240240
}
241241
// Verify the block's difficulty based in it's timestamp and parent's difficulty
242-
expected := CalcDifficulty(chain.Config(), header.Time.Uint64(), parent.Time.Uint64(), parent.Number, parent.Difficulty)
242+
expected := CalcDifficulty(chain.Config(), header.Time.Uint64(), parent)
243243
if expected.Cmp(header.Difficulty) != 0 {
244244
return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
245245
}
@@ -283,16 +283,19 @@ func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent *
283283
return nil
284284
}
285285

286-
// CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
287-
// that a new block should have when created at time given the parent block's time
288-
// and difficulty.
286+
// CalcDifficulty is the difficulty adjustment algorithm. It returns
287+
// the difficulty that a new block should have when created at time
288+
// given the parent block's time and difficulty.
289289
//
290290
// TODO (karalabe): Move the chain maker into this package and make this private!
291-
func CalcDifficulty(config *params.ChainConfig, time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
292-
if config.IsHomestead(new(big.Int).Add(parentNumber, common.Big1)) {
293-
return calcDifficultyHomestead(time, parentTime, parentNumber, parentDiff)
291+
func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Header) *big.Int {
292+
next := new(big.Int).Add(parent.Number, common.Big1)
293+
switch {
294+
case config.IsHomestead(next):
295+
return calcDifficultyHomestead(time, parent)
296+
default:
297+
return calcDifficultyFrontier(time, parent)
294298
}
295-
return calcDifficultyFrontier(time, parentTime, parentNumber, parentDiff)
296299
}
297300

298301
// Some weird constants to avoid constant memory allocs for them.
@@ -305,15 +308,15 @@ var (
305308
// calcDifficultyHomestead is the difficulty adjustment algorithm. It returns
306309
// the difficulty that a new block should have when created at time given the
307310
// parent block's time and difficulty. The calculation uses the Homestead rules.
308-
func calcDifficultyHomestead(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
311+
func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
309312
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.mediawiki
310313
// algorithm:
311314
// diff = (parent_diff +
312315
// (parent_diff / 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
313316
// ) + 2^(periodCount - 2)
314317

315-
bigTime := new(big.Int).SetUint64(time)
316-
bigParentTime := new(big.Int).SetUint64(parentTime)
318+
bigTime := new(big.Int).Set(parent.Time)
319+
bigParentTime := new(big.Int).Set(parent.Time)
317320

318321
// holds intermediate values to make the algo easier to read & audit
319322
x := new(big.Int)
@@ -329,16 +332,16 @@ func calcDifficultyHomestead(time, parentTime uint64, parentNumber, parentDiff *
329332
x.Set(bigMinus99)
330333
}
331334
// (parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99))
332-
y.Div(parentDiff, params.DifficultyBoundDivisor)
335+
y.Div(parent.Difficulty, params.DifficultyBoundDivisor)
333336
x.Mul(y, x)
334-
x.Add(parentDiff, x)
337+
x.Add(parent.Difficulty, x)
335338

336339
// minimum difficulty can ever be (before exponential factor)
337340
if x.Cmp(params.MinimumDifficulty) < 0 {
338341
x.Set(params.MinimumDifficulty)
339342
}
340343
// for the exponential factor
341-
periodCount := new(big.Int).Add(parentNumber, common.Big1)
344+
periodCount := new(big.Int).Add(parent.Number, common.Big1)
342345
periodCount.Div(periodCount, expDiffPeriod)
343346

344347
// the exponential factor, commonly referred to as "the bomb"
@@ -354,25 +357,25 @@ func calcDifficultyHomestead(time, parentTime uint64, parentNumber, parentDiff *
354357
// calcDifficultyFrontier is the difficulty adjustment algorithm. It returns the
355358
// difficulty that a new block should have when created at time given the parent
356359
// block's time and difficulty. The calculation uses the Frontier rules.
357-
func calcDifficultyFrontier(time, parentTime uint64, parentNumber, parentDiff *big.Int) *big.Int {
360+
func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
358361
diff := new(big.Int)
359-
adjust := new(big.Int).Div(parentDiff, params.DifficultyBoundDivisor)
362+
adjust := new(big.Int).Div(parent.Difficulty, params.DifficultyBoundDivisor)
360363
bigTime := new(big.Int)
361364
bigParentTime := new(big.Int)
362365

363366
bigTime.SetUint64(time)
364-
bigParentTime.SetUint64(parentTime)
367+
bigParentTime.Set(parent.Time)
365368

366369
if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
367-
diff.Add(parentDiff, adjust)
370+
diff.Add(parent.Difficulty, adjust)
368371
} else {
369-
diff.Sub(parentDiff, adjust)
372+
diff.Sub(parent.Difficulty, adjust)
370373
}
371374
if diff.Cmp(params.MinimumDifficulty) < 0 {
372375
diff.Set(params.MinimumDifficulty)
373376
}
374377

375-
periodCount := new(big.Int).Add(parentNumber, common.Big1)
378+
periodCount := new(big.Int).Add(parent.Number, common.Big1)
376379
periodCount.Div(periodCount, expDiffPeriod)
377380
if periodCount.Cmp(common.Big1) > 0 {
378381
// diff = diff + 2^(periodCount - 2)
@@ -434,8 +437,7 @@ func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header)
434437
if parent == nil {
435438
return consensus.ErrUnknownAncestor
436439
}
437-
header.Difficulty = CalcDifficulty(chain.Config(), header.Time.Uint64(),
438-
parent.Time.Uint64(), parent.Number, parent.Difficulty)
440+
header.Difficulty = CalcDifficulty(chain.Config(), header.Time.Uint64(), parent)
439441

440442
return nil
441443
}

‎consensus/ethash/consensus_test.go‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"testing"
2424

2525
"github.com/ethereum/go-ethereum/common/math"
26+
"github.com/ethereum/go-ethereum/core/types"
2627
"github.com/ethereum/go-ethereum/params"
2728
)
2829

@@ -71,7 +72,11 @@ func TestCalcDifficulty(t *testing.T) {
7172
config := &params.ChainConfig{HomesteadBlock: big.NewInt(1150000)}
7273
for name, test := range tests {
7374
number := new(big.Int).Sub(test.CurrentBlocknumber, big.NewInt(1))
74-
diff := CalcDifficulty(config, test.CurrentTimestamp, test.ParentTimestamp, number, test.ParentDifficulty)
75+
diff := CalcDifficulty(config, test.CurrentTimestamp, &types.Header{
76+
Number: number,
77+
Time: test.ParentTimestamp,
78+
Difficulty: test.ParentDifficulty,
79+
})
7580
if diff.Cmp(test.CurrentDifficulty) != 0 {
7681
t.Error(name, "failed. Expected", test.CurrentDifficulty, "and calculated", diff)
7782
}

‎core/chain_makers.go‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ func (b *BlockGen) AddTx(tx *types.Transaction) {
8484
if b.gasPool == nil {
8585
b.SetCoinbase(common.Address{})
8686
}
87-
b.statedb.StartRecord(tx.Hash(), common.Hash{}, len(b.txs))
87+
b.statedb.Prepare(tx.Hash(), common.Hash{}, len(b.txs))
8888
receipt, _, err := ApplyTransaction(b.config, nil, &b.header.Coinbase, b.gasPool, b.statedb, b.header, tx, b.header.GasUsed, vm.Config{})
8989
if err != nil {
9090
panic(err)
@@ -142,7 +142,7 @@ func (b *BlockGen) OffsetTime(seconds int64) {
142142
if b.header.Time.Cmp(b.parent.Header().Time) <= 0 {
143143
panic("block time out of range")
144144
}
145-
b.header.Difficulty = ethash.CalcDifficulty(b.config, b.header.Time.Uint64(), b.parent.Time().Uint64(), b.parent.Number(), b.parent.Difficulty())
145+
b.header.Difficulty = ethash.CalcDifficulty(b.config, b.header.Time.Uint64(), b.parent.Header())
146146
}
147147

148148
// GenerateChain creates a chain of n blocks. The first block's
@@ -209,15 +209,23 @@ func makeHeader(config *params.ChainConfig, parent *types.Block, state *state.St
209209
} else {
210210
time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds
211211
}
212+
parentHeader := parent.Header()
213+
// adjust the parent time
214+
parentHeader.Time = new(big.Int).Sub(time, big.NewInt(10))
215+
212216
return &types.Header{
213217
Root: state.IntermediateRoot(config.IsEIP158(parent.Number())),
214218
ParentHash: parent.Hash(),
215219
Coinbase: parent.Coinbase(),
216-
Difficulty: ethash.CalcDifficulty(config, time.Uint64(), new(big.Int).Sub(time, big.NewInt(10)).Uint64(), parent.Number(), parent.Difficulty()),
217-
GasLimit: CalcGasLimit(parent),
218-
GasUsed: new(big.Int),
219-
Number: new(big.Int).Add(parent.Number(), common.Big1),
220-
Time: time,
220+
Difficulty: ethash.CalcDifficulty(config, time.Uint64(), &types.Header{
221+
Number: parent.Number(),
222+
Time: new(big.Int).Sub(time, big.NewInt(10)),
223+
Difficulty: parent.Difficulty(),
224+
}),
225+
GasLimit: CalcGasLimit(parent),
226+
GasUsed: new(big.Int),
227+
Number: new(big.Int).Add(parent.Number(), common.Big1),
228+
Time: time,
221229
}
222230
}
223231

‎core/state/statedb.go‎

Lines changed: 57 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,9 @@ type StateDB struct {
6262
codeSizeCache *lru.Cache
6363

6464
// This map holds 'live' objects, which will get modified while processing a state transition.
65-
stateObjects map[common.Address]*stateObject
66-
stateObjectsDirty map[common.Address]struct{}
65+
stateObjects map[common.Address]*stateObject
66+
stateObjectsDirty map[common.Address]struct{}
67+
stateObjectsDestructed map[common.Address]struct{}
6768

6869
// The refund counter, also used by state transitioning.
6970
refund *big.Int
@@ -92,14 +93,15 @@ func New(root common.Hash, db ethdb.Database) (*StateDB, error) {
9293
}
9394
csc, _ := lru.New(codeSizeCacheSize)
9495
return &StateDB{
95-
db: db,
96-
trie: tr,
97-
codeSizeCache: csc,
98-
stateObjects: make(map[common.Address]*stateObject),
99-
stateObjectsDirty: make(map[common.Address]struct{}),
100-
refund: new(big.Int),
101-
logs: make(map[common.Hash][]*types.Log),
102-
preimages: make(map[common.Hash][]byte),
96+
db: db,
97+
trie: tr,
98+
codeSizeCache: csc,
99+
stateObjects: make(map[common.Address]*stateObject),
100+
stateObjectsDirty: make(map[common.Address]struct{}),
101+
stateObjectsDestructed: make(map[common.Address]struct{}),
102+
refund: new(big.Int),
103+
logs: make(map[common.Hash][]*types.Log),
104+
preimages: make(map[common.Hash][]byte),
103105
}, nil
104106
}
105107

@@ -114,14 +116,15 @@ func (self *StateDB) New(root common.Hash) (*StateDB, error) {
114116
return nil, err
115117
}
116118
return &StateDB{
117-
db: self.db,
118-
trie: tr,
119-
codeSizeCache: self.codeSizeCache,
120-
stateObjects: make(map[common.Address]*stateObject),
121-
stateObjectsDirty: make(map[common.Address]struct{}),
122-
refund: new(big.Int),
123-
logs: make(map[common.Hash][]*types.Log),
124-
preimages: make(map[common.Hash][]byte),
119+
db: self.db,
120+
trie: tr,
121+
codeSizeCache: self.codeSizeCache,
122+
stateObjects: make(map[common.Address]*stateObject),
123+
stateObjectsDirty: make(map[common.Address]struct{}),
124+
stateObjectsDestructed: make(map[common.Address]struct{}),
125+
refund: new(big.Int),
126+
logs: make(map[common.Hash][]*types.Log),
127+
preimages: make(map[common.Hash][]byte),
125128
}, nil
126129
}
127130

@@ -138,6 +141,7 @@ func (self *StateDB) Reset(root common.Hash) error {
138141
self.trie = tr
139142
self.stateObjects = make(map[common.Address]*stateObject)
140143
self.stateObjectsDirty = make(map[common.Address]struct{})
144+
self.stateObjectsDestructed = make(map[common.Address]struct{})
141145
self.thash = common.Hash{}
142146
self.bhash = common.Hash{}
143147
self.txIndex = 0
@@ -173,12 +177,6 @@ func (self *StateDB) pushTrie(t *trie.SecureTrie) {
173177
}
174178
}
175179

176-
func (self *StateDB) StartRecord(thash, bhash common.Hash, ti int) {
177-
self.thash = thash
178-
self.bhash = bhash
179-
self.txIndex = ti
180-
}
181-
182180
func (self *StateDB) AddLog(log *types.Log) {
183181
self.journal = append(self.journal, addLogChange{txhash: self.thash})
184182

@@ -510,21 +508,25 @@ func (self *StateDB) Copy() *StateDB {
510508

511509
// Copy all the basic fields, initialize the memory ones
512510
state := &StateDB{
513-
db: self.db,
514-
trie: self.trie,
515-
pastTries: self.pastTries,
516-
codeSizeCache: self.codeSizeCache,
517-
stateObjects: make(map[common.Address]*stateObject, len(self.stateObjectsDirty)),
518-
stateObjectsDirty: make(map[common.Address]struct{}, len(self.stateObjectsDirty)),
519-
refund: new(big.Int).Set(self.refund),
520-
logs: make(map[common.Hash][]*types.Log, len(self.logs)),
521-
logSize: self.logSize,
522-
preimages: make(map[common.Hash][]byte),
511+
db: self.db,
512+
trie: self.trie,
513+
pastTries: self.pastTries,
514+
codeSizeCache: self.codeSizeCache,
515+
stateObjects: make(map[common.Address]*stateObject, len(self.stateObjectsDirty)),
516+
stateObjectsDirty: make(map[common.Address]struct{}, len(self.stateObjectsDirty)),
517+
stateObjectsDestructed: make(map[common.Address]struct{}, len(self.stateObjectsDestructed)),
518+
refund: new(big.Int).Set(self.refund),
519+
logs: make(map[common.Hash][]*types.Log, len(self.logs)),
520+
logSize: self.logSize,
521+
preimages: make(map[common.Hash][]byte),
523522
}
524523
// Copy the dirty states, logs, and preimages
525524
for addr := range self.stateObjectsDirty {
526525
state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state, state.MarkStateObjectDirty)
527526
state.stateObjectsDirty[addr] = struct{}{}
527+
if self.stateObjects[addr].suicided {
528+
state.stateObjectsDestructed[addr] = struct{}{}
529+
}
528530
}
529531
for hash, logs := range self.logs {
530532
state.logs[hash] = make([]*types.Log, len(logs))
@@ -590,6 +592,27 @@ func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
590592
return s.trie.Hash()
591593
}
592594

595+
// Prepare sets the current transaction hash and index and block hash which is
596+
// used when the EVM emits new state logs.
597+
func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) {
598+
self.thash = thash
599+
self.bhash = bhash
600+
self.txIndex = ti
601+
}
602+
603+
// Finalise finalises the state by removing the self destructed objects
604+
// in the current stateObjectsDestructed buffer and clears the journal
605+
// as well as the refunds.
606+
//
607+
// Please note that Finalise is used by EIP#98 and is used instead of
608+
// IntermediateRoot.
609+
func (s *StateDB) Finalise() {
610+
for addr := range s.stateObjectsDestructed {
611+
s.deleteStateObject(s.stateObjects[addr])
612+
}
613+
s.clearJournalAndRefund()
614+
}
615+
593616
// DeleteSuicides flags the suicided objects for deletion so that it
594617
// won't be referenced again when called / queried up on.
595618
//

‎core/state_processor.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg
6969
}
7070
// Iterate over and process the individual transactions
7171
for i, tx := range block.Transactions() {
72-
statedb.StartRecord(tx.Hash(), block.Hash(), i)
72+
statedb.Prepare(tx.Hash(), block.Hash(), i)
7373
receipt, _, err := ApplyTransaction(p.config, p.bc, nil, gp, statedb, header, tx, totalUsedGas, cfg)
7474
if err != nil {
7575
return nil, nil, nil, err
@@ -107,7 +107,8 @@ func ApplyTransaction(config *params.ChainConfig, bc *BlockChain, author *common
107107
usedGas.Add(usedGas, gas)
108108
// Create a new receipt for the transaction, storing the intermediate root and gas used by the tx
109109
// based on the eip phase, we're passing wether the root touch-delete accounts.
110-
receipt := types.NewReceipt(statedb.IntermediateRoot(config.IsEIP158(header.Number)).Bytes(), usedGas)
110+
root := statedb.IntermediateRoot(config.IsEIP158(header.Number))
111+
receipt := types.NewReceipt(root.Bytes(), usedGas)
111112
receipt.TxHash = tx.Hash()
112113
receipt.GasUsed = new(big.Int).Set(gas)
113114
// if the transaction created a contract, store the creation address in the receipt.

‎core/types/transaction_signing.go‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,12 @@ import (
2727
"github.com/ethereum/go-ethereum/params"
2828
)
2929

30-
var ErrInvalidChainId = errors.New("invalid chaid id for signer")
30+
var (
31+
ErrInvalidChainId = errors.New("invalid chaid id for signer")
32+
33+
errAbstractSigner = errors.New("abstract signer")
34+
abstractSignerAddress = common.HexToAddress("ffffffffffffffffffffffffffffffffffffff")
35+
)
3136

3237
// sigCache is used to cache the derived sender and contains
3338
// the signer used to derive it.
@@ -103,6 +108,17 @@ type Signer interface {
103108
Equal(Signer) bool
104109
}
105110

111+
/*
112+
// WithSignature returns a new transaction with the given signature. This signature
113+
// needs to be in the [R || S || V] format where V is 0 or 1.
114+
func (s EIP86Signer) WithSignature(tx *Transaction, sig []byte) (*Transaction, error) {
115+
}
116+
117+
// Hash returns the hash to be signed by the sender.
118+
// It does not uniquely identify the transaction.
119+
func (s EIP86Signer) Hash(tx *Transaction) common.Hash {}
120+
*/
121+
106122
// EIP155Transaction implements TransactionInterface using the
107123
// EIP155 rules
108124
type EIP155Signer struct {

0 commit comments

Comments
 (0)