Commit Graph

15611 Commits

Author SHA1 Message Date
Martin Holst Swende efeb350092
core/state: fixes for issues found during fuzzing 2024-12-16 15:05:21 +01:00
Marius van der Wijden 773979c36d
core/state: added journal fuzzer
core/state: refactor journal-fuzzer

core/state: work on fuzztest for journals/state
2024-12-16 15:05:18 +01:00
Martin Holst Swende 81fa3e6b76
core/state: simplify journal api, remove externally visible snapshot ids
cmd/evm: post-rebase fixup
2024-12-16 15:00:17 +01:00
Martin Holst Swende 10fc900287
core/state: make journalling set-based
core/state: add handling for DiscardSnapshot
core/state: use new journal
core/state, genesis: fix flaw re discard/commit.
	In case the state is committed, the journal is reset, thus it is not correct to Discard/Revert snapshots at that point.
core/state: fix nil defer in merge
core/state: fix bugs in setjournal
core/state: journal api changes
core/state: bugfixes in sparse journal
core/state: journal tests
core/state: improve post-state check in journal-fuzzing test
core/state: post-rebase fixups
miner: remove discard-snapshot call, it's not needed since journal will be reset in Finalize
core/state: fix tests
core/state: lint
core/state: supply origin-value when reverting storage change
Update core/genesis.go
core/state: fix erroneous comments
core/state: review-nits regarding the journal
2024-12-16 15:00:05 +01:00
Martin Holst Swende 2f246a5b17
core/state: test to demonstrate flaw in dirty-handling 2024-12-16 14:44:46 +01:00
Martin Holst Swende 2c9afab254
core/state: separate journal-implementation behind interface, implement createaccount 2024-12-16 14:44:42 +01:00
rjl493456442 bc1ec69008
trie/pathdb: state iterator (snapshot integration pt 4) (#30654)
In this pull request, the state iterator is implemented. It's mostly a copy-paste
from the original state snapshot package, but still has some important changes
to highlight here:

(a) The iterator for the disk layer consists of a diff iterator and a disk iterator.

Originally, the disk layer in the state snapshot was a wrapper around the disk, 
and its corresponding iterator was also a wrapper around the disk iterator.
However, due to structural differences, the disk layer iterator is divided into
two parts:

- The disk iterator, which traverses the content stored on disk.
- The diff iterator, which traverses the aggregated state buffer.

Checkout `BinaryIterator` and `FastIterator` for more details.

(b) The staleness management is improved in the diffAccountIterator and
diffStorageIterator

Originally, in the `diffAccountIterator`, the layer’s staleness had to be checked 
within the Next function to ensure the iterator remained usable. Additionally, 
a read lock on the associated diff layer was required to first retrieve the account 
blob. This read lock protection is essential to prevent concurrent map read/write. 
Afterward, a staleness check was performed to ensure the retrieved data was 
not outdated.

The entire logic can be simplified as follows: a loadAccount callback is provided 
to retrieve account data. If the corresponding state is immutable (e.g., diff layers
in the path database), the staleness check can be skipped, and a single account 
data retrieval is sufficient. However, if the corresponding state is mutable (e.g., 
the disk layer in the path database), the callback can operate as follows:

```go
func(hash common.Hash) ([]byte, error) {
    dl.lock.RLock()
    defer dl.lock.RUnlock()

    if dl.stale {
        return nil, errSnapshotStale
    }
    return dl.buffer.states.mustAccount(hash)
}
```

The callback solution can eliminate the complexity for managing
concurrency with the read lock for atomic operation.
2024-12-16 21:10:08 +08:00
lightclient f808d7357e
all: implement eip-7702 set code tx (#30078)
This PR implements EIP-7702: "Set EOA account code". 
Specification: https://eips.ethereum.org/EIPS/eip-7702

> Add a new transaction type that adds a list of `[chain_id, address,
nonce, y_parity, r, s]` authorization tuples. For each tuple, write a
delegation designator `(0xef0100 ++ address)` to the signing account’s
code. All code reading operations must load the code pointed to by the
designator.

---------

Co-authored-by: Mario Vega <marioevz@gmail.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
Co-authored-by: Felix Lange <fjl@twurst.com>
2024-12-16 11:29:37 +01:00
Lucas 804d45cc2e
p2p: DNS resolution for static nodes (#30822)
Closes #23210 

# Context 
When deploying Geth in Kubernetes with ReplicaSets, we encountered two
DNS-related issues affecting node connectivity. First, during startup,
Geth tries to resolve DNS names for static nodes too early in the config
unmarshaling phase. If peer nodes aren't ready yet (which is common in
Kubernetes rolling deployments), this causes an immediate failure:


```
INFO [11-26|10:03:42.816] Starting Geth on Ethereum mainnet...
INFO [11-26|10:03:42.817] Bumping default cache on mainnet         provided=1024 updated=4096
Fatal: config.toml, line 81: (p2p.Config.StaticNodes) lookup idontexist.geth.node: no such host
``` 

The second issue comes up when pods get rescheduled to different nodes -
their IPs change but peers keep using the initially resolved IP, never
updating the DNS mapping.

This PR adds proper DNS support for enode:// URLs by deferring resolution
to connection time. It also handles DNS failures gracefully instead of failing
fatally during startup, making it work better in container environments where
IPs are dynamic and peers come and go during rollouts.

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2024-12-13 12:46:12 +01:00
Antony Denyer 88cbfab332
internal/ethapi: add block override to estimateGas (#30695)
Add block overrides to `eth_estimateGas` to align consistency with
`eth_call`.


https://github.com/ethereum/go-ethereum/issues/27800#issuecomment-1658186166

Fixes https://github.com/ethereum/go-ethereum/issues/28175

---------

Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2024-12-12 12:39:03 +01:00
lorenzo c1c2507148
p2p: fix DiscReason encoding/decoding (#30855)
This fixes an issue where the disconnect message was not wrapped in a list.
The specification requires it to be a list like any other message.

In order to remain compatible with legacy geth versions, we now accept both
encodings when parsing a disconnect message.

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2024-12-12 12:33:42 +01:00
gitglorythegreat c7e740f40c
core/state: remove pointless wrapper functions (#30891) 2024-12-11 11:05:59 +01:00
Darren Kelly 330190e476
accounts/abi: support unpacking solidity errors (#30738)
This PR adds the error fragments to `func (abi ABI) getArguments` which
allows typed decoding of errors.
2024-12-10 14:30:24 +01:00
Hteev Oli 4ed36ea1f8
build: update to Go 1.23.4 (#30872) 2024-12-10 14:22:43 +01:00
Martin HS 9045b79bc2
metrics, cmd/geth: change init-process of metrics (#30814)
This PR modifies how the metrics library handles `Enabled`: previously,
the package `init` decided whether to serve real metrics or just
dummy-types.

This has several drawbacks: 
- During pkg init, we need to determine whether metrics are enabled or
not. So we first hacked in a check if certain geth-specific
commandline-flags were enabled. Then we added a similar check for
geth-env-vars. Then we almost added a very elaborate check for
toml-config-file, plus toml parsing.

- Using "real" types and dummy types interchangeably means that
everything is hidden behind interfaces. This has a performance penalty,
and also it just adds a lot of code.

This PR removes the interface stuff, uses concrete types, and allows for
the setting of Enabled to happen later. It is still assumed that
`metrics.Enable()` is invoked early on.

The somewhat 'heavy' operations, such as ticking meters and exp-decay,
now checks the enable-flag to prevent resource leak.

The change may be large, but it's mostly pretty trivial, and from the
last time I gutted the metrics, I ensured that we have fairly good test
coverage.

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2024-12-10 13:27:29 +01:00
Zheyuan He 4ecf08584c
core/vm: remove unnecessary comment (#30887) 2024-12-10 13:10:17 +01:00
Martin HS 75f847390f
cmd/evm: consolidate evm output switches (#30849)
This PR attempts to clean up some ambiguities and quirks from recent
changes to evm flag handling.

This PR mainly focuses on `evm run` subcommand, to use the same flags
for configuring tracing/output options as `statetest/blocktest` does.

Additionally, it adds quite a lot of tests for expected outputs of the
various subcommands, to avoid accidental changes.

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2024-12-10 09:43:24 +01:00
rjl493456442 a91dcf3ee5
core/state: enable partial-functional reader (snapshot integration pt 3) (#30650)
It's a pull request based on https://github.com/ethereum/go-ethereum/pull/30643

In this pull request, the partial functional state reader is enabled if **legacy snapshot
is not enabled**. The tracked flat states in pathdb will be used to serve the state
retrievals, as the second implementation to fasten the state access.

This pull request should be a noop change in normal cases.
2024-12-10 10:10:49 +08:00
steven a722adb774
core/txpool: remove unused parameter `local` (#30871) 2024-12-09 19:29:19 +01:00
Guillaume Ballet 08e6bdb550
trie/utils: ensure master can generate a correct genesis for kaustinen7 (#30856)
This imports the following fixes:

 - update gnark to 1.1.0
 - update go-verkle to 0.2.2
 - fix: main storage offset bug (gballet/go-ethereum#329)
 - fix: tree key generation (gballet/go-ethereum#401)

---------

Signed-off-by: Guillaume Ballet <3272758+gballet@users.noreply.github.com>
Co-authored-by: Ignacio Hagopian <jsign.uy@gmail.com>
2024-12-06 12:14:05 +01:00
Nebojsa Urosevic 67a3b08795
core/tracing: extends tracing.Hooks with OnSystemCallStartV2 (#30786)
This PR extends the Hooks interface with a new method,
`OnSystemCallStartV2`, which takes `VMContext` as its parameter.

Motivation

By including `VMContext` as a parameter, the `OnSystemCallStartV2` hook
achieves parity with the `OnTxStart` hook in terms of provided insights.
This alignment simplifies the inner tracer logic, enabling consistent
handling of state changes and internal calls within the same framework.

---------

Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2024-12-04 09:40:37 +01:00
Martin HS f0e7382f38
cmd/evm, eth/tracers: refactor structlogger and make it streaming (#30806)
This PR refactors the structlog a bit, making it so that it can be used
in a streaming mode.

-------------

OBS: this PR makes a change in the input `config` config, the third
input-parem field to `debug.traceCall`. Previously, seteting it to e.g.
` {"enableMemory": true, "limit": 1024}` would mean that the response
was limited to `1024` items. Since an 'item' may include both memory and
storage, the actual size of the response was undertermined.
After this change, the response will be limited to `1024` __`bytes`__
(or thereabouts).



-----------


The commandline usage of structlog now uses the streaming mode, leaving
the non-streaming mode of operation for the eth_Call.

There are two benefits of streaming mode 
1. Not have to maintain a long list of operations, 
2. Not have to duplicate / n-plicate data, e.g. memory / stack /
returndata so that each entry has their own private slice.


---------

Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2024-12-04 08:52:59 +01:00
Felix Lange 84cabb587b
CODEOWNERS: add some more entries for auto assignment (#30851) 2024-12-03 16:11:26 +01:00
Felix Lange 4afab7ef76
eth/downloader: move SyncMode to package eth/ethconfig (#30847)
Lots of packages depend on eth/downloader just for the SyncMode type.
Since we have a dedicated package for eth protocol configuration, it
makes more sense to define SyncMode there, turning eth/downloader into
more of a leaf package.
2024-12-03 09:30:26 +01:00
Felix Lange ae5a16f870
internal/debug: rename --trace to --go-execution-trace (#30846)
This flag is very rarely needed, so it's OK for it to have a verbose
name. The name --trace also conflicts with the concept of EVM tracing,
which is much more heavily used.
2024-12-02 18:17:43 +01:00
Martin HS 9848e9b046
fuzzing: fix oss-fuzz fuzzer (#30845)
The fuzzer added recenly to fuzz the eth handler doesn't
build on oss-fuzz, because it also has dependencies in the peer_test.go.

This change fixes it, I hope, by adding that file also for preprocessing.
2024-12-02 15:43:17 +01:00
lightclient 5347280319
cmd/evm: improve block/state test runner (#30633)
* unify `staterunner` and `blockrunner` CLI flags, especially around
tracing
* added support for struct logger or json logging (although having issue
#30658)
* new --cross-check flag to validate the stateless witness collection
  / execution matches stateful
* adds support for tracing the stateless execution when a tracer is set
  (to more easily debug differences)
* --human for more readable test summary
* directory or file input, so if you pass tests/spec-tests/fixtures/blockchain_tests it will execute all
blockchain tests
2024-12-02 15:18:02 +01:00
Sina M ce8cec007c
eth/tracers: fix state hooks in API (#30830)
When a tx/block was being traced through the API the state hooks weren't
being called as they should. This is due to #30745 moving the hooked
statedb one level up in the state processor. This PR fixes that.

---------

Co-authored-by: Martin HS <martin@swende.se>
Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2024-11-29 18:42:28 +01:00
rjl493456442 a793bc7f5f
core: switch EVM tx context in ApplyMessage (#30809)
This change relocates the EVM tx context switching to the ApplyMessage function.
With this change, we can remove a lot of EVM.SetTxContext calls before
message execution.

### Tracing API changes

- This PR replaces the `GasPrice` field of the `VMContext` struct with
  `BaseFee`. Users may instead take the effective gas price from
  `tx.EffectiveGasTipValue(env.BaseFee)`.

---------

Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2024-11-29 15:39:42 +01:00
rjl493456442 03c37cdb2b
core/state: introduce code reader interface (#30816)
This PR introduces a `ContractCodeReader` interface with functions defined:

type ContractCodeReader interface {
	Code(addr common.Address, codeHash common.Hash) ([]byte, error)
	CodeSize(addr common.Address, codeHash common.Hash) (int, error)
}

This interface can be implemented in various ways. Although the codebase
currently includes only one implementation, additional implementations
could be created for different purposes and scenarios, such as a code
reader designed for the Verkle tree approach or one that reads code from
the witness.

*Notably, this interface modifies the function’s semantics. If the
contract code is not found, no error will be returned. An error should
only be returned in the event of an unexpected issue, primarily for
future implementations.*

The original state.Reader interface is extended with ContractCodeReader
methods, it gives us more flexibility to manipulate the reader with additional
logic on top, e.g. Hooks.

type Reader interface {
	ContractCodeReader
	StateReader
}

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2024-11-29 15:32:45 +01:00
rjl493456442 05148d972c
triedb/pathdb: track flat state changes in pathdb (snapshot integration pt 2) (#30643)
This pull request ports some changes from the main state snapshot
integration one, specifically introducing the flat state tracking in
pathdb.

Note, the tracked flat state changes are only held in memory and won't
be persisted in the disk. Meanwhile, the correspoding state retrieval in
persistent state is also not supported yet. The states management in
disk is more complicated and will be implemented in a separate pull
request.

Part 1: https://github.com/ethereum/go-ethereum/pull/30752
2024-11-29 19:30:45 +08:00
Felix Lange c7a8bcecbe
core/types: add length check in CalcRequestsHash (#30829)
The existing implementation is correct when building and verifying
blocks, since we will only collect non-empty requests into the block
requests list.

But it isn't correct for cases where a requests list containing empty
items is sent by the consensus layer on the engine API. We want to
ensure that empty requests do not cause a difference in validation
there, so the commitment computation should explicitly skip them.
2024-11-28 18:43:39 +01:00
Marius van der Wijden 53f66c1b03
cmd/bootnode: remove bootnode utility (#30813)
Since we don't really support custom networks anymore, we don't need the
bootnode utility. In case a discovery-only node is wanted, it can still be run using cmd/devp2p.
2024-11-28 14:37:36 +01:00
Felix Lange db8eed860d
all: exclude empty outputs in requests commitment (#30670)
Implements changes from these spec PRs:

- https://github.com/ethereum/EIPs/pull/8989
- https://github.com/ethereum/execution-apis/pull/599
2024-11-28 11:48:50 +01:00
Ng Wei Han 2406305175
trie: combine validation loops in VerifyRangeProof (#30823)
Small optimization. It's guaranteed that `len(keys)` == `len(values)`,
so we can combine the checks in a single loop rather than 2 separate
loops.
2024-11-28 17:17:58 +08:00
rjl493456442 8c1a36dad3
core/state/snapshot: handle legacy journal (#30802)
This workaround is meant to minimize the possibility for snapshot generation
once the geth node upgrades to new version (specifically #30752 )

In #30752, the journal format in state snapshot is modified by removing
the destruct set. Therefore, the existing old format (version = 0) will be
discarded and all in-memory layers will be lost. Unfortunately, the lost 
in-memory layers can't be recovered by some other approaches, and the 
entire state snapshot will be regenerated (it will last about 2.5 hours).

This pull request introduces a workaround to adopt the legacy journal if
the destruct set contained is empty. Since self-destruction has been
deprecated following the cancun fork, the destruct set is expected to be nil for
layers above the fork block. However, an exception occurs during contract 
deployment: pre-funded accounts may self-destruct, causing accounts with 
non-zero balances to be removed from the state. For example,
https://etherscan.io/tx/0xa087333d83f0cd63b96bdafb686462e1622ce25f40bd499e03efb1051f31fe49).


For nodes with a fully synced state, the legacy journal is likely compatible with
the updated definition, eliminating the need for regeneration. Unfortunately,
nodes performing a full sync of historical chain segments or encountering 
pre-funded account deletions may face incompatibilities, leading to automatic 
snapshot regeneration.
2024-11-28 11:21:31 +08:00
wangjingcun e0deac7f6f
core: better document reason for dropping error on return (#30811)
Add a comment for error return of nil

Signed-off-by: wangjingcun <wangjingcun@aliyun.com>
2024-11-27 07:17:03 +01:00
jwasinger 915248cd6b
cmd/evm: don't reuse state between iterations, show errors (#30780)
Reusing state between benchmark iterations resulted in inconsistent
results across runs, which surfaced in https://github.com/ethereum/go-ethereum/issues/30778 .

If these errors are triggered again, they will now trigger panic. 

---------

Co-authored-by: Martin HS <martin@swende.se>
2024-11-26 16:12:38 +01:00
rjl493456442 a11b4bebcb
Revert "core/state/snapshot: simplify snapshot rebuild (#30772)" (#30810)
This reverts commit 23800122b3.

The original pull request introduces a bug and some flaky tests are
detected because of this flaw.

```
--- FAIL: TestRecoverSnapshotFromWipingCrash (0.27s)
    blockchain_snapshot_test.go:158: The disk layer is not integrated snapshot is not constructed
{"pc":0,"op":88,"gas":"0x7148","gasCost":"0x2","memSize":0,"stack":[],"depth":1,"refund":0,"opName":"PC"}
{"pc":1,"op":255,"gas":"0x7146","gasCost":"0x1db0","memSize":0,"stack":["0x0"],"depth":1,"refund":0,"opName":"SELFDESTRUCT"}
{"output":"","gasUsed":"0x0"}
{"output":"","gasUsed":"0x1db2"}
{"pc":0,"op":116,"gas":"0x13498","gasCost":"0x3","memSize":0,"stack":[],"depth":1,"refund":0,"opName":"PUSH21"}
```

Before the original PR, the snapshot would block the function until the
disk layer
was fully generated under the following conditions:

(a) explicitly required by users with `AsyncBuild = false`.
(b) the snapshot was being fully rebuilt or *the disk layer generation
had resumed*.

Unfortunately, with the changes introduced in that PR, the snapshot no
longer waits
for disk layer generation to complete if the generation is resumed. It
brings lots of
uncertainty and breaks this tiny debug feature.
2024-11-26 11:33:59 +01:00
Nebojsa Urosevic d7e7b54190
core/tracing: add GetCodeHash to StateDB (#30784)
This PR extends the tracing.StateDB interface by adding a GetCodeHash function.
2024-11-26 08:16:00 +01:00
Felix Lange b4d99e3917
eth/ethconfig: improve error message if TTD missing (#30807)
This updates the message you get when trying to initialize Geth with
genesis.json that doesn't have `terminalTotalDifficulty`. The previous
message was a bit obscure, I had to check the code to find out what the
problem was.
2024-11-26 09:49:12 +08:00
Arran Schlosberg 23800122b3
core/state/snapshot: simplify snapshot rebuild (#30772)
This PR is purely for improved readability; I was doing work involving
the file and think this may help others who are trying to understand
what's going on.

1. `snapshot.Tree.Rebuild()` now returns a function that blocks until
regeneration is complete, allowing `Tree.waitBuild()` to be removed
entirely as all it did was search for the `done` channel behind this new
function.
2. Its usage inside `New()` is also simplified by (a) only waiting if
`!AsyncBuild`; and (b) avoiding the double negative of `if !NoBuild`.

---------

Co-authored-by: Martin HS <martin@swende.se>
2024-11-25 13:43:23 +01:00
Jordan Krage 3c754e2a09
accounts/abi: fix MakeTopics mutation of big.Int inputs (#30785)
#28764 updated `func MakeTopics` to support negative `*big.Int`s.
However, it also changed the behavior of the function from just
_reading_ the input `*big.Int` via `Bytes()`, to leveraging
`big.U256Bytes` which is documented as being _destructive_:

This change updates `MakeTopics` to not mutate the original, and 
also applies the same change in signer/core/apitypes.
2024-11-25 13:34:50 +01:00
Hyunsoo Shin (Lake) 19fa71b917
internal/ethapi: remove double map-clone (#30803)
Similar to https://github.com/ethereum/go-ethereum/pull/30788
2024-11-25 13:33:28 +01:00
Martin HS 02159d553f
eth/tracers/logger: improve markdown logger (#30805)
This PR improves the output of the markdown logger a bit.

- Remove `RStack` field, 
- Move `Stack` last, since it may have very large vertical expansion
- Make the pre- and post-exec  metadata structured into a bullet-list
2024-11-25 13:29:27 +01:00
Martin HS ab4a1cc01f
eth/tracers/logger: fix json-logger output missing (#30804)
Fixes a flaw introduced in
https://github.com/ethereum/go-ethereum/pull/29795 , discovered while
reviewing https://github.com/ethereum/go-ethereum/pull/30633 .
2024-11-25 10:07:50 +01:00
Daniel Liu 5e1a39d67f
internal/flags: fix "flag redefined" bug for alias on custom flags (#30796)
This change fixes a bug on the `DirectoryFlag` and the `BigFlag`, which would trigger a `panic` with the message "flag redefined" in case an alias was added to such a flag.
2024-11-24 20:09:38 +01:00
rjl493456442 6485d5e3ff
core, triedb: remove destruct flag in state snapshot (#30752)
This pull request removes the destruct flag from the state snapshot to
simplify the code.

Previously, this flag indicated that an account was removed during a
state transition, making all associated storage slots inaccessible.
Because storage deletion can involve a large number of slots, the actual
deletion is deferred until the end of the process, where it is handled
in batches.

With the deprecation of self-destruct in the Cancun fork, storage
deletions are no longer expected. Historically, the largest storage
deletion event in Ethereum was around 15 megabytes—manageable in memory.

In this pull request, the single destruct flag is replaced by a set of
deletion markers for individual storage slots. Each deleted storage slot
will now appear in the Storage set with a nil value.

This change will simplify a lot logics, such as storage accessing,
storage flushing, storage iteration and so on.
2024-11-22 16:55:43 +08:00
j2gg0s 6eeff3ee7d
trie: replace custom logic with bytes.HasPrefix (#30771)
in `trie`
- Replace custom logic with `bytes.HasPrefix`
- Remove unnecessary code in `GetNode`
2024-11-22 09:16:42 +01:00
wangjingcun 16f2f7155f
all: typos in comments (#30779)
fixes some typos
2024-11-22 09:02:45 +01:00