Skip to content

Commit 59f0b61

Browse files
authored
Merge branch 'ethereum:master' into gethintegration
2 parents c879bcc + fa86416 commit 59f0b61

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

55 files changed

+784
-349
lines changed

beacon/blsync/engineclient.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import (
2626
"github.com/ethereum/go-ethereum/beacon/params"
2727
"github.com/ethereum/go-ethereum/beacon/types"
2828
"github.com/ethereum/go-ethereum/common"
29+
"github.com/ethereum/go-ethereum/common/hexutil"
2930
ctypes "github.com/ethereum/go-ethereum/core/types"
3031
"github.com/ethereum/go-ethereum/log"
3132
"github.com/ethereum/go-ethereum/rpc"
@@ -104,7 +105,11 @@ func (ec *engineClient) callNewPayload(fork string, event types.ChainHeadEvent)
104105
method = "engine_newPayloadV4"
105106
parentBeaconRoot := event.BeaconHead.ParentRoot
106107
blobHashes := collectBlobHashes(event.Block)
107-
params = append(params, blobHashes, parentBeaconRoot, event.ExecRequests)
108+
hexRequests := make([]hexutil.Bytes, len(event.ExecRequests))
109+
for i := range event.ExecRequests {
110+
hexRequests[i] = hexutil.Bytes(event.ExecRequests[i])
111+
}
112+
params = append(params, blobHashes, parentBeaconRoot, hexRequests)
108113
case "deneb":
109114
method = "engine_newPayloadV3"
110115
parentBeaconRoot := event.BeaconHead.ParentRoot

cmd/geth/consolecmd_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,17 +102,17 @@ func TestAttachWelcome(t *testing.T) {
102102
"--http", "--http.port", httpPort,
103103
"--ws", "--ws.port", wsPort)
104104
t.Run("ipc", func(t *testing.T) {
105-
waitForEndpoint(t, ipc, 4*time.Second)
105+
waitForEndpoint(t, ipc, 2*time.Minute)
106106
testAttachWelcome(t, geth, "ipc:"+ipc, ipcAPIs)
107107
})
108108
t.Run("http", func(t *testing.T) {
109109
endpoint := "http://127.0.0.1:" + httpPort
110-
waitForEndpoint(t, endpoint, 4*time.Second)
110+
waitForEndpoint(t, endpoint, 2*time.Minute)
111111
testAttachWelcome(t, geth, endpoint, httpAPIs)
112112
})
113113
t.Run("ws", func(t *testing.T) {
114114
endpoint := "ws://127.0.0.1:" + wsPort
115-
waitForEndpoint(t, endpoint, 4*time.Second)
115+
waitForEndpoint(t, endpoint, 2*time.Minute)
116116
testAttachWelcome(t, geth, endpoint, httpAPIs)
117117
})
118118
geth.Kill()

core/bench_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ func benchInsertChain(b *testing.B, disk bool, gen func(int, *BlockGen)) {
183183
if !disk {
184184
db = rawdb.NewMemoryDatabase()
185185
} else {
186-
pdb, err := pebble.New(b.TempDir(), 128, 128, "", false, true)
186+
pdb, err := pebble.New(b.TempDir(), 128, 128, "", false)
187187
if err != nil {
188188
b.Fatalf("cannot create temporary database: %v", err)
189189
}
@@ -303,7 +303,7 @@ func makeChainForBench(db ethdb.Database, genesis *Genesis, full bool, count uin
303303
func benchWriteChain(b *testing.B, full bool, count uint64) {
304304
genesis := &Genesis{Config: params.AllEthashProtocolChanges}
305305
for i := 0; i < b.N; i++ {
306-
pdb, err := pebble.New(b.TempDir(), 1024, 128, "", false, true)
306+
pdb, err := pebble.New(b.TempDir(), 1024, 128, "", false)
307307
if err != nil {
308308
b.Fatalf("error opening database: %v", err)
309309
}
@@ -316,7 +316,7 @@ func benchWriteChain(b *testing.B, full bool, count uint64) {
316316
func benchReadChain(b *testing.B, full bool, count uint64) {
317317
dir := b.TempDir()
318318

319-
pdb, err := pebble.New(dir, 1024, 128, "", false, true)
319+
pdb, err := pebble.New(dir, 1024, 128, "", false)
320320
if err != nil {
321321
b.Fatalf("error opening database: %v", err)
322322
}
@@ -332,7 +332,7 @@ func benchReadChain(b *testing.B, full bool, count uint64) {
332332
b.ResetTimer()
333333

334334
for i := 0; i < b.N; i++ {
335-
pdb, err = pebble.New(dir, 1024, 128, "", false, true)
335+
pdb, err = pebble.New(dir, 1024, 128, "", false)
336336
if err != nil {
337337
b.Fatalf("error opening database: %v", err)
338338
}

core/blockchain.go

Lines changed: 94 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,8 @@ var (
6565
headFinalizedBlockGauge = metrics.NewRegisteredGauge("chain/head/finalized", nil)
6666
headSafeBlockGauge = metrics.NewRegisteredGauge("chain/head/safe", nil)
6767

68-
chainInfoGauge = metrics.NewRegisteredGaugeInfo("chain/info", nil)
68+
chainInfoGauge = metrics.NewRegisteredGaugeInfo("chain/info", nil)
69+
chainMgaspsGauge = metrics.NewRegisteredGauge("chain/mgasps", nil)
6970

7071
accountReadTimer = metrics.NewRegisteredResettingTimer("chain/account/reads", nil)
7172
accountHashTimer = metrics.NewRegisteredResettingTimer("chain/account/hashes", nil)
@@ -92,8 +93,10 @@ var (
9293
blockReorgAddMeter = metrics.NewRegisteredMeter("chain/reorg/add", nil)
9394
blockReorgDropMeter = metrics.NewRegisteredMeter("chain/reorg/drop", nil)
9495

95-
blockPrefetchExecuteTimer = metrics.NewRegisteredTimer("chain/prefetch/executes", nil)
96-
blockPrefetchInterruptMeter = metrics.NewRegisteredMeter("chain/prefetch/interrupts", nil)
96+
blockPrefetchExecuteTimer = metrics.NewRegisteredResettingTimer("chain/prefetch/executes", nil)
97+
blockPrefetchInterruptMeter = metrics.NewRegisteredMeter("chain/prefetch/interrupts", nil)
98+
blockPrefetchTxsInvalidMeter = metrics.NewRegisteredMeter("chain/prefetch/txs/invalid", nil)
99+
blockPrefetchTxsValidMeter = metrics.NewRegisteredMeter("chain/prefetch/txs/valid", nil)
97100

98101
errInsertionInterrupted = errors.New("insertion is interrupted")
99102
errChainStopped = errors.New("blockchain is stopped")
@@ -979,17 +982,16 @@ func (bc *BlockChain) setHeadBeyondRoot(head uint64, time uint64, root common.Ha
979982
// Ignore the error here since light client won't hit this path
980983
frozen, _ := bc.db.Ancients()
981984
if num+1 <= frozen {
982-
// Truncate all relative data(header, total difficulty, body, receipt
983-
// and canonical hash) from ancient store.
984-
if _, err := bc.db.TruncateHead(num); err != nil {
985-
log.Crit("Failed to truncate ancient data", "number", num, "err", err)
986-
}
987-
// Remove the hash <-> number mapping from the active store.
988-
rawdb.DeleteHeaderNumber(db, hash)
985+
// The chain segment, such as the block header, canonical hash,
986+
// body, and receipt, will be removed from the ancient store
987+
// in one go.
988+
//
989+
// The hash-to-number mapping in the key-value store will be
990+
// removed by the hc.SetHead function.
989991
} else {
990-
// Remove relative body and receipts from the active store.
991-
// The header, total difficulty and canonical hash will be
992-
// removed in the hc.SetHead function.
992+
// Remove the associated body and receipts from the key-value store.
993+
// The header, hash-to-number mapping, and canonical hash will be
994+
// removed by the hc.SetHead function.
993995
rawdb.DeleteBody(db, hash, num)
994996
rawdb.DeleteReceipts(db, hash, num)
995997
}
@@ -1361,7 +1363,7 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [
13611363
size += writeSize
13621364

13631365
// Sync the ancient store explicitly to ensure all data has been flushed to disk.
1364-
if err := bc.db.Sync(); err != nil {
1366+
if err := bc.db.SyncAncient(); err != nil {
13651367
return 0, err
13661368
}
13671369
// Write hash to number mappings
@@ -1759,18 +1761,6 @@ func (bc *BlockChain) insertChain(chain types.Blocks, setHead bool, makeWitness
17591761
bc.reportBlock(block, nil, err)
17601762
return nil, it.index, err
17611763
}
1762-
// No validation errors for the first block (or chain prefix skipped)
1763-
var activeState *state.StateDB
1764-
defer func() {
1765-
// The chain importer is starting and stopping trie prefetchers. If a bad
1766-
// block or other error is hit however, an early return may not properly
1767-
// terminate the background threads. This defer ensures that we clean up
1768-
// and dangling prefetcher, without deferring each and holding on live refs.
1769-
if activeState != nil {
1770-
activeState.StopPrefetcher()
1771-
}
1772-
}()
1773-
17741764
// Track the singleton witness from this chain insertion (if any)
17751765
var witness *stateless.Witness
17761766

@@ -1826,63 +1816,20 @@ func (bc *BlockChain) insertChain(chain types.Blocks, setHead bool, makeWitness
18261816
continue
18271817
}
18281818
// Retrieve the parent block and it's state to execute on top
1829-
start := time.Now()
18301819
parent := it.previous()
18311820
if parent == nil {
18321821
parent = bc.GetHeader(block.ParentHash(), block.NumberU64()-1)
18331822
}
1834-
statedb, err := state.New(parent.Root, bc.statedb)
1835-
if err != nil {
1836-
return nil, it.index, err
1837-
}
1838-
1839-
// If we are past Byzantium, enable prefetching to pull in trie node paths
1840-
// while processing transactions. Before Byzantium the prefetcher is mostly
1841-
// useless due to the intermediate root hashing after each transaction.
1842-
if bc.chainConfig.IsByzantium(block.Number()) {
1843-
// Generate witnesses either if we're self-testing, or if it's the
1844-
// only block being inserted. A bit crude, but witnesses are huge,
1845-
// so we refuse to make an entire chain of them.
1846-
if bc.vmConfig.StatelessSelfValidation || (makeWitness && len(chain) == 1) {
1847-
witness, err = stateless.NewWitness(block.Header(), bc)
1848-
if err != nil {
1849-
return nil, it.index, err
1850-
}
1851-
}
1852-
statedb.StartPrefetcher("chain", witness)
1853-
}
1854-
activeState = statedb
1855-
1856-
// If we have a followup block, run that against the current state to pre-cache
1857-
// transactions and probabilistically some of the account/storage trie nodes.
1858-
var followupInterrupt atomic.Bool
1859-
if !bc.cacheConfig.TrieCleanNoPrefetch {
1860-
if followup, err := it.peek(); followup != nil && err == nil {
1861-
throwaway, _ := state.New(parent.Root, bc.statedb)
1862-
1863-
go func(start time.Time, followup *types.Block, throwaway *state.StateDB) {
1864-
// Disable tracing for prefetcher executions.
1865-
vmCfg := bc.vmConfig
1866-
vmCfg.Tracer = nil
1867-
bc.prefetcher.Prefetch(followup, throwaway, vmCfg, &followupInterrupt)
1868-
1869-
blockPrefetchExecuteTimer.Update(time.Since(start))
1870-
if followupInterrupt.Load() {
1871-
blockPrefetchInterruptMeter.Mark(1)
1872-
}
1873-
}(time.Now(), followup, throwaway)
1874-
}
1875-
}
1876-
18771823
// The traced section of block import.
1878-
res, err := bc.processBlock(block, statedb, start, setHead)
1879-
followupInterrupt.Store(true)
1824+
start := time.Now()
1825+
res, err := bc.processBlock(parent.Root, block, setHead, makeWitness && len(chain) == 1)
18801826
if err != nil {
18811827
return nil, it.index, err
18821828
}
18831829
// Report the import stats before returning the various results
18841830
stats.processed++
18851831
stats.usedGas += res.usedGas
1832+
witness = res.witness
18861833

18871834
var snapDiffItems, snapBufItems common.StorageSize
18881835
if bc.snaps != nil {
@@ -1938,11 +1885,74 @@ type blockProcessingResult struct {
19381885
usedGas uint64
19391886
procTime time.Duration
19401887
status WriteStatus
1888+
witness *stateless.Witness
19411889
}
19421890

19431891
// processBlock executes and validates the given block. If there was no error
19441892
// it writes the block and associated state to database.
1945-
func (bc *BlockChain) processBlock(block *types.Block, statedb *state.StateDB, start time.Time, setHead bool) (_ *blockProcessingResult, blockEndErr error) {
1893+
func (bc *BlockChain) processBlock(parentRoot common.Hash, block *types.Block, setHead bool, makeWitness bool) (_ *blockProcessingResult, blockEndErr error) {
1894+
var (
1895+
err error
1896+
startTime = time.Now()
1897+
statedb *state.StateDB
1898+
interrupt atomic.Bool
1899+
)
1900+
defer interrupt.Store(true) // terminate the prefetch at the end
1901+
1902+
if bc.cacheConfig.TrieCleanNoPrefetch {
1903+
statedb, err = state.New(parentRoot, bc.statedb)
1904+
if err != nil {
1905+
return nil, err
1906+
}
1907+
} else {
1908+
// If prefetching is enabled, run that against the current state to pre-cache
1909+
// transactions and probabilistically some of the account/storage trie nodes.
1910+
//
1911+
// Note: the main processor and prefetcher share the same reader with a local
1912+
// cache for mitigating the overhead of state access.
1913+
reader, err := bc.statedb.ReaderWithCache(parentRoot)
1914+
if err != nil {
1915+
return nil, err
1916+
}
1917+
throwaway, err := state.NewWithReader(parentRoot, bc.statedb, reader)
1918+
if err != nil {
1919+
return nil, err
1920+
}
1921+
statedb, err = state.NewWithReader(parentRoot, bc.statedb, reader)
1922+
if err != nil {
1923+
return nil, err
1924+
}
1925+
go func(start time.Time, throwaway *state.StateDB, block *types.Block) {
1926+
// Disable tracing for prefetcher executions.
1927+
vmCfg := bc.vmConfig
1928+
vmCfg.Tracer = nil
1929+
bc.prefetcher.Prefetch(block, throwaway, vmCfg, &interrupt)
1930+
1931+
blockPrefetchExecuteTimer.Update(time.Since(start))
1932+
if interrupt.Load() {
1933+
blockPrefetchInterruptMeter.Mark(1)
1934+
}
1935+
}(time.Now(), throwaway, block)
1936+
}
1937+
1938+
// If we are past Byzantium, enable prefetching to pull in trie node paths
1939+
// while processing transactions. Before Byzantium the prefetcher is mostly
1940+
// useless due to the intermediate root hashing after each transaction.
1941+
var witness *stateless.Witness
1942+
if bc.chainConfig.IsByzantium(block.Number()) {
1943+
// Generate witnesses either if we're self-testing, or if it's the
1944+
// only block being inserted. A bit crude, but witnesses are huge,
1945+
// so we refuse to make an entire chain of them.
1946+
if bc.vmConfig.StatelessSelfValidation || makeWitness {
1947+
witness, err = stateless.NewWitness(block.Header(), bc)
1948+
if err != nil {
1949+
return nil, err
1950+
}
1951+
}
1952+
statedb.StartPrefetcher("chain", witness)
1953+
defer statedb.StopPrefetcher()
1954+
}
1955+
19461956
if bc.logger != nil && bc.logger.OnBlockStart != nil {
19471957
bc.logger.OnBlockStart(tracing.BlockEvent{
19481958
Block: block,
@@ -2001,7 +2011,7 @@ func (bc *BlockChain) processBlock(block *types.Block, statedb *state.StateDB, s
20012011
}
20022012
}
20032013
xvtime := time.Since(xvstart)
2004-
proctime := time.Since(start) // processing + validation + cross validation
2014+
proctime := time.Since(startTime) // processing + validation + cross validation
20052015

20062016
// Update the metrics touched during block processing and validation
20072017
accountReadTimer.Update(statedb.AccountReads) // Account reads are complete(in processing)
@@ -2042,9 +2052,14 @@ func (bc *BlockChain) processBlock(block *types.Block, statedb *state.StateDB, s
20422052
triedbCommitTimer.Update(statedb.TrieDBCommits) // Trie database commits are complete, we can mark them
20432053

20442054
blockWriteTimer.Update(time.Since(wstart) - max(statedb.AccountCommits, statedb.StorageCommits) /* concurrent */ - statedb.SnapshotCommits - statedb.TrieDBCommits)
2045-
blockInsertTimer.UpdateSince(start)
2046-
2047-
return &blockProcessingResult{usedGas: res.GasUsed, procTime: proctime, status: status}, nil
2055+
blockInsertTimer.UpdateSince(startTime)
2056+
2057+
return &blockProcessingResult{
2058+
usedGas: res.GasUsed,
2059+
procTime: proctime,
2060+
status: status,
2061+
witness: witness,
2062+
}, nil
20482063
}
20492064

20502065
// insertSideChain is called when an import batch hits upon a pruned ancestor
@@ -2627,7 +2642,8 @@ func (bc *BlockChain) InsertHeadersBeforeCutoff(headers []*types.Header) (int, e
26272642
if err != nil {
26282643
return 0, err
26292644
}
2630-
if err := bc.db.Sync(); err != nil {
2645+
// Sync the ancient store explicitly to ensure all data has been flushed to disk.
2646+
if err := bc.db.SyncAncient(); err != nil {
26312647
return 0, err
26322648
}
26332649
// Write hash to number mappings

core/blockchain_insert.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,12 @@ func (st *insertStats) report(chain []*types.Block, index int, snapDiffItems, sn
4343
// Fetch the timings for the batch
4444
var (
4545
now = mclock.Now()
46-
elapsed = now.Sub(st.startTime)
46+
elapsed = now.Sub(st.startTime) + 1 // prevent zero division
47+
mgasps = float64(st.usedGas) * 1000 / float64(elapsed)
4748
)
49+
// Update the Mgas per second gauge
50+
chainMgaspsGauge.Update(int64(mgasps))
51+
4852
// If we're at the last block of the batch or report period reached, log
4953
if index == len(chain)-1 || elapsed >= statsReportLimit {
5054
// Count the number of transactions in this segment
@@ -58,7 +62,7 @@ func (st *insertStats) report(chain []*types.Block, index int, snapDiffItems, sn
5862
context := []interface{}{
5963
"number", end.Number(), "hash", end.Hash(),
6064
"blocks", st.processed, "txs", txs, "mgas", float64(st.usedGas) / 1000000,
61-
"elapsed", common.PrettyDuration(elapsed), "mgasps", float64(st.usedGas) * 1000 / float64(elapsed),
65+
"elapsed", common.PrettyDuration(elapsed), "mgasps", mgasps,
6266
}
6367
if timestamp := time.Unix(int64(end.Time()), 0); time.Since(timestamp) > time.Minute {
6468
context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...)
@@ -138,6 +142,7 @@ func (it *insertIterator) next() (*types.Block, error) {
138142
//
139143
// Both header and body validation errors (nil too) is cached into the iterator
140144
// to avoid duplicating work on the following next() call.
145+
// nolint:unused
141146
func (it *insertIterator) peek() (*types.Block, error) {
142147
// If we reached the end of the chain, abort
143148
if it.index+1 >= len(it.chain) {

0 commit comments

Comments
 (0)