Commit graph

408 commits

Author SHA1 Message Date
Jonny Rhea
c709c19b40
eth/catalyst: add initial OpenTelemetry tracing for newPayload (#33521)
This PR adds initial OpenTelemetry tracing to the Engine API, focusing
on engine_newPayload*.

```
jsonrpc.engine/newPayloadV4 
|  |- engine.newPayload  [block.number, block.hash, tx.count]
|     |- core.blockchain.InsertBlockWithoutSetHead
|        |- bc.processor.Process
|        |  |- core.ApplyTransactionWithEVM  [tx.hash, tx.index]
|        |  |- core.ApplyTransactionWithEVM  [tx.hash, tx.index]
|        |  |- ...  (one per transaction)
|        |  |- core.postExecution
|        |- bc.validator.ValidateState
```

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2026-02-17 17:08:57 +01:00
CPerezz
1e9dfd5bb0
core: standardize slow block JSON output for cross-client metrics (#33655)
Some checks are pending
/ Docker Image (push) Waiting to run
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
/ Keeper Build (push) Waiting to run
/ Windows Build (push) Waiting to run
Implement standardized JSON format for slow block logging to enable
cross-client performance analysis and protocol research.

This change is part of the Cross-Client Execution Metrics initiative
proposed by Gary Rong: https://hackmd.io/dg7rizTyTXuCf2LSa2LsyQ

The standardized metrics enabled data-driven analysis like the EIP-7907
research: https://ethresear.ch/t/data-driven-analysis-on-eip-7907/23850

JSON format includes:
- block: number, hash, gas_used, tx_count
- timing: execution_ms, total_ms
- throughput: mgas_per_sec
- state_reads: accounts, storage_slots, bytecodes, code_bytes
- state_writes: accounts, storage_slots, bytecodes
- cache: account/storage/code hits, misses, hit_rate


This should come after merging #33522

---------

Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2026-01-28 20:58:41 +08:00
rjl493456442
c2595381bf
core: extend the code reader statistics (#33659)
Some checks are pending
/ Windows Build (push) Waiting to run
/ Docker Image (push) Waiting to run
/ Keeper Build (push) Waiting to run
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
This PR extends the statistics of contract code read by adding these
fields:

- **CacheHitBytes**: the total number of bytes served by cache
- **CacheMissBytes**: the total number of bytes read on cache miss
- **CodeReadBytes**: the total number of bytes for contract code read
2026-01-26 11:25:53 +01:00
rjl493456442
1022c7637d
core, eth, internal, triedb/pathdb: enable eth_getProofs for history (#32727)
Some checks are pending
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
/ Keeper Build (push) Waiting to run
/ Windows Build (push) Waiting to run
/ Docker Image (push) Waiting to run
This PR enables the `eth_getProofs ` endpoint against the historical states.
2026-01-22 09:19:27 +08:00
rjl493456442
add1890a57
triedb/pathdb: enable trienode history (#32621)
It's the part-4 for trienode history. The trienode history persistence
has been enabled with this PR by flag `history.trienode <non-negative-number>`
2026-01-17 21:23:48 +08:00
Csaba Kiraly
127d1f42bb
core: remove duplicate chainHeadFeed.Send code (#33563)
Some checks failed
/ Linux Build (push) Has been cancelled
/ Linux Build (arm) (push) Has been cancelled
/ Keeper Build (push) Has been cancelled
/ Windows Build (push) Has been cancelled
/ Docker Image (push) Has been cancelled
The code was simply duplicate, so we can remove some code lines here.

Signed-off-by: Csaba Kiraly <csaba.kiraly@gmail.com>
2026-01-09 14:40:40 +01:00
Ng Wei Han
01b39c96bf
core/state, core/tracing: new state update hook (#33490)
### Description
Add a new `OnStateUpdate` hook which gets invoked after state is
committed.

### Rationale
For our particular use case, we need to obtain the state size metrics at
every single block when fuly syncing from genesis. With the current
state sizer, whenever the node is stopped, the background process must
be freshly initialized. During this re-initialization, it can skip some
blocks while the node continues executing blocks, causing gaps in the
recorded metrics.

Using this state update hook allows us to customize our own data
persistence logic, and we would never skip blocks upon node restart.

---------

Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2026-01-08 11:07:19 +08:00
Andrew Davis
a8a4804895
ethstats: report newPayload processing time to stats server (#33395)
Some checks are pending
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
/ Keeper Build (push) Waiting to run
/ Windows Build (push) Waiting to run
/ Docker Image (push) Waiting to run
Add NewPayloadEvent to track engine API newPayload block processing
times and report them to ethstats. This enables monitoring of block
processing performance.

https://notes.ethereum.org/@savid/block-observability

related: https://github.com/ethereum/go-ethereum/pull/33231

---------

Co-authored-by: MariusVanDerWijden <m.vanderwijden@live.de>
2026-01-05 17:49:30 +01:00
shhhh
32fea008d8
core/blockchain.go: cleanup finalized block on rewind in setHeadBeyondRoot (#33486)
Some checks are pending
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
/ Keeper Build (push) Waiting to run
/ Windows Build (push) Waiting to run
/ Docker Image (push) Waiting to run
Fix #33390 

`setHeadBeyondRoot` was failing to invalidate finalized blocks because
it compared against the original head instead of the rewound root. This
fix updates the comparison to use the post-rewind block number,
preventing the node from reporting a finalized block that no longer
exists. Also added relevant test cases for it.
2025-12-31 14:02:44 +08:00
rjl493456442
bf141fbfb1
core, eth: add lock protection in snap sync (#33428)
Fixes #33396, #33397, #33398
2025-12-19 09:36:48 +01:00
rjl493456442
ffe9dc97e5
core: add code read statistics (#33442)
Some checks are pending
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
/ Keeper Build (push) Waiting to run
/ Windows Build (push) Waiting to run
/ Docker Image (push) Waiting to run
2025-12-18 17:24:02 +08:00
Ng Wei Han
9a346873b8
core/state: fix incorrect contract code state metrics (#33376)
## Description
This PR fixes incorrect contract code state metrics by ensuring
duplicate codes are not counted towards the reported results.

## Rationale
The contract code metrics don't consider database deduplication. The
current implementation assumes that the results are only **slightly
inaccurate**, but this is not true, especially for data collection
efforts that started from the genesis block.
2025-12-10 11:33:59 +08:00
rjl493456442
042c47ce1a
core: log detailed statistics for slow block (#32812)
This PR introduces a new debug feature, logging the slow blocks with
detailed performance statistics, such as state read, EVM execution and
so on.

Notably, the detailed performance statistics of slow blocks won't be
logged during the sync to not overwhelm users. Specifically, the statistics
are only logged if there is a single block processed.

Example output

```
########## SLOW BLOCK #########
Block: 23537063 (0xa7f878611c2dd27f245fc41107d12ebcf06b4e289f1d6acf44d49a169554ee09) txs: 248, mgasps: 202.99

EVM execution: 63.295ms
Validation: 1.130ms
Account read: 6.634ms(648)
Storage read: 17.391ms(1434)
State hash: 6.722ms
DB commit: 3.260ms
Block write: 1.954ms
Total: 99.094ms

State read cache: account (hit: 622, miss: 26), storage (hit: 1325, miss: 109)
##############################
```
2025-12-02 14:43:51 +01:00
10gic
11208553dd
eth/filters: add transactionReceipts subscription (#32697)
Some checks are pending
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
/ Windows Build (push) Waiting to run
/ Docker Image (push) Waiting to run
- Introduce a new subscription kind `transactionReceipts` to allow clients to
  receive transaction receipts over WebSocket as soon as they are available.
- Accept optional `transactionHashes` filter to subscribe to receipts for specific
  transactions; an empty or omitted filter subscribes to all receipts.
- Preserve the same receipt format as returned by `eth_getTransactionReceipt`.
- Avoid additional HTTP polling, reducing RPC load and latency.

---------

Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2025-10-09 14:14:53 +02:00
hero5512
fc8c8c1314
core: refactor StateProcessor to accept ChainContext interface (#32739)
This pr implements https://github.com/ethereum/go-ethereum/issues/32733
to make StateProcessor more customisable.

## Compatibility notes

This introduces a breaking change to users using geth EVM as a library.
The `NewStateProcessor` function now takes one parameter which has the
chainConfig embedded instead of 2 parameters.
2025-10-02 14:34:06 +02:00
lightclient
339cae81d8
core: fix fork readiness log (#32623)
When I implemented in #31340 I didn't expect multiple forks to be
configured at once, but this is exactly how BPOs are defined. This
updates the method to determine the next scheduled fork rather than the
last fork.
2025-09-18 06:28:03 +02:00
Guillaume Ballet
2d3704c4d8
core/stateless: add vmwitnessstats cli flag to report leaf stats + log to console (#32619)
The format that is currently reported by the chain isn't very useful, as
it gives an average for ALL the nodes, and not only the leaves, which
skews the results.

Also, until now there was no way to activate the reporting of errors.

We also decided that metrics weren't the right tool to report this data,
so we decided to dump it to the console if the flag is enabled. A better
system should be built, but for now, printing to the logs does the job.
2025-09-17 15:06:39 +02:00
Guillaume Ballet
03b77d1a49
core/stateless: API methods to get execution witness of block
This PR adds a new RPC call, which re-executes a block with stateless
mode activated, so that the witness data are collected and returned.

They are `debug_executionWitnessByHash` which takes in a block hash
and `debug_executionWitness` which takes in a block number.

---------

Signed-off-by: Guillaume Ballet <3272758+gballet@users.noreply.github.com>
2025-09-16 14:46:28 +02:00
Delweng
c4ec4504bb
core/state: state size tracking (#32362)
Add state size tracking and retrieve api, start geth with `--state.size-tracking`, 
the initial bootstrap is required (around 1h on mainnet), after the bootstrap, 
use `debug_stateSize()` RPC to retrieve the state size:

```
> debug.stateSize()
{
  accountBytes: "0x39681967b",
  accountTrienodeBytes: "0xc57939f0c",
  accountTrienodes: "0x198b36ac",
  accounts: "0x129da14a",
  blockNumber: "0x1635e90",
  contractCodeBytes: "0x2b63ef481",
  contractCodes: "0x1c7b45",
  stateRoot: "0x9c36a3ec3745d72eea8700bd27b90dcaa66de0494b187c5600750044151e620a",
  storageBytes: "0x18a6e7d3f1",
  storageTrienodeBytes: "0x2e7f53fae6",
  storageTrienodes: "0x6e49a234",
  storages: "0x517859c5"
}
```

---------

Signed-off-by: jsvisa <delweng@gmail.com>
Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2025-09-08 14:00:23 +08:00
rjl493456442
902ec5baae
cmd, core, eth, triedb/pathdb: track node origins in the path database (#32418)
This PR is the first step in the trienode history series.

It introduces the `nodeWithOrigin` struct in the path database, which tracks
the original values of dirty nodes to support trienode history construction.

Note, the original value is always empty in this PR, so it won't break the 
existing journal for encoding and decoding. The compatibility of journal 
should be handled in the following PR.
2025-09-05 10:37:05 +08:00
shazam8253
e9656238a7
core, miner, trie: add metrics tracking state trie depth (#32388)
Co-authored-by: shantichanal <158101918+shantichanal@users.noreply.github.com>
Co-authored-by: Gary Rong <garyrong0905@gmail.com>
Co-authored-by: Guillaume Ballet <3272758+gballet@users.noreply.github.com>
2025-08-22 22:09:14 +08:00
nthumann
29eebb5eac
core: replace the empty fmt.Errorf with errors.New (#32274)
The `errors.new` function does not require string formatting, so its
performance is better than that of `fmt.Errorf`.
2025-07-28 09:13:50 +08:00
Delweng
17903fedf0
triedb/pathdb: introduce file-based state journal (#32060)
Introduce file-based state journal in path database, fixing
the Pebble restriction when the journal size exceeds 4GB.

---------

Signed-off-by: jsvisa <delweng@gmail.com>
Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2025-07-15 11:45:20 +08:00
Ömer Faruk Irmak
f70aaa8399
ethapi: reduce some of the wasted effort in GetTransactionReceipt (#32021)
Some checks are pending
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
/ Docker Image (push) Waiting to run
Towards https://github.com/ethereum/go-ethereum/issues/26974

---------

Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2025-07-01 15:18:49 +08:00
rjl493456442
9c5c0e37bf
core/rawdb, triedb/pathdb: implement history indexer (#31156)
This pull request is part-1 for shipping the core part of archive node
in PBSS mode.
2025-06-24 14:36:12 +02:00
Delweng
78b6059341
eth: quick canceling block inserting when debug_setHead is invoked (#32067)
Some checks are pending
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
/ Docker Image (push) Waiting to run
If Geth is engaged in a long-run block synchronization, such as a full
syncing over a large number of blocks, invoking `debug_setHead` will
cause `downloader.Cancel` to wait for all fetchers to stop first.
This can be time-consuming, particularly for the block processing
thread.

To address this, we manually call `blockchain.StopInsert` to interrupt
the blocking processing thread and allow it to exit immediately, and
after that call `blockchain.ResumeInsert` to resume the block
downloading process.

Additionally, we add a sanity check for the input block number of
`debug_setHead` to ensure its validity.

---------

Signed-off-by: jsvisa <delweng@gmail.com>
Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2025-06-23 14:04:21 +08:00
rjl493456442
21920207e4
triedb/pathdb, eth: use double-buffer mechanism in pathdb (#30464)
Some checks are pending
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
/ Docker Image (push) Waiting to run
Previously, PathDB used a single buffer to aggregate database writes,
which needed to be flushed atomically. However, flushing large amounts
of data (e.g., 256MB) caused significant overhead, often blocking the
system for around 3 seconds during the flush.

To mitigate this overhead and reduce performance spikes, a double-buffer
mechanism is introduced. When the active buffer fills up, it is marked
as frozen and a background flushing process is triggered. Meanwhile, a
new buffer is allocated for incoming writes, allowing operations to
continue uninterrupted.

This approach reduces system blocking times and provides flexibility in
adjusting buffer parameters for improved performance.
2025-06-22 20:40:54 +08:00
rjl493456442
c7b8924fe4
core/state: expose the state reader stats (#31998)
This pull request introduces a mechanism to expose statistics from the
state reader, specifically related to cache utilization during state prefetching.

To improve state access performance, a pair of state readers is constructed 
with a shared local cache. One reader to execute transactions  ahead of time
to warm up the cache. The other reader is used by the actual chain processing 
logic, which can benefit from the prefetched states.

This PR adds visibility into how effective the cache is by exposing relevant 
usage statistics.

---------

Signed-off-by: Csaba Kiraly <csaba.kiraly@gmail.com>
Co-authored-by: Csaba Kiraly <csaba.kiraly@gmail.com>
2025-06-21 12:58:04 +08:00
rjl493456442
ac50181b74
core: consolidate BlockChain constructor options (#31925)
Some checks are pending
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
/ Docker Image (push) Waiting to run
In this pull request, the original `CacheConfig` has been renamed to `BlockChainConfig`.

Over time, more fields have been added to `CacheConfig` to support
blockchain configuration. Such as `ChainHistoryMode`, which clearly extends
beyond just caching concerns.

Additionally, adding new parameters to the blockchain constructor has
become increasingly complicated, since it’s initialized across multiple
places in the codebase. A natural solution is to consolidate these arguments 
into a dedicated configuration struct.

As a result, the existing `CacheConfig` has been redefined as `BlockChainConfig`.
Some parameters, such as `VmConfig`, `TxLookupLimit`, and `ChainOverrides`
have been moved into `BlockChainConfig`. Besides, a few fields in `BlockChainConfig`
were renamed, specifically:

- `TrieCleanNoPrefetch` -> `NoPrefetch`
- `TrieDirtyDisabled` -> `ArchiveMode`

Notably, this change won't affect the command line flags or the toml
configuration file. It's just an internal refactoring and fully backward-compatible.

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2025-06-19 12:21:15 +02:00
Delweng
8219bfcadd
eth,core: terminate the downloader immediately when shutdown signal is received (#32062)
Closes https://github.com/ethereum/go-ethereum/issues/32058
2025-06-19 09:44:39 +08:00
Sean Liao
82c2c8191f
metrics: add chain/gas for cumulative gas usage (#32004)
Some checks are pending
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
/ Docker Image (push) Waiting to run
This is a followup to #31753.

A cumulative counter is more useful when we need to measure / aggregate
the metric over a longer period of time. It also means we won't miss data,
e.g. our prometheus scrapes every 30 seconds, and so may miss a transient 
spike in the pre-aggregated mgas/s.

---------

Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2025-06-12 20:30:54 +08:00
Marius van der Wijden
7e79254605
eth/protocols/eth: implement eth/69 (#29158)
This PR implements eth/69. This protocol version drops the bloom filter
from receipts messages, reducing the amount of data needed for a sync
by ~530GB (2.3B txs * 256 byte) uncompressed. Compressed this will
be reduced to ~100GB

The new version also changes the Status message and introduces the
BlockRangeUpdate message to relay information about the available history
range.

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2025-05-16 17:10:47 +02:00
rjl493456442
892a661ee2
core, triedb/pathdb: final integration (snapshot integration pt 5) (#30661)
In this pull request, snapshot generation in pathdb has been ported from 
the legacy state snapshot implementation. Additionally, when running in 
path mode, legacy state snapshot data is now managed by the pathdb
based snapshot logic.

Note: Existing snapshot data will be re-generated, regardless of whether 
it was previously fully constructed.
2025-05-16 18:29:38 +08:00
Delweng
88a7ef233a
core: use unix time to check fork readiness (#31800) 2025-05-14 09:26:08 +08:00
Marcel
fa86416ce9
metrics: add chain/mgasps to track gas usage rate (#31753)
This adds a metric called `chain/mgasps`, which records how many million
gas per second are being used during block insertion.

The value is calculated as `usedGas * 1000 / elapsed`, and it's updated
in the `insertStats.report` method. Also cleaned up the log output to
reuse the same value instead of recalculating it.

Useful for monitoring block processing throughput.

---------

Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2025-05-10 08:27:27 +08:00
rjl493456442
485ff4bbff
core: implement in-block prefetcher (#31557)
This pull request enhances the block prefetcher by executing transactions 
in parallel to warm the cache alongside the main block processor.

Unlike the original prefetcher, which only executes the next block and
is limited to chain syncing, the new implementation can be applied to any 
block. This makes it useful not only during chain sync but also for regular 
block insertion after the initial sync.


---------

Co-authored-by: Marius van der Wijden <m.vanderwijden@live.de>
2025-05-08 22:28:16 +08:00
rjl493456442
10519768a2
core, ethdb: introduce database sync function (#31703)
This pull request introduces a SyncKeyValue function to the
ethdb.KeyValueStore
interface, providing the ability to forcibly flush all previous writes
to disk.

This functionality is critical for go-ethereum, which internally uses
two independent
database engines: a key-value store (such as Pebble, LevelDB, or
memoryDB for
testing) and a flat-file–based freezer. To ensure write-order
consistency between
these engines, the key-value store must be explicitly synced before
writing to the
freezer and vice versa.

Fixes 
- https://github.com/ethereum/go-ethereum/issues/31405
- https://github.com/ethereum/go-ethereum/issues/29819
2025-05-08 19:10:26 +08:00
lightclient
13b157a461
core,params: add fork readiness indicator in logs (#31340)
closes #31310 

This has been requested a few times in the past and I think it is a nice
quality-of-life improvement for users. At a predetermined interval,
there will now be a "Fork ready" log when a future fork is scheduled,
but not yet active.

It can only possibly print after block import, which kinda avoids the
scenario where the client isn't progressing or is syncing and the user
thinks it's "ready" because it sees a ready log.

New output:

```console
INFO [03-08|21:32:57.472] Imported new potential chain segment     number=7 hash=aa24ee..f09e62 blocks=1 txs=0 mgas=0.000 elapsed="874.916µs" mgasps=0.000 snapdiffs=973.00B triediffs=7.05KiB triedirty=0.00B
INFO [03-08|21:32:57.473] Ready for fork activation                fork=Prague date="18 Mar 25 19:29 CET" remaining=237h57m0s timestamp=1,742,322,597
INFO [03-08|21:32:57.475] Chain head was updated                   number=7 hash=aa24ee..f09e62 root=19b0de..8d32f2 elapsed="129.125µs"
```

Easiest way to verify this behavior is to apply this patch and run `geth
--dev --dev.period=12`

```patch
diff --git a/params/config.go b/params/config.go
index 9c7719d901..030c4f80e7 100644
--- a/params/config.go
+++ b/params/config.go
@@ -174,7 +174,7 @@ var (
                ShanghaiTime:            newUint64(0),
                CancunTime:              newUint64(0),
                TerminalTotalDifficulty: big.NewInt(0),
-               PragueTime:              newUint64(0),
+               PragueTime:              newUint64(uint64(time.Now().Add(time.Hour * 300).Unix())),
                BlobScheduleConfig: &BlobScheduleConfig{
                        Cancun: DefaultCancunBlobConfig,
                        Prague: DefaultPragueBlobConfig,
```
2025-04-17 10:46:47 +02:00
Sina M
e444823394
core: fix sync reset in pruned nodes (#31638)
This is an attempt at fixing #31601. I think what happens is the startup
logic will try to get the full block body (it's `bc.loadLastState`) and
fail because genesis block has been pruned from the freezer. This will
cause it to keep repeating the reset logic, causing a deadlock.

This can happen when due to an unsuccessful sync we don't have the state
for the head (or any other state) fully, and try to redo the snap sync.

---------

Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2025-04-17 16:32:40 +08:00
Felix Lange
cb21177aa8
core: fix history pruning initialization for empty DB (#31656)
This fixes an issue where running geth with `--history.chain postmerge`
would not work on an empty database.

```
ERROR[04-16|23:11:12.913] Chain history database is pruned to unknown block tail=0
Fatal: Failed to register the Ethereum service: unexpected database tail
```
2025-04-17 10:39:21 +08:00
Felix Lange
48ec86abbb
core: initialize history pruning in BlockChain (#31636)
I added the history mode configuration in eth/ethconfig initially, since
it seemed like the logical place. But it turns out we need access to the
intended pruning setting at a deeper level, and it actually needs to be
integrated with the blockchain startup procedure.

With this change applied, if a node previously had its history pruned,
and is subsequently restarted **without** the `--history.chain
postmerge` flag, the `BlockChain` initialization code will now verify
the freezer tail against the known pruning point of the predefined
network and will restore pruning status. Note that this logic is quite
restrictive, we allow non-zero tail only for known networks, and only
for the specific pruning point that is defined.
2025-04-15 14:32:46 +02:00
rjl493456442
90d44e715d
core, eth/downloader: implement pruning mode sync (#31414)
This pull request introduces new sync logic for pruning mode. The downloader will now skip
insertion of block bodies and receipts before the configured history cutoff point.

Originally, in snap sync, the header chain and other components (bodies and receipts) were
inserted separately. However, in Proof-of-Stake, this separation is unnecessary since the
sync target is already verified by the CL.

To simplify the process, this pull request modifies `InsertReceiptChain` to insert headers
along with block bodies and receipts together. Besides, `InsertReceiptChain` doesn't have
the notion of reorg, as the common ancestor is always be found before the sync and extra
side chain is truncated at the beginning if they fall in the ancient store. The stale
canonical chain flags will always be rewritten by the new chain. Explicit reorg logic is
no longer required in `InsertReceiptChain`.
2025-04-03 15:16:35 +02:00
Sina M
8fe09df54f
cmd/geth: add prune history command (#31384)
This adds a new subcommand 'geth prune-history' that removes the pre-merge history
on supported networks. Geth is not fully ready to work in this mode, please do not run
this command on your production node.

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2025-03-21 13:12:56 +01:00
Felföldi Zsolt
07cca7ab9f
core/bloombits: remove old bloombits logic and chain indexer (#31081)
This PR is #3 of a 3-part series that implements the new log index
intended to replace core/bloombits.
Based on https://github.com/ethereum/go-ethereum/pull/31079 and
https://github.com/ethereum/go-ethereum/pull/31080
Replaces https://github.com/ethereum/go-ethereum/pull/30370

This part removes the old bloombits package and the chain indexer that
was only used by bloombits. Deletes the old bloombits database.

FilterMaps data structure explanation:
https://gist.github.com/zsfelfoldi/a60795f9da7ae6422f28c7a34e02a07e

Log index generator code overview:
https://gist.github.com/zsfelfoldi/97105dff0b1a4f5ed557924a24b9b9e7

Search pattern matcher code overview:
https://gist.github.com/zsfelfoldi/5981735641c956afb18065e84f8aff34

Note that the possibility of a tree hashing scheme and remote proof
protocol are mentioned in the documents above but they are not exactly
specified yet. These specs are WIP and will be finalized after the local
log indexer/filter code is finalized and merged.

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2025-03-21 10:47:58 +01:00
Felföldi Zsolt
f3e4866073
core: update blockProcFeed in insertChain (#31065)
This PR moves the updating of the `blockProcFeed` event feed from
`InsertChain` to `insertChain` in order to ensure that the feed
subscribers are notified whenever block processing happens.
Note that this event is not subscribed to anywhere in our codebase at
the moment, earlier it was used by the LES server to avoid slowing down
block processing. Now I want to do the same with the log indexer, the
problem is that back then every block insertion was done by
`InsertChain`, now the regular payload insertion is done by
`InsertBlockWithoutSetHead`. Both of these (and also `SetCanonical` if
needed) calls `insertChain` so I moved the feed update there.
2025-03-13 12:35:10 +01:00
Felix Lange
1ca2da81e6
eth/ethconfig: add HistoryMode (#31365)
Here I am adding a config option and geth flag (`--history.chain`) for
configuring history pruning. There are two options available:

- `--history.chain all` is the default and will keep all history like
before.
- `--history.chain postmerge` will configure the history cutoff point to
the merge block.

The option doesn't actually do anything right now, but we need it as a
precursor for other history pruning changes.
2025-03-13 11:43:00 +01:00
lightclient
e6f3ce7b16
params,core: add max and target value to chain config (#31002)
Implements [EIP-7840](https://github.com/ethereum/EIPs/pull/9129) and
[EIP-7691](d96625a4dc/EIPS/eip-7691.md).

---------

Co-authored-by: Marius van der Wijden <m.vanderwijden@live.de>
Co-authored-by: Felix Lange <fjl@twurst.com>
2025-02-04 15:43:18 +01:00
rjl493456442
0ad0966cec
core/rawdb: introduce flush offset in freezer (#30392)
This is a follow-up PR to #29792 to get rid of the data file sync.

**This is a non-backward compatible change, which increments the
database version from 8 to 9**.

We introduce a flushOffset for each freezer table, which tracks the position
of the most recently fsync’d item in the index file. When this offset moves
forward, it indicates that all index entries below it, along with their corresponding
data items, have been properly persisted to disk. The offset can also be moved
backward when truncating from either the head or tail of the file.

Previously, the data file required an explicit fsync after every mutation, which
was highly inefficient. With the introduction of the flush offset, the synchronization
strategy becomes more flexible, allowing the freezer to sync every 30 seconds
instead.

The data items above the flush offset are regarded volatile and callers must ensure
they are recoverable after the unclean shutdown, or explicitly sync the freezer
before any proceeding operations.

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2025-02-04 11:45:45 +01:00
Péter Szilágyi
39638c81c5
all: nuke total difficulty (#30744)
The total difficulty is the sum of all block difficulties from genesis
to a certain block. This value was used in PoW for deciding which chain
is heavier, and thus which chain to select. Since PoS has a different
fork selection algorithm, all blocks since the merge have a difficulty
of 0, and all total difficulties are the same for the past 2 years.

Whilst the TDs are mostly useless nowadays, there was never really a
reason to mess around removing them since they are so tiny. This
reasoning changes when we go down the path of pruned chain history. In
order to reconstruct any TD, we **must** retrieve all the headers from
chain head to genesis and then iterate all the difficulties to compute
the TD.

In a world where we completely prune past chain segments (bodies,
receipts, headers), it is not possible to reconstruct the TD at all. In
a world where we still keep chain headers and prune only the rest,
reconstructing it possible as long as we process (or download) the chain
forward from genesis, but trying to snap sync the head first and
backfill later hits the same issue, the TD becomes impossible to
calculate until genesis is backfilled.

All in all, the TD is a messy out-of-state, out-of-consensus computed
field that is overall useless nowadays, but code relying on it forces
the client into certain modes of operation and prevents other modes or
other optimizations. This PR completely nukes out the TD from the node.
It doesn't compute it, it doesn't operate on it, it's as if it didn't
even exist.

Caveats:

- Whenever we have APIs that return TD (devp2p handshake, tracer, etc.)
we return a TD of 0.
- For era files, we recompute the TD during export time (fairly quick)
to retain the format content.
- It is not possible to "verify" the merge point (i.e. with TD gone, TTD
is useless). Since we're not verifying PoW any more, just blindly trust
it, not verifying but blindly trusting the many year old merge point
seems just the same trust model.
- Our tests still need to be able to generate pre and post merge blocks,
so they need a new way to split the merge without TTD. The PR introduces
a settable ttdBlock field on the consensus object which is used by tests
as the block where originally the TTD happened. This is not needed for
live nodes, we never want to generate old blocks.
- One merge transition consensus test was disabled. With a
non-operational TD, testing how the client reacts to TTD is useless, it
cannot react.

Questions:

- Should we also drop total terminal difficulty from the genesis json?
It's a number we cannot react on any more, so maybe it would be cleaner
to get rid of even more concepts.

---------

Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2025-01-28 18:55:41 +01:00
rjl493456442
a7f9523ae1
all: implement state history v2 (#30107)
This pull request delivers the new version of the state history, where
the raw storage key is used instead of the hash.

Before the cancun fork, it's supported by protocol to destruct a
specific account and therefore, all the storage slot owned by it should
be wiped in the same transition.

Technically, storage wiping should be performed through storage
iteration, and only the storage key hash will be available for traversal
if the state snapshot is not available. Therefore, the storage key hash
is chosen as the identifier in the old version state history.

Fortunately, account self-destruction has been deprecated by the
protocol since the Cancun fork, and there are no empty accounts eligible
for deletion under EIP-158. Therefore, we can conclude that no storage
wiping should occur after the Cancun fork. In this case, it makes no
sense to keep using hash.

Besides, another big reason for making this change is the current format
state history is unusable if verkle is activated. Verkle tree has a
different key derivation scheme (merkle uses keccak256), the preimage of
key hash must be provided in order to make verkle rollback functional.
This pull request is a prerequisite for landing verkle.

Additionally, the raw storage key is more human-friendly for those who
want to manually check the history, even though Solidity already
performs some hashing to derive the storage location.

---

This pull request doesn't bump the database version, as I believe the
database should still be compatible if users degrade from the new geth
version to old one, the only side effect is the persistent new version
state history will be unusable.

---------

Co-authored-by: Zsolt Felfoldi <zsfelfoldi@gmail.com>
2025-01-17 02:59:02 +01:00