Compare commits

...

568 Commits

Author SHA1 Message Date
84cb3b705e
Fix bug where the defensive copy loses the computed leaf paths. (#401) 2023-07-21 18:46:18 -05:00
c72b45fab4
Fix bug where the defensive copy loses the computed leaf paths. (#400) 2023-07-21 18:42:07 -05:00
9bc81a3f68
Use GITEA_PUBLISH_TOKEN 2023-07-21 14:25:03 -05:00
1b72d2f737
398: Statediff missing parent blocks automatically. (#399)
* Statediff missing parent blocks automatically.

* Use local ipld-eth-db.
2023-07-18 14:41:20 -05:00
e2e2e85678
396: Don't skip any blocks if the head of the chain advances by more than one block. (#397)
* 396: don't skip any blocks if the head of the chain advances by more than one block.

* Combine backfilling of the gap-to-head and the fix for 396.
2023-07-06 12:00:59 -05:00
4ddaf430b1
292: Backfill gaps in the recent past on startup when tracking head. (#395)
* Backfill gaps in the recent past when statediffing head.
2023-06-23 23:04:57 -05:00
caa685321a
367: Check if the statediff is already in progress or completed. (#392)
* Check if the statediff is already in progress or completed.

* Update mock

* Add comments.
2023-06-01 13:21:33 -05:00
bac14cc48a
367: Fix deferred rollback on error. (#391)
* Fix rollback call on error.

* Skip the pointers.
2023-05-31 19:36:36 -05:00
Ian Norden
71f764bafa
Merge pull request #388 from cerc-io/v1.11.6-statediff-5.0.5
bump meta version
2023-05-19 10:51:11 -05:00
Ian Norden
dd1d8493a8
Merge pull request #389 from cerc-io/roy/v5-dev-1.11.6
Patch for concurrent iterator & others (onto v1.11.6)
2023-05-19 10:49:07 -05:00
i-norden
e6e2acb073 bump meta version 2023-05-18 12:47:31 -05:00
79a7643a28 concurrent iterator: pass a constructor method instead of state.Trie
This allows us to use our alt trie implementation
2023-05-19 00:59:19 +08:00
i-norden
3555790e76 Small fixes
replace new(trie.Trie)

reduce debug noise

patch postgres config - add driver, rename DefaultConfig => TestConfig
2023-05-19 00:59:19 +08:00
Ian Norden
368f3e09fc
Merge pull request #384 from cerc-io/v1.11.6-statediff-5.0.5
fix isWatchedAddress and isValidPath usage
2023-05-18 09:35:47 -05:00
i-norden
ea6dfb8fa5 fix isWatchedAddress and isValidPath usage 2023-05-17 08:15:38 -05:00
Ian Norden
643dc6807b
Merge pull request #382 from cerc-io/v1.11.6-statediff-5.0.4
update ipld-eth-db version
2023-05-15 11:06:31 -05:00
i-norden
c70b1cf0b1 update ipld-eth-db version 2023-05-15 10:40:17 -05:00
Ian Norden
0ebcd5f4af
Merge pull request #380 from cerc-io/v1.11.6-statediff-5.0.4
#379 for v1.11.6
2023-05-15 07:29:50 -05:00
i-norden
4c058e515e bump meta version 2023-05-14 14:41:44 -05:00
i-norden
30ab52a6a6 construct leafkey instead of calling it.LeafKey() (to avoid panics when we pass in a subtrie iterator at an odd position in the trie) 2023-05-14 14:41:13 -05:00
Ian Norden
fd7cacd437
Merge pull request #368 from cerc-io/ian/v5_dev
expose parent path from trie.Iterator
2023-05-11 06:54:48 -05:00
i-norden
911b86ee8b bump meta version 2023-05-10 20:26:57 -05:00
i-norden
79bd86501b expose parent path from iterator 2023-05-10 20:24:17 -05:00
Ian Norden
fe3e3b1119
Merge pull request #372 from cerc-io/v1.11.6-statediff-5.0.2
Statediff version meta
2023-05-02 22:19:43 -05:00
i-norden
35b70d31af more adjustments after rebase 2023-05-02 21:11:58 -05:00
i-norden
0c51ba5dc9 version meta 2023-05-02 20:16:40 -05:00
i-norden
b59a60eed8 statediffing service squashed commit 2023-05-02 20:12:04 -05:00
Martin Holst Swende
ea9e62ca3d
params: go-ethereum v1.11.6 stable 2023-04-20 20:14:51 +02:00
rjl493456442
99f81d2724
all: refactor trie API (#26995)
In this PR, all TryXXX(e.g. TryGet) APIs of trie are renamed to XXX(e.g. Get) with an error returned.

The original XXX(e.g. Get) APIs are renamed to MustXXX(e.g. MustGet) and does not return any error -- they print a log output. A future PR will change the behaviour to panic on errorrs.
2023-04-20 06:57:24 -04:00
s7v7nislands
ae93e0b484
metrics: use atomic type (#27121) 2023-04-20 03:36:54 -04:00
Alex Beregszaszi
3f7afc3f57
core/vm: order opcodes properly (#27113) 2023-04-20 02:52:00 -04:00
Adrian Sutton
f2df2b1981
cmd/geth: rename --vmodule to --log.vmodule (#27071)
renames `--vmodule` to `--log.vmodule`, and prints a warning if the old form is used.
2023-04-19 07:18:02 -04:00
Martin Holst Swende
2b0a34bea6
cmd/devp2p: make crawler-route53-updater less verbose (#27116)
Follow-up to #26697, makes the crawler less verbose on route53-based scenarios.

It also changes the loglevel from debug to info on Updates, which are typically the root, and can be interesting to see.
2023-04-19 06:46:56 -04:00
s7v7nislands
3768b00747
consensus/ethash: use atomic type (#27068) 2023-04-18 14:54:06 +02:00
joohhnnn
b1972627d9
p2p: access embedded fields of Server directly (#27078) 2023-04-18 11:57:08 +02:00
Delweng
5e4d726e2a
params: remove EIP150Hash from chainconfig (#27087)
The EIP150Hash was an idea where, after the fork, we hardcoded the forked hash as an extra defensive mechanism. It wasn't really used, since forks weren't contentious and for all the various testnets and private networks it's been a hassle to have around. 

This change removes that config field. 

---------

Signed-off-by: jsvisa <delweng@gmail.com>
2023-04-18 03:49:09 -04:00
Anusha
cb66eba85a
core: fix comment to reflect function name (#27070) 2023-04-17 11:02:31 -04:00
Taeguk Kwon
bedf2856d1
signer/core: rename testdata files (#27063)
Sets a meaningful name on test-files
2023-04-17 10:36:47 -04:00
noel
8fe807c8f2
cmd/devp2p: fix erroneous log output in crawler (#27089)
cmd/devp2p: fix log of ignored recent nodes counter
2023-04-17 10:29:27 -04:00
Parithosh Jayanthi
5aa5295cf9
params: new sepolia bootnodes (#27099)
New sepolia bootnodes managed by EF devops
2023-04-17 04:15:25 -04:00
Péter Szilágyi
4a9fa31450
Merge pull request #27051 from sandakersmann/master
build: upgrade -dlgo version to Go 1.20.3
2023-04-08 17:13:55 +03:00
rjl493456442
b946b7a13b
core, miner: drop transactions from the same sender when error occurs (#27038)
This PR unifies the error handling in miner. 

Whenever an error occur while applying a transaction, the transaction should be regarded as invalid and all following transactions from the same sender not executable because of the nonce restriction. The only exception is the `nonceTooLow` error which is handled separately.
2023-04-05 07:09:25 -04:00
Marius van der Wijden
230df98e4d
core/txpool: disallow future churn by remote txs (#26907)
Prior to this change, it was possible that transactions are erroneously deemed as 'future' although they are in fact 'pending', causing them to be dropped due to 'future' not being allowed to replace 'pending'. 

This change fixes that, by doing a more in-depth inspection of the queue.
2023-04-05 04:59:32 -04:00
Marius Kjærstad
9d37102134
build: upgrade -dlgo version to Go 1.20.3 2023-04-04 22:24:30 +02:00
s7v7nislands
2adce0b066
eth/tracers: use atomic type (#27031)
Use the new atomic types in package eth/tracers

---------

Co-authored-by: Martin Holst Swende <martin@swende.se>
Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2023-04-04 12:34:52 -04:00
Exca-DK
b4dcd1a391
metrics: make gauge_float64 and counter_float64 lock free (#27025)
Makes the float-gauges lock-free

name                      old time/op  new time/op  delta
CounterFloat64Parallel-8  1.45µs ±10%  0.85µs ± 6%  -41.65%  (p=0.008 n=5+5)

---------

Co-authored-by: Exca-DK <dev@DESKTOP-RI45P4J.localdomain>
Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-04-04 09:53:44 -04:00
Martin Holst Swende
ab1a404b01
all: remove debug-field from vm config (#27048)
This PR removes the Debug field from vmconfig, making it so that if a tracer is set, debug=true is implied.

---------

Co-authored-by: 0xTylerHolmes <tyler@ethereum.org>
Co-authored-by: Sina Mahmoodi <1591639+s1na@users.noreply.github.com>
2023-04-04 09:50:13 -04:00
Delweng
0b76eb3708
eth/tracers: report correct gasLimit in call tracers (#27029)
This includes a semantic change to the `callTracer` as well as `flatCallTracer`.
The value of field `gas` in the **first** call frame will change as follows:

- It previously contained gas available after initial deductions (i.e. tx costs)
- It will now contain the full tx gasLimit value

Signed-off-by: jsvisa <delweng@gmail.com>
2023-04-04 12:34:23 +02:00
Péter Szilágyi
d2cf49327f
consensus/misc, params: add EIP-4844 blobfee conversions (#27041)
* consensus/misc, params: add EIP-4844 blobfee conversions

* consensus/misc: pull in fakeExponential test cases

* consensus/misc: reuse bigints

* consensus/misc: nit renames, additional larger testcase

---------

Co-authored-by: Roberto Bayardo <bayardo@alum.mit.edu>
Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-04-04 11:25:28 +03:00
Péter Szilágyi
91faf2c559
consensus, core/typer: add 4844 excessDataGas to header, tie it to Cancun (#27046) 2023-04-04 10:02:50 +03:00
joohhnnn
9b1a82c600
core/vm: clarify comment (#27045) 2023-04-04 02:59:40 -04:00
s7v7nislands
db18293c32
eth/downloader: use atomic types (#27030)
* eth/downloader: use atomic type

* Update eth/downloader/downloader_test.go

Co-authored-by: Martin Holst Swende <martin@swende.se>

* Update eth/downloader/downloader_test.go

Co-authored-by: Martin Holst Swende <martin@swende.se>

---------

Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-04-03 22:48:10 +03:00
Martin Holst Swende
beda6c41ad
core/txpool: move some validation to outside of mutex (#27006)
Currently, most of transaction validation while holding the txpool mutex: one exception being an early-on signature check. 

This PR changes that, so that we do all non-stateful checks before we entering the mutex area. This means they can be performed in parallel, and to enable that, certain fields have been made atomic bools and uint64.
2023-04-03 07:16:57 -04:00
Martin Holst Swende
a25dd8064e
test/fuzzers: fuzz rlp handling of big.Int and uint256.Int (#26917)
test/fuzzers: fuzz rlp handling of big.Lnt and uint256.Int
2023-04-03 05:42:34 -04:00
rjl493456442
94457cce07
cmd, miner, signer: avoid panic if keystore is not available (#27039)
* cmd, miner, singer: avoid panic if keystore is not available

* cmd/geth: print warning instead of panic
2023-04-03 05:08:06 -04:00
sudeep
7076ae00aa
cmd/geth: enable log rotation (#26843)
This change enables log rotation, which can be activated using the flag --log.rotate. Additional parameters that can be given are: 

  - log.maxsize to set maximum size before files are rotated,
  - log.maxbackups to set how many files are retailed, 
  - log.maxage to configure max age of rotated files, 
  - log.compress whether to compress rotated files

The way to configure location of the logfile(s) is left unchanged, via the `log.logfile` parameter.  

---------

Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-04-03 05:05:36 -04:00
lightclient
2c5798464e
common: delete MakeName (#27023)
common,p2p: remove unused function MakeName
2023-04-03 03:51:31 -04:00
ucwong
dc2f4b9304
go.mod : update snappy (#27027) 2023-04-03 03:35:13 -04:00
Guruprasad Kamath
bed07cd590
cmd/evm: use correct parent number for t8n base fee calculation (#27032)
Currently the t8n tool uses the same block number for the current block and its parent while calculating the base fee. This causes incorrect base fee calculation for the london fork block. This commit sets the parent block number to be one less than the current block number
2023-04-03 03:33:17 -04:00
aaronbuchwald
00a73fbcce
accounts/abi/bind: handle UnpackLog with zero topics (#26920)
Adds error handling for the case that UnpackLog or UnpackLogIntoMap is called with a log that has zero topics.

---------

Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2023-03-31 02:35:29 -04:00
s7v7nislands
b92d0ea3bb
miner: use atomic type (#27013)
Use the new typed atomics in the miner package
2023-03-31 02:32:47 -04:00
openex
d0fbb10658
eth/catalyst: improve consensus heartbeat (#26896)
improve the heartbeat function that is no longer suitable in the current situation

Co-authored-by: “openex27” <“openexkevin@gmail.com”>
2023-03-30 15:09:35 -04:00
rjl493456442
9ce047452e
common: fix json marshaller MixedcaseAddress (#26998)
Fix the json marshaller of MixedcaseAddress
2023-03-30 15:04:28 -04:00
s7v7nislands
50317bdace
ethdb/pebble: use atomic type (#27014) 2023-03-30 15:02:14 -04:00
Adrian Sutton
2d1492821d
cmd/geth: Add --log.format cli param (#27001)
Removes the new --log.logfmt directive and hides --log.json, replacing both with log.format=(json|logfmt|terminal). The hidden log.json option is still respected if log.format is not specified for backwards compatibility.

Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-03-30 09:24:48 -04:00
Sina Mahmoodi
62fb7d3f85
graphql: revert storage access regression (#27007) 2023-03-30 06:57:49 -04:00
s7v7nislands
949cee2fe3
core: use atomic type (#27011) 2023-03-30 06:53:32 -04:00
Guillaume Ballet
a03490c6b2
remove @gballet as a GraphQL codeowner (#27012) 2023-03-30 04:58:23 -04:00
David Murdoch
7ca4f60a1a
docs: update outdated DeriveSha docs comment (#26968) 2023-03-28 08:59:37 -04:00
Adrian Sutton
56c1f98f8a
internal/debug: add log.logfmt flag to set logging to use logfmt (#26970) 2023-03-28 15:37:40 +03:00
jwasinger
fd94b4fcfa
eth/tracers/native: prevent panic for LOG edge-cases (#26848)
This PR fixes OOM panic in the callTracer as well as panicing on
opcode validation errors (e.g. stack underflow) in callTracer and
prestateTracer.

Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-03-28 11:46:53 +02:00
Sina Mahmoodi
a236e03d00
graphql: fix data races (#26965)
Fixes multiple data races caused by the fact that resolving fields are done concurrently by the graphql library. It also enforces caching at the stateobject level for account fields.
2023-03-28 03:08:10 -04:00
s7v7nislands
fb8a3aaf1e
core/state: use atomic.Bool (#26992) 2023-03-28 03:06:50 -04:00
s7v7nislands
79532a25b1
core/bloombits: use atomic type (#26993) 2023-03-28 03:05:29 -04:00
s7v7nislands
881fed032c
core/vm: use atomic.Bool (#26951)
Make use of new atomic types
---------

Co-authored-by: Felix Lange <fjl@twurst.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-03-27 09:40:20 -04:00
Delweng
117530b0e6
metrics/librato: ensure resp.body closed (#26969)
This change ensures that we call Close on a http response body, in various places in the source code (mostly tests)
2023-03-27 07:44:41 -04:00
Guillaume Ballet
41f89ca944
core/state, trie: remove Try prefix in Trie accessors (#26975)
This change renames StateTrie methods to remove the Try* prefix. 

We added the Trie methods with prefix 'Try' a long time ago, working
around the problem that most existing methods of Trie did not return the
database error. This weird naming convention has persisted until now.

Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2023-03-27 10:48:46 +02:00
norwnd
df383addee
ethclient: ensure returned subscription is nil on error (#26976) 2023-03-25 22:38:43 +01:00
ucwong
792d893ed0
rlp/rlpgen: print want/expect output string if mismatch (#26932)
Co-authored-by: Marius van der Wijden <m.vanderwijden@live.de>
2023-03-24 14:17:39 +01:00
Martin Holst Swende
0137bd69c5
go.mod: update golang.org/x/tools (#26960) 2023-03-24 12:39:20 +01:00
aaronbuchwald
b1acaf47aa
eth/gasprice: change feehistory input type from int to uint64 (#26922)
Change input param type from int to uint64
2023-03-23 16:12:37 -04:00
Martin Holst Swende
f6c3a534a4
metrics/influxdb: use smaller dependency and reuse code between v1 and v2 reporters (#26963)
This change switches to use the smaller influxdata/influxdb1-client package instead of depending on the whole infuxdb package. The new smaller client is very similar to the influxdb-v2 client, which made it possible to refactor the two reporters to reuse code a lot more.
2023-03-23 15:12:32 -04:00
turboboost55
7dc100714d
metrics: add cpu counters (#26796)
This PR adds counter metrics for the CPU system and the Geth process.
Currently the only metrics available for these items are gauges. Gauges are
fine when the consumer scrapes metrics data at the same interval as Geth
produces new values (every 3 seconds), but it is likely that most consumers
will not scrape that often. Intervals of 10, 15, or maybe even 30 seconds
are probably more common.

So the problem is, how does the consumer estimate what the CPU was doing in
between scrapes. With a counter, it's easy ... you just subtract two
successive values and divide by the time to get a nice, accurate average.
But with a gauge, you can't do that. A gauge reading is an instantaneous
picture of what was happening at that moment, but it gives you no idea
about what was going on between scrapes. Taking an average of values is
meaningless.
2023-03-23 14:13:50 +01:00
Guillaume Ballet
8990c92aea
core/state: add account address to Trie slot accessors (#26934)
This changes the Trie interface to add the plain account address as a
parameter to all storage-related methods.

After the introduction of the TryAccount* functions, TryGet, TryUpdate and
TryDelete are now only meant to read an account's storage. In their current
form, they assume that an account storage is stored in a separate trie, and
that the hashing of the slot is independent of its account's address.

The proposed structure for a stateless storage breaks these two
assumptions: the hashing of a slot key requires the address and all slots
and accounts are stored in a single trie.

This PR therefore adds an address parameter to the interface. It is ignored
in the MPT version, so this change has no functional impact, however it
will reduce the diff size when merging verkle trees.
2023-03-23 11:52:22 +01:00
lightclient
37ecff0967
cmd/evm, tests: record preimages if dump is expected (#26955)
With #25287 we made it so that preimages were not recorded by default. This had the side effect that the evm command is no longer able to dump state since it does a preimage lookup to determine the address represented by a key.

This change enables the recording of preimages when the dump command is given.
2023-03-23 05:15:40 -04:00
Delweng
7f3fc15a8b
core/rawdb: update freezertable read meter (#26946)
The meter for "for measuring the effective amount of data read" within the freezertable was never updated. This change remedies that. 
---------

Signed-off-by: jsvisa <delweng@gmail.com>
2023-03-23 03:34:40 -04:00
Marius van der Wijden
20f8eb756b
eth/catalyst: fix races (#26950) 2023-03-22 13:36:26 -04:00
Martin Holst Swende
b3f43c89b3
core/vm: expose jumptable constructors (#26880)
When interacting with geth as a library to e.g. produce state tests, it is desirable to obtain the consensus-correct jumptable definition for a given fork. This changes adds accessors so the instructionset can be obtained and characteristics about opcodes can be inspected.
2023-03-21 07:14:47 -04:00
s7v7nislands
905a723fae
core/rawdb: use atomic int added in go1.19 (#26935) 2023-03-21 07:10:23 -04:00
Péter Szilágyi
8a9a73c99b
log: add special casing of uint256 into the logger (#26936) 2023-03-21 12:01:43 +02:00
Péter Szilágyi
2ed8013f08
build: allow building nightly archives via cron jobs (#26938) 2023-03-21 11:52:29 +02:00
Martin Holst Swende
7ecb578564
params: begin v1.11.6 release cycle 2023-03-21 09:04:26 +01:00
Martin Holst Swende
a38f410857
params: go-ethereum v1.11.5 stable 2023-03-21 09:03:04 +01:00
Marius van der Wijden
e6b6a8b738
core/txpool: allow future local transactions (#26930)
Local transactions should not be subject to the "future shouldn't churn pending txs" rule
2023-03-20 09:15:18 -04:00
Marius van der Wijden
5d23d21fff
params: schedule shanghai fork on mainnet (#26908)
Schedules the shanghai hardfork on timestamp 1681338455 as discussed on ACDE 157: https://github.com/ethereum/execution-specs/pull/727
2023-03-20 07:38:34 -04:00
s7v7nislands
80ff0b4e6a
core/txpool: use atomic int added in go1.19 (#26913)
Makes use of atomic.Uint64 instead of atomic by pointer
2023-03-20 04:12:24 -04:00
Marius van der Wijden
81b0aa0cc7
trie: reduce unit test time (#26918) 2023-03-20 04:09:35 -04:00
Darioush Jalali
ee8e83fa5f
eth: fix output file permissions in admin_exportChain (#26912)
* api: Use 0700 file permissions for ExportChain

* change perm to 0644

* Update api.go

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2023-03-17 20:06:06 +02:00
Martin Holst Swende
58d0f6440b
rlp: support for uint256 (#26898)
This adds built-in support in package rlp for encoding, decoding and generating code dealing with uint256.Int.

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2023-03-17 06:51:55 -04:00
Darioush Jalali
b7bfbc1e64
trie, accounts/abi: add error-checks (#26914) 2023-03-17 06:19:51 -04:00
Darioush Jalali
f733657383
internal/ethapi: avoid int overflow in GetTransactionReceipt (#26911) 2023-03-16 23:53:39 +01:00
Marius van der Wijden
d8066dcde8
eth/catalyst: increase update consensus timeout (#26840)
Increases the time between consensus updates that we give the CL before we start warning the user.
2023-03-16 15:35:36 -04:00
rjl493456442
48d1bf0678
consensus: improve consensus engine definition (#26871)
Makes clear the distinction between Finalize and FinalizedAndAssemble:

- In Finalize function, a series of state operations are applied according to consensus rules. The statedb is mutated and the root hash can be checked and compared afterwards.

This function should be used in block processing(receive afrom network and apply it locally) but not block generation.

- In FinalizeAndAssemble function, after applying state mutations, the block is also to be assembled with the latest
  state root computed, updating the header. 

 This function should be used in block generation only.
2023-03-16 15:34:25 -04:00
rjl493456442
bba2a1bac5
core: show db error-info in case of mismatched hash root (#26870)
When a database failure occurs, bubble it up a into statedb, and report it in suitable places, such as during a 'bad block' report.
2023-03-16 03:12:34 -04:00
Felix Lange
f86913bc3e
cmd/devp2p, cmd/geth: add version in --help output (#26895)
Not sure why this was removed, it's pretty useful to see the version
also in --help.
2023-03-15 14:34:36 +01:00
Jonathan Otto
6bc68f8d94
Increase websocket frame size (from erigon rpc client) (#26883)
This increases the maximum allowed message size to 32MB.

Originally submitted at https://github.com/ledgerwatch/erigon/pull/2739

example block failure: https://etherscan.io/tx/0x1317d973a55cedf9b0f2df6ea48e8077dd176f5444a3423368a46d6e4db89982#internal
2023-03-14 18:41:28 +01:00
Stephen Flynn
b5c9be3358
all: update links in documentation (#26882)
Co-authored-by: Stephen Flynn <stephen.flynn@gapac.com>
2023-03-14 10:23:49 -04:00
Martin Holst Swende
eca3d39c31
p2p/discover: pass invalid discv5 packets to Unhandled channel (#26699)
This makes it possible to run another protocol alongside discv5, by reading 
unhandled packets from the channel.
2023-03-14 12:40:40 +01:00
rjl493456442
c8a6b7100c
core/state, trie: port changes from PBSS (#26763) 2023-03-14 04:50:53 -04:00
Felix Lange
94ff721911
.travis.yml: reenable PPA build on tag push (#26873) 2023-03-13 14:10:19 +01:00
lightclient
5f81db68c6
eth: return error if 'safe' or 'finalized' tag used pre-merge (#26862)
Co-authored-by: Martin Holst Swende <martin@swende.se>
Co-authored-by: Felix Lange <fjl@twurst.com>
2023-03-13 06:51:23 -04:00
ucwong
d1c5f918a3
core/txpool: use priceList.Put instead of heap.Push (#26863)
Minor refactor to use the 'intended' accessor
2023-03-13 04:45:25 -04:00
s7v7nislands
a20e38720c
core: minor code refactor (#26852)
* core: refactor code

* core: drop it from this anonymous goroutine func
2023-03-13 04:02:50 -04:00
xiyang
ca61048178
code/vm: fix comment typo (#26865)
it should be constantinople rather than contantinople
2023-03-13 09:30:32 +02:00
Guruprasad Kamath
789de23d16
tests: define MuirGlacier fork (#26856)
add muir glacier to t8n
2023-03-10 15:47:05 -05:00
Felix Lange
4930614a09 params: begin v1.11.5 release cycle 2023-03-10 20:00:23 +01:00
Felix Lange
7e3b149be0 params: go-ethereum v1.11.4 stable 2023-03-10 19:53:52 +01:00
Marius van der Wijden
6cf2e921a7
core/txpool: implement additional DoS defenses (#26648)
This adds two new rules to the transaction pool:

- A future transaction can not evict a pending transaction.
- A transaction can not overspend available funds of a sender.

---

Co-authored-by: dwn1998 <42262393+dwn1998@users.noreply.github.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-03-10 18:30:26 +01:00
Felix Lange
564db9a95f
core: add Timestamp method in BlockGen (#26844)
Since forks are now scheduled by block time, it can be necessary
to check the timestamp of a block while generating transactions.
2023-03-10 14:03:27 +01:00
panicalways
051493d9bf
p2p: small comment typo (#26850)
Update server.go
2023-03-10 11:45:49 +02:00
Péter Szilágyi
df02799543
travis: only build PPAs nightly, not on every push, too heavy (#26846) 2023-03-09 16:44:54 +02:00
Roberto Bayardo
67ac5f0ae7
core, core/types: plain Message struct (#25977)
Here, the core.Message interface turns into a plain struct and
types.Message gets removed.

This is a breaking change to packages core and core/types. While we do
not promise API stability for package core, we do for core/types. An
exception can be made for types.Message, since it doesn't have any
purpose apart from invoking the state transition in package core.
types.Message was also marked deprecated by the same commit it
got added in, 4dca5d4db7 (November 2016).

The core.Message interface was added in December 2014, in commit
db494170dc, for the purpose of 'testing' state transitions. It's the
same change that made transaction struct fields private. Before that,
the state transition used *types.Transaction directly.

Over time, multiple implementations of the interface accrued across
different packages, since constructing a Message is required whenever
one wants to invoke the state transition. These implementations all
looked very similar, a struct with private fields exposing the fields
as accessor methods.

By changing Message into a struct with public fields we can remove all
these useless interface implementations. It will also hopefully
simplify future changes to the type with less updates to apply across
all of go-ethereum when a field is added to Message.

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2023-03-09 14:19:12 +01:00
Martin Holst Swende
08f6a2a89d
cmd/evm: update readmes for the tests (#26841) 2023-03-09 07:06:47 -05:00
Felix Lange
5395362e0f
core/forkid: fix issue in validation test (#26544)
This changes the test to match the comment description. Using timestampedConfig in this test case is incorrect, the comment says 'local is at Gray Glacier' and isn't aware of more forks.
2023-03-09 06:37:44 -05:00
xiyang
1bf1168432
core/vm: fix typo in comment (#26838)
fixes eip 220 ->  2200
2023-03-09 04:39:17 -05:00
Martin Holst Swende
b80f05bde2
core/vm: use golang native big.Int (#26834)
reverts #26021, to use the upstream bigint instead.
2023-03-08 13:12:53 -05:00
Rafael Matias
e14043db71
params: remove EF azure bootnodes (#26828) 2023-03-08 11:13:56 +01:00
Daniel Fernandes
02796f6bee
signer/core: accept all solidity primitive types for EIP-712 signing (#26770)
Accept all primitive types in Solidity for EIP-712 from intN, uintN, intN[], uintN[] for N as 0 to 256 in multiples of 8

---------

Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-03-08 02:48:53 -05:00
rjl493456442
f7661a662a
core/rawdb: find smallest block stored in key-value store when chain gapped (#26719)
This change prints out more information about the problem, in the case where geth detects a gap between leveldb and ancients, so we can determine more exactly where the gap is (what the first missing is). Also prints out more metadata. 

---------

Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-03-08 02:39:13 -05:00
Felix Lange
bb4ac2d396 params: begin v1.11.4 release cycle 2023-03-07 18:18:59 +01:00
Felix Lange
5ed08c4735 params: go-ethereum v1.11.3 stable 2023-03-07 18:17:32 +01:00
Felix Lange
a54d91ac5a
build: update to go 1.20.2 (#26824) 2023-03-07 18:16:21 +01:00
Marius van der Wijden
78429f7733
beacon/engine: don't omit empty withdrawals in ExecutionPayloadBodies (#26698)
This ensures the "withdrawals" field will always be present in responses
to getPayloadBodiesByRangeV1 and getPayloadBodiesByHashV1.

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2023-03-07 16:30:04 +01:00
James Prestwich
1e3177de22
accounts/usbwallet: mitigate ledger app chunking issue (#26773)
This PR mitigates an issue with Ledger's on-device RLP deserialization, see
https://github.com/LedgerHQ/app-ethereum/issues/409

Ledger's RLP deserialization code does not validate the length of the RLP list received,
and it may prematurely enter the signing flow when a APDU chunk boundary falls immediately
before the EIP-155 chain_id when deserializing a transaction. Since the chain_id is
uninitialized, it is 0 during this signing flow. This may cause the user to accidentally
sign the transaction with chain_id = 0. That signature would be returned from the device 1
packet earlier than expected by the communication loop. The device blocks the
second-to-last packet waiting for the signer flow, and then errors on the successive
packet (which contains the chain_id, zeroed r, and zeroed s)

Since the signature's early arrival causes successive errors during the communication
process, geth does not parse the improper signature produced by the device, and therefore
no improperly-signed transaction can be created. User funds are not at risk.

We mitigate by selecting the highest chunk size that leaves at least 4 bytes in the
final chunk.
2023-03-07 15:20:04 +01:00
Sina Mahmoodi
41af42e97c
eth/tracers/native: set created address to nil in case of failure (#26779)
Fixes #26073
2023-03-07 14:39:11 +01:00
Guruprasad Kamath
cb1f6bdbc8
cmd/evm: correct alloc for t8n testdata (#26822)
Fixes a minor error in the testdata
2023-03-07 05:32:52 -05:00
Adrian Sutton
39be753bf5
internal/ethapi: add tests for transaction types JSON marshal/unmarshal (#26667)
Checks that Transaction.MarshalJSON and newRPCTransaction JSON output can be parsed by Transaction.UnmarshalJSON

---------

Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-03-07 05:26:19 -05:00
rjl493456442
77e33e5a49
core, miner: revert block gas counter in case of invalid transaction (#26799)
This change fixes a flaw where, in certain scenarios, the block sealer did not accurately reset the remaining gas after failing to include an invalid transaction. Fixes #26791
2023-03-07 05:23:52 -05:00
Felix Lange
4688d3c8f4
ethclient: fix panic when requesting missing blocks (#26817)
This fixes a regression introduced by #26723.
Fixes #26816.
2023-03-07 05:21:23 -05:00
turboboost55
544e4a700b
metrics: improve accuracy of CPU gauges (#26793)
This PR changes metrics collection to actually measure the time interval between collections, rather
than assume 3 seconds. I did some ad hoc profiling, and on slower hardware (eg, my Raspberry Pi 4)
I routinely saw intervals between 3.3 - 3.5 seconds, with some being as high as 4.5 seconds. This
will generally cause the CPU gauge readings to be too high, and in some cases can cause impossibly
large values for the CPU load metrics (eg. greater than 400 for a 4 core CPU).

---------

Co-authored-by: Felix Lange <fjl@twurst.com>
2023-03-07 00:29:48 +01:00
Marius van der Wijden
5bc2ef984f
core, eth/catalyst: fix race conditions in tests (#26790)
Fixes a race in TestNewPayloadOnInvalidTerminalBlock where setting the TTD raced with
the miner. Solution: set the TTD on the blockchain config not the genesis config.

Also fixes a race in CopyHeader which resulted in race reports all over the place.
2023-03-06 23:32:27 +01:00
Felix Lange
87186148e0
core/types: add EffectiveGasPrice in Receipt (#26713)
This change adds a struct field EffectiveGasPrice in types.Receipt. The field is present
in RPC responses, but not in the Go struct, and thus can't easily be accessed via ethclient.

Co-authored-by: PulsarAI <dev@pulsar-systems.fi>
2023-03-06 17:19:41 +01:00
Péter Szilágyi
4c23fe97c5
eth: remove admin.peers[i].eth.head and difficulty (#26804) 2023-03-06 09:27:46 +02:00
Marius van der Wijden
d865a5d6ae
core, params: schedule Shanghai on goerli (#26795)
* core: params: schedule Shanghai on goerli

* core/forkid: fix comment
2023-03-06 09:26:43 +02:00
Péter Szilágyi
27e59827d8 travi: remove strange leftover Go version 2023-03-03 12:26:04 +02:00
Péter Szilágyi
403cac71eb
README, go.mod, event, internal/version: bump min Go to 1.19 (#26803) 2023-03-03 12:24:09 +02:00
Péter Szilágyi
010189538e
core: fix a merge fault (#26802) 2023-03-03 12:11:39 +02:00
Péter Szilágyi
19f74fa3c0
core/rawdb, ethdb/pebble: disable pebble on openbsd (#26801) 2023-03-03 12:05:00 +02:00
Péter Szilágyi
cd31f2dee2
all: change chain head markers from block to header (#26777) 2023-03-02 08:29:15 +02:00
Peter (bitfly)
e1b98f49a5
ethclient: include withdrawals in ethclient block responses (#26778)
* include withdrawals in ethclient responses

* omit empty withdrawals array in json serialization
2023-02-28 15:40:24 +02:00
rjl493456442
2bb622ce40
ethdb/pebble: fix max memorytable size (#26776) 2023-02-28 15:34:12 +02:00
rjl493456442
98b0ea62b5
ethdb/pebble: fix range compaction (#26771)
* ethdb/pebble: fix range compaction

* ethdb/pebble: add comment
2023-02-28 15:32:51 +02:00
Dan Cline
2ea48f8a22
core: improve withdrawal index assignment in GenerateChain (#26756)
This fixes an issue where the withdrawal index was not calculated correctly
for multiple withdrawals in a single block.

Co-authored-by: Gary Rong <garyrong0905@gmail.com>
Co-authored-by: Felix Lange <fjl@twurst.com>
2023-02-28 11:46:32 +01:00
Chris Ziogas
2ad150d986
eth/tracers: add native flatCallTracer (aka parity style tracer) (#26377)
Adds support for a native call tracer with the Parity format, which outputs call frames
in a flat array. This tracer accepts the following options:

- `convertParityErrors: true` will convert error messages to match those of Parity
- `includePrecompiles: true` will report all calls to precompiles. The default
  matches Parity's behavior where CALL and STATICCALLs to precompiles are excluded

Incompatibilities with Parity include:

- Parity removes the result object in case of failure. This behavior is maintained
  with the exception of reverts. Revert output usually contains useful information,
  i.e. Solidity revert reason.
- The `gasUsed` field accounts for intrinsic gas (e.g. 21000 for simple transfers)
  and refunds unlike Parity
- Block rewards are not reported

Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2023-02-28 13:54:37 +03:30
Martin Holst Swende
c155c8e179
cmd/devp2p: faster crawling + less verbose dns updates (#26697)
This improves the speed of DHT crawling by using concurrent requests.
It also removes logging of individual DNS updates.
2023-02-27 11:36:26 +01:00
Péter Szilágyi
ee530c0d5a
Merge pull request #26721 from holiman/nocover
ci: disable coverage reporting in appveyor and travis
2023-02-23 13:24:31 +02:00
Péter Szilágyi
b3ae073488
eth: use the last announced finalized block as the sync ancient limit (#26685) 2023-02-23 13:22:41 +02:00
Martin Holst Swende
09a9ccdbce
core/rawdb, node: use standalone flock dependency (#26633) 2023-02-23 09:11:50 +02:00
Nate Armstrong
a36c68f12c
log: improve documentation (#26753)
Add usage examples
2023-02-22 07:39:41 -05:00
Péter Szilágyi
f6a7cc68d5 params: begin v.1.11.3 release cycle 2023-02-22 14:25:19 +02:00
Péter Szilágyi
73b01f40ce params: release Geth v1.11.2 2023-02-22 14:23:51 +02:00
Péter Szilágyi
f86f048646
common/math: allow HexOrDecimal to accept unquoted decimals too (#26758) 2023-02-22 13:55:09 +02:00
Yier
4034c675be
eth/filters: fix a breaking change and return rpctransaction (#26757)
* eth/filters: fix a breaking change and return rpctransaction

* eth/filters: fix test cases

---------

Co-authored-by: Catror <me@catror.com>
2023-02-22 13:06:43 +02:00
rjl493456442
fe01a2f63b
all: use unified emptyRootHash and emptyCodeHash (#26718)
The EmptyRootHash and EmptyCodeHash are defined everywhere in the codebase, this PR replaces all of them with unified one defined in core/types package, and also defines constants for TxRoot, WithdrawalsRoot and UncleRoot
2023-02-21 06:12:27 -05:00
Péter Szilágyi
2f20fd31ee
core/rawdb: expose chain freezer constructor without internals (#26748) 2023-02-21 13:10:01 +02:00
Martin Holst Swende
6d2d126100
core: fix accessor mismatch for genesis state (#26747) 2023-02-21 12:18:33 +02:00
Péter Szilágyi
90d25514af
core, eth: merge snap-sync chain download progress logs (#26676) 2023-02-21 12:17:34 +02:00
Sungwoo Kim
7d4db69607
cmd/geth: clarify dumpconfig options (#26729)
Clarifies the documentation around dumpconfi

Signed-off-by: Sungwoo Kim <git@sung-woo.kim>
2023-02-21 02:35:04 -05:00
rjl493456442
13ef21d467
Revert "core/trie: remove trie tracer (#26665)" (#26732)
This reverts commit 7c749c947a.
2023-02-20 09:54:52 -05:00
Péter Szilágyi
ba4267fcac build: enable Lunar Lobster PPA builds 2023-02-20 13:26:37 +02:00
Péter Szilágyi
41dee2623e build: fix Go 1.19.0 bootstrapper issues on 386 PPA 2023-02-20 12:36:46 +02:00
Péter Szilágyi
4519054816 build: fix (finaly?) the PPA env vars for Go bootstrapping 2023-02-20 11:31:19 +02:00
Péter Szilágyi
c02334be1e build: yet another weird PPA fix 2023-02-20 11:07:33 +02:00
Péter Szilágyi
165268430c internal/build: revert raising the chunk size for PPA 2023-02-20 10:43:55 +02:00
Péter Szilágyi
a43efceaf2 build: add some PPA debug logs, sigh 2023-02-20 10:31:35 +02:00
Péter Szilágyi
4ec4235fc4 build: fix gobootstrap path for the PPA 2023-02-20 10:09:00 +02:00
Péter Szilágyi
e1e2781105 build: fix setting env var, temp early exit 2023-02-20 09:57:37 +02:00
Péter Szilágyi
2166c86041
build: ship bootstrapper Go along with builder for PPA (#26731) 2023-02-20 08:53:15 +02:00
Felix Lange
1db978ca6b
rpc: fix unmarshaling of null result in CallContext (#26723)
The change fixes unmarshaling of JSON null results into json.RawMessage.

---------

Co-authored-by: Jason Yuan <jason.yuan@curvegrid.com>
Co-authored-by: Jason Yuan <jason.yuan869@gmail.com>
2023-02-19 14:23:18 -05:00
Martin Holst Swende
7c749c947a
core/trie: remove trie tracer (#26665)
This PR contains a small portion of the full pbss PR, namely

    Remove the tracer from trie (and comitter), and instead using an accessList.
    Related changes to the Nodeset.


---------

Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2023-02-19 14:10:19 -05:00
Roman Krasiuk
15e5e6176b
eth/catalyst: request too large error (#26722)
The method `GetPayloadBodiesByRangeV1` now returns "-38004: Too large request" error if the requested range is too large, according to spec

Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-02-17 13:30:38 -05:00
Martin Holst Swende
a0d63bc69a
ci: disable coverage reporting in appveyor and travis 2023-02-17 15:34:30 +01:00
Marius van der Wijden
6428663faf
eth/catalyst: send INVALID instead of INVALID_BLOCK_HASH (#26696)
This change will break one hive test, but pass another and it will be the better way going forward
2023-02-17 05:25:09 -05:00
Martin Holst Swende
b40c10916c
params: begin v1.11.2 release cycle 2023-02-16 20:53:16 +01:00
Martin Holst Swende
769610667d
params: go-ethereum v1.11.1 stable 2023-02-16 20:51:51 +01:00
Martin Holst Swende
4d3525610e
all: remove deprecated uses of math.rand (#26710)
This PR is a (superior) alternative to https://github.com/ethereum/go-ethereum/pull/26708, it handles deprecation, primarily two specific cases. 

`rand.Seed` is typically used in two ways
- `rand.Seed(time.Now().UnixNano())` -- we seed it, just to be sure to get some random, and not always get the same thing on every run. This is not needed, with global seeding, so those are just removed. 
- `rand.Seed(1)` this is typically done to ensure we have a stable test. If we rely on this, we need to fix up the tests to use a deterministic prng-source. A few occurrences like this has been replaced with a proper custom source. 

`rand.Read` has been replaced by `crypto/rand`.`Read` in this PR.
2023-02-16 14:36:58 -05:00
ucwong
e9d42499bb
eth/downloader: fix typo (#26716) 2023-02-16 19:40:16 +02:00
Martin Holst Swende
13d7de77f4
eth/downloader: fix empty-body case in queue fetchresult (#26707) 2023-02-16 12:28:01 +02:00
Martin Holst Swende
645e3e86c4
core, eth/downloader: make body validation more strict (#26704) 2023-02-16 12:10:16 +02:00
rjl493456442
08bf8a60c3
core: check genesis state presence by disk read (#26703) 2023-02-16 12:09:41 +02:00
Péter Szilágyi
5ccc99b258
travis, build: update Go to 1.20.1 (#26653)
travis, build: update Go to 1.20
2023-02-16 09:00:45 +02:00
Martin Holst Swende
194b5c9152
params: begin v1.11.1 release cycle 2023-02-15 19:15:31 +01:00
Martin Holst Swende
18b641b064
params: go-ethereum v1.11.0 stable 2023-02-15 19:14:20 +01:00
Marius van der Wijden
7fb42e6db2
eth/downloader: handle missing withdrawals if empty list is expected (#26675)
This PR relaxes the block body ingress handling a bit: if block body withdrawals are missing (but expected to be empty), the body withdrawals are set to 'empty list' before being passed to upper layers. 

This fixes an issue where a block passed from EthereumJS to geth was deemed invalid.
2023-02-15 07:23:07 -05:00
Patrick O'Grady
5967a2290a
ethdb/pebble: Fix MemTableStopWritesThreshold (#26692)
MemTableStopWritesThreshold was set to the max size of all memtables before blocking writing but should be set to the max number of memtables. This is documented [here](https://github.com/cockroachdb/pebble/blob/master/options.go#L738-L742).
2023-02-15 03:27:52 -05:00
Marius van der Wijden
dbd6c1324d
eth/catalyst: return error if withdrawals are nil post-shanghai (#26691)
Spec: https://github.com/ethereum/execution-apis/blob/main/src/engine/shanghai.md#request
2023-02-14 13:39:00 -05:00
Felix Lange
101587b3f4
p2p/dnsdisc: fix tests with Go 1.20 (#26690) 2023-02-14 15:58:43 +02:00
Sina Mahmoodi
ff38c9ee2e
eth/filters: replace atomic pointer with value (#26689)
* eth/filters: replace atomic.Pointer

* fix

* improve

Co-authored-by: Martin Holst Swende <martin@swende.se>

---------

Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-02-14 15:48:22 +02:00
Martin Holst Swende
f44ebc4838
params: update mainnet + rinkeby CHT (#26677)
This change updates the CHT entries for mainnet and rinkeby
2023-02-14 04:12:34 -05:00
Martin Holst Swende
1c5fa40a78
cmd/devp2p: reduce output of node crawler (#26674)
Our discovery crawler spits out a huge amount of logs, most of which is pretty non-interesting. This change moves the very verbose output to Debug, and adds a 8-second status log message giving the general idea about what's going on.
2023-02-14 03:08:06 -05:00
Martin Holst Swende
03585ed7a9
tests/fuzzers: supply gnark multiexp config, fixes #26669 (#26670)
This change fixes a fuzzer which broke when we updated the gnark dependency earlier.
2023-02-13 08:14:34 -05:00
Darioush Jalali
7d29fff415
eth/tracers: more fork overrides in traceBlockToFile (#26655)
This change allows all post-Berlin forks to be specified as overrides for futureForkBlock in the config parameter for traceBlockToFile.
2023-02-13 05:01:35 -05:00
Sina Mahmoodi
2def62b99b
eth/filters: avoid block body retrieval when no matching logs (#25199)
Logs stored on disk have minimal information. Contextual information such as block
number, index of log in block, index of transaction in block are filled in upon request.
We can fill in all these fields only having the block header and list of receipts.
But determining the transaction hash of a log requires the block body.

The goal of this PR is postponing this retrieval until we are sure we the transaction hash.
It happens often that the header bloom filter signals there might be matches in a block,
but after actually checking them reveals the logs do not match. We want to avoid fetching
the body in this case.

Note that this changes the semantics of Backend.GetLogs. Downstream callers of
GetLogs now assume log context fields have not been derived, and need to call
DeriveFields on the logs if necessary.
2023-02-13 10:59:27 +01:00
Marius van der Wijden
241cf62b5c
params: schedule shanghai fork on sepolia (#26662)
* params: schedule shanghai fork on sepolia

* params: u64 -> newUint64
2023-02-10 13:34:45 +02:00
rjl493456442
0ea65d4020
ethdb: add benchmark test suite (#26659) 2023-02-10 04:35:00 -05:00
Chris Ziogas
b0cd8c4a5c
core/vm: set tracer-observable value of a delegatecall to match parent value (#26632)
This is a breaking change in the tracing hooks API as well as semantics of the callTracer:

- CaptureEnter hook provided a nil value argument in case of DELEGATECALL. However to stay consistent with how delegate calls behave in EVM this hook is changed to pass in the value of the parent call.
- callTracer will return parent call's value for DELEGATECALL frames.

---------

Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2023-02-10 10:26:43 +01:00
Péter Szilágyi
77380b9629
go.mod: update pebble to latest master (#26654) 2023-02-09 19:01:31 +02:00
Martin Holst Swende
22c3ad1d12
core/state, trie: remove unused error-return from trie Commit operation (#26641) 2023-02-09 08:56:59 -05:00
Péter Szilágyi
3086c256c9
eth/downloader: fix timeout resurrection panic (#26652)
* common/prque, eth/downloader: fix timeout resurrection panic

* common/prque: revert -1 hack for les, temporaryly!
2023-02-09 14:56:15 +02:00
Péter Szilágyi
da3c974c36
ethdb/pebble: fix nil callbacks (#26650) 2023-02-09 13:31:42 +02:00
Péter Szilágyi
bf1798e04e
common/prque: generic priority queue (#26290)
* common, core, eth, les, trie: make prque generic

* les/vflux/server: fixed issues in priorityPool

* common, core, eth, les, trie: make priority also generic in prque

* les/flowcontrol: add test case for priority accumulator overflow

* les/flowcontrol: avoid priority value overflow

* common/prque: use int priority in some tests

No need to convert to int64 when we can just change the type used by the
queue.

* common/prque: remove comment about int64 range

---------

Co-authored-by: Zsolt Felfoldi <zsfelfoldi@gmail.com>
Co-authored-by: Felix Lange <fjl@twurst.com>
2023-02-09 13:03:54 +02:00
Marius van der Wijden
6a148dd5c3
eth/catalyst: disallow forkchoiceupdate v1 post-shanghai (#26645) 2023-02-09 10:53:22 +02:00
Martin Holst Swende
ed51b8c5d3
ethdb: pebble backend (64bit platforms only) (#26517)
* ethdb: use pebble

Co-authored-by: Gary Rong <garyrong0905@gmail.com>

foo

update

* apply suggested changes

* flags: go format

node: fix ddir lookup mistake

accounts/abi/bind: fix go.mod replacement for generated binding

deps: update pebble + with fix 32-bit build

* ethdb/pebble: respect max memtable size

* core/rawdb, ethdb: enable pebble on non-32bit platforms only

* core/rawdb: fix build tags, fix some review concerns

* core/rawdb: refactor methods for database opening

* core/rawdb: remove erroneous build tag

* cmd/geth: fix the flag default handling + testcase

* cmd/geth: improve testing regarding custom backends

* ethdb/pebble, deps: update pebble dependency

* core/rawdb: replace method with Open

* ethdb/pebble: several updates for pebble (#49)

* ethdb/pebble: fix size count in batch

* ethdb/pebble: disable seek compaction

* ethdb/pebble: more fixes

* ethdb, core, cmd: polish and fixes (#50)

* cmd/utils, core/rawdb, ethdb/pebble: address some review concerns

* Update flags.go

* ethdb/pebble: minor refactors

* ethdb/pebble: avoid copy on batch replay

* ethdb: fix compilation flaw

* cmd: fix test fail due to mismatching error message

* cmd/geth, node: rename backingdb to db.engine

---------

Co-authored-by: Jared Wasinger <j-wasinger@hotmail.com>
Co-authored-by: rjl493456442 <garyrong0905@gmail.com>
Co-authored-by: Péter Szilágyi <peterke@gmail.com>
2023-02-09 10:48:34 +02:00
Péter Szilágyi
095e365fac
all: remove support for Ropsten (#26644) 2023-02-09 10:03:00 +02:00
jwasinger
0c9eb8c9a4
eth/catalyst: make getPayloadBodiesByRange take hex inputs (#26624)
Co-authored-by: Martin Holst Swende <martin@swende.se>
Co-authored-by: Marius van der Wijden <m.vanderwijden@live.de>
2023-02-08 10:04:40 -05:00
rjl493456442
9842301376
all: remove database commit callback, rework noderesolver (#26637)
This change ports some changes from the main PBSS PR:

  - get rid of callback function in `trie.Database.Commit` which is not required anymore
  - rework the `nodeResolver` in `trie.Iterator` to make it compatible with multiple state scheme
  - some other shallow changes in tests and typo-fixes
2023-02-08 06:14:34 -05:00
Felix Lange
8c18b48bf1
log: allow tabs in log messages (#26630)
* log: allow tabs in log messages

This fixes a regression where panic reports in RPC handlers were quoted
because they contain tab characters.

* Update format.go
2023-02-08 11:39:17 +02:00
halilylm
00a9b80b5c
light: fix receiver name from Python style to Go (#26631)
Co-authored-by: Halil Yildirim <halilgolang@gmail.com>
2023-02-08 11:37:33 +02:00
Marius van der Wijden
2f73f4f028
eth/catalyst,miner: include withdrawals in payload id calculation (#26554)
According to the spec the payloadID needs to be random or dependent on all arguments, to prevent two payloads from clashing. This change adds withdrawals into the payload derivation. 

---------

Co-authored-by: lightclient@protonmail.com <lightclient@protonmail.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
Co-authored-by: Felix Lange <fjl@twurst.com>
2023-02-07 13:16:53 -05:00
Felix Lange
31d401ea68
rpc: remove DecimalOrHex type (#26629)
It's the same as math.HexOrDecimal64, which has more uses across the codebase.
2023-02-07 15:44:27 +01:00
zhiqiangxu
cefc0fa00f
accounts/abi: fix integer encoding/decoding (#26568)
This PR fixes this abi encoder/decoder to be more stringent.
2023-02-07 08:32:27 -05:00
Martin Holst Swende
91cb6f863a
tests: update (#26548)
This updates the reference tests to the latest version.

Co-authored-by: Felix Lange <fjl@twurst.com>
2023-02-06 14:52:51 -05:00
Felix Lange
37e3208e33
build: upgrade to golangci-lint v1.51.1 (#26618) 2023-02-06 18:15:13 +01:00
Felföldi Zsolt
3a5aceed8f
beacon/engine: move core/beacon to beacon/engine (#26616)
This PR moves core/beacon to beacon/engine so that beacon-chain related code has its own top level package which also can house the the beacon lightclient-code.
2023-02-06 10:37:58 -05:00
Martin Holst Swende
8860b39754
all: prepare for path-based trie storage (#26603)
This PR moves some trie-related db accessor methods to a different file, and also removes the schema type. Instead of the schema type, a string is used to distinguish between hashbased/pathbased db accessors.
This also moves some code from trie package to rawdb package.

This PR is intended to be a no-functionality-change prep PR for #25963 .

---------

Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2023-02-06 10:28:40 -05:00
Marius Kjærstad
10c14847af
README: remove text about GPU mining (#26609)
Co-authored-by: Felix Lange <fjl@twurst.com>
2023-02-06 15:10:46 +01:00
raulk
918aed4e31
core/vm: add bn256ScalarMul testcase for zero scalar value (#26607)
EIP-196 allows a zero value in the scalar argument to precompile `0x07`. This change adds a test for that case.
2023-02-06 07:41:29 -05:00
Martin Holst Swende
8e92881a3d
rpc: fix off-by-one in ipc endpoint length check (#26614)
This change fixes a minor flaw in the check for ipc endpoint length. The max_path_size is the max path that an ipc endpoint can have, which is 208. However, that size concerns the null-terminated pathname, so we need to account for an extra null-character too.
2023-02-06 07:25:42 -05:00
delihiros
bd726f86b8
readme: fix broken link (#26612) 2023-02-06 05:18:50 -05:00
Marius van der Wijden
9826cd65bc
eth/catalyst: implement engine_getPayloadBodiesByHash/Range methods (#26232)
This change implements engine_getPayloadBodiesByHash and engine_getPayloadBodiesByRange, according to the specification at https://github.com/ethereum/execution-apis/blob/main/src/engine/shanghai.md#specification-4 .

Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-02-06 04:21:40 -05:00
lmittmann
877d2174fb
core/vm: improve EVM instance reusability (#26341)
This change improves reusability of the EVM struct. Two methods are added:

- SetBlockContext(...)
- SetTracer(...)

Other attributes like the TransactionContext and the StateDB can already be updated.
BlockContext and Tracer are partially not updateable right now. This change fixes it and
opens the potential to reuse an EVM struct in more ways.

Co-authored-by: Felix Lange <fjl@twurst.com>
2023-02-05 15:11:25 +01:00
Péter Szilágyi
3a79a99f80
Merge pull request #26599 from karalabe/mobile-nuke
accounts, build, mobile: remove Android and iOS support
2023-02-03 12:52:10 +02:00
Péter Szilágyi
d9699c8238
accounts, build, mobile: remove Andriod and iOS support 2023-02-03 12:29:07 +02:00
Marius van der Wijden
d0a4989a8d
cmd, eth, node: deprecate personal namespace (#26390)
* eth: cmd: deprecate personal namespace

* eth: cmd: move deprecation to node

* node: disable toml of enablepersonal

* node: disable personal on ipc as well

* Update node/node.go

Co-authored-by: Martin Holst Swende <martin@swende.se>

* console: error -> warn

* node: less roulette

---------

Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-02-02 13:52:19 +02:00
Marius van der Wijden
a8cf4399a9
eth/catalyst: return invalid params instead of invalid payload params (#26591) 2023-02-02 11:52:26 +02:00
Péter Szilágyi
5d8bff1d72
Merge pull request #26581 from holiman/nuke_puppet
cmd/puppeth: remove puppeth
2023-02-02 10:00:23 +02:00
Martin Holst Swende
5c8cc10d1e
core: improve ambiguous block validation message (#26582) 2023-02-01 10:08:25 -05:00
Martin Holst Swende
8ded6a9fcd
cmd/puppeth: remove puppeth 2023-01-31 10:16:30 +01:00
lightclient
bd6a05e1ee
internal/ethapi: always return block withdrawals if present (#26565)
The execution-apis specification says that the full list of withdrawals should always be returned when requesting a block over RPC:

378c4304f7/src/schemas/block.yaml (L90-L94)

This change adopts the expected behavior.
2023-01-31 03:34:03 -05:00
rjl493456442
efbd508d21
eth/tracer: rename to revertReason (#26574) 2023-01-31 03:29:17 -05:00
Mio
78d089b5b7
ethclient/gethclient: fix typo (#26580)
fix grammar typo
2023-01-31 03:28:32 -05:00
Martin Holst Swende
17017b2516
log: better sanitation (#26556) 2023-01-30 18:43:12 +01:00
Pascal Marco Caversaccio
3ff3d07e2c
cmd/devp2p: fix broken link in readme(#26576)
fix broken link to DNS discovery tutorial
2023-01-30 09:12:55 -05:00
ucwong
fd4230f695
log: fix typo in comment (#26569) 2023-01-30 08:33:03 -05:00
Felix Lange
df52967ff6
eth/catalyst: fix panic in TestWithdrawals (#26563)
Fixes a regression introduced in #26549
2023-01-27 15:33:28 +01:00
Mario Vega
90f15a0230
cmd/evm: add blocktest subcommand to evm (#26526)
Adds blocktest subcommand to the evm command, which is very similar to statetest, but instead of loading a StateTest static test it loads a BlockchainTest from a json file and runs it.

Co-authored-by: Martin Holst Swende <martin@swende.se>
Co-authored-by: lightclient <14004106+lightclient@users.noreply.github.com>
2023-01-27 08:30:13 -05:00
ucwong
a63875bf4d
go.mod: gnark-crypto upgrade (#26545) 2023-01-27 07:39:26 -05:00
Nicola Cocchiaro
abe4159cb5
params: remove deprecated bootnodes (#26530)
This change removes the Infura rinkeby bootnode as well as two deprecated ropsten bootnodes. 

Co-authored-by: Nicola Cocchiaro <ncocchiaro@users.noreply.github.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-01-27 07:32:24 -05:00
Felix Lange
34115c8f63
params: fix timestamp display in fork banner (#26553) 2023-01-27 12:03:34 +01:00
Marius van der Wijden
2fecac6041
eth/catalyst: implement exchangeCapabilities method (#26555)
Spec: ethereum/execution-apis#364
2023-01-27 12:03:03 +01:00
Marius van der Wijden
245cff0a1a
eth/catalyst: error on nil withdrawals post-shanghai (#26549)
This adds explicit checks for the presence of withdrawals in the engine API.

Co-authored-by: Felix Lange <fjl@twurst.com>
2023-01-27 11:42:14 +01:00
Felix Lange
55f41d198c
cmd/utils: fix error at geth startup in --dev mode (#26550)
This fixes a regression in #26541 where we turned the miner address
being missing into a startup error. The address was not configured in
--dev mode.
2023-01-26 10:07:20 +01:00
Marius van der Wijden
2a2b0419fb
all: implement withdrawals (EIP-4895) (#26484)
This change implements withdrawals as specified in EIP-4895.

Co-authored-by: lightclient@protonmail.com <lightclient@protonmail.com>
Co-authored-by: marioevz <marioevz@gmail.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
Co-authored-by: Felix Lange <fjl@twurst.com>
2023-01-25 15:32:25 +01:00
Martin Holst Swende
2b57a27d9e
all: make timestamp-based fork checks based on uint64 (#26474)
This PR changes the API so that uint64 is used for fork timestamps.
It's a good choice because types.Header also uses uint64 for time.

Co-authored-by: Felix Lange <fjl@twurst.com>
2023-01-25 12:12:28 +01:00
Felix Lange
59a48e0289
cmd/utils: improve parsing of --miner.etherbase address (#26541)
This fixes a regression where the flag did not accept values without
the 0x prefix anymore. What's worse, if an invalid value was passed,
the client would just log an INFO level message and continue.
2023-01-24 11:11:33 +01:00
Shude Li
163e996d0e
all: use http package to replace http method names (#26535) 2023-01-24 11:12:25 +02:00
ucwong
e4fa2cf5e3
go.sum: go mod tidy (#26536) 2023-01-24 00:59:57 +01:00
Sina Mahmoodi
d36e6fc49d
go.mod: upgrade to latest goja (#26523)
Co-authored-by: Felix Lange <fjl@twurst.com>
2023-01-23 17:59:25 +01:00
rjl493456442
2b44ef5f93
miner, cmd, eth: require explicit etherbase address (#26413)
This change introduces a breaking change to miner.etherbase is configured.

Previously, users did not need to explicitly set the  etherbase address via flag, since 'first' local account was used as etherbase automatically. This change removes the  "default first account" feature.

In Proof-of-stake world, the fee recipient address is provided by CL, and not configured in Geth any more - meaning that miner.etherbase is mostly for legacy networks(pow, clique networks etc).
2023-01-20 11:26:01 -05:00
Martin Holst Swende
4f4a25d79f
signer/core: don't require capital lettered reference types (#26462) 2023-01-20 12:01:33 +02:00
rjl493456442
50e65392aa
params: define cancun and prague as timestamp based forks (#26481)
* params: define cancun and osaka as timestamp based forks

* core, params: change osaka to prague

* params: fix
2023-01-20 11:57:50 +02:00
ucwong
3f544ce8eb
.travis.yml: go1.19.5 for android builds (#26524) 2023-01-20 11:54:53 +02:00
ucwong
87489723ac
go.sum: tidy (#26525) 2023-01-20 11:53:24 +02:00
meehow
24c7023df6
go.mod: upgrade to go-bip39 v1.1.0 (#26527) 2023-01-20 10:33:41 +01:00
Sina Mahmoodi
2d2c069ffe
console, internal/jsre: fix autocomplete issues (#26518)
Fixes #26505 where the console crashed when a property getter
raised an exception during autocompletion. I also noticed while fixing this
issue that autocomplete wasn't working for objects/fields with numbers in
them (most importantly web3.<tab><tab>) which is also now fixed.
2023-01-19 19:43:29 +01:00
Zachinquarantine
690338f0fa
all: remove Kiln testnet (#26522)
Kiln was deprecated after the merge.
2023-01-19 10:49:48 +01:00
Marius van der Wijden
a35b654f25
core/txpool: check if initcode size is exceeded (#26504)
* core/txpool: check if initcode size is exceeded

* core/txpool: move check
2023-01-18 03:47:42 -05:00
ucwong
4a3fb585dd
les/fetcher : fix requestTimer leak (#26514)
les/fetcher : fix requestTimer leak
2023-01-18 03:46:32 -05:00
Paul
97401b6c63
eth/filters: fix typo in comment (#26515) 2023-01-17 23:29:08 +01:00
ucwong
297ec0669d
metrics/influxdb: fix time ticker leaks (#26507) 2023-01-17 13:45:35 +01:00
ucwong
f2758a8dac
cmd/evm: typo fix in docs (#26506) 2023-01-16 13:14:21 -05:00
Marius Kjærstad
8d4c81dab1
build: upgrade -dlgo version to Go 1.19.5 (#26472) 2023-01-16 14:24:11 +01:00
Ikko Eltociear Ashimine
c858da555d
cmd/evm: fix typo in README.md (#26500) 2023-01-16 11:23:24 +01:00
Seungbae Yu
d345a4a3c6
cmd/bootnode, cmd/utils: add 'pmp:<IP>' to --nat flag description (#26381) 2023-01-16 11:21:41 +01:00
ucwong
55c3b6fc37
swarm: fix outdated link (#26501) 2023-01-16 11:00:55 +01:00
Zachinquarantine
554c8d77c5
cmd/utils: update Rinkeby deprecation message (#26496) 2023-01-16 10:57:35 +01:00
Martin Holst Swende
0b53b29078
core/rawdb: fix cornercase shutdown behaviour in freezer (#26485)
This PR does a few things. 
It fixes a shutdown-order flaw in the chainfreezer. Previously, the chain-freezer would shutdown the freezer backend first, and then signal for the loop to exit. This can lead to a scenario where the freezer tries to fsync closed files, which is an error-conditon that could lead to exit via log.Crit. 

It also makes the printout more detailed when truncating 'dangling' items, by showing the exact number instead of approximate MB.

This PR also adds calls to fsync files before closing them, and also makes the `db inspect` command slightly more robust.
2023-01-16 03:57:27 -05:00
David Hwang
450d771bee
readme: fix broken link to installation instructions (#26497)
update link to the installation instructions
2023-01-15 03:23:58 -05:00
Marius van der Wijden
0e486a56c9
Use filepath.clean instead of path.clean (#26404)
* internal/flags: use filepath.Clean instead of path.Clean

* internal/flags: fix windows pipe issue

* internal/flags: modify test for windows

* internal/flags: use backticks, fix test
2023-01-13 09:48:42 -05:00
rjl493456442
e04d63ebd3
core/rawdb: fsync head data file before closing it (#26490)
This PR fixes an issue which might result in data lost in freezer.

Whenever mutation happens in freezer, all data will be written into head data file
and it will be rotated with a new one in case the size of file reaches the threshold.

Theoretically, the rotated old data file should be fsync'd to prevent data loss.
In freezer.Sync function, we only fsync: (1) index file (2) meta file and (3) head
data file. So this PR forcibly fsync the head data file if mutation happens in the
boundary of data file.
2023-01-13 05:55:50 -05:00
rjl493456442
a21e963ac2
eth/catalyst: trigger beacon sync directly with provided chain head (#26489) 2023-01-13 08:13:27 +01:00
Felix Lange
d379e3f605
ethclient/gethclient: ensure getProof keys parameter is not null (#26409)
Other clients do not accept a parameter value of null for this array.
2023-01-12 11:31:21 +01:00
rjl493456442
b748709a11
eth/downloader: fix cornercase when clean stale beacon headers (#26441) 2023-01-12 11:19:16 +01:00
lightclient
6f858fa806
rpc: fix setting client in DialHTTPWithClient (#26470) 2023-01-12 11:04:34 +01:00
Andrew Ashikhmin
c125e6e00c
core/vm: enable EIP-3855 (PUSH0) in Shanghai (#26475) 2023-01-12 11:00:08 +01:00
Andrei Maiboroda
793f0f9ec8
core/vm: implement EIP-3860: Limit and meter initcode (#23847)
Implementation of https://eips.ethereum.org/EIPS/eip-3860, limit and meter initcode. This PR enables EIP-3860 as part of the Shanghai fork. 


Co-authored-by: lightclient@protonmail.com <lightclient@protonmail.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
Co-authored-by: Marius van der Wijden <m.vanderwijden@live.de>
2023-01-11 04:05:47 -05:00
Péter Szilágyi
452a12aa79
eth/downloader: move the pivot in beacon sync mode too (#26453)
In legacy (pre-merge) sync mode, headers were contiguously downloaded from the network and when no more headers were available, we checked every few seconds whether there are 64 new blocks to move the pivot.

In beacon (post-merge) sync mode, we don't need to check for new skeleton headers non stop, since those re delivered one by one by the engine API. The missing code snippet from the header fetcher was to actually look at the latest head and move the pivot if it was more than 2*64-8 away. This PR adds the missing movement logic.
2023-01-10 12:16:54 -05:00
Martin Holst Swende
2c6dda5ad7
eth/tracers: use non-threaded tracechain (#24283)
This makes non-JS tracers execute all block txs on a single goroutine.
In the previous implementation, we used to prepare every tx pre-state
on one goroutine, and then run the transactions again with tracing enabled.
Native tracers are usually faster, so it is faster overall to use their output as
the pre-state for tracing the next transaction.

Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2023-01-10 15:11:53 +01:00
Martin Holst Swende
7a489623ac
core/state: remove notion of fake storage (#24916)
This PR removes the notion of fakeStorage from the state objects, and instead, for any state modifications that are needed, it simply makes the changes.
2023-01-10 08:24:30 -05:00
Martin Holst Swende
4ada314fff
tests: fix DIFFICULTY error in state executor (#26465) 2023-01-10 08:22:43 -05:00
Joseph Cook
b8bc8c2465
README.md: add website contribution instructions (#26442) 2023-01-10 14:20:47 +01:00
jwasinger
faff980d97
crypto/bls12381: use worst case scalar for input to G1/G2 mul benchmarks (#26447)
* test

* crypto/bls12381: use worst case scalar for input to G1/G2 mul benchmarks
2023-01-10 03:16:17 -05:00
Mario Vega
ccacb9930e
cmd/evm: support shanghai in tests + evm t8n (#26458) 2023-01-10 03:04:21 -05:00
Péter Szilágyi
43692c84d1
Merge pull request #26451 from rjl493456442/fix-beacon-sync-2
eth/downloader: fix unexpected skeleton header deletion
2023-01-09 12:55:51 +02:00
Péter Szilágyi
71f7988b0f
eth/downloader: create repro testcase for beacon header loss 2023-01-09 12:12:25 +02:00
Gary Rong
686f7438d3 eth/downloader: fix unexpected skeleton header deletion 2023-01-09 15:07:08 +08:00
Péter Szilágyi
2189773093
Merge pull request #25878 from MariusVanDerWijden/shanghai-by-time
params: core: enable shanghai based on timestamps
2023-01-06 16:10:12 +02:00
Péter Szilágyi
b56c796220
cmd, core, eth, els, params: disallow setheads below genesis, tweaks 2023-01-06 15:29:58 +02:00
Péter Szilágyi
fcf3d00488
eth, les: polish forkid a bit, fix races and transition validation 2023-01-06 15:29:57 +02:00
Marius Kjærstad
f426805fdd
build: upgrade -dlgo version to Go 1.19.4 (#26440) 2023-01-06 13:25:58 +02:00
rjl493456442
6c149fd4ad
core, eth, trie, light: clean up trie interface (#26388)
* all: cleanup trie interface

* eth, trie: address comments
2023-01-03 15:41:40 +02:00
Martin Holst Swende
41fe9d646c
cmd/evm: update documentation (#26385) 2023-01-03 12:37:48 +01:00
Felix Lange
a251bca67c
p2p/discover: add more packet information in logs (#26307)
* p2p/discover: add more packet information in logs

This adds more fields to discv5 packet logs. These can be useful when
debugging multi-packet interactions.

The FINDNODE message also gets an additional field, OpID for debugging
purposes. This field is not encoded onto the wire.

I'm also removing topic system related message types in this change.
These will come back in the future, where support for them will be
guarded by a config flag.

* p2p/discover/v5wire: rename 'Total' to 'RespCount'

The new name captures the meaning of this field better.
2023-01-03 12:36:38 +01:00
Felix Lange
9e6a1c3834
common/mclock: add Alarm (#26333)
Alarm is a timer utility that simplifies code where a timer needs to be rescheduled over
and over. Doing this can be tricky with time.Timer or time.AfterFunc because the channel
requires draining in some cases.

Alarm is optimized for use cases where items are tracked in a heap according to their expiry
time, and a goroutine with a for/select loop wants to be woken up whenever the next item expires.
In this application, the timer needs to be rescheduled when an item is added or removed
from the heap. Using a timer naively, these updates will always require synchronization
with the global runtime timer datastructure to update the timer using Reset. Alarm avoids
this by tracking the next expiry time and only modifies the timer if it would need to fire earlier
than already scheduled.

As an example use, I have converted p2p.dialScheduler to use Alarm instead of AfterFunc.
2023-01-03 12:10:48 +01:00
Péter Szilágyi
d021157820
core, les, light: implement timestamp based sethead and genesis rewinds 2023-01-03 12:57:07 +02:00
Péter Szilágyi
08481028fe
core, les, params: add timestamp based fork compatibility checks 2023-01-03 12:57:06 +02:00
Marius van der Wijden
a4e19c5ca3
all: implement forkid changes for shanghai 2023-01-03 12:57:06 +02:00
Marius van der Wijden
efc9409ca9
params: core: enable shanghai based on timestamps 2023-01-03 12:56:25 +02:00
strykerin
c6a2f77c2e
cmd/devp2p/internal/v4test: add pong validation in bond (#26400) 2023-01-03 11:30:34 +01:00
Marius Kjærstad
dad92500e7
cmd, internal: update copyright year to 2023 (#26382)
* internal/flags: update copyright year to 2023

* cmd/geth: update copyright year to 2023
2023-01-03 11:04:54 +02:00
Ha DANG
9d38466437
eth/downloader: fix some typos (#26396) 2023-01-03 11:03:44 +02:00
Marius van der Wijden
db82ea2ee3
core: reset txpool on sethead (#26392)
This change sends a HeadChainEvent when SetHead is invoked. The txpool will then reset the txnoncer on receiving the event.
2022-12-29 07:24:34 -05:00
rjl493456442
c87f321b8f
core/state: maintain destruction flag by default (#26371)
This changes moves the tracking of "deleted in this block" out from snap-only domain, so that it happens regardless of whether the execution is snapshot-backed or trie-backed.
2022-12-28 08:53:43 -05:00
Marius van der Wijden
9921ca0f0a
miner: allow for extradata in post-merge blocks (#26387)
* miner: allow for extradata in post-merge blocks

* miner: nits

* miner: remove extradata checks
2022-12-28 10:48:26 +02:00
Zachinquarantine
577db2edf7
build: add support for Ubuntu 22.10 (Kinetic Kudu) (#26379)
Adds uploads to Kinetic in Launchpad, and removes the upload for 21.10 impish (not supported since July)
2022-12-27 02:52:29 -05:00
rjl493456442
01808421e2
core/state: return error when storage trie can't be opened (#26350)
This changes the StorageTrie method to return an error when the trie
is not available. It used to return an 'empty trie' in this case, but that's
not possible anymore under PBSS.
2022-12-21 10:21:21 +01:00
Martin Holst Swende
b818e73ef3
tests: update tests (#26314)
This PR builds on #26299, but also updates the tests to the most recent version, which includes tests regarding TheMerge.

This change adds checks to the beacon consensus engine, making it more strict in validating the pre- and post-headers, and not relying on the caller to have already correctly sanitized the headers/blocks.
2022-12-20 09:56:52 -05:00
rjl493456442
79a478bb61
core/rawdb: implement resettable freezer (#26324)
This PR implements resettable freezer by adding a ResettableFreezer wrapper.

The resettable freezer wraps the original freezer in a way that makes it possible to ensure atomic resets. Implementation wise, it relies on the os.Rename and os.RemoveAll to atomically delete the original freezer data and re-create a new one from scratch.
2022-12-19 04:59:12 -05:00
rjl493456442
d3411b9f67
trie: wrap deletion in case trie.root is nil (#26365)
This PR fixes an error in trie commit. If the trie.root is nil, it can be two possible scenarios:

-  The trie was empty, and no change happens
-  The trie was non-empty and all nodes are dropped

For the latter one, we should collect the deletions and apply them into database(e.g. in PBSS).
2022-12-19 04:56:13 -05:00
Felix Lange
f53ff0ff4a
eth/filters, eth/tracers: add request cancellation checks (#26320)
This ensures that RPC method handlers will react to a timeout or
cancelled request soon after the event occurs.


Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2022-12-15 07:52:07 -05:00
Ikko Ashimine
f51f6edb40
core: fix typo in blockchain_snapshot_test.go (#26357)
correspnding -> corresponding
2022-12-14 11:48:12 +02:00
Martin Holst Swende
502fa829a6
signer/core: handle gnosis safe problem with missing chain id (#26309)
This PR adds a check that the safetxhash that we sign corresponds to the one that is expected by the input. If it differs, it tries again with the configured chainid.
2022-12-14 04:33:57 -05:00
Martin Holst Swende
fa97788c75
eth/tracers/native: fix possible crash in prestate tracer (#26351) 2022-12-13 08:32:29 -05:00
rjl493456442
cda051eba7
core, cmd: fill blockNumber in logs (#26345)
* core, cmd: fill blockNumber in logs

* Update core/state/statedb.go

Co-authored-by: Martin Holst Swende <martin@swende.se>

* core/types: revert

* core/state: improve comments

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-12-13 07:54:16 -05:00
Alex Stokes
250a80a50e
core: fix comment about recipient for contract creation (#26349)
A comment suggests that contract creation happens if the recipient of a call is 0x00..00 ("zero address") but in fact the sender must be nil. The zero address is a regular valid address that is commonly used as a "burn" address.
2022-12-13 03:33:40 -05:00
Michael de Hoog
262bd38fce
eth/tracers: return proper error from debug_TraceTransaction when tx not found (#26211)
Currently calling `debug_TraceTransaction` with a transaction hash that doesn't exist returns a confusing error: `genesis is not traceable`. This PR changes the behaviour to instead return an error message saying `transaction not found`

Co-authored-by: Martin Holst Swende <martin@swende.se>
Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2022-12-10 08:34:43 -05:00
Felix Lange
3775e198df
event: add FeedOf[T] (#26310)
This PR adds a new type event.FeedOf[T], which is like event.Feed but parameterized
over the channel element type. Performance is unchanged, and it still uses reflect. But
unlike Feed, the generic version doesn't need to type-check interface{} arguments.
All panic cases are gone from the API.
2022-12-09 16:20:46 +01:00
Felix Lange
3315bad256
core: pass block into collectLogs (#26335)
While investigating another issue, I found that all callers of collectLogs have the
complete block available. rawdb.ReadReceipts loads the block from the database,
so it is better to use ReadRawReceipts here, and derive the receipt information using
the block which is already in memory.
2022-12-09 16:14:33 +01:00
Sina Mahmoodi
711afbc7fd
core,eth: add debug_setTrieFlushInterval to change trie flush frequency (#24785)
This PR makes it possible to modify the flush interval time via RPC. On one extreme, `0s`, it would act as an archive node. If set to `1h`, means that after one hour of effective block processing time, the trie would be flushed. If one block takes 200ms, this means that a flush would occur every `5*3600=18000`  blocks -- however, if the memory size of the cached states grows too large, it will flush sooner. 

Essentially, this makes it possible to configure the node to be more or less "archive:ish", and without restarting the node while reconfiguring it.
2022-12-09 07:40:17 -05:00
rjl493456442
890e2efca2
eth, cmd: remove syncTarget from eth config (#26330)
--syncTarget is a feature for development purpose in post-merge world. Previously
it's added into eth.Config. But it turns out that's a stupid idea.

- syncTarget is a block object, which is hard to be put in config file(large)
- syncTarget is just a dev feature, doesn't make too much sense to add it in config file

So I remove it from the eth config object. And it also fixes the #26328
2022-12-08 14:40:43 +01:00
zhiqiangxu
a9dfac0332
p2p/discover: improve nodesByDistance.push code (#26019)
This improves readability of function 'push'.

sort.Search(N, ...) will at most return N when no match, so ix should be compared
with N. The previous version would compare ix with N+1 in case an additional item
was appended. No bug resulted from this comparison, but it's not easy to understand
why.

Co-authored-by: Felix Lange <fjl@twurst.com>
2022-12-07 23:31:47 +01:00
Sina Mahmoodi
6891288787
core: fix state flushing for catalyst mode (#26319)
The gcproc field tracks the amount of time spent processing blocks,
and is used to trigger a state flush to disk when a certain threshold is
reached. After the merge, single block insertion by CL is the most
common source of block processing time, but this time was not added
into gcproc.
2022-12-07 17:36:54 +01:00
Seungbae Yu
42212808f0
p2p/nat: handle responses with alternative port in NAT-PMP (#26321)
Co-authored-by: Felix Lange <fjl@twurst.com>
2022-12-07 16:22:04 +01:00
Sina Mahmoodi
f20eba426a
graphql, node, rpc: improve HTTP write timeout handling (#25457)
Here we add special handling for sending an error response when the write timeout of the
HTTP server is just about to expire. This is surprisingly difficult to get right, since is
must be ensured that all output is fully flushed in time, which needs support from
multiple levels of the RPC handler stack:

The timeout response can't use chunked transfer-encoding because there is no way to write
the final terminating chunk. net/http writes it when the topmost handler returns, but the
timeout will already be over by the time that happens. We decided to disable chunked
encoding by setting content-length explicitly.

Gzip compression must also be disabled for timeout responses because we don't know the
true content-length before compressing all output, i.e. compression would reintroduce
chunked transfer-encoding.
2022-12-07 14:02:14 +01:00
Felix Lange
b44abf56a9
cmd/devp2p: add --extaddr flag (#26312)
The new flag allows configuring an explicit endpoint which is to be
announced in the DHT. This feature was originally developed for the
discv5 wormhole experiment (#25798), but it's useful in other contexts
as well.
2022-12-06 16:25:53 +01:00
qiuhaohao
01953b3470
cmd/geth: fix typo in comment (#26308) 2022-12-05 18:59:00 +01:00
Martin Holst Swende
41306b0af3
cmd/evm: output stateroot in statetest result (#26297)
This adds stateRoot as a field in the JSON output.
2022-12-05 18:58:32 +01:00
Martin Holst Swende
1f35988a00
eth/tracers, core/vm: remove time from trace output and tracing interface (#26291)
This removes the 'time' field from logs, as well as from the tracer interface. This change makes the trace output deterministic.  If a tracer needs the time they can measure it themselves. No need for evm to do this.

Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2022-12-05 16:57:47 +01:00
Håvard Anda Estensen
06632da2bb
all: assign zero after resize in implementations of heap.Interface (#26296)
This changes the Pop method to assign the zero value before
reducing slice size. Doing so ensures the backing array does not
reference removed item values.
2022-12-05 13:49:54 +01:00
Sina Mahmoodi
10347c6b54
core: drop legacy receipt types (#26225)
This PR drops the legacy receipt types, the freezer-migrate command and the startup check. The previous attempt #22852 at this failed because there were users who still had legacy receipts in their db, so it had to be reverted #23247. Since then we added a command to migrate legacy dbs #24028.

As of the last hardforks all users either must have done the migration, or used the --ignore-legacy-receipts flag which will stop working now.
2022-12-03 21:42:11 +01:00
Oskar Haarklou Veileborg
e24d6003b1
miner: fix potential goroutine leak in test (#26281) 2022-12-02 12:26:52 +01:00
RichΛrd
c1aa1db69e
p2p/discover: add config option for discv5 protocol ID (#26041)
This option is occasionally useful for advanced uses of the discv5 protocol.

Co-authored-by: Felix Lange <fjl@twurst.com>
2022-11-30 22:03:34 +01:00
Felix Lange
1b8a392153
console: use default APIs when server doesn't have rpc_modules (#26267) 2022-11-28 20:27:01 +01:00
rjl493456442
743e404906
core, eth, les, tests, trie: abstract node scheme (#25532)
This PR introduces a node scheme abstraction. The interface is only implemented by `hashScheme` at the moment, but will be extended by `pathScheme` very soon.

Apart from that, a few changes are also included which is worth mentioning:

-  port the changes in the stacktrie, tracking the path prefix of nodes during commit
-  use ethdb.Database for constructing trie.Database. This is not necessary right now, but it is required for path-based used to open reverse diff freezer
2022-11-28 14:31:28 +01:00
Sina Mahmoodi
0e06735201
internal/web3ext: fix eth_call in console, part III (#26268)
Fixes regression in #26266.
2022-11-28 11:30:05 +01:00
Sina Mahmoodi
63ffda3251
internal/web3ext: fix eth.call regression in console (#26266)
Fixes a regression from #26265, which made it so that the call only worked if all three parameters were provided.
2022-11-28 11:15:34 +01:00
Paweł Bylica
eb01927e46
tests: update evm-benchmarks (#26255)
tests: update evm-benchmarks
2022-11-28 11:13:41 +01:00
setunapo
0dc9b01c11
core: clarify code in forkchoice (#26257)
refactoring without logic change
2022-11-28 11:07:25 +01:00
Sina Mahmoodi
1325fef102
internal/web3ext: fix eth_call stateOverrides in console (#26265)
web3.js's eth_call which we were defaulting to doesn't have the stateOverrides parameter, so this param wasn't working in the console.
2022-11-28 11:03:20 +01:00
Seungbae Yu
53d1ae096a
p2p/nat: use IP.IsPrivate (#26252) 2022-11-25 16:30:07 +01:00
Wihan de Beer
8c6e74eed4
rpc: decrease websocket ping interval (#26253)
This is to cater for more node providers.
2022-11-25 16:29:38 +01:00
Martin Holst Swende
6a4e05c93a
signer: enable typed data signing from signer rpc (#26241)
This PR should makes it easier to sign EIP-712 typed data via the accounts.Wallet API, by using the mimetype for typed data. 

Co-authored-by: nasdf <keenan.nemetz@gmail.com>
2022-11-25 09:13:45 +01:00
rjl493456442
add1bff13f
core/rawdb: fix freezer validation (#26251)
* core/rawdb: fix freezer validation

* core/rawdb: address comment
2022-11-25 09:10:31 +01:00
Felix Lange
c5dc61c62d cmd/utils: gofmt 2022-11-24 13:03:38 +01:00
6xiaowu9
e76813eb13
signer/core/apitypes: deep convert types in slice (#26203) 2022-11-24 11:45:20 +01:00
Felix Lange
8846c07d04
cmd/utils: print warning when --metrics.port set without --metrics.addr (#26248) 2022-11-24 11:37:58 +01:00
Felix Lange
193f350eb9
core/rawdb: improve freezerTable.Sync (#26245)
While investigating #22374, I noticed that the Sync operation of the
freezer does not take the table lock. It also doesn't call sync for all files
if there is an error with one of them. I doubt this will fix anything, but
didn't want to drop the fix on the floor either.
2022-11-24 10:50:28 +01:00
Marius van der Wijden
ec2ec2d08e
core: implement EIP-3651, warm coinbase (#25819)
Implements EIP-3651, "Warm Coinbase", for Shanghai hardfork. Specification: https://eips.ethereum.org/EIPS/eip-3651.
2022-11-22 22:39:52 +01:00
kumavis
64dccf7aa4
cmd/utils: log path used when checking disk space (#26212)
This change logs the path checked when encountering low disk space.
2022-11-21 10:18:18 +01:00
Martin Holst Swende
6975f09998
eth/catalyst: make tests less time-sensitive (#26201)
This makes a couple of sometimes-failing tests less brittle.
2022-11-21 09:52:12 +01:00
Martin Holst Swende
c2e0abce2e
ethstats: set readlimit on ethstats server connection (#26207)
This prevents DoS when connected to a malicious ethstats server.
2022-11-17 15:33:03 +01:00
Martin Holst Swende
97c563e055
rpc, internal/guide: speed up tests a bit (#26193)
This removes an RPC test which takes > 90s to execute, and updates the
internal/guide tests to use lighter scrypt parameters.

Co-authored-by: Felix Lange <fjl@twurst.com>
2022-11-17 15:30:53 +01:00
therainisme
722bb210bf
rlp: improve tests for Split functions (#26200)
This PR improves and extends the tests a bit
2022-11-17 14:19:03 +01:00
Felix Lange
12df45662a
all: remove remaining uses of untyped golang-lru (#26194) 2022-11-17 11:15:28 +01:00
Felix Lange
c3b42683b3
Dockerfile: upgrade to Go 1.19 (#26195) 2022-11-17 10:54:28 +01:00
Sina Mahmoodi
64067fbdc4
eth/tracers: small refactor for native tracers (#26196)
Use noopTracer as a base for other native tracers to avoid extra boilerplate for unimplemented hooks.
2022-11-17 09:27:48 +01:00
storyicon
add337e0f7
rpc: support injecting HTTP headers through context (#26023)
This adds a way to specify HTTP headers per request.

Co-authored-by: Martin Holst Swende <martin@swende.se>
Co-authored-by: Felix Lange <fjl@twurst.com>
2022-11-16 15:22:12 +01:00
Mark Tyneway
b4ea2bf7dd
all: implement EIP-1153 transient storage (#26003)
Implements TSTORE and TLOAD as specified by the following EIP:

https://eips.ethereum.org/EIPS/eip-1153
https://ethereum-magicians.org/t/eip-1153-transient-storage-opcodes/553


Co-authored-by: Sara Reynolds <snreynolds2506@gmail.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
Co-authored-by: Gary Rong <garyrong0905@gmail.com>
2022-11-16 10:18:52 +01:00
ligi
bc90a88263
ethclient: docs, fix misleading comment (#26189)
closes #26188
2022-11-16 08:44:54 +01:00
Felix Lange
ae42148093
rpc: fix connection tracking set in Server (#26180)
rpc: fix connection tracking in Server

When upgrading to mapset/v2 with generics, the set element type used in
rpc.Server had to be changed to *ServerCodec because ServerCodec is not
'comparable'. While the distinction is technically correct, we know all
possible ServerCodec types, and all of them are comparable. So just use
a map instead.
2022-11-15 14:05:16 +01:00
Felix Lange
9afc6816d2
common/lru: add generic LRU implementation (#26162)
It seems there is no fully typed library implementation of an LRU cache.
So I wrote one. Method names are the same as github.com/hashicorp/golang-lru,
and the new type can be used as a drop-in replacement.

Two reasons to do this:

- It's much easier to understand what a cache is for when the types are right there.
- Performance: the new implementation is slightly faster and performs zero memory
   allocations in Add when the cache is at capacity. Overall, memory usage of the cache
   is much reduced because keys are values are no longer wrapped in interface.
2022-11-14 15:41:56 +01:00
Jolly Zhao
f58ebd9696
all: use github.com/deckarep/golang-set/v2 (generic set) (#26159)
Co-authored-by: Felix Lange <fjl@twurst.com>
2022-11-14 15:16:52 +01:00
Martin Holst Swende
8c5ce1107b
eth/filters: send rpctransactions in pending-subscription (#26126)
This PR changes the pending tx subscription to return RPCTransaction types instead of normal Transaction objects. This will fix the inconsistencies with other tx returning API methods (i.e. getTransactionByHash), and also fill in the sender value for the tx.

co-authored by @s1na
2022-11-14 14:48:01 +01:00
Martin Holst Swende
e34e540e4c
accounts/keystore: replace inotify with fsnotify (#26176) 2022-11-14 12:38:10 +01:00
Martin Holst Swende
8334b5f51a
common/lru: fix race in lru (#26164)
This fixes a problem in the SizeConstrainedLRU. The SCLRU uses an underlying simple lru which is not thread safe.
During the Get operation, the recentness of the accessed item is updated, so it is not a pure read-operation. Therefore, the mutex we need is a full mutex, not RLock.

This PR changes the mutex to be a regular Mutex, instead of RWMutex, so a reviewer can at a glance see that all affected locations are fixed.
2022-11-11 19:48:36 +01:00
Martin Holst Swende
ea65edaa28
eth, catalyst: fix flaky tests (#26153)
* eth/catalyst: fix time-dependent (flaky) test

* eth: increase timeout on TestTransactionPropagation
2022-11-11 13:22:54 +01:00
Felix Lange
c539bda166
metrics: improve reading Go runtime metrics (#25886)
This changes how we read performance metrics from the Go runtime. Instead
of using runtime.ReadMemStats, we now rely on the API provided by package
runtime/metrics.

runtime/metrics provides more accurate information. For example, the new
interface has better reporting of memory use. In my testing, the reported
value of held memory more accurately reflects the usage reported by the OS.

The semantics of metrics system/memory/allocs and system/memory/frees have
changed to report amounts in bytes. ReadMemStats only reported the count of
allocations in number-of-objects. This is imprecise: 'tiny objects' are not
counted because the runtime allocates them in batches; and certain
improvements in allocation behavior, such as struct size optimizations,
will be less visible when the number of allocs doesn't change.

Changing allocation reports to be in bytes makes it appear in graphs that
lots more is being allocated. I don't think that's a problem because this
metric is primarily interesting for geth developers.

The metric system/memory/pauses has been changed to report statistical
values from the histogram provided by the runtime. Its name in influxdb has
changed from geth.system/memory/pauses.meter to
geth.system/memory/pauses.histogram.

We also have a new histogram metric, system/cpu/schedlatency, reporting the
Go scheduler latency.
2022-11-11 13:16:13 +01:00
Felix Lange
62c973eba6
go.mod: minimum Go version 1.18 (#26160)
This will allow use of generics and other new standard library APIs
such as package net/netip.
2022-11-11 13:11:24 +01:00
Felix Lange
5b4c149f97
internal/debug: add --log.file option (#26149)
This adds an option to direct log output to a file. This feature has been
requested a lot. It's sometimes useful to have this available when running
geth in an environment that doesn't easily allow redirecting the output.

Notably, there is no support for log rotation with this change. The --log.file option
opens the file once on startup and then keeps writing to the file handle. 
This can become an issue when external log rotation tools are involved, so it's
best not to use them with this option for now.
2022-11-11 11:33:18 +01:00
protolambda
0ad2014026
go.mod: update status-im/keycard-go (#26141) 2022-11-10 01:32:02 +01:00
Martin Holst Swende
093b2ac32a
eth/filters: fix failing benchmark-test (#26144) 2022-11-09 09:49:42 +01:00
Martin Holst Swende
dffd93b475
cmd/evm: slight change in how t8n handles coinbase pre eip-158 (#26139)
This PR fixes a subtle bug in t8n. After this PR, t8n behaves like our state-test runner in certain pre-EIP-158 scenarios
2022-11-09 09:34:42 +01:00
Martin Holst Swende
5fded04037
core/state: replace fastcache code cache with gc-friendly structure (#26092)
This PR replaces fastcache with a pretty simple LRU which does not require explicit closing.
2022-11-09 08:06:02 +01:00
yihuang
7dc5e785a8
core/vm: deepcopy jumptable when enabling extra eips (#26137)
When the interpreter is configured to use extra-eips, this change makes it so that all the opcodes are deep-copied, to prevent accidental modification of the 'base' jumptable. 

Closes: #26136

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-11-09 07:52:13 +01:00
Joseph Cook
6685f88455
cmd/clef: only print first N accounts on startup (#26128)
PR #26082 added account listing to OnSignerStartup but did not consider the case where a user has a large number of accounts which would be annoying to display.

This PR updates showAccounts() so that if there are more than 20 accounts available the user sees the first 20 displayed in the console followed by: First 20 accounts listed (N more available).

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-11-08 21:17:12 +01:00
Ahmet Avci
ee9ff06469
graphql: add query timeout (#26116)
This PR adds a 60 second timeout to graphql queries.
2022-11-08 13:14:14 +01:00
Felix Lange
913973436b
cmd/devp2p: add more nodekey commands (#26129)
This adds new commands to turn a node key file into signed ENR / node ID.
2022-11-08 12:15:32 +01:00
Mark Tyneway
a609e7b81f
common/types: add Address.Big (#26132)
Many of the other types have a function to convert the type to a big.Int,
but Address was missing this function.

It is useful to be able to turn an Address into a big.Int when doing
EVM-like computations natively in Go. Sometimes a Solidity address
type is casted to a uint256 and having a Big method on the Address
type makes this easy.
2022-11-08 12:14:11 +01:00
zhiqiangxu
4cb1fca43d
p2p/enode: implement per-source timeout in FairMix (#25962)
Co-authored-by: Felix Lange <fjl@twurst.com>
2022-11-08 12:12:36 +01:00
Sina Mahmoodi
53b624b56d
eth/tracers: add multiplexing tracer (#26086)
* eth/tracers: add native multiplexing tracer

* minor improv callTracer

* mv evm cancellation to api
2022-11-08 10:16:52 +01:00
Marcin Sobczak
d629e02047
cmd/devp2p/internal/v4test: ignore FINDNODE in BondThenPingWithWrongFrom (#26085)
This fixes a race in the test.

Co-authored-by: Felix Lange <fjl@twurst.com>
2022-11-07 22:46:21 +01:00
Marius van der Wijden
055528ae05
cmd/devp2p/internal/ethtest: add support for eth/68 (#26078)
Co-authored-by: Felix Lange <fjl@twurst.com>
2022-11-07 20:47:04 +01:00
Felix Lange
9027ee0b45
p2p/discover: improve discv5 NODES response packing (#26033)
Instead of using a limit of three nodes per message, we can pack more nodes
into each message based on ENR size. In my testing, this halves the number
of sent NODES messages, because ENR size is usually < 300 bytes.

This also adds RLP helper functions that compute the encoded size of
[]byte and string.

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-11-07 19:19:02 +01:00
Joseph Cook
55a92fa0a4
cmd/clef: list accounts at startup (#26082)
Reports accounts known to Clef during startup, after master seed is provided by the user.
2022-11-07 16:41:36 +01:00
Martin Holst Swende
ca948b8579
eth/catalyst, miner: deduplicate work + show payload id (#26115)
This PR now also includes a fix to the problem of mult-routines building blocks on the same input. This PR works as before with regards to stopping the work, but it just will not spin up a second routine if one is already building. So if the CL does N calls to FCU+buildblock, and N calls to GetPayload, only the first of each will do something, the other calls will be mostly no-ops.

This PR also adds printout of the payload id into the logs.
2022-11-07 15:30:54 +01:00
Nicolas Gotchac
111ed1af1b
accounts/abi: properly quote untrusted data in error message (#26110)
* abi: Format data as hex-string instead of string(data)

* Update accounts/abi/abi.go

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-11-07 13:58:00 +01:00
Martin Holst Swende
17744639da
cmd/clef: add importraw feature to clef (#26058)
This adds a subcommand that imports a raw secp256k1 key
into the keystore managed by clef.
2022-11-06 13:02:49 +01:00
Saman H. Pasha
33e23ee37d
accounts/abi.bind: don't fetch head in transact unless required (#25988)
If GasFeeCap and GasTipCap are specified, we don't need to retrieve the head block for constructing a transaction
2022-11-04 22:03:34 +01:00
Obtuse7772
6d55908347
signer/core/apitypes: support more input types for eip-712 encoding (#26074)
* apitypes: synchronize handling of types

* signer/core/apitypes: improve array check

* apitypes: add a test for big.Int -> int32

* signer/core/apitypes: Add a test for parsing addresses from [20]byte, []byte and string

* signer/core/apitypes: add some testcases

Co-authored-by: Felix Lange <fjl@twurst.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-11-04 16:28:12 +01:00
protolambda
a51188a163
params: make eip1559 params non-global (#25994)
This PR changes geth to read the eip1559 params from the chain config instead of the globals.

This way the parameters may be changed by forking the chain config code, without creating a large diff throughout the past and future usages of the parameters.

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-11-04 16:27:15 +01:00
rjl493456442
08fb1aade6
miner: display change in fees, change recommit period (#26097)
* miner: add logs for displaying fees change

* miner: simplify feesInEther calculation

* miner: fix lock

* miner: change to default recommit to 2 seconds
2022-11-03 15:18:28 +01:00
jwasinger
9a4e8e222e
crypto/bls12381: docs - fix broken links to references (#26095) 2022-11-03 08:48:13 +01:00
Joseph Cook
f3a005f176
cmd/clef: add list-accounts and list-wallets to CLI (#26080)
This commit adds support for two new commands to clef, making it possible to list accounts / wallets from the command-line-interface. 

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-11-02 19:02:32 +01:00
Jordan Krage
05037eaffc
rpc: handle wrong HTTP batch response length (#26064) 2022-11-02 15:29:33 +01:00
Roberto Bayardo
4a81e5afea
rlp: add more tests for nil pointer / optional field encoding (#26077) 2022-11-02 14:50:48 +01:00
Justin Traglia
621b423ac1
p2p/discover: fix handling of distance 256 in lookupDistances (#26087)
Noticed that lookupDistances for FINDNODE requests didn't consider 256 a valid
distance. This is actually part of the example in the comment above the
function, surprised that wasn't tested before.
2022-11-02 14:50:07 +01:00
Roberto Bayardo
24f08ece62
miner: fail early if core.NewBlockChain fails (#26079)
don't ignore errors returned by core.NewBlockChain when initializing tests
2022-11-02 12:57:09 +01:00
rjl493456442
a2a144c593
miner, eth: implement recommit mechanism for payload building (#25836)
* miner, eth: implement recommit for payload building

* miner: address comments from marius
2022-11-02 10:32:20 +01:00
Sebastian Supreme
2415911f53
docs/postmortems: remove wrong parentheses (#26066)
Removed parentheses in line 71 because line 80 doesn't have them either.
2022-11-01 14:50:03 +01:00
zhiqiangxu
2b65219550
consensus/ethash: fix typo (#26016)
fix typo
2022-11-01 14:39:39 +01:00
zhiqiangxu
8578eb2fe1
accounts/abi: return error on fixed bytes with size larger than 32 bytes (#26075)
* fixed bytes with size larger than 32 bytes is not allowed

* add testcase
2022-11-01 14:28:40 +01:00
Sina Mahmoodi
0c40df5f28
eth/tracers: prestateTracer - exclude unchanged storage slots in diffMode (#25944)
Fixes #25943
2022-11-01 14:25:44 +01:00
Delweng
8e69622c68
eth/tracers: add withLog to callTracer (#25991)
In some cases, it is desirable to capture what is triggered by each trace, when using the `callTracer`. For example: call `USDT.transfer` will trigger a `Transfer(from, to, value)` event.

This PR adds the option to capture logs to the call tracer, by specifying `{"withLog": true}` in the tracerconfig. 
Any logs belonging to failed/reverted call-scopes are removed from the output, to prevent interpretation mistakes.

Signed-off-by: Delweng <delweng@gmail.com>
Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2022-11-01 12:03:26 +01:00
vdwijden
b0d44338bb
eth: implement eth/68 (#25980)
* eth: implement eth/68

* eth/protocols/eth: added tx size to announcement

* eth/protocols/eth: check equal lengths on receiving announcement

* eth/protocols/eth: add +1 to tx size because of the type byte

* eth: happy lint, add eth68 tests, enable eth68

* eth: various nitpick fixes on eth/68

* eth/protocols/eth: fix announced tx size wrt type byte

Co-authored-by: MariusVanDerWijden <m.vanderwijden@live.de>
Co-authored-by: Péter Szilágyi <peterke@gmail.com>
2022-10-31 16:23:26 +02:00
Nicolas Gotchac
5329aa3786
Fix trace call for inner reverts (#25971)
Inner call reverts will now return the reason similar to the top-level call. Separately, if top-level call is of type CREATE and it fails, its `to` field will now be cleared to `0x00...00` instead of being set to the created address.
2022-10-31 12:20:21 +03:30
s7v7nislands
fb4a97f33f
rpc: update docstring (#26072)
Co-authored-by: seven <seven@nodereal.io>
2022-10-31 09:42:25 +01:00
rjl493456442
2c1af8b1ec
cmd, eth: implement full-sync tester (#26035)
This PR adds a parameter to startup, --synctarget. The synctarget flag is a developer-flag, that can be useful in some scenarios as a replacement for a CL node. It defines a fixed block sync target:

geth --syncmode=full --synctarget=./block_15816882.hex_rlp 

The --synctarget is only made available during syncmode=full
2022-10-28 14:48:08 +02:00
Sina Mahmoodi
0f4942214d
eth/tracers: fix gasUsed for native and JS tracers (#26048)
* eth/tracers: fix gasUsed in call tracer

* fix js tracers gasUsed

* fix legacy prestate tracer

* fix restGas in test

* drop intrinsicGas field from js tracers
2022-10-28 12:28:29 +02:00
lightclient
fbdeff99ce
cmd/evm: calc base fee if parent data is present (#26051)
Currently, in order to chain together sequential valid t8n transitions the caller must manually calculate the block base fee. This PR adds support for the necessary parent fee market data to calculate the base fee for the current transition.

Concretely, env is extended to accept the following:

    parentBaseFee
    parentGasUsed
    parentGasLimit

Example usage can be found in ./cmd/evm/testdata/25.

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-10-28 12:25:37 +02:00
rjl493456442
60e30a940b
core/rawdb: refactor db inspector for extending multiple ancient store (#25896)
This PR ports a few changes from PBSS:

- Fix the snapshot generator waiter in case the generation is not even initialized
- Refactor db inspector for ancient store
2022-10-28 10:23:49 +02:00
Martin Holst Swende
a1fc0d8144
eth/filters: change filter block to be by-ref (#26054)
This PR changes the block field in the filter to be a pointer, to disambiguate between empty hash and no hash
2022-10-27 15:25:01 +02:00
Martin Holst Swende
9d795d0836
core/vm: use optimized bigint (#26021) 2022-10-27 10:39:01 +02:00
Jakub Freebit
4984c4e63f
build: make ios work again (#26052) 2022-10-27 11:23:11 +03:00
Guillaume Ballet
0c66d971e7
accounts/scwallet: fix keycard data signing error (#25331)
accounts/scwallet: fix keycard data signing
2022-10-27 10:06:28 +02:00
Péter Szilágyi
7496ad8edc
Merge pull request #26049 from sandakersmann/master
build: upgrade -dlgo version to Go 1.19.2
2022-10-27 11:01:12 +03:00
Marius Kjærstad
1d0c4e27bf
build: upgrade -dlgo version to Go 1.19.2 2022-10-26 14:49:12 +02:00
Péter Szilágyi
c4a662176e
core, eth: for types with accurate size calcs, return uint64, not float (#26046)
* core, eth: for types with accurate size calcs, return uint64, not float

* core/types: proper tx size tests

* core/types: extend tx size test with decoded sizes, fix error

* core/txpool: fix linter

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-10-26 15:23:07 +03:00
Péter Szilágyi
5bed24dd77
Merge pull request #26044 from karalabe/rename-typed-tx-files
core/types: rename tx files to group them better together
2022-10-26 13:51:46 +03:00
Péter Szilágyi
68ba845bb5
core/types: rename tx files to group them better together 2022-10-26 13:30:51 +03:00
Péter Szilágyi
a2b7481b78
Merge pull request #26038 from karalabe/split-txpool
all: refactor txpool into it's own package in prep for 4844
2022-10-24 20:30:33 +03:00
Péter Szilágyi
a6dda03644
all: refactor txpool into it's own package in prep for 4844 2022-10-24 16:35:53 +03:00
Martin Holst Swende
5f70f9fd37
eth/tracers: simplify test framework (#25973)
Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2022-10-21 17:55:15 +02:00
Delweng
a404195c7b
eth/tracers: fix the issue prestate missing existing contract state (#25996)
The prestate tracer did not report accounts that existed at a given address prior to a contract being created at that address.

Signed-off-by: Delweng <delweng@gmail.com>
Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com>
2022-10-21 11:48:53 +02:00
s7v7nislands
9b9a1b677d
internal/ethapi, accounts/abi/backends: use error defined in core (#26012)
Co-authored-by: seven <seven@nodereal.io>
2022-10-20 12:56:12 +02:00
rjl493456442
b9ba6f6e4d
core/rawdb: open meta file in read only mode (#26009) 2022-10-19 21:15:43 +02:00
s7v7nislands
d86fe26f67
core/rawdb: refactor db key prefix (#26000)
Co-authored-by: seven <seven@nodereal.io>
2022-10-19 09:53:09 +02:00
Martin Holst Swende
6069d8294e
cmd/utils: enable snapshot generation in import-mode (#25990)
This PR fixes a regression causing snapshots not to be generated in "geth --import" mode.  It also fixes the geth export command to be truly readonly, and adds a new test for geth export.
2022-10-19 08:20:39 +02:00
Martin Holst Swende
15b7e0b254
common/math, tests/fuzzers: use big.Int clone (#26006)
* common/math, tests/fuzzers: use big.Int clone

* common/math: license
2022-10-18 15:42:16 +02:00
Martin Holst Swende
fb75f11e87
Revert "go.mod: upgrade github.com/dop251/goja" (#25975)
Revert "go.mod: upgrade github.com/dop251/goja (#25955)"

This reverts commit 9207e348f0.
2022-10-12 20:08:36 +02:00
Delweng
c776a98c83
eth/tracers: fix the issue of panic in prestate with diffmode (#25957)
In some cases, inner contract creation may not be successful, and an inner contract was not created. This PR fixes a crash that could occur when doing tracing in such situations.
2022-10-12 12:50:01 +02:00
ucwong
9207e348f0
go.mod: upgrade github.com/dop251/goja (#25955)
This upgrade pulls in a fix to handling of 'continue' in loops.
2022-10-12 12:03:45 +02:00
lmittmann
5b1a04b9c7
eth/filters, ethclient/gethclient: add fullTx option to pending tx filter (#25186)
This PR adds a way to subscribe to the _full_ pending transactions, as opposed to just being notified about hashes. 

In use cases where client subscribes to newPendingTransactions and gets txhashes only to then request the actual transaction, the caller can now shortcut that flow and obtain the transactions directly. 


Co-authored-by: Felix Lange <fjl@twurst.com>
2022-10-12 11:54:52 +02:00
Jens W
010f47f76a
eth/protocols/eth: fix typo in log message (#25969) 2022-10-12 11:15:19 +02:00
Martin Holst Swende
eaf095ccd4
accounts/keystore: faster tests (#25827)
This PR removes some optimistic tests -- a'la "do something,
wait a while, and hope it has trickled through and continue" -- and
instead uses some introspection to ensure that prerequisites are met.
2022-10-12 10:53:01 +02:00
Sina Mahmoodi
3630cafb34
node: drop support for static & trusted node list files (#25610)
This changes the node setup to ignore datadir files

    static-nodes.json
    trusted-nodes.json

When these files are present, it an error will be printed to the log.
2022-10-12 10:50:12 +02:00
Felix Lange
e257b3add7
tests/fuzzers/modexp: gofmt (#25972) 2022-10-12 10:39:21 +02:00
Martin Holst Swende
bed3b10086
common/math: optimized modexp (+ fuzzer) (#25525)
This adds a 
* core/vm, tests: optimized modexp + fuzzer

* common/math: modexp optimizations

* core/vm: special case base 1 in big modexp

* core/vm: disable fastexp
2022-10-12 10:34:52 +02:00
Marius van der Wijden
a007ab786c
core/types: add more context around ErrInvalidChainID (#25367)
This changes the error message for mismatching chain ID to show
the given and expected value. Callers expecting this error must be
changed to use errors.Is.
2022-10-12 10:27:39 +02:00
Martin Holst Swende
28d076d37e
core/rawdb: provide more info on 'gap in the chain' error (#25938) 2022-10-12 09:35:09 +02:00
Paul
1c737e8b6d
cmd/geth, core: fix typo in comment (#25954)
* fix typo on comment

* typo "can't accept"
2022-10-11 09:37:33 +02:00
Martin Holst Swende
5a02b2d6d0
all: fix spelling mistakes (#25961) 2022-10-11 09:37:00 +02:00
jin
7eafbec741
accounts/usbwallet: support Ledger Nano S Plus and FTS (#25933)
* usbwallet support Ledger Nano S Plus

* accounts/usbwallet: add definitions + ref to ledger docs

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-10-11 09:31:32 +02:00
Felix Lange
564751668a
cmd/geth: fix help output issues (#25941)
This update resolves an issue where StringSliceFlag would not be
rendered correctly in help output + mention that -H can be used multiple times

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-10-06 19:59:23 +02:00
Ryan Schneider
df2b3cd2bd
eth/filters: fix for eth_getLogs failing with finalized- and safe tag (#25922)
Prior to this change, f.begin (and possibly end) stay negative, leading to strange results later in the code. With this change, filters using "safe" and "finalized" block produce results consistent w/ the overall behavior of this RPC method.

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-10-06 14:43:55 +02:00
Felix Lange
9cddfe92a3
node: prevent exposing engine API on unauthenticated endpoint (#25939)
* node: prevent exposing engine API on unauthenticated endpoint

* node: improve RPC setup
2022-10-06 14:01:04 +02:00
Martin Holst Swende
067bac3f24
core, ethclient/gethclient: improve flaky tests (#25918)
* ethclient/gethclient: improve time-sensitive flaky test

* eth/catalyst: fix (?) flaky test

* core: stop blockchains in tests after use

* core: fix dangling blockchain instances

* core: rm whitespace

* eth/gasprice, eth/tracers, consensus/clique: stop dangling blockchains in tests

* all: address review concerns

* core: goimports

* eth/catalyst: fix another time-sensitive test

* consensus/clique: add snapshot test run function

* core: rename stop() to stopWithoutSaving()

Co-authored-by: Felix Lange <fjl@twurst.com>
2022-10-06 13:39:20 +02:00
Martin Holst Swende
deead99731
core/bloombits: speed up windows-test (#25844)
core/bloombits: remove micro-sleep
2022-10-06 11:41:07 +02:00
rjl493456442
e50aeac4d0
eth/traces: add state limit (#25812)
This PR introduces a new mechanism in chain tracer for preventing creating too many trace states.

The workflow of chain tracer can be divided into several parts:

- state creator generates trace state in a thread
- state tracer retrieves the trace state and applies the tracing on top in another thread
- state collector gathers all result from state tracer and stream to users

It's basically a producer-consumer model here, while if we imagine that the state producer generates states too fast, then it will lead to accumulate lots of unused states in memory. Even worse, in path-based state scheme it will only keep the latest 128 states in memory, and the newly generated state will invalidate the oldest one by marking it as stale.

The solution for fixing it is to limit the speed of state generation. If there are over 128 states un-consumed in memory, then the creation will be paused until the states are be consumed properly.
2022-10-06 10:48:04 +02:00
Delweng
5d52a35931
eth/tracers: add diffMode to prestateTracer (#25422)
Backwards compatibility warning: The result will from now on omit empty fields instead
of including a zero value (e.g. no more `balance: '0x'`).

The prestateTracer will now take an option `diffMode: bool`. In this mode
the tracer will output the pre state and post data for the modified parts of state.
Read-only accesses will be completely omitted. Creations (be it account or slot)
will be signified by omission in the `pre` list and inclusion in `post`. Whereas
deletion (be it account or slot) will be signified by inclusion in `pre` and omission
in `post` list.

Signed-off-by: Delweng <delweng@gmail.com>
2022-10-05 19:05:43 -05:00
Martin Holst Swende
e14164d516
core: fix linter complaint (#25927) 2022-10-04 18:09:05 +02:00
Péter Szilágyi
4f7a425aa8
Merge pull request #25924 from holiman/comments_fix
all: fix docstrings
2022-10-04 13:30:00 +03:00
Martin Holst Swende
ee301c750b
all: fix docstrings 2022-10-04 09:18:02 +02:00
rjl493456442
1913b50111
eth, miner: add timeout for building sealing block (#25407)
* eth, miner: add timeout for building sealing block

* eth, cmd, miner: add newpayloadtimeout flag

* eth, miner, cmd: address comments

* eth, miner: minor fixes

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-10-03 14:10:00 +02:00
Martin Holst Swende
f61b50b1e8
eth/protocols/snap: serve snap requests when possible (#25644)
This PR makes it so that the snap server responds to trie heal requests when possible, even if the snapshot does not exist. The idea being that it might prolong the lifetime of a state root, so we don't have to pivot quite as often.
2022-10-03 13:37:17 +02:00
zhiqiangxu
a724163e59
core/types: add a testcase to TestLegacyReceiptDecoding (#25909)
add a testcase to TestLegacyReceiptDecoding
2022-10-03 12:56:21 +02:00
Martin Holst Swende
ea26fc8a6c
cmd/geth, cmd/utils: geth attach with custom headers (#25829)
This PR makes it possible to set custom headers, in particular for two scenarios: 

- geth attach
- geth commands which can use --remotedb, e..g geth db inspect

The ability to use custom headers is typically useful for connecting to cloud-apis, e.g. providing an infura- or alchemy key, or for that matter access-keys for environments behind cloudflare.  

Co-authored-by: Felix Lange <fjl@twurst.com>
2022-09-30 13:50:25 +02:00
Martin Holst Swende
07e0704ca9
internal/flags: fix issue with stringslice migration (#25830)
This fixes a cornercase bug where the flag migration would mess
up the value of StringSlice flags.
2022-09-29 20:16:36 +02:00
Mikhail Vazhnov
f651d6d56b
accounts/abi/bind: parse ABI only once on bind (#25574)
* accounts/abi/bind: parse ABI once on bind

* accounts/abi/bind: suppress 'imported and not used' error for abi package
2022-09-29 11:44:22 +02:00
Sina Mahmoodi
ff1f49245d
eth/tracers: remove revertReasonTracer, add revert reason to callTracer (#25508)
* eth/tracers: add revertReason to callTracer

* update callframe gen json

* add revertal to calltrace test
2022-09-29 11:36:07 +02:00
Ceyhun Onur
c2918c2f47
accounts/abi: return toGoType error immediately (#25565) 2022-09-29 10:47:12 +02:00
rjl493456442
052c634917
core: rework tx indexer (#25723)
This PR reworks tx indexer a bit. Compared to the original version, one scenario is no longer handled - upgrading  from legacy geth without indexer support. 

The tx indexer was introduced in 2020 and have been present through hardforks, so it can be assumed that all Geth nodes have tx indexer already. So we can simplify the tx indexer logic a bit:

-    If the tail flag is not present, it means node is just initialized may or may not with an ancient store attached. In this case all blocks are regarded as unindexed
-   If the tail flag is present, it means blocks below tail are unindexed, blocks above tail are indexed

This change also address some weird cornercases that could make the indexer not work after a crash.
2022-09-29 09:50:24 +02:00
TY
88132afc3f
internal/ethapi: handle odd length hex in decodeHash (#25883)
This change adds zero-padding (prefix) of odd nibbles in the decodeHash function. 

Co-authored-by: ty <ty@oncoder.com>
2022-09-28 18:55:44 +02:00
Delweng
85aafcfb2b
eth/tracers: fix a bug in prestateTracer (#25884) 2022-09-28 17:52:39 +02:00
lmittmann
2b1299b1c0
core/vm: minor trivial clean up (#25880)
* dropped `vm.keccakState` for `crypto.KeccakState`

* cleaned up `OpCode.IsPush()`
2022-09-28 13:21:54 +02:00
Alexey Shekhirin
53d68feea8
tests: report mgas/s metric in evm benchmarks (#25700)
* test(state): report mgas/s metric in EVM benchmark

* revert testdata submodule update

* aggregate mgas/s results

* calculate elapsed time better

* tests: benchmarks - handle access list + take refund into account

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-09-28 10:39:20 +02:00
lightclient
1743e61130
accounts/abi/bind/backends: fix AdjustTime to respect Fork (#25225) 2022-09-28 09:55:07 +02:00
Martin Holst Swende
456b187892
trie, eth/protocols/snap: less tiny db-writes during trie-healing (#25681)
This PR prevent making tiny writes during state healing, by only performing the batch-write if the accumulated data is large enough to be meaningful.
2022-09-28 08:08:18 +02:00
Janko Simonovic
1a63a76fcc
ethclient/gethclient: fix bugs in override object encoding (#25616)
This fixes a bug where contract code would be overridden to empty code ("0x")
when the Code field of OverrideAccount was left nil. The change also cleans up
the encoding of overrides to only send necessary fields, and improves documentation.

Fixes #25615

Co-authored-by: Felix Lange <fjl@twurst.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-09-27 19:23:53 +02:00
Martin Holst Swende
80cc34ac3c
eth/downloader: make flakey test less flakey (#25879) 2022-09-27 15:49:52 +02:00
zhiqiangxu
13e6985929
eth: return state error via GetEVM (#25876)
* make vmError more useful

* fix for review

* Update api.go

* revert calling site

Co-authored-by: rjl493456442 <garyrong0905@gmail.com>
2022-09-27 13:16:54 +02:00
rjl493456442
bff84a99fe
cmd, core, eth, les, light: track deleted nodes (#25757)
* cmd, core, eth, les, light: track deleted nodes

* trie: add docs

* trie: address comments

* cmd, core, eth, les, light, trie: trie id

* trie: add tests

* trie, core: updates

* trie: fix imports

* trie: add utility print-method for nodeset

* trie: import err

* trie: fix go vet warnings

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-09-27 10:01:02 +02:00
Sina Mahmoodi
fc3e6d0162
eth/tracers: use gencodec for native tracers (#25637)
The call tracer and prestate tracer store data JSON-encoded in memory. In order to support alternative encodings (specifically RLP), it's better to keep data a native format during tracing. This PR does marshalling at the end, using gencodec.

OBS! 
This PR changes the call tracer result slightly:

-  Order of type and value fields are changed (should not matter). 
-  Output fields are completely omitted when they're empty (no more output: "0x"). Previously, this was only _sometimes_ omitted (e.g. when call ended in a non-revert error) and otherwise 0x when the output was actually empty.
2022-09-26 18:35:44 +02:00
meowsbits
3ec6fe6101
tests: fix state test error checking (#25702)
Some tests define an 'expectException' error but the tests runner does not check for conditions where this test value is filled (error expected) but in which no error is returned by the test runner.

An example of this scenario is GeneralStateTests/stTransactionTest/HighGasPrice.json, which expects a 'TR_NoFunds' error, but the test runner does not return any error.

Signed-off-by: meows <b5c6@protonmail.com>
2022-09-26 16:00:56 +02:00
jwasinger
7227c9ef07
cmd/geth: make dumpgenesis load genesis datadir if it exists (#25135)
`geth dumpgenesis` currently does not respect the content of the data directory. Instead, it outputs the genesis block created by command-line flags. This PR fixes it to read the genesis from the database, if the database already exists.


Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-09-26 13:55:18 +02:00
Leon
c55c56cf0a
core/vm: better handle error on eip activation check (#25131)
* core/vm: correct logic for eip check of NewEVMInterpreter

* refactor
2022-09-26 13:20:38 +02:00
zhiqiangxu
b32d20324e
eth/downloader, les/downloader: fix subtle flaw in queue delivery (#25861)
* fix queue.deliver

* les/downloader: fix queue.deliver

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-09-26 12:33:21 +02:00
Martin Holst Swende
e004e7d256
core: fix datarace in txpool, fixes #25870 and #25869 (#25872)
core: fix datarace in txpool pendingnoce, fixes #25870
2022-09-26 11:34:15 +02:00
omahs
a3c6d1d9b6
cmd/faucet: fix readme typos (#25867)
* Fix: typos

Fix: typos

* Undo change

Undo change
2022-09-26 11:30:50 +02:00
Sina Mahmoodi
4dc212d4f1
eth/tracers: pad memory slice on OOB case (#25213)
* eth/tracers: pad memory slice on oob case

* eth/tracers/js: fix testfailure due to err msg capitalization

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-09-26 09:56:45 +02:00
zhiqiangxu
367e60549a
core/types: improve accuracy of header.Size() (#25859)
The header.Size() method did not take the basefee into account.
2022-09-26 09:10:39 +02:00
Zachinquarantine
15b4a4bf2e
cmd/puppeth, cmd/utils: finalize removal of gasTarget flag (#24370)
This PR fully removes the --miner.gastarget flag, as previously it was only hidden from the geth --help command, but could still be used.
2022-09-23 22:32:10 +02:00
rjl493456442
3da42f85d9
all: clean up the configs for pruner and snapshotter (#22396)
This PR cleans up the configurations for pruner and snapshotter by passing a config struct.

And also, this PR disables the snapshot background generation if the chain is opened in "read-only" mode. The read-only mode is necessary in some cases. For example, we have a list of commands to open the etheruem node in "read-only" mode, like export-chain. In these cases, the snapshot background generation is non expected and should be banned explicitly.
2022-09-23 20:20:36 +02:00
Zachinquarantine
9b35f3f5b1
tests, les, eth: remove mentions of deprecated Morden testnet (#23570)
* remove morden

* Update commons.go

* Update handler.go

* empty commit to make appveyor happy
2022-09-23 19:33:15 +02:00
Sebastian Stammler
e87806727d
cmd/abigen: change --exc to exclude by type name (#22620)
The abigen exclusion pattern, previously on the form "path:type", now supports wildcards. Examples "*:type" to exclude a named type in all files, or "/path/to/foo.sol:*" all types in foo.sol.
2022-09-23 19:04:02 +02:00
Felix Lange
65f3c1b46f
internal/version: use gitCommit injection in version handling code (#25851)
This changes the CI build to store the git commit and date into package
internal/version instead of package main. Doing this essentially merges our
two ways of tracking the go-ethereum version into a single place, achieving
two objectives:

- Bad block reports, which use version.Info(), will now have the git commit
  information even when geth is built in an environment such as
  launchpad.net where git access is unavailable.

- For geth builds created by `go build ./cmd/geth` (i.e. not using `go run
  build/ci.go install`), git information stored by the go tool is now used
  in the p2p node name as well as in `geth version` and `geth
  version-check`.
2022-09-23 14:08:25 +02:00
Boqin@MetaSecureLabs
e6d4aedb8c
p2p: add channel buffers to avoid goroutine leaks in tests (#24929) 2022-09-23 10:51:12 +02:00
Sina Mahmoodi
220bdd3277
.github: add CL client to issue template (#25814) 2022-09-23 10:25:16 +02:00
Martin Holst Swende
fb500d12d5
eth/protocols/snap: make log messages more clear that sync is ongoing (#25837)
* eth/protocols/snap: make log messages more clear that sync is ongoing

* Update sync.go

Co-authored-by: Felix Lange <fjl@twurst.com>
2022-09-23 11:11:41 +03:00
Delweng
6215b92523
cmd/utils: make --authrpc.jwtsecret a DirectoryFlag (#25849)
Signed-off-by: Delweng <delweng@gmail.com>
2022-09-22 15:43:47 +02:00
Martin Holst Swende
400ab0d94f
eth/catalyst: make tests run faster (#25818) 2022-09-21 15:12:45 +02:00
Martin Holst Swende
6eb8f3225e
eth/catalyst: add locking around newpayload (#25816)
Sometimes we get stuck on db compaction, and the CL re-issues the "same" command to us multiple times. Each request get stuck on the same place, in the middle of the handler.

This changes makes it so we do not reprocess the same payload, but instead detects it early.
2022-09-21 13:48:09 +02:00
makcandrov
5d11d38f4d
eth/tracers: fix trace config for TraceCall (#25821)
Co-authored-by:  AtomicAzzaz  <AtomicAzzaz@users.noreply.github.com>
Co-authored-by:  ewile <ewile@users.noreply.github.com>
2022-09-21 09:55:48 +02:00
lightclient
338bb2e36c
core/blockchain: downgrade tx indexing and unindexing logs (#25832)
core/blockchain: downgrade tx indexing and unindexing logs from info to debug

If a user has a finite tx lookup limit, they will see an "unindexing" info level log each time a block is imported. This information might help a user understand that they are removing the index each block and some txs may not be retrievable by hash, but overall it is generally more of a nuisance than a benefit. This change downgrades the log to a debug log.
2022-09-21 09:49:17 +02:00
jwasinger
d8ada03eac
core/vm: return copy of input slice in identity precompile, avoid returndata copy (#25183)
* core/vm: return copy of input slice in identity precompile.  don't deep copy return data slice upon call completion

* make use of common.CopyBytes
2022-09-20 14:58:03 +02:00
Péter Szilágyi
18a001fa3e
Merge pull request #25831 from karalabe/fix-challenge-stop-hang
eth: fix a rare datarace on CHT challenge reply / shutdown
2022-09-20 15:30:15 +03:00
Péter Szilágyi
d728ba97d8
eth: fix a rare datarace on CHT challenge reply / shutdown 2022-09-20 14:14:24 +03:00
Felix Lange
468d1844c7
core: move build version reading to its own package (#25806)
This fixes the build with Go 1.17, which does not have BuildInfo.Settings yet.
2022-09-19 10:04:16 +02:00
lightclient
8e5201551d
core: more compact bad block report (#25714)
This shortens the chain config summary in bad block reports,
and adds go-ethereum version information as well.

Co-authored-by: Felix Lange <fjl@twurst.com>
2022-09-17 21:27:10 +02:00
Seungbae Yu
ada603fab5
core: don't cache zero nonce in txNoncer (#25603)
This changes the nonce cache used by TxPool to not store cached
nonces for non-existing accounts.
2022-09-16 18:23:13 +02:00
lightclient
8ade5e6c14
internal/ethapi: return error when requesting invalid trie key (#25762)
This change makes eth_getProof and eth_getStorageAt return an error when
the argument contains invalid hex in storage keys.

Co-authored-by: Felix Lange <fjl@twurst.com>
2022-09-16 18:16:32 +02:00
George Carder
d213cb0924
crypto/bls12381: docfix of g1 Affine (#25729)
bls12381: docfix of g1 Affine.
2022-09-16 11:40:42 +02:00
ucwong
83989a19be
core/rawdb: fix leak of backoff timer (#25776) 2022-09-16 11:33:48 +02:00
Amir Hossein
57a65f00c9
trie: handle more batch commit errors in Database (#25674) 2022-09-15 23:35:53 +02:00
Marius van der Wijden
a89b7addd4
params: set TerminalTotalDifficultyPassed to true (#25769)
* params: set TerminalTotalDifficultyPassed to true

* Update params/config.go

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-09-15 18:50:54 +03:00
pinkiebell
1d2f5cf610
les/catalyst/api: add support for ExchangeTransitionConfigurationV1 (#25752)
This method is missing in light client mode and breaks consensus clients
that require a valid response.
2022-09-15 15:36:31 +02:00
Felix Lange
3db4a13230
node: fix lint issue in rpcstack.go (#25774) 2022-09-15 15:21:44 +02:00
Felix Lange
0ee8b273f2
core: fix log order in "Imported new chain segment" (#25768) 2022-09-15 13:18:23 +02:00
Nicolas Gotchac
25b35c9728
node: fix HTTP server always force closing (#25755)
Co-authored-by: Felix Lange <fjl@twurst.com>
2022-09-14 18:37:53 +02:00
Guillaume Ballet
9d717167aa
cmd/geth: add a verkle subcommand (#25718)
* cmd/geth: add a verkle subcommand

* fix copyright year

* remove unused command parameters

* check that the output file was successfully written to

Co-authored-by: Martin Holst Swende <martin@swende.se>

* cmd/geth: goimports fix

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-09-14 12:05:03 +02:00
Sina Mahmoodi
818ff32ff5
graphql: fixes missing tx logs (#25745)
* graphql: fix tx logs

* graphql: refactor test service setup

* graphql: add test for tx logs
2022-09-13 22:49:52 +03:00
Benjamin Prosnitz
9a3bd114e7
accounts/abi: fix typo in error message (#25742) 2022-09-13 14:02:34 +02:00
Seungbae Yu
3a4cef5402
core: preallocate maps in TxPool helper methods (#25737) 2022-09-12 15:02:41 +02:00
Seungbae Yu
0c1888a367
p2p/discover/v5wire: reject packets smaller than 63 bytes (#25740) 2022-09-12 15:02:03 +02:00
Felix Lange
b628d72766
build: upgrade to go 1.19 (#25726)
This changes the CI / release builds to use the latest Go version. It also
upgrades golangci-lint to a newer version compatible with Go 1.19.

In Go 1.19, godoc has gained official support for links and lists. The
syntax for code blocks in doc comments has changed and now requires a
leading tab character. gofmt adapts comments to the new syntax
automatically, so there are a lot of comment re-formatting changes in this
PR. We need to apply the new format in order to pass the CI lint stage with
Go 1.19.

With the linter upgrade, I have decided to disable 'gosec' - it produces
too many false-positive warnings. The 'deadcode' and 'varcheck' linters
have also been removed because golangci-lint warns about them being
unmaintained. 'unused' provides similar coverage and we already have it
enabled, so we don't lose much with this change.
2022-09-10 13:25:40 +02:00
Martin Holst Swende
389021a5af
core: place a cap on reorglogs (#25711)
This PR makes the event-sending for deleted and new logs happen in batches, to prevent OOM situation due to large reorgs. 

Co-authored-by: Felix Lange <fjl@twurst.com>
2022-09-09 15:25:55 +02:00
Nicholas
610cf02c4a
rpc: improve error codes for internal server errors (#25678)
This changes the error code returned by the RPC server in certain situations:

- handler panic: code -32603
- result marshaling error: code -32603
- attempt to subscribe via HTTP: code -32001

In all of the above cases, the server previously returned the default error
code -32000.

Co-authored-by: Nicholas Zhao <nicholas.zhao@gmail.com>
Co-authored-by: Felix Lange <fjl@twurst.com>
2022-09-09 14:03:23 +02:00
Martin Holst Swende
06151eb581
p2p/msgrate: be more lenient when calculating 'mean' (#25653)
The p2p msgrate tracker is a thing which tries to estimate some mean round-trip times. However, it did so in a very curious way: if a node had 200 peers, it would sort their 200 respective rtt estimates, and then it would pick item number 2 as the mean. So effectively taking third fastest and calling it mean. This probably works "ok" when the number of peers are low (there are other factors too, such as ttlScaling which takes some of the edge off this) -- however when the number of peers is high, it becomes very skewed.

This PR instead bases the 'mean' on the square root of the length of the list. Still pretty harsh, but a bit more lenient.
2022-09-09 10:47:30 +02:00
Péter Szilágyi
de8d5fa042
eth/protocols/snap: throttle trie heal requests when peers DoS us (#25666)
* eth/protocols/snap: throttle trie heal requests when peers DoS us

* eth/protocols/snap: lower heal throttle log to debug

Co-authored-by: Martin Holst Swende <martin@swende.se>

* eth/protocols/snap: fix comment

Co-authored-by: Martin Holst Swende <martin@swende.se>
2022-09-09 11:42:57 +03:00
Darioush Jalali
8363f79f8f
trie: update comments + err check for preimages (#25672)
This PR includes minor updates to comments in trie/committer that reference insertion to the db, and adds an err != nil check for the return value of preimages.commit.
2022-09-08 12:36:07 +02:00
rjl493456442
6a575eda6f
eth/tracer: fix broken test (#25715) 2022-09-08 08:06:06 +02:00
rjl493456442
b1f6dccfba
eth, les: rework chain tracer (#25143)
This PR simplifies the logic of chain tracer and also adds the unit tests.

The most important change has been made in this PR is the state management. Whenever a tracing state is acquired there is a corresponding release function be returned as well. It must be called once the state is used up, otherwise resource leaking can happen.

And also the logic of state management has been simplified a lot. Specifically, the state provider(eth backend, les backend) should ensure the state is available and referenced. State customers can use the state according to their own needs, or build other states based on the given state. But once the release function is called, there is no guarantee of the availability of the state.


Co-authored-by: Sina Mahmoodi <1591639+s1na@users.noreply.github.com>
Co-authored-by: Péter Szilágyi <peterke@gmail.com>
2022-09-07 20:25:58 +02:00
rjl493456442
dea1fb3cfc
all: cleanup tests (#25641)
Follow-up to PR #25523 to cleanup all relevant tests.
2022-09-07 20:21:59 +02:00
Marius van der Wijden
d30e39b2f8
core/vm: rename RANDOM to PREVRANDAO (#25691)
See: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4399.md

>  This EIP supplants the semantics of the return value of existing DIFFICULTY (0x44) opcode and renames the opcode to PREVRANDAO (0x44).
2022-09-07 13:09:52 +02:00
rjl493456442
a32a02f237
params: update chts (#25707) 2022-09-07 11:48:34 +02:00
rjl493456442
5ddedd2f83
core, light, trie: remove DiskDB function from trie database (#25690) 2022-09-07 09:08:56 +02:00
Péter Szilágyi
d408cb6fba
Merge pull request #25694 from karalabe/concurrent-heal-check
trie: check childrens' existence concurrently for snap heal
2022-09-06 15:49:13 +03:00
Péter Szilágyi
a9ec2ab2e6
trie: check childrens' existence concurrently for snap heal 2022-09-06 12:57:03 +03:00
Felix Lange
731885809c
eth/tracers/js: improve integer types in log object (#25668)
All fields related to gas must be represented as uint64. Depth is
internally tracked as int, so it makes sense to also store it as int.
2022-09-05 14:06:16 +02:00
Amir Hossein
4b9c307d26
trie: fix unhandled error in test (#25628) 2022-09-02 18:07:55 +02:00
Seungbae Yu
0d68b6bf10
trie: fix typo in comment (#25667) 2022-09-02 17:48:26 +02:00
Seungbae Yu
38e002f464
rpc: check that "version" is "2.0" in request objects (#25570)
The JSON-RPC spec requires the "version" field to be exactly "2.0",
so we should verify that. This change is not backwards-compatible with
sloppy client implementations, but I decided to go ahead with it anyway
because the failure will be caught via the returned error.
2022-09-02 17:47:29 +02:00
protolambda
90711efb0a
node, rpc: add JWT auth support in client (#24911)
This adds a generic mechanism for 'dial options' in the RPC client,
and also implements a specific dial option for the JWT authentication
mechanism used by the engine API. Some real tests for the server-side
authentication handling are also added.

Co-authored-by: Joshua Gutow <jgutow@optimism.io>
Co-authored-by: Felix Lange <fjl@twurst.com>
2022-09-02 17:40:41 +02:00
Martin Holst Swende
7f2890a9be
eth/fetcher: throttle peers which deliver many invalid transactions (#25573)
Co-authored-by: Felix Lange <fjl@twurst.com>
2022-09-02 17:28:33 +02:00
Sina Mahmoodi
d6a12bc7b8
eth/tracers/js: fill in log.refund field (#25661)
For some reason, an accessor method for this field exists in JS, but
the value was never actually assigned.
2022-09-02 17:08:25 +02:00
xternet
198fa956f4
README.md: improve grammar (#25646)
Co-authored-by: Felix Lange <fjl@twurst.com>
2022-09-02 16:58:20 +02:00
Jakub Freebit
d2027accdc
mobile: register filter APIs (#25642)
This fixes a regression introduced in PR #25459.
2022-09-02 16:53:58 +02:00
Péter Szilágyi
511bf8f188
Merge pull request #25651 from holiman/fix_snapqueue
eth/protocols/snap: fix problems due to idle-but-busy peers
2022-09-01 12:38:34 +03:00
rjl493456442
d46184c969
core/state: filter out nil trie for copy (#25575) 2022-09-01 09:34:32 +02:00
Martin Holst Swende
d79bd2f0f6
trie: better error reporting (#25645) 2022-09-01 08:41:10 +02:00
Marius van der Wijden
95a2c221d4
eth/catalyst: prevent division by zero (#25654)
eth/catalyst: prevent diff by zero
2022-08-31 21:29:39 +03:00
rjl493456442
3f79afb599
trie: cleanup stateTrie (#25640)
It's a trivial PR to hide the error log when the trie node is not found in the database. The idea for this change is for all TryXXX functions, the error is already returned and we don't need to fire a log explicitly.

Recently there are a few tickets #25613 #25589 reporting that the trie nodes are missing because of debug.SetHead. The root cause is after resetting, the chain rewinds to a historical point and re-imports the blocks on top.

Since the node is already synced and started to accept transactions previously, these transactions are still kept in the txpool and verified by txpool with a live state. This live state is constructed based on the live trie database, which is changed fast by node referencing and de-referencing.

Unfortunately, when we construct a live state(like the state in txpool), we don't reference the state we have. The blockchain will garbage collect the intermediate version nodes in another thread which leads the broken live state.

The best solution for this is to forcibly obtain a reference for all live states we create and call release function once it's used up. But it might end up with more junks persisted into disk. Will try to find an elegant solution later in the following PR.
2022-08-31 18:18:18 +02:00
Martin Holst Swende
dafa40e7a7
eth/protocols/snap: fix problems due to idle-but-busy peers 2022-08-31 17:58:18 +02:00
aaronbuchwald
3d68bb03c3
trie: fix grammar in comment (#25648) 2022-08-31 16:26:39 +02:00
Sina Mahmoodi
8cfcb41e57
graphql: return correct logs for tx (#25612)
* graphql: fix tx logs

* minor

* Use optimized search for selecting tx logs
2022-08-31 16:14:53 +02:00
Jakub Freebit
279afd7947
mobile: close node on error (#25643) 2022-08-31 13:31:16 +03:00
Martin Holst Swende
362256ebff
eth/catalyst: adjust eta for themerge (#25601)
* eth/catalyst: adjust eta for themerge

* squash

* squash

* eth/catalyst: address review concerns
2022-08-31 13:28:35 +03:00
rjl493456442
d10c280309
all: move genesis initialization to blockchain (#25523)
* all: move genesis initialization to blockchain

* core: add one more check

* core: fix tests
2022-08-30 18:22:28 +02:00
Felix Lange
2b6df280de
node: fix regression in TestJWT (#25635) 2022-08-30 16:41:09 +02:00
Seungbae Yu
7813b675f5
node: change JWT error status to 401 Unauthorized (#25629) 2022-08-30 15:25:02 +02:00
Rachel Bousfield
8df8eb4e7a
ethclient: add 'finalized' and 'safe' block number support (#25580) 2022-08-30 14:56:39 +02:00
Marius Kjærstad
44b36a0cdd
docs: specify execution client (#25566)
Co-authored-by: Felix Lange <fjl@twurst.com>
2022-08-30 14:48:04 +02:00
uji
6d882a51e0
build: fix ignored errors (#25591) 2022-08-30 14:40:15 +02:00
Sina Mahmoodi
6e6b5087f1
cmd/geth: fix legacy receipt detection for empty db (#25609) 2022-08-30 14:38:35 +02:00
Abirdcfly
c394c308e6
all: remove duplicate word in comments (#25618)
Signed-off-by: Abirdcfly <fp544037857@gmail.com>

Signed-off-by: Abirdcfly <fp544037857@gmail.com>
2022-08-29 11:16:34 +03:00
xinbenlv
f03c37b73e
accounts/abi/bind: add const for tx fee elasticity multiplier (#25504)
Co-authored-by: Felix Lange <fjl@twurst.com>
Co-authored-by: rjl493456442 <garyrong0905@gmail.com>
2022-08-25 10:59:50 +02:00
lightclient
70e1e65b1d
internal/ethapi: rename debug getters to match spec (#25176)
Some small fixes to get the existing debug methods to conform to the spec. Mainly dropping the encoding information from the method name as it should be deduced from the debug context and allowing the method to be invoked by either block number or block hash. It also adds the method debug_getTransaction which returns the raw tx bytes by tx hash. This is pretty much equivalent to the eth_getRawTransactionByHash method.
2022-08-25 10:41:37 +02:00
Felix Lange
6c40aed146 params: begin go-ethereum v1.11 release cycle 2022-08-25 10:37:04 +02:00
Péter Szilágyi
57896d6fbe
params: begin v1.10.24 release cycle 2022-08-24 12:11:17 +03:00
996 changed files with 63437 additions and 23173 deletions

4
.github/CODEOWNERS vendored
View File

@ -5,16 +5,14 @@ accounts/usbwallet @karalabe
accounts/scwallet @gballet accounts/scwallet @gballet
accounts/abi @gballet @MariusVanDerWijden accounts/abi @gballet @MariusVanDerWijden
cmd/clef @holiman cmd/clef @holiman
cmd/puppeth @karalabe
consensus @karalabe consensus @karalabe
core/ @karalabe @holiman @rjl493456442 core/ @karalabe @holiman @rjl493456442
eth/ @karalabe @holiman @rjl493456442 eth/ @karalabe @holiman @rjl493456442
eth/catalyst/ @gballet eth/catalyst/ @gballet
eth/tracers/ @s1na eth/tracers/ @s1na
graphql/ @gballet @s1na graphql/ @s1na
les/ @zsfelfoldi @rjl493456442 les/ @zsfelfoldi @rjl493456442
light/ @zsfelfoldi @rjl493456442 light/ @zsfelfoldi @rjl493456442
mobile/ @karalabe @ligi
node/ @fjl node/ @fjl
p2p/ @fjl @zsfelfoldi p2p/ @fjl @zsfelfoldi
rpc/ @fjl @holiman rpc/ @fjl @holiman

View File

@ -35,6 +35,6 @@ and help.
## Configuration, dependencies, and tests ## Configuration, dependencies, and tests
Please see the [Developers' Guide](https://geth.ethereum.org/docs/developers/devguide) Please see the [Developers' Guide](https://geth.ethereum.org/docs/developers/geth-developer/dev-guide)
for more details on configuring your environment, managing project dependencies for more details on configuring your environment, managing project dependencies
and testing procedures. and testing procedures.

View File

@ -9,6 +9,7 @@ assignees: ''
#### System information #### System information
Geth version: `geth version` Geth version: `geth version`
CL client & version: e.g. lighthouse/nimbus/prysm@v1.0.0
OS & Version: Windows/Linux/OSX OS & Version: Windows/Linux/OSX
Commit hash : (if `develop`) Commit hash : (if `develop`)

15
.github/workflows/checks.yml vendored Normal file
View File

@ -0,0 +1,15 @@
name: checks
on: [pull_request]
jobs:
linter-check:
runs-on: ubuntu-latest
steps:
- uses: actions/setup-go@v3
with:
go-version: "1.19"
check-latest: true
- uses: actions/checkout@v2
- name: Run linter
run: go run build/ci.go lint

View File

@ -0,0 +1,21 @@
name: MANUAL Override Publish geth binary to release
on:
workflow_dispatch:
inputs:
giteaPublishTag:
description: 'Package to publish TO on gitea; e.g. v1.10.25-statediff-4.2.1-alpha'
required: true
cercContainerTag:
description: 'Tagged Container to extract geth binary FROM'
required: true
jobs:
build:
name: Manual override publish of geth binary FROM tagged release TO TAGGED package on git.vdb.to
runs-on: ubuntu-latest
steps:
- name: Copy ethereum binary file
run: docker run --rm --entrypoint cat git.vdb.to/cerc-io/go-ethereum/go-ethereum:${{ github.event.inputs.cercContainerTag }} /usr/local/bin/geth > geth-linux-amd64
- name: curl
uses: enflo/curl-action@master
with:
curl: --user cerccicd:${{ secrets.GITEA_TOKEN }} --upload-file geth-linux-amd64 https://git.vdb.to/api/packages/cerc-io/generic/go-ethereum/${{ github.event.inputs.giteaPublishTag }}/geth-linux-amd64

21
.github/workflows/manual_publish.yaml vendored Normal file
View File

@ -0,0 +1,21 @@
name: MANUAL Override Publish geth binary to release
on:
workflow_dispatch:
inputs:
giteaPublishTag:
description: 'Package to publish TO on gitea; e.g. v1.10.25-statediff-4.2.1-alpha'
required: true
cercContainerTag:
description: 'Tagged Container to extract geth binary FROM'
required: true
jobs:
build:
name: Manual override publish of geth binary FROM tagged release TO TAGGED package on git.vdb.to
runs-on: ubuntu-latest
steps:
- name: Copy ethereum binary file
run: docker run --rm --entrypoint cat git.vdb.to/cerc-io/go-ethereum/go-ethereum:${{ github.event.inputs.cercContainerTag }} /usr/local/bin/geth > geth-linux-amd64
- name: curl
uses: enflo/curl-action@master
with:
curl: --user circcicd:${{ secrets.GITEA_TOKEN }} --upload-file geth-linux-amd64 https://git.vdb.to/api/packages/cerc-io/generic/go-ethereum/${{ github.event.inputs.giteaPublishTag }}/geth-linux-amd64

7
.github/workflows/on-pr.yml vendored Normal file
View File

@ -0,0 +1,7 @@
name: Build and test
on: [pull_request]
jobs:
run-tests:
uses: ./.github/workflows/tests.yml

36
.github/workflows/publish.yaml vendored Normal file
View File

@ -0,0 +1,36 @@
name: Publish geth to release
on:
release:
types: [published]
jobs:
run-tests:
uses: ./.github/workflows/tests.yml
build:
name: Run docker build and publish
needs: run-tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run docker build
run: docker build -t cerc-io/go-ethereum -f Dockerfile .
- name: Get the version
id: vars
run: |
echo ::set-output name=sha::$(echo ${GITHUB_SHA:0:7})
echo ::set-output name=tag::$(echo ${GITHUB_REF#refs/tags/})
- name: Tag docker image
run: docker tag cerc-io/go-ethereum git.vdb.to/cerc-io/go-ethereum/go-ethereum:${{steps.vars.outputs.sha}}
- name: Tag docker image
run: docker tag git.vdb.to/cerc-io/go-ethereum/go-ethereum:${{steps.vars.outputs.sha}} git.vdb.to/cerc-io/go-ethereum/go-ethereum:${{steps.vars.outputs.tag}}
- name: Docker Login
run: echo ${{ secrets.GITEA_PUBLISH_TOKEN }} | docker login https://git.vdb.to -u cerccicd --password-stdin
- name: Docker Push
run: docker push git.vdb.to/cerc-io/go-ethereum/go-ethereum:${{steps.vars.outputs.sha}}
- name: Docker Push TAGGED
run: docker push git.vdb.to/cerc-io/go-ethereum/go-ethereum:${{steps.vars.outputs.tag}}
- name: Copy ethereum binary file
run: docker run --rm --entrypoint cat git.vdb.to/cerc-io/go-ethereum/go-ethereum:${{steps.vars.outputs.sha}} /usr/local/bin/geth > geth-linux-amd64
- name: curl
uses: enflo/curl-action@master
with:
curl: --user cerccicd:${{ secrets.GITEA_PUBLISH_TOKEN }} --upload-file geth-linux-amd64 https://git.vdb.to/api/packages/cerc-io/generic/go-ethereum/${{steps.vars.outputs.tag}}/geth-linux-amd64

150
.github/workflows/tests.yml vendored Normal file
View File

@ -0,0 +1,150 @@
name: Tests for Geth that are used in multiple jobs.
on:
workflow_call:
env:
stack-orchestrator-ref: ${{ github.event.inputs.stack-orchestrator-ref || 'e62830c982d4dfc5f3c1c2b12c1754a7e9b538f1'}}
ipld-eth-db-ref: ${{ github.event.inputs.ipld-eth-db-ref || '1b922dbff350bfe2a9aec5fe82079e9d855ea7ed' }}
GOPATH: /tmp/go
jobs:
build:
name: Run docker build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run docker build
run: docker build -t cerc-io/go-ethereum .
geth-unit-test:
name: Run geth unit test
runs-on: ubuntu-latest
env:
GO111MODULE: on
steps:
- name: Create GOPATH
run: mkdir -p /tmp/go
- uses: actions/setup-go@v3
with:
go-version: "1.19"
check-latest: true
- name: Checkout code
uses: actions/checkout@v2
- name: Run unit tests
run: |
make test
statediff-unit-test:
name: Run state diff unit test
runs-on: ubuntu-latest
steps:
- name: Create GOPATH
run: mkdir -p /tmp/go
- uses: actions/setup-go@v3
with:
go-version: "1.19"
check-latest: true
- name: Checkout code
uses: actions/checkout@v2
- uses: actions/checkout@v3
with:
ref: ${{ env.ipld-eth-db-ref }}
repository: cerc-io/ipld-eth-db
path: "./ipld-eth-db/"
fetch-depth: 0
- name: Build ipld-eth-db
run: |
docker build -f ./ipld-eth-db/Dockerfile ./ipld-eth-db/ -t cerc/ipld-eth-db:local
- name: Run docker compose
run: |
docker-compose up -d
- name: Give the migration a few seconds
run: sleep 30;
- name: Run unit tests
run: make statedifftest
private-network-test:
name: Start Geth in a private network.
runs-on: ubuntu-latest
steps:
- name: Create GOPATH
run: mkdir -p /tmp/go
- uses: actions/setup-go@v3
with:
go-version: "1.19"
check-latest: true
- name: Checkout code
uses: actions/checkout@v3
with:
path: "./go-ethereum"
- uses: actions/checkout@v3
with:
ref: ${{ env.stack-orchestrator-ref }}
path: "./stack-orchestrator/"
repository: cerc-io/mshaw_stack_hack
fetch-depth: 0
- uses: actions/checkout@v3
with:
ref: ${{ env.ipld-eth-db-ref }}
repository: cerc-io/ipld-eth-db
path: "./ipld-eth-db/"
fetch-depth: 0
- name: Create config file
run: |
echo vulcanize_ipld_eth_db=$GITHUB_WORKSPACE/ipld-eth-db/ > $GITHUB_WORKSPACE/config.sh
echo vulcanize_go_ethereum=$GITHUB_WORKSPACE/go-ethereum/ >> $GITHUB_WORKSPACE/config.sh
echo db_write=true >> $GITHUB_WORKSPACE/config.sh
echo genesis_file_path=start-up-files/go-ethereum/genesis.json >> $GITHUB_WORKSPACE/config.sh
cat $GITHUB_WORKSPACE/config.sh
- name: Compile Geth
run: |
cd $GITHUB_WORKSPACE/stack-orchestrator/helper-scripts
./compile-geth.sh -e docker -p $GITHUB_WORKSPACE/config.sh
cd -
- name: Run docker compose
run: |
docker-compose \
-f "$GITHUB_WORKSPACE/stack-orchestrator/docker/local/docker-compose-go-ethereum.yml" \
-f "$GITHUB_WORKSPACE/stack-orchestrator/docker/local/docker-compose-db-sharding.yml" \
--env-file $GITHUB_WORKSPACE/config.sh \
up -d --build
- name: Make sure the /root/transaction_info/STATEFUL_TEST_DEPLOYED_ADDRESS exists within a certain time frame.
shell: bash
run: |
COUNT=0
ATTEMPTS=15
docker logs local_go-ethereum_1
docker compose -f "$GITHUB_WORKSPACE/stack-orchestrator/docker/local/docker-compose-db-sharding.yml" -f "$GITHUB_WORKSPACE/stack-orchestrator/docker/local/docker-compose-go-ethereum.yml" exec go-ethereum ps aux
until $(docker compose -f "$GITHUB_WORKSPACE/stack-orchestrator/docker/local/docker-compose-db-sharding.yml" -f "$GITHUB_WORKSPACE/stack-orchestrator/docker/local/docker-compose-go-ethereum.yml" cp go-ethereum:/root/transaction_info/STATEFUL_TEST_DEPLOYED_ADDRESS ./STATEFUL_TEST_DEPLOYED_ADDRESS) || [[ $COUNT -eq $ATTEMPTS ]]; do echo -e "$(( COUNT++ ))... \c"; sleep 10; done
[[ $COUNT -eq $ATTEMPTS ]] && echo "Could not find the successful contract deployment" && (exit 1)
cat ./STATEFUL_TEST_DEPLOYED_ADDRESS
echo "Address length: `wc ./STATEFUL_TEST_DEPLOYED_ADDRESS`"
sleep 15;
- name: Create a new transaction.
shell: bash
run: |
docker logs local_go-ethereum_1
docker compose -f "$GITHUB_WORKSPACE/stack-orchestrator/docker/local/docker-compose-db-sharding.yml" -f "$GITHUB_WORKSPACE/stack-orchestrator/docker/local/docker-compose-go-ethereum.yml" exec go-ethereum /bin/bash /root/transaction_info/NEW_TRANSACTION
echo $?
- name: Make sure we see entries in the header table
shell: bash
run: |
rows=$(docker compose -f "$GITHUB_WORKSPACE/stack-orchestrator/docker/local/docker-compose-db-sharding.yml" -f "$GITHUB_WORKSPACE/stack-orchestrator/docker/local/docker-compose-go-ethereum.yml" exec ipld-eth-db psql -U vdbm -d vulcanize_testing -AXqtc "SELECT COUNT(*) FROM eth.header_cids")
[[ "$rows" -lt "1" ]] && echo "We could not find any rows in postgres table." && (exit 1)
echo $rows
docker compose -f "$GITHUB_WORKSPACE/stack-orchestrator/docker/local/docker-compose-db-sharding.yml" -f "$GITHUB_WORKSPACE/stack-orchestrator/docker/local/docker-compose-go-ethereum.yml" exec ipld-eth-db psql -U vdbm -d vulcanize_testing -AXqtc "SELECT * FROM eth.header_cids"

16
.gitignore vendored
View File

@ -47,3 +47,19 @@ profile.cov
/dashboard/assets/package-lock.json /dashboard/assets/package-lock.json
**/yarn-error.log **/yarn-error.log
logs/
foundry/deployments/local-private-network/geth-linux-amd64
foundry/projects/local-private-network/geth-linux-amd64
# Helpful repos
related-repositories/foundry-test/**
related-repositories/hive/**
related-repositories/ipld-eth-db/**
related-repositories/foundry-test/
related-repositories/ipld-eth-db/
# files generated by statediffing tests
statediff/indexer/database/sql/statediffing_test_file.sql
statediff/statediffing_test_file.sql
statediff/known_gaps.sql
statediff/indexer/database/file/statediffing_test

View File

@ -12,7 +12,6 @@ run:
linters: linters:
disable-all: true disable-all: true
enable: enable:
- deadcode
- goconst - goconst
- goimports - goimports
- gosimple - gosimple
@ -20,14 +19,12 @@ linters:
- ineffassign - ineffassign
- misspell - misspell
- unconvert - unconvert
- varcheck
- typecheck - typecheck
- unused - unused
- staticcheck - staticcheck
- bidichk - bidichk
- durationcheck - durationcheck
- exportloopref - exportloopref
- gosec
- whitespace - whitespace
# - structcheck # lots of false positives # - structcheck # lots of false positives
@ -45,11 +42,6 @@ linters-settings:
goconst: goconst:
min-len: 3 # minimum length of string constant min-len: 3 # minimum length of string constant
min-occurrences: 6 # minimum number of occurrences min-occurrences: 6 # minimum number of occurrences
gosec:
excludes:
- G404 # Use of weak random number generator - lots of FP
- G107 # Potential http request -- those are intentional
- G306 # G306: Expect WriteFile permissions to be 0600 or less
issues: issues:
exclude-rules: exclude-rules:
@ -58,16 +50,15 @@ issues:
- deadcode - deadcode
- staticcheck - staticcheck
- path: internal/build/pgp.go - path: internal/build/pgp.go
text: 'SA1019: package golang.org/x/crypto/openpgp is deprecated' text: 'SA1019: "golang.org/x/crypto/openpgp" is deprecated: this package is unmaintained except for security fixes.'
- path: core/vm/contracts.go - path: core/vm/contracts.go
text: 'SA1019: package golang.org/x/crypto/ripemd160 is deprecated' text: 'SA1019: "golang.org/x/crypto/ripemd160" is deprecated: RIPEMD-160 is a legacy hash and should not be used for new applications.'
- path: accounts/usbwallet/trezor.go - path: accounts/usbwallet/trezor.go
text: 'SA1019: package github.com/golang/protobuf/proto is deprecated' text: 'SA1019: "github.com/golang/protobuf/proto" is deprecated: Use the "google.golang.org/protobuf/proto" package instead.'
- path: accounts/usbwallet/trezor/ - path: accounts/usbwallet/trezor/
text: 'SA1019: package github.com/golang/protobuf/proto is deprecated' text: 'SA1019: "github.com/golang/protobuf/proto" is deprecated: Use the "google.golang.org/protobuf/proto" package instead.'
exclude: exclude:
- 'SA1019: event.TypeMux is deprecated: use Feed' - 'SA1019: event.TypeMux is deprecated: use Feed'
- 'SA1019: strings.Title is deprecated' - 'SA1019: strings.Title is deprecated'
- 'SA1019: strings.Title has been deprecated since Go 1.18 and an alternative has been available since Go 1.0: The rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.' - 'SA1019: strings.Title has been deprecated since Go 1.18 and an alternative has been available since Go 1.0: The rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.'
- 'SA1029: should not use built-in type string as key for value' - 'SA1029: should not use built-in type string as key for value'
- 'G306: Expect WriteFile permissions to be 0600 or less'

View File

@ -5,18 +5,15 @@ jobs:
allow_failures: allow_failures:
- stage: build - stage: build
os: osx os: osx
go: 1.17.x
env: env:
- azure-osx - azure-osx
- azure-ios
- cocoapods-ios
include: include:
# This builder only tests code linters on latest version of Go # This builder only tests code linters on latest version of Go
- stage: lint - stage: lint
os: linux os: linux
dist: bionic dist: bionic
go: 1.18.x go: 1.20.x
env: env:
- lint - lint
git: git:
@ -31,7 +28,7 @@ jobs:
os: linux os: linux
arch: amd64 arch: amd64
dist: bionic dist: bionic
go: 1.18.x go: 1.20.x
env: env:
- docker - docker
services: services:
@ -48,7 +45,7 @@ jobs:
os: linux os: linux
arch: arm64 arch: arm64
dist: bionic dist: bionic
go: 1.18.x go: 1.20.x
env: env:
- docker - docker
services: services:
@ -60,37 +57,13 @@ jobs:
script: script:
- go run build/ci.go docker -image -manifest amd64,arm64 -upload ethereum/client-go - go run build/ci.go docker -image -manifest amd64,arm64 -upload ethereum/client-go
# This builder does the Ubuntu PPA upload
- stage: build
if: type = push
os: linux
dist: bionic
go: 1.18.x
env:
- ubuntu-ppa
- GO111MODULE=on
git:
submodules: false # avoid cloning ethereum/tests
addons:
apt:
packages:
- devscripts
- debhelper
- dput
- fakeroot
- python-bzrlib
- python-paramiko
script:
- echo '|1|7SiYPr9xl3uctzovOTj4gMwAC1M=|t6ReES75Bo/PxlOPJ6/GsGbTrM0= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0aKz5UTUndYgIGG7dQBV+HaeuEZJ2xPHo2DS2iSKvUL4xNMSAY4UguNW+pX56nAQmZKIZZ8MaEvSj6zMEDiq6HFfn5JcTlM80UwlnyKe8B8p7Nk06PPQLrnmQt5fh0HmEcZx+JU9TZsfCHPnX7MNz4ELfZE6cFsclClrKim3BHUIGq//t93DllB+h4O9LHjEUsQ1Sr63irDLSutkLJD6RXchjROXkNirlcNVHH/jwLWR5RcYilNX7S5bIkK8NlWPjsn/8Ua5O7I9/YoE97PpO6i73DTGLh5H9JN/SITwCKBkgSDWUt61uPK3Y11Gty7o2lWsBjhBUm2Y38CBsoGmBw==' >> ~/.ssh/known_hosts
- go run build/ci.go debsrc -upload ethereum/ethereum -sftp-user geth-ci -signer "Go Ethereum Linux Builder <geth-ci@ethereum.org>"
# This builder does the Linux Azure uploads # This builder does the Linux Azure uploads
- stage: build - stage: build
if: type = push if: type = push
os: linux os: linux
dist: bionic dist: bionic
sudo: required sudo: required
go: 1.18.x go: 1.20.x
env: env:
- azure-linux - azure-linux
- GO111MODULE=on - GO111MODULE=on
@ -120,53 +93,13 @@ jobs:
- go run build/ci.go install -dlgo -arch arm64 -cc aarch64-linux-gnu-gcc - go run build/ci.go install -dlgo -arch arm64 -cc aarch64-linux-gnu-gcc
- go run build/ci.go archive -arch arm64 -type tar -signer LINUX_SIGNING_KEY -signify SIGNIFY_KEY -upload gethstore/builds - go run build/ci.go archive -arch arm64 -type tar -signer LINUX_SIGNING_KEY -signify SIGNIFY_KEY -upload gethstore/builds
# This builder does the Android Maven and Azure uploads # This builder does the OSX Azure uploads
- stage: build
if: type = push
os: linux
dist: bionic
addons:
apt:
packages:
- openjdk-8-jdk
env:
- azure-android
- maven-android
- GO111MODULE=on
git:
submodules: false # avoid cloning ethereum/tests
before_install:
# Install Android and it's dependencies manually, Travis is stale
- export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
- curl https://dl.google.com/android/repository/commandlinetools-linux-6858069_latest.zip -o android.zip
- unzip -q android.zip -d $HOME/sdk && rm android.zip
- mv $HOME/sdk/cmdline-tools $HOME/sdk/latest && mkdir $HOME/sdk/cmdline-tools && mv $HOME/sdk/latest $HOME/sdk/cmdline-tools
- export PATH=$PATH:$HOME/sdk/cmdline-tools/latest/bin
- export ANDROID_HOME=$HOME/sdk
- yes | sdkmanager --licenses >/dev/null
- sdkmanager "platform-tools" "platforms;android-15" "platforms;android-19" "platforms;android-24" "ndk-bundle"
# Install Go to allow building with
- curl https://dl.google.com/go/go1.18.linux-amd64.tar.gz | tar -xz
- export PATH=`pwd`/go/bin:$PATH
- export GOROOT=`pwd`/go
- export GOPATH=$HOME/go
script:
# Build the Android archive and upload it to Maven Central and Azure
- mkdir -p $GOPATH/src/github.com/ethereum
- ln -s `pwd` $GOPATH/src/github.com/ethereum/go-ethereum
- go run build/ci.go aar -signer ANDROID_SIGNING_KEY -signify SIGNIFY_KEY -deploy https://oss.sonatype.org -upload gethstore/builds
# This builder does the OSX Azure, iOS CocoaPods and iOS Azure uploads
- stage: build - stage: build
if: type = push if: type = push
os: osx os: osx
go: 1.18.x go: 1.20.x
env: env:
- azure-osx - azure-osx
- azure-ios
- cocoapods-ios
- GO111MODULE=on - GO111MODULE=on
git: git:
submodules: false # avoid cloning ethereum/tests submodules: false # avoid cloning ethereum/tests
@ -174,58 +107,67 @@ jobs:
- go run build/ci.go install -dlgo - go run build/ci.go install -dlgo
- go run build/ci.go archive -type tar -signer OSX_SIGNING_KEY -signify SIGNIFY_KEY -upload gethstore/builds - go run build/ci.go archive -type tar -signer OSX_SIGNING_KEY -signify SIGNIFY_KEY -upload gethstore/builds
# Build the iOS framework and upload it to CocoaPods and Azure
- gem uninstall cocoapods -a -x
- gem install cocoapods
- mv ~/.cocoapods/repos/master ~/.cocoapods/repos/master.bak
- sed -i '.bak' 's/repo.join/!repo.join/g' $(dirname `gem which cocoapods`)/cocoapods/sources_manager.rb
- if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then git clone --depth=1 https://github.com/CocoaPods/Specs.git ~/.cocoapods/repos/master && pod setup --verbose; fi
- xctool -version
- xcrun simctl list
# Workaround for https://github.com/golang/go/issues/23749
- export CGO_CFLAGS_ALLOW='-fmodules|-fblocks|-fobjc-arc'
- go run build/ci.go xcode -signer IOS_SIGNING_KEY -signify SIGNIFY_KEY -deploy trunk -upload gethstore/builds
# These builders run the tests # These builders run the tests
- stage: build - stage: build
os: linux os: linux
arch: amd64 arch: amd64
dist: bionic dist: bionic
go: 1.18.x go: 1.20.x
env: env:
- GO111MODULE=on - GO111MODULE=on
script: script:
- go run build/ci.go test -coverage $TEST_PACKAGES - go run build/ci.go test $TEST_PACKAGES
- stage: build - stage: build
if: type = pull_request if: type = pull_request
os: linux os: linux
arch: arm64 arch: arm64
dist: bionic dist: bionic
go: 1.18.x go: 1.19.x
env: env:
- GO111MODULE=on - GO111MODULE=on
script: script:
- go run build/ci.go test -coverage $TEST_PACKAGES - go run build/ci.go test $TEST_PACKAGES
- stage: build - stage: build
os: linux os: linux
dist: bionic dist: bionic
go: 1.17.x go: 1.19.x
env: env:
- GO111MODULE=on - GO111MODULE=on
script: script:
- go run build/ci.go test -coverage $TEST_PACKAGES - go run build/ci.go test $TEST_PACKAGES
# This builder does the Ubuntu PPA nightly uploads
- stage: build
if: type = cron || (type = push && tag ~= /^v[0-9]/)
os: linux
dist: bionic
go: 1.20.x
env:
- ubuntu-ppa
- GO111MODULE=on
git:
submodules: false # avoid cloning ethereum/tests
addons:
apt:
packages:
- devscripts
- debhelper
- dput
- fakeroot
- python-bzrlib
- python-paramiko
script:
- echo '|1|7SiYPr9xl3uctzovOTj4gMwAC1M=|t6ReES75Bo/PxlOPJ6/GsGbTrM0= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0aKz5UTUndYgIGG7dQBV+HaeuEZJ2xPHo2DS2iSKvUL4xNMSAY4UguNW+pX56nAQmZKIZZ8MaEvSj6zMEDiq6HFfn5JcTlM80UwlnyKe8B8p7Nk06PPQLrnmQt5fh0HmEcZx+JU9TZsfCHPnX7MNz4ELfZE6cFsclClrKim3BHUIGq//t93DllB+h4O9LHjEUsQ1Sr63irDLSutkLJD6RXchjROXkNirlcNVHH/jwLWR5RcYilNX7S5bIkK8NlWPjsn/8Ua5O7I9/YoE97PpO6i73DTGLh5H9JN/SITwCKBkgSDWUt61uPK3Y11Gty7o2lWsBjhBUm2Y38CBsoGmBw==' >> ~/.ssh/known_hosts
- go run build/ci.go debsrc -upload ethereum/ethereum -sftp-user geth-ci -signer "Go Ethereum Linux Builder <geth-ci@ethereum.org>"
# This builder does the Azure archive purges to avoid accumulating junk # This builder does the Azure archive purges to avoid accumulating junk
- stage: build - stage: build
if: type = cron if: type = cron
os: linux os: linux
dist: bionic dist: bionic
go: 1.18.x go: 1.20.x
env: env:
- azure-purge - azure-purge
- GO111MODULE=on - GO111MODULE=on
@ -239,9 +181,9 @@ jobs:
if: type = cron if: type = cron
os: linux os: linux
dist: bionic dist: bionic
go: 1.18.x go: 1.20.x
env: env:
- GO111MODULE=on - GO111MODULE=on
script: script:
- go run build/ci.go test -race -coverage $TEST_PACKAGES - go run build/ci.go test -race $TEST_PACKAGES

View File

@ -4,7 +4,7 @@ ARG VERSION=""
ARG BUILDNUM="" ARG BUILDNUM=""
# Build Geth in a stock Go builder container # Build Geth in a stock Go builder container
FROM golang:1.18-alpine as builder FROM golang:1.20-alpine as builder
RUN apk add --no-cache gcc musl-dev linux-headers git RUN apk add --no-cache gcc musl-dev linux-headers git

View File

@ -4,7 +4,7 @@ ARG VERSION=""
ARG BUILDNUM="" ARG BUILDNUM=""
# Build Geth in a stock Go builder container # Build Geth in a stock Go builder container
FROM golang:1.18-alpine as builder FROM golang:1.20-alpine as builder
RUN apk add --no-cache gcc musl-dev linux-headers git RUN apk add --no-cache gcc musl-dev linux-headers git

7
Dockerfile.amd64 Normal file
View File

@ -0,0 +1,7 @@
# Build Geth in a stock Go builder container
FROM golang:1.15.5 as builder
#RUN apk add --no-cache make gcc musl-dev linux-headers git
ADD . /go-ethereum
RUN cd /go-ethereum && make geth

50
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,50 @@
pipeline {
agent any
stages {
stage('Build') {
steps {
script{
docker.withRegistry('https://git.vdb.to'){
echo 'Building geth image...'
//def geth_image = docker.build("cerc-io/go-ethereum:jenkinscicd")
echo 'built geth image'
}
}
}
}
stage('Test') {
agent {
docker {
image 'cerc-io/foundation:jenkinscicd'
//image 'cerc-io/foundation_alpine:jenkinscicd'
}
}
environment {
GO111MODULE = "on"
CGO_ENABLED = 1
//GOPATH = "${JENKINS_HOME}/jobs/${JOB_NAME}/builds/${BUILD_ID}"
//GOPATH = "/go"
GOPATH = "/tmp/go"
//GOMODCACHE = "/go/pkg/mod"
GOCACHE = "${WORKSPACE}/.cache/go-build"
GOENV = "${WORKSPACE}/.config/go/env"
GOMODCACHE = "/tmp/go/pkg/mod"
GOWORK=""
//GOFLAGS=""
}
steps {
echo 'Testing ...'
//sh '/usr/local/go/bin/go test -p 1 -v ./...'
sh 'make test'
}
}
stage('Packaging') {
steps {
echo 'Packaging ...'
}
}
}
}

View File

@ -4,10 +4,31 @@
.PHONY: geth android ios evm all test clean .PHONY: geth android ios evm all test clean
BIN = $(GOPATH)/bin
## Migration tool
GOOSE = $(BIN)/goose
$(BIN)/goose:
go get -u github.com/pressly/goose/cmd/goose
GOBIN = ./build/bin GOBIN = ./build/bin
GO ?= latest GO ?= latest
GORUN = env GO111MODULE=on go run GORUN = env GO111MODULE=on go run
#Database
HOST_NAME = localhost
PORT = 5432
USER = vdbm
PASSWORD = password
# Set env variable
# `PGPASSWORD` is used by `createdb` and `dropdb`
export PGPASSWORD=$(PASSWORD)
#Test
TEST_DB = cerc_testing
TEST_CONNECT_STRING = postgresql://$(USER):$(PASSWORD)@$(HOST_NAME):$(PORT)/$(TEST_DB)?sslmode=disable
geth: geth:
$(GORUN) build/ci.go install ./cmd/geth $(GORUN) build/ci.go install ./cmd/geth
@echo "Done building." @echo "Done building."
@ -16,18 +37,6 @@ geth:
all: all:
$(GORUN) build/ci.go install $(GORUN) build/ci.go install
android:
$(GORUN) build/ci.go aar --local
@echo "Done building."
@echo "Import \"$(GOBIN)/geth.aar\" to use the library."
@echo "Import \"$(GOBIN)/geth-sources.jar\" to add javadocs"
@echo "For more info see https://stackoverflow.com/questions/20994336/android-studio-how-to-attach-javadoc"
ios:
$(GORUN) build/ci.go xcode --local
@echo "Done building."
@echo "Import \"$(GOBIN)/Geth.framework\" to use the library."
test: all test: all
$(GORUN) build/ci.go test $(GORUN) build/ci.go test
@ -48,3 +57,13 @@ devtools:
env GOBIN= go install ./cmd/abigen env GOBIN= go install ./cmd/abigen
@type "solc" 2> /dev/null || echo 'Please install solc' @type "solc" 2> /dev/null || echo 'Please install solc'
@type "protoc" 2> /dev/null || echo 'Please install protoc' @type "protoc" 2> /dev/null || echo 'Please install protoc'
.PHONY: statedifftest
statedifftest: | $(GOOSE)
GO111MODULE=on go get github.com/stretchr/testify/assert@v1.7.0
GO111MODULE=on MODE=statediff go test -p 1 ./statediff/... -v
.PHONY: statediff_filewriting_test
statediff_filetest: | $(GOOSE)
GO111MODULE=on go get github.com/stretchr/testify/assert@v1.7.0
GO111MODULE=on MODE=statediff STATEDIFF_DB=file go test -p 1 ./statediff/... -v

143
README.md
View File

@ -1,10 +1,8 @@
## Go Ethereum ## Go Ethereum
Official Golang implementation of the Ethereum protocol. Official Golang execution layer implementation of the Ethereum protocol.
[![API Reference]( [![API Reference](https://camo.githubusercontent.com/915b7be44ada53c290eb157634330494ebe3e30a/68747470733a2f2f676f646f632e6f72672f6769746875622e636f6d2f676f6c616e672f6764646f3f7374617475732e737667)](https://pkg.go.dev/github.com/ethereum/go-ethereum?tab=doc)
https://camo.githubusercontent.com/915b7be44ada53c290eb157634330494ebe3e30a/68747470733a2f2f676f646f632e6f72672f6769746875622e636f6d2f676f6c616e672f6764646f3f7374617475732e737667
)](https://pkg.go.dev/github.com/ethereum/go-ethereum?tab=doc)
[![Go Report Card](https://goreportcard.com/badge/github.com/ethereum/go-ethereum)](https://goreportcard.com/report/github.com/ethereum/go-ethereum) [![Go Report Card](https://goreportcard.com/badge/github.com/ethereum/go-ethereum)](https://goreportcard.com/report/github.com/ethereum/go-ethereum)
[![Travis](https://travis-ci.com/ethereum/go-ethereum.svg?branch=master)](https://travis-ci.com/ethereum/go-ethereum) [![Travis](https://travis-ci.com/ethereum/go-ethereum.svg?branch=master)](https://travis-ci.com/ethereum/go-ethereum)
[![Discord](https://img.shields.io/badge/discord-join%20chat-blue.svg)](https://discord.gg/nthXNEv) [![Discord](https://img.shields.io/badge/discord-join%20chat-blue.svg)](https://discord.gg/nthXNEv)
@ -12,11 +10,26 @@ https://camo.githubusercontent.com/915b7be44ada53c290eb157634330494ebe3e30a/6874
Automated builds are available for stable releases and the unstable master branch. Binary Automated builds are available for stable releases and the unstable master branch. Binary
archives are published at https://geth.ethereum.org/downloads/. archives are published at https://geth.ethereum.org/downloads/.
## Vulcanize Specific
This section captures components specific to vulcanize.
### Branching Structure
We currently follow the following branching structure.
1. Create a branch: `v1.10.18-statediff-vX` --> feature/some-feature`
2. Create a PR upstream: `feature/some-feature` --> `v1.10.18-statediff-vX`
3. When a release is ready, create a release branch: `v1.10.18-statediff-vX` --> `v1.10.18-statediff-X.Y.Z`
4. When `v1.10.18-statediff-vX` is stable, merge it to `statediff`.
This process is subject to change.
## Building the source ## Building the source
For prerequisites and detailed build instructions please read the [Installation Instructions](https://geth.ethereum.org/docs/install-and-build/installing-geth). For prerequisites and detailed build instructions please read the [Installation Instructions](https://geth.ethereum.org/docs/getting-started/installing-geth).
Building `geth` requires both a Go (version 1.16 or later) and a C compiler. You can install Building `geth` requires both a Go (version 1.19 or later) and a C compiler. You can install
them using your favourite package manager. Once the dependencies are installed, run them using your favourite package manager. Once the dependencies are installed, run
```shell ```shell
@ -34,21 +47,20 @@ make all
The go-ethereum project comes with several wrappers/executables found in the `cmd` The go-ethereum project comes with several wrappers/executables found in the `cmd`
directory. directory.
| Command | Description | | Command | Description |
| :-----------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | :--------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`geth`** | Our main Ethereum CLI client. It is the entry point into the Ethereum network (main-, test- or private net), capable of running as a full node (default), archive node (retaining all historical state) or a light node (retrieving data live). It can be used by other processes as a gateway into the Ethereum network via JSON RPC endpoints exposed on top of HTTP, WebSocket and/or IPC transports. `geth --help` and the [CLI page](https://geth.ethereum.org/docs/interface/command-line-options) for command line options. | | **`geth`** | Our main Ethereum CLI client. It is the entry point into the Ethereum network (main-, test- or private net), capable of running as a full node (default), archive node (retaining all historical state) or a light node (retrieving data live). It can be used by other processes as a gateway into the Ethereum network via JSON RPC endpoints exposed on top of HTTP, WebSocket and/or IPC transports. `geth --help` and the [CLI page](https://geth.ethereum.org/docs/fundamentals/command-line-options) for command line options. |
| `clef` | Stand-alone signing tool, which can be used as a backend signer for `geth`. | | `clef` | Stand-alone signing tool, which can be used as a backend signer for `geth`. |
| `devp2p` | Utilities to interact with nodes on the networking layer, without running a full blockchain. | | `devp2p` | Utilities to interact with nodes on the networking layer, without running a full blockchain. |
| `abigen` | Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages. It operates on plain [Ethereum contract ABIs](https://docs.soliditylang.org/en/develop/abi-spec.html) with expanded functionality if the contract bytecode is also available. However, it also accepts Solidity source files, making development much more streamlined. Please see our [Native DApps](https://geth.ethereum.org/docs/dapp/native-bindings) page for details. | | `abigen` | Source code generator to convert Ethereum contract definitions into easy-to-use, compile-time type-safe Go packages. It operates on plain [Ethereum contract ABIs](https://docs.soliditylang.org/en/develop/abi-spec.html) with expanded functionality if the contract bytecode is also available. However, it also accepts Solidity source files, making development much more streamlined. Please see our [Native DApps](https://geth.ethereum.org/docs/developers/dapp-developer/native-bindings) page for details. |
| `bootnode` | Stripped down version of our Ethereum client implementation that only takes part in the network node discovery protocol, but does not run any of the higher level application protocols. It can be used as a lightweight bootstrap node to aid in finding peers in private networks. | | `bootnode` | Stripped down version of our Ethereum client implementation that only takes part in the network node discovery protocol, but does not run any of the higher level application protocols. It can be used as a lightweight bootstrap node to aid in finding peers in private networks. |
| `evm` | Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode. Its purpose is to allow isolated, fine-grained debugging of EVM opcodes (e.g. `evm --code 60ff60ff --debug run`). | | `evm` | Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode. Its purpose is to allow isolated, fine-grained debugging of EVM opcodes (e.g. `evm --code 60ff60ff --debug run`). |
| `rlpdump` | Developer utility tool to convert binary RLP ([Recursive Length Prefix](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp)) dumps (data encoding used by the Ethereum protocol both network as well as consensus wise) to user-friendlier hierarchical representation (e.g. `rlpdump --hex CE0183FFFFFFC4C304050583616263`). | | `rlpdump` | Developer utility tool to convert binary RLP ([Recursive Length Prefix](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp)) dumps (data encoding used by the Ethereum protocol both network as well as consensus wise) to user-friendlier hierarchical representation (e.g. `rlpdump --hex CE0183FFFFFFC4C304050583616263`). |
| `puppeth` | a CLI wizard that aids in creating a new Ethereum network. |
## Running `geth` ## Running `geth`
Going through all the possible command line flags is out of scope here (please consult our Going through all the possible command line flags is out of scope here (please consult our
[CLI Wiki page](https://geth.ethereum.org/docs/interface/command-line-options)), [CLI Wiki page](https://geth.ethereum.org/docs/fundamentals/command-line-options)),
but we've enumerated a few common parameter combos to get you up to speed quickly but we've enumerated a few common parameter combos to get you up to speed quickly
on how you can run your own `geth` instance. on how you can run your own `geth` instance.
@ -56,23 +68,23 @@ on how you can run your own `geth` instance.
Minimum: Minimum:
* CPU with 2+ cores - CPU with 2+ cores
* 4GB RAM - 4GB RAM
* 1TB free storage space to sync the Mainnet - 1TB free storage space to sync the Mainnet
* 8 MBit/sec download Internet service - 8 MBit/sec download Internet service
Recommended: Recommended:
* Fast CPU with 4+ cores * Fast CPU with 4+ cores
* 16GB+ RAM * 16GB+ RAM
* High Performance SSD with at least 1TB free space * High-performance SSD with at least 1TB of free space
* 25+ MBit/sec download Internet service * 25+ MBit/sec download Internet service
### Full node on the main Ethereum network ### Full node on the main Ethereum network
By far the most common scenario is people wanting to simply interact with the Ethereum By far the most common scenario is people wanting to simply interact with the Ethereum
network: create accounts; transfer funds; deploy and interact with contracts. For this network: create accounts; transfer funds; deploy and interact with contracts. For this
particular use-case the user doesn't care about years-old historical data, so we can particular use case, the user doesn't care about years-old historical data, so we can
sync quickly to the current state of the network. To do so: sync quickly to the current state of the network. To do so:
```shell ```shell
@ -83,11 +95,11 @@ This command will:
* Start `geth` in snap sync mode (default, can be changed with the `--syncmode` flag), * Start `geth` in snap sync mode (default, can be changed with the `--syncmode` flag),
causing it to download more data in exchange for avoiding processing the entire history causing it to download more data in exchange for avoiding processing the entire history
of the Ethereum network, which is very CPU intensive. of the Ethereum network, which is very CPU intensive.
* Start up `geth`'s built-in interactive [JavaScript console](https://geth.ethereum.org/docs/interface/javascript-console), * Start the built-in interactive [JavaScript console](https://geth.ethereum.org/docs/interacting-with-geth/javascript-console),
(via the trailing `console` subcommand) through which you can interact using [`web3` methods](https://github.com/ChainSafe/web3.js/blob/0.20.7/DOCUMENTATION.md) (via the trailing `console` subcommand) through which you can interact using [`web3` methods](https://github.com/ChainSafe/web3.js/blob/0.20.7/DOCUMENTATION.md)
(note: the `web3` version bundled within `geth` is very old, and not up to date with official docs), (note: the `web3` version bundled within `geth` is very old, and not up to date with official docs),
as well as `geth`'s own [management APIs](https://geth.ethereum.org/docs/rpc/server). as well as `geth`'s own [management APIs](https://geth.ethereum.org/docs/interacting-with-geth/rpc).
This tool is optional and if you leave it out you can always attach to an already running This tool is optional and if you leave it out you can always attach it to an already running
`geth` instance with `geth attach`. `geth` instance with `geth attach`.
### A Full node on the Görli test network ### A Full node on the Görli test network
@ -102,12 +114,12 @@ the main network, but with play-Ether only.
$ geth --goerli console $ geth --goerli console
``` ```
The `console` subcommand has the exact same meaning as above and they are equally The `console` subcommand has the same meaning as above and is equally
useful on the testnet too. Please, see above for their explanations if you've skipped here. useful on the testnet too.
Specifying the `--goerli` flag, however, will reconfigure your `geth` instance a bit: Specifying the `--goerli` flag, however, will reconfigure your `geth` instance a bit:
* Instead of connecting the main Ethereum network, the client will connect to the Görli * Instead of connecting to the main Ethereum network, the client will connect to the Görli
test network, which uses different P2P bootnodes, different network IDs and genesis test network, which uses different P2P bootnodes, different network IDs and genesis
states. states.
* Instead of using the default data directory (`~/.ethereum` on Linux for example), `geth` * Instead of using the default data directory (`~/.ethereum` on Linux for example), `geth`
@ -118,34 +130,21 @@ Specifying the `--goerli` flag, however, will reconfigure your `geth` instance a
`geth attach <datadir>/goerli/geth.ipc`. Windows users are not affected by `geth attach <datadir>/goerli/geth.ipc`. Windows users are not affected by
this. this.
*Note: Although there are some internal protective measures to prevent transactions from *Note: Although some internal protective measures prevent transactions from
crossing over between the main network and test network, you should make sure to always crossing over between the main network and test network, you should always
use separate accounts for play-money and real-money. Unless you manually move use separate accounts for play and real money. Unless you manually move
accounts, `geth` will by default correctly separate the two networks and will not make any accounts, `geth` will by default correctly separate the two networks and will not make any
accounts available between them.* accounts available between them._
### Full node on the Rinkeby test network ### Full node on the Rinkeby test network
Go Ethereum also supports connecting to the older proof-of-authority based test network Go Ethereum also supports connecting to the older proof-of-authority based test network
called [*Rinkeby*](https://www.rinkeby.io) which is operated by members of the community. called [_Rinkeby_](https://www.rinkeby.io) which is operated by members of the community.
```shell ```shell
$ geth --rinkeby console $ geth --rinkeby console
``` ```
### Full node on the Ropsten test network
In addition to Görli and Rinkeby, Geth also supports the ancient Ropsten testnet. The
Ropsten test network is based on the Ethash proof-of-work consensus algorithm. As such,
it has certain extra overhead and is more susceptible to reorganization attacks due to the
network's low difficulty/security.
```shell
$ geth --ropsten console
```
*Note: Older Geth configurations store the Ropsten database in the `testnet` subdirectory.*
### Configuration ### Configuration
As an alternative to passing the numerous flags to the `geth` binary, you can also pass a As an alternative to passing the numerous flags to the `geth` binary, you can also pass a
@ -155,14 +154,14 @@ configuration file via:
$ geth --config /path/to/your_config.toml $ geth --config /path/to/your_config.toml
``` ```
To get an idea how the file should look like you can use the `dumpconfig` subcommand to To get an idea of how the file should look like you can use the `dumpconfig` subcommand to
export your existing configuration: export your existing configuration:
```shell ```shell
$ geth --your-favourite-flags dumpconfig $ geth --your-favourite-flags dumpconfig
``` ```
*Note: This works only with `geth` v1.6.0 and above.* _Note: This works only with `geth` v1.6.0 and above._
#### Docker quick start #### Docker quick start
@ -175,7 +174,7 @@ docker run -d --name ethereum-node -v /Users/alice/ethereum:/root \
ethereum/client-go ethereum/client-go
``` ```
This will start `geth` in snap-sync mode with a DB memory allowance of 1GB just as the This will start `geth` in snap-sync mode with a DB memory allowance of 1GB, as the
above command does. It will also create a persistent volume in your home directory for above command does. It will also create a persistent volume in your home directory for
saving your blockchain as well as map the default ports. There is also an `alpine` tag saving your blockchain as well as map the default ports. There is also an `alpine` tag
available for a slim version of the image. available for a slim version of the image.
@ -189,7 +188,7 @@ accessible from the outside.
As a developer, sooner rather than later you'll want to start interacting with `geth` and the As a developer, sooner rather than later you'll want to start interacting with `geth` and the
Ethereum network via your own programs and not manually through the console. To aid Ethereum network via your own programs and not manually through the console. To aid
this, `geth` has built-in support for a JSON-RPC based APIs ([standard APIs](https://ethereum.github.io/execution-apis/api-documentation/) this, `geth` has built-in support for a JSON-RPC based APIs ([standard APIs](https://ethereum.github.io/execution-apis/api-documentation/)
and [`geth` specific APIs](https://geth.ethereum.org/docs/rpc/server)). and [`geth` specific APIs](https://geth.ethereum.org/docs/interacting-with-geth/rpc)).
These can be exposed via HTTP, WebSockets and IPC (UNIX sockets on UNIX based These can be exposed via HTTP, WebSockets and IPC (UNIX sockets on UNIX based
platforms, and named pipes on Windows). platforms, and named pipes on Windows).
@ -209,7 +208,7 @@ HTTP based JSON-RPC API options:
* `--ws.addr` WS-RPC server listening interface (default: `localhost`) * `--ws.addr` WS-RPC server listening interface (default: `localhost`)
* `--ws.port` WS-RPC server listening port (default: `8546`) * `--ws.port` WS-RPC server listening port (default: `8546`)
* `--ws.api` API's offered over the WS-RPC interface (default: `eth,net,web3`) * `--ws.api` API's offered over the WS-RPC interface (default: `eth,net,web3`)
* `--ws.origins` Origins from which to accept websockets requests * `--ws.origins` Origins from which to accept WebSocket requests
* `--ipcdisable` Disable the IPC-RPC server * `--ipcdisable` Disable the IPC-RPC server
* `--ipcapi` API's offered over the IPC-RPC interface (default: `admin,debug,eth,miner,net,personal,txpool,web3`) * `--ipcapi` API's offered over the IPC-RPC interface (default: `admin,debug,eth,miner,net,personal,txpool,web3`)
* `--ipcpath` Filename for IPC socket/pipe within the datadir (explicit paths escape it) * `--ipcpath` Filename for IPC socket/pipe within the datadir (explicit paths escape it)
@ -302,8 +301,8 @@ that other nodes can use to connect to it and exchange peer information. Make su
replace the displayed IP address information (most probably `[::]`) with your externally replace the displayed IP address information (most probably `[::]`) with your externally
accessible IP to get the actual `enode` URL. accessible IP to get the actual `enode` URL.
*Note: You could also use a full-fledged `geth` node as a bootnode, but it's the less _Note: You could also use a full-fledged `geth` node as a bootnode, but it's the less
recommended way.* recommended way._
#### Starting up your member nodes #### Starting up your member nodes
@ -317,17 +316,13 @@ do also specify a custom `--datadir` flag.
$ geth --datadir=path/to/custom/data/folder --bootnodes=<bootnode-enode-url-from-above> $ geth --datadir=path/to/custom/data/folder --bootnodes=<bootnode-enode-url-from-above>
``` ```
*Note: Since your network will be completely cut off from the main and test networks, you'll _Note: Since your network will be completely cut off from the main and test networks, you'll
also need to configure a miner to process transactions and create new blocks for you.* also need to configure a miner to process transactions and create new blocks for you._
#### Running a private miner #### Running a private miner
Mining on the public Ethereum network is a complex task as it's only feasible using GPUs,
requiring an OpenCL or CUDA enabled `ethminer` instance. For information on such a
setup, please consult the [EtherMining subreddit](https://www.reddit.com/r/EtherMining/)
and the [ethminer](https://github.com/ethereum-mining/ethminer) repository.
In a private network setting, however a single CPU miner instance is more than enough for In a private network setting a single CPU miner instance is more than enough for
practical purposes as it can produce a stable stream of blocks at the correct intervals practical purposes as it can produce a stable stream of blocks at the correct intervals
without needing heavy resources (consider running on a single thread, no need for multiple without needing heavy resources (consider running on a single thread, no need for multiple
ones either). To start a `geth` instance for mining, run it with all your usual flags, extended ones either). To start a `geth` instance for mining, run it with all your usual flags, extended
@ -344,7 +339,7 @@ transactions are accepted at (`--miner.gasprice`).
## Contribution ## Contribution
Thank you for considering to help out with the source code! We welcome contributions Thank you for considering helping out with the source code! We welcome contributions
from anyone on the internet, and are grateful for even the smallest of fixes! from anyone on the internet, and are grateful for even the smallest of fixes!
If you'd like to contribute to go-ethereum, please fork, fix, commit and send a pull request If you'd like to contribute to go-ethereum, please fork, fix, commit and send a pull request
@ -356,24 +351,30 @@ and merge procedures quick and simple.
Please make sure your contributions adhere to our coding guidelines: Please make sure your contributions adhere to our coding guidelines:
* Code must adhere to the official Go [formatting](https://golang.org/doc/effective_go.html#formatting) - Code must adhere to the official Go [formatting](https://golang.org/doc/effective_go.html#formatting)
guidelines (i.e. uses [gofmt](https://golang.org/cmd/gofmt/)). guidelines (i.e. uses [gofmt](https://golang.org/cmd/gofmt/)).
* Code must be documented adhering to the official Go [commentary](https://golang.org/doc/effective_go.html#commentary) - Code must be documented adhering to the official Go [commentary](https://golang.org/doc/effective_go.html#commentary)
guidelines. guidelines.
* Pull requests need to be based on and opened against the `master` branch. - Pull requests need to be based on and opened against the `master` branch.
* Commit messages should be prefixed with the package(s) they modify. - Commit messages should be prefixed with the package(s) they modify.
* E.g. "eth, rpc: make trace configs optional" - E.g. "eth, rpc: make trace configs optional"
Please see the [Developers' Guide](https://geth.ethereum.org/docs/developers/devguide) Please see the [Developers' Guide](https://geth.ethereum.org/docs/developers/geth-developer/dev-guide)
for more details on configuring your environment, managing project dependencies, and for more details on configuring your environment, managing project dependencies, and
testing procedures. testing procedures.
### Contributing to geth.ethereum.org
For contributions to the [go-ethereum website](https://geth.ethereum.org), please checkout and raise pull requests against the `website` branch.
For more detailed instructions please see the `website` branch [README](https://github.com/ethereum/go-ethereum/tree/website#readme) or the
[contributing](https://geth.ethereum.org/docs/developers/geth-developer/contributing) page of the website.
## License ## License
The go-ethereum library (i.e. all code outside of the `cmd` directory) is licensed under the The go-ethereum library (i.e. all code outside of the `cmd` directory) is licensed under the
[GNU Lesser General Public License v3.0](https://www.gnu.org/licenses/lgpl-3.0.en.html), [GNU Lesser General Public License v3.0](https://www.gnu.org/licenses/lgpl-3.0.en.html),
also included in our repository in the `COPYING.LESSER` file. also included in our repository in the `COPYING.LESSER` file.
The go-ethereum binaries (i.e. all code inside of the `cmd` directory) is licensed under the The go-ethereum binaries (i.e. all code inside of the `cmd` directory) are licensed under the
[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.en.html), also [GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.en.html), also
included in our repository in the `COPYING` file. included in our repository in the `COPYING` file.

View File

@ -87,7 +87,7 @@ func (abi ABI) getArguments(name string, data []byte) (Arguments, error) {
var args Arguments var args Arguments
if method, ok := abi.Methods[name]; ok { if method, ok := abi.Methods[name]; ok {
if len(data)%32 != 0 { if len(data)%32 != 0 {
return nil, fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data) return nil, fmt.Errorf("abi: improperly formatted output: %q - Bytes: %+v", data, data)
} }
args = method.Outputs args = method.Outputs
} }
@ -246,7 +246,10 @@ func UnpackRevert(data []byte) (string, error) {
if !bytes.Equal(data[:4], revertSelector) { if !bytes.Equal(data[:4], revertSelector) {
return "", errors.New("invalid data for unpacking") return "", errors.New("invalid data for unpacking")
} }
typ, _ := NewType("string", "", nil) typ, err := NewType("string", "", nil)
if err != nil {
return "", err
}
unpacked, err := (Arguments{{Type: typ}}).Unpack(data[4:]) unpacked, err := (Arguments{{Type: typ}}).Unpack(data[4:])
if err != nil { if err != nil {
return "", err return "", err

View File

@ -165,8 +165,9 @@ func TestInvalidABI(t *testing.T) {
// TestConstructor tests a constructor function. // TestConstructor tests a constructor function.
// The test is based on the following contract: // The test is based on the following contract:
// contract TestConstructor { //
// constructor(uint256 a, uint256 b) public{} // contract TestConstructor {
// constructor(uint256 a, uint256 b) public{}
// } // }
func TestConstructor(t *testing.T) { func TestConstructor(t *testing.T) {
json := `[{ "inputs": [{"internalType": "uint256","name": "a","type": "uint256" },{ "internalType": "uint256","name": "b","type": "uint256"}],"stateMutability": "nonpayable","type": "constructor"}]` json := `[{ "inputs": [{"internalType": "uint256","name": "a","type": "uint256" },{ "internalType": "uint256","name": "b","type": "uint256"}],"stateMutability": "nonpayable","type": "constructor"}]`
@ -724,16 +725,19 @@ func TestBareEvents(t *testing.T) {
} }
// TestUnpackEvent is based on this contract: // TestUnpackEvent is based on this contract:
// contract T { //
// event received(address sender, uint amount, bytes memo); // contract T {
// event receivedAddr(address sender); // event received(address sender, uint amount, bytes memo);
// function receive(bytes memo) external payable { // event receivedAddr(address sender);
// received(msg.sender, msg.value, memo); // function receive(bytes memo) external payable {
// receivedAddr(msg.sender); // received(msg.sender, msg.value, memo);
// } // receivedAddr(msg.sender);
// } // }
// }
//
// When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt: // When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt:
// receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]} //
// receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]}
func TestUnpackEvent(t *testing.T) { func TestUnpackEvent(t *testing.T) {
const abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"receive","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"receivedAddr","type":"event"}]` const abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"receive","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"receivedAddr","type":"event"}]`
abi, err := JSON(strings.NewReader(abiJSON)) abi, err := JSON(strings.NewReader(abiJSON))
@ -1078,8 +1082,9 @@ func TestDoubleDuplicateMethodNames(t *testing.T) {
// TestDoubleDuplicateEventNames checks that if send0 already exists, there won't be a name // TestDoubleDuplicateEventNames checks that if send0 already exists, there won't be a name
// conflict and that the second send event will be renamed send1. // conflict and that the second send event will be renamed send1.
// The test runs the abi of the following contract. // The test runs the abi of the following contract.
// contract DuplicateEvent { //
// event send(uint256 a); // contract DuplicateEvent {
// event send(uint256 a);
// event send0(); // event send0();
// event send(); // event send();
// } // }
@ -1106,7 +1111,8 @@ func TestDoubleDuplicateEventNames(t *testing.T) {
// TestUnnamedEventParam checks that an event with unnamed parameters is // TestUnnamedEventParam checks that an event with unnamed parameters is
// correctly handled. // correctly handled.
// The test runs the abi of the following contract. // The test runs the abi of the following contract.
// contract TestEvent { //
// contract TestEvent {
// event send(uint256, uint256); // event send(uint256, uint256);
// } // }
func TestUnnamedEventParam(t *testing.T) { func TestUnnamedEventParam(t *testing.T) {

View File

@ -187,6 +187,9 @@ func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) {
virtualArgs := 0 virtualArgs := 0
for index, arg := range nonIndexedArgs { for index, arg := range nonIndexedArgs {
marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data) marshalledValue, err := toGoType((index+virtualArgs)*32, arg.Type, data)
if err != nil {
return nil, err
}
if arg.Type.T == ArrayTy && !isDynamicType(arg.Type) { if arg.Type.T == ArrayTy && !isDynamicType(arg.Type) {
// If we have a static array, like [3]uint256, these are coded as // If we have a static array, like [3]uint256, these are coded as
// just like uint256,uint256,uint256. // just like uint256,uint256,uint256.
@ -204,9 +207,6 @@ func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) {
// coded as just like uint256,bool,uint256 // coded as just like uint256,bool,uint256
virtualArgs += getTypeSize(arg.Type)/32 - 1 virtualArgs += getTypeSize(arg.Type)/32 - 1
} }
if err != nil {
return nil, err
}
retval = append(retval, marshalledValue) retval = append(retval, marshalledValue)
} }
return retval, nil return retval, nil

View File

@ -78,9 +78,12 @@ type SimulatedBackend struct {
// and uses a simulated blockchain for testing purposes. // and uses a simulated blockchain for testing purposes.
// A simulated backend always uses chainID 1337. // A simulated backend always uses chainID 1337.
func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend { func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend {
genesis := core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: gasLimit, Alloc: alloc} genesis := core.Genesis{
genesis.MustCommit(database) Config: params.AllEthashProtocolChanges,
blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{}, nil, nil) GasLimit: gasLimit,
Alloc: alloc,
}
blockchain, _ := core.NewBlockChain(database, nil, &genesis, nil, ethash.NewFaker(), vm.Config{}, nil, nil)
backend := &SimulatedBackend{ backend := &SimulatedBackend{
database: database, database: database,
@ -92,7 +95,10 @@ func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.Genesis
backend.filterSystem = filters.NewFilterSystem(filterBackend, filters.Config{}) backend.filterSystem = filters.NewFilterSystem(filterBackend, filters.Config{})
backend.events = filters.NewEventSystem(backend.filterSystem, false) backend.events = filters.NewEventSystem(backend.filterSystem, false)
backend.rollback(blockchain.CurrentBlock()) header := backend.blockchain.CurrentBlock()
block := backend.blockchain.GetBlock(header.Hash(), header.Number.Uint64())
backend.rollback(block)
return backend return backend
} }
@ -132,7 +138,10 @@ func (b *SimulatedBackend) Rollback() {
b.mu.Lock() b.mu.Lock()
defer b.mu.Unlock() defer b.mu.Unlock()
b.rollback(b.blockchain.CurrentBlock()) header := b.blockchain.CurrentBlock()
block := b.blockchain.GetBlock(header.Hash(), header.Number.Uint64())
b.rollback(block)
} }
func (b *SimulatedBackend) rollback(parent *types.Block) { func (b *SimulatedBackend) rollback(parent *types.Block) {
@ -171,7 +180,7 @@ func (b *SimulatedBackend) Fork(ctx context.Context, parent common.Hash) error {
// stateByBlockNumber retrieves a state by a given blocknumber. // stateByBlockNumber retrieves a state by a given blocknumber.
func (b *SimulatedBackend) stateByBlockNumber(ctx context.Context, blockNumber *big.Int) (*state.StateDB, error) { func (b *SimulatedBackend) stateByBlockNumber(ctx context.Context, blockNumber *big.Int) (*state.StateDB, error) {
if blockNumber == nil || blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) == 0 { if blockNumber == nil || blockNumber.Cmp(b.blockchain.CurrentBlock().Number) == 0 {
return b.blockchain.State() return b.blockchain.State()
} }
block, err := b.blockByNumber(ctx, blockNumber) block, err := b.blockByNumber(ctx, blockNumber)
@ -300,7 +309,7 @@ func (b *SimulatedBackend) BlockByNumber(ctx context.Context, number *big.Int) (
// (associated with its hash) if found without Lock. // (associated with its hash) if found without Lock.
func (b *SimulatedBackend) blockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) { func (b *SimulatedBackend) blockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
if number == nil || number.Cmp(b.pendingBlock.Number()) == 0 { if number == nil || number.Cmp(b.pendingBlock.Number()) == 0 {
return b.blockchain.CurrentBlock(), nil return b.blockByHash(ctx, b.blockchain.CurrentBlock().Hash())
} }
block := b.blockchain.GetBlockByNumber(uint64(number.Int64())) block := b.blockchain.GetBlockByNumber(uint64(number.Int64()))
@ -428,7 +437,7 @@ func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallM
b.mu.Lock() b.mu.Lock()
defer b.mu.Unlock() defer b.mu.Unlock()
if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 { if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number) != 0 {
return nil, errBlockNumberUnsupported return nil, errBlockNumberUnsupported
} }
stateDB, err := b.blockchain.State() stateDB, err := b.blockchain.State()
@ -452,7 +461,7 @@ func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereu
defer b.mu.Unlock() defer b.mu.Unlock()
defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot()) defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot())
res, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState) res, err := b.callContract(ctx, call, b.pendingBlock.Header(), b.pendingState)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -524,7 +533,7 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMs
available := new(big.Int).Set(balance) available := new(big.Int).Set(balance)
if call.Value != nil { if call.Value != nil {
if call.Value.Cmp(available) >= 0 { if call.Value.Cmp(available) >= 0 {
return 0, errors.New("insufficient funds for transfer") return 0, core.ErrInsufficientFundsForTransfer
} }
available.Sub(available, call.Value) available.Sub(available, call.Value)
} }
@ -546,7 +555,7 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMs
call.Gas = gas call.Gas = gas
snapshot := b.pendingState.Snapshot() snapshot := b.pendingState.Snapshot()
res, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState) res, err := b.callContract(ctx, call, b.pendingBlock.Header(), b.pendingState)
b.pendingState.RevertToSnapshot(snapshot) b.pendingState.RevertToSnapshot(snapshot)
if err != nil { if err != nil {
@ -596,7 +605,7 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMs
// callContract implements common code between normal and pending contract calls. // callContract implements common code between normal and pending contract calls.
// state is modified during execution, make sure to copy it if necessary. // state is modified during execution, make sure to copy it if necessary.
func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, stateDB *state.StateDB) (*core.ExecutionResult, error) { func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, header *types.Header, stateDB *state.StateDB) (*core.ExecutionResult, error) {
// Gas prices post 1559 need to be initialized // Gas prices post 1559 need to be initialized
if call.GasPrice != nil && (call.GasFeeCap != nil || call.GasTipCap != nil) { if call.GasPrice != nil && (call.GasFeeCap != nil || call.GasTipCap != nil) {
return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified") return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
@ -635,20 +644,33 @@ func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallM
if call.Value == nil { if call.Value == nil {
call.Value = new(big.Int) call.Value = new(big.Int)
} }
// Set infinite balance to the fake caller account. // Set infinite balance to the fake caller account.
from := stateDB.GetOrNewStateObject(call.From) from := stateDB.GetOrNewStateObject(call.From)
from.SetBalance(math.MaxBig256) from.SetBalance(math.MaxBig256)
// Execute the call.
msg := callMsg{call}
txContext := core.NewEVMTxContext(msg) // Execute the call.
evmContext := core.NewEVMBlockContext(block.Header(), b.blockchain, nil) msg := &core.Message{
From: call.From,
To: call.To,
Value: call.Value,
GasLimit: call.Gas,
GasPrice: call.GasPrice,
GasFeeCap: call.GasFeeCap,
GasTipCap: call.GasTipCap,
Data: call.Data,
AccessList: call.AccessList,
SkipAccountChecks: true,
}
// Create a new environment which holds all relevant information // Create a new environment which holds all relevant information
// about the transaction and calling mechanisms. // about the transaction and calling mechanisms.
txContext := core.NewEVMTxContext(msg)
evmContext := core.NewEVMBlockContext(header, b.blockchain, nil)
vmEnv := vm.NewEVM(evmContext, txContext, stateDB, b.config, vm.Config{NoBaseFee: true}) vmEnv := vm.NewEVM(evmContext, txContext, stateDB, b.config, vm.Config{NoBaseFee: true})
gasPool := new(core.GasPool).AddGas(math.MaxUint64) gasPool := new(core.GasPool).AddGas(math.MaxUint64)
return core.NewStateTransition(vmEnv, msg, gasPool).TransitionDb() return core.ApplyMessage(vmEnv, msg, gasPool)
} }
// SendTransaction updates the pending block to include the given transaction. // SendTransaction updates the pending block to include the given transaction.
@ -790,8 +812,13 @@ func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error {
if len(b.pendingBlock.Transactions()) != 0 { if len(b.pendingBlock.Transactions()) != 0 {
return errors.New("Could not adjust time on non-empty block") return errors.New("Could not adjust time on non-empty block")
} }
// Get the last block
block := b.blockchain.GetBlockByHash(b.pendingBlock.ParentHash())
if block == nil {
return fmt.Errorf("could not find parent")
}
blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) { blocks, _ := core.GenerateChain(b.config, block, ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
block.OffsetTime(int64(adjustment.Seconds())) block.OffsetTime(int64(adjustment.Seconds()))
}) })
stateDB, _ := b.blockchain.State() stateDB, _ := b.blockchain.State()
@ -807,23 +834,6 @@ func (b *SimulatedBackend) Blockchain() *core.BlockChain {
return b.blockchain return b.blockchain
} }
// callMsg implements core.Message to allow passing it as a transaction simulator.
type callMsg struct {
ethereum.CallMsg
}
func (m callMsg) From() common.Address { return m.CallMsg.From }
func (m callMsg) Nonce() uint64 { return 0 }
func (m callMsg) IsFake() bool { return true }
func (m callMsg) To() *common.Address { return m.CallMsg.To }
func (m callMsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
func (m callMsg) GasFeeCap() *big.Int { return m.CallMsg.GasFeeCap }
func (m callMsg) GasTipCap() *big.Int { return m.CallMsg.GasTipCap }
func (m callMsg) Gas() uint64 { return m.CallMsg.Gas }
func (m callMsg) Value() *big.Int { return m.CallMsg.Value }
func (m callMsg) Data() []byte { return m.CallMsg.Data }
func (m callMsg) AccessList() types.AccessList { return m.CallMsg.AccessList }
// filterBackend implements filters.Backend to support filtering for logs without // filterBackend implements filters.Backend to support filtering for logs without
// taking bloom-bits acceleration structures into account. // taking bloom-bits acceleration structures into account.
type filterBackend struct { type filterBackend struct {
@ -836,17 +846,35 @@ func (fb *filterBackend) ChainDb() ethdb.Database { return fb.db }
func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") } func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") }
func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) { func (fb *filterBackend) HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error) {
if block == rpc.LatestBlockNumber { switch number {
case rpc.PendingBlockNumber:
if block := fb.backend.pendingBlock; block != nil {
return block.Header(), nil
}
return nil, nil
case rpc.LatestBlockNumber:
return fb.bc.CurrentHeader(), nil return fb.bc.CurrentHeader(), nil
case rpc.FinalizedBlockNumber:
return fb.bc.CurrentFinalBlock(), nil
case rpc.SafeBlockNumber:
return fb.bc.CurrentSafeBlock(), nil
default:
return fb.bc.GetHeaderByNumber(uint64(number.Int64())), nil
} }
return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil
} }
func (fb *filterBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { func (fb *filterBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
return fb.bc.GetHeaderByHash(hash), nil return fb.bc.GetHeaderByHash(hash), nil
} }
func (fb *filterBackend) GetBody(ctx context.Context, hash common.Hash, number rpc.BlockNumber) (*types.Body, error) {
if body := fb.bc.GetBody(hash); body != nil {
return body, nil
}
return nil, errors.New("block body not found")
}
func (fb *filterBackend) PendingBlockAndReceipts() (*types.Block, types.Receipts) { func (fb *filterBackend) PendingBlockAndReceipts() (*types.Block, types.Receipts) {
return fb.backend.pendingBlock, fb.backend.pendingReceipts return fb.backend.pendingBlock, fb.backend.pendingReceipts
} }
@ -890,6 +918,14 @@ func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.Matche
panic("not supported") panic("not supported")
} }
func (fb *filterBackend) ChainConfig() *params.ChainConfig {
panic("not supported")
}
func (fb *filterBackend) CurrentHeader() *types.Header {
panic("not supported")
}
func nullSubscription() event.Subscription { func nullSubscription() event.Subscription {
return event.NewSubscription(func(quit <-chan struct{}) error { return event.NewSubscription(func(quit <-chan struct{}) error {
<-quit <-quit

View File

@ -93,17 +93,18 @@ func TestSimulatedBackend(t *testing.T) {
var testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") var testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
// the following is based on this contract: // the following is based on this contract:
// contract T {
// event received(address sender, uint amount, bytes memo);
// event receivedAddr(address sender);
// //
// function receive(bytes calldata memo) external payable returns (string memory res) { // contract T {
// emit received(msg.sender, msg.value, memo); // event received(address sender, uint amount, bytes memo);
// emit receivedAddr(msg.sender); // event receivedAddr(address sender);
// return "hello world"; //
// } // function receive(bytes calldata memo) external payable returns (string memory res) {
// } // emit received(msg.sender, msg.value, memo);
// emit receivedAddr(msg.sender);
// return "hello world";
// }
// }
const abiJSON = `[ { "constant": false, "inputs": [ { "name": "memo", "type": "bytes" } ], "name": "receive", "outputs": [ { "name": "res", "type": "string" } ], "payable": true, "stateMutability": "payable", "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "sender", "type": "address" }, { "indexed": false, "name": "amount", "type": "uint256" }, { "indexed": false, "name": "memo", "type": "bytes" } ], "name": "received", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "sender", "type": "address" } ], "name": "receivedAddr", "type": "event" } ]` const abiJSON = `[ { "constant": false, "inputs": [ { "name": "memo", "type": "bytes" } ], "name": "receive", "outputs": [ { "name": "res", "type": "string" } ], "payable": true, "stateMutability": "payable", "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "sender", "type": "address" }, { "indexed": false, "name": "amount", "type": "uint256" }, { "indexed": false, "name": "memo", "type": "bytes" } ], "name": "received", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "sender", "type": "address" } ], "name": "receivedAddr", "type": "event" } ]`
const abiBin = `0x608060405234801561001057600080fd5b506102a0806100206000396000f3fe60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029` const abiBin = `0x608060405234801561001057600080fd5b506102a0806100206000396000f3fe60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029`
const deployedCode = `60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029` const deployedCode = `60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029`
@ -417,12 +418,13 @@ func TestEstimateGas(t *testing.T) {
/* /*
pragma solidity ^0.6.4; pragma solidity ^0.6.4;
contract GasEstimation { contract GasEstimation {
function PureRevert() public { revert(); } function PureRevert() public { revert(); }
function Revert() public { revert("revert reason");} function Revert() public { revert("revert reason");}
function OOG() public { for (uint i = 0; ; i++) {}} function OOG() public { for (uint i = 0; ; i++) {}}
function Assert() public { assert(false);} function Assert() public { assert(false);}
function Valid() public {} function Valid() public {}
}*/ }
*/
const contractAbi = "[{\"inputs\":[],\"name\":\"Assert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"OOG\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"PureRevert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"Revert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"Valid\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" const contractAbi = "[{\"inputs\":[],\"name\":\"Assert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"OOG\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"PureRevert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"Revert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"Valid\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"
const contractBin = "0x60806040523480156100115760006000fd5b50610017565b61016e806100266000396000f3fe60806040523480156100115760006000fd5b506004361061005c5760003560e01c806350f6fe3414610062578063aa8b1d301461006c578063b9b046f914610076578063d8b9839114610080578063e09fface1461008a5761005c565b60006000fd5b61006a610094565b005b6100746100ad565b005b61007e6100b5565b005b6100886100c2565b005b610092610135565b005b6000600090505b5b808060010191505061009b565b505b565b60006000fd5b565b600015156100bf57fe5b5b565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f72657665727420726561736f6e0000000000000000000000000000000000000081526020015060200191505060405180910390fd5b565b5b56fea2646970667358221220345bbcbb1a5ecf22b53a78eaebf95f8ee0eceff6d10d4b9643495084d2ec934a64736f6c63430006040033" const contractBin = "0x60806040523480156100115760006000fd5b50610017565b61016e806100266000396000f3fe60806040523480156100115760006000fd5b506004361061005c5760003560e01c806350f6fe3414610062578063aa8b1d301461006c578063b9b046f914610076578063d8b9839114610080578063e09fface1461008a5761005c565b60006000fd5b61006a610094565b005b6100746100ad565b005b61007e6100b5565b005b6100886100c2565b005b610092610135565b005b6000600090505b5b808060010191505061009b565b505b565b60006000fd5b565b600015156100bf57fe5b5b565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f72657665727420726561736f6e0000000000000000000000000000000000000081526020015060200191505060405180910390fd5b565b5b56fea2646970667358221220345bbcbb1a5ecf22b53a78eaebf95f8ee0eceff6d10d4b9643495084d2ec934a64736f6c63430006040033"
@ -994,7 +996,8 @@ func TestCodeAt(t *testing.T) {
} }
// When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt: // When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt:
// receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]} //
// receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]}
func TestPendingAndCallContract(t *testing.T) { func TestPendingAndCallContract(t *testing.T) {
testAddr := crypto.PubkeyToAddress(testKey.PublicKey) testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
sim := simTestBackend(testAddr) sim := simTestBackend(testAddr)
@ -1057,27 +1060,27 @@ func TestPendingAndCallContract(t *testing.T) {
// This test is based on the following contract: // This test is based on the following contract:
/* /*
contract Reverter { contract Reverter {
function revertString() public pure{ function revertString() public pure{
require(false, "some error"); require(false, "some error");
} }
function revertNoString() public pure { function revertNoString() public pure {
require(false, ""); require(false, "");
} }
function revertASM() public pure { function revertASM() public pure {
assembly { assembly {
revert(0x0, 0x0) revert(0x0, 0x0)
} }
} }
function noRevert() public pure { function noRevert() public pure {
assembly { assembly {
// Assembles something that looks like require(false, "some error") but is not reverted // Assembles something that looks like require(false, "some error") but is not reverted
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(0x4, 0x0000000000000000000000000000000000000000000000000000000000000020) mstore(0x4, 0x0000000000000000000000000000000000000000000000000000000000000020)
mstore(0x24, 0x000000000000000000000000000000000000000000000000000000000000000a) mstore(0x24, 0x000000000000000000000000000000000000000000000000000000000000000a)
mstore(0x44, 0x736f6d65206572726f7200000000000000000000000000000000000000000000) mstore(0x44, 0x736f6d65206572726f7200000000000000000000000000000000000000000000)
return(0x0, 0x64) return(0x0, 0x64)
} }
} }
}*/ }*/
func TestCallContractRevert(t *testing.T) { func TestCallContractRevert(t *testing.T) {
testAddr := crypto.PubkeyToAddress(testKey.PublicKey) testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
@ -1186,7 +1189,7 @@ func TestFork(t *testing.T) {
sim.Commit() sim.Commit()
} }
// 3. // 3.
if sim.blockchain.CurrentBlock().NumberU64() != uint64(n) { if sim.blockchain.CurrentBlock().Number.Uint64() != uint64(n) {
t.Error("wrong chain length") t.Error("wrong chain length")
} }
// 4. // 4.
@ -1196,7 +1199,7 @@ func TestFork(t *testing.T) {
sim.Commit() sim.Commit()
} }
// 6. // 6.
if sim.blockchain.CurrentBlock().NumberU64() != uint64(n+1) { if sim.blockchain.CurrentBlock().Number.Uint64() != uint64(n+1) {
t.Error("wrong chain length") t.Error("wrong chain length")
} }
} }
@ -1204,11 +1207,11 @@ func TestFork(t *testing.T) {
/* /*
Example contract to test event emission: Example contract to test event emission:
pragma solidity >=0.7.0 <0.9.0; pragma solidity >=0.7.0 <0.9.0;
contract Callable { contract Callable {
event Called(); event Called();
function Call() public { emit Called(); } function Call() public { emit Called(); }
} }
*/ */
const callableAbi = "[{\"anonymous\":false,\"inputs\":[],\"name\":\"Called\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"Call\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" const callableAbi = "[{\"anonymous\":false,\"inputs\":[],\"name\":\"Called\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"Call\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"
@ -1226,7 +1229,7 @@ const callableBin = "6080604052348015600f57600080fd5b5060998061001e6000396000f3f
// 7. Mine two blocks to trigger a reorg. // 7. Mine two blocks to trigger a reorg.
// 8. Check that the event was removed. // 8. Check that the event was removed.
// 9. Re-send the transaction and mine a block. // 9. Re-send the transaction and mine a block.
// 10. Check that the event was reborn. // 10. Check that the event was reborn.
func TestForkLogsReborn(t *testing.T) { func TestForkLogsReborn(t *testing.T) {
testAddr := crypto.PubkeyToAddress(testKey.PublicKey) testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
sim := simTestBackend(testAddr) sim := simTestBackend(testAddr)
@ -1341,7 +1344,7 @@ func TestCommitReturnValue(t *testing.T) {
sim := simTestBackend(testAddr) sim := simTestBackend(testAddr)
defer sim.Close() defer sim.Close()
startBlockHeight := sim.blockchain.CurrentBlock().NumberU64() startBlockHeight := sim.blockchain.CurrentBlock().Number.Uint64()
// Test if Commit returns the correct block hash // Test if Commit returns the correct block hash
h1 := sim.Commit() h1 := sim.Commit()
@ -1374,3 +1377,23 @@ func TestCommitReturnValue(t *testing.T) {
t.Error("Could not retrieve the just created block (side-chain)") t.Error("Could not retrieve the just created block (side-chain)")
} }
} }
// TestAdjustTimeAfterFork ensures that after a fork, AdjustTime uses the pending fork
// block's parent rather than the canonical head's parent.
func TestAdjustTimeAfterFork(t *testing.T) {
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
sim := simTestBackend(testAddr)
defer sim.Close()
sim.Commit() // h1
h1 := sim.blockchain.CurrentHeader().Hash()
sim.Commit() // h2
sim.Fork(context.Background(), h1)
sim.AdjustTime(1 * time.Second)
sim.Commit()
head := sim.blockchain.CurrentHeader()
if head.Number == common.Big2 && head.ParentHash != h1 {
t.Errorf("failed to build block on fork")
}
}

View File

@ -32,6 +32,13 @@ import (
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
) )
const basefeeWiggleMultiplier = 2
var (
errNoEventSignature = errors.New("no event signature")
errEventSignatureMismatch = errors.New("event signature mismatch")
)
// SignerFn is a signer function callback when a contract requires a method to // SignerFn is a signer function callback when a contract requires a method to
// sign the transaction before submission. // sign the transaction before submission.
type SignerFn func(common.Address, *types.Transaction) (*types.Transaction, error) type SignerFn func(common.Address, *types.Transaction) (*types.Transaction, error)
@ -254,7 +261,7 @@ func (c *BoundContract) createDynamicTx(opts *TransactOpts, contract *common.Add
if gasFeeCap == nil { if gasFeeCap == nil {
gasFeeCap = new(big.Int).Add( gasFeeCap = new(big.Int).Add(
gasTipCap, gasTipCap,
new(big.Int).Mul(head.BaseFee, big.NewInt(2)), new(big.Int).Mul(head.BaseFee, big.NewInt(basefeeWiggleMultiplier)),
) )
} }
if gasFeeCap.Cmp(gasTipCap) < 0 { if gasFeeCap.Cmp(gasTipCap) < 0 {
@ -371,6 +378,8 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i
) )
if opts.GasPrice != nil { if opts.GasPrice != nil {
rawTx, err = c.createLegacyTx(opts, contract, input) rawTx, err = c.createLegacyTx(opts, contract, input)
} else if opts.GasFeeCap != nil && opts.GasTipCap != nil {
rawTx, err = c.createDynamicTx(opts, contract, input, nil)
} else { } else {
// Only query for basefee if gasPrice not specified // Only query for basefee if gasPrice not specified
if head, errHead := c.transactor.HeaderByNumber(ensureContext(opts.Context), nil); errHead != nil { if head, errHead := c.transactor.HeaderByNumber(ensureContext(opts.Context), nil); errHead != nil {
@ -484,8 +493,12 @@ func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]inter
// UnpackLog unpacks a retrieved log into the provided output structure. // UnpackLog unpacks a retrieved log into the provided output structure.
func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error { func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
// Anonymous events are not supported.
if len(log.Topics) == 0 {
return errNoEventSignature
}
if log.Topics[0] != c.abi.Events[event].ID { if log.Topics[0] != c.abi.Events[event].ID {
return fmt.Errorf("event signature mismatch") return errEventSignatureMismatch
} }
if len(log.Data) > 0 { if len(log.Data) > 0 {
if err := c.abi.UnpackIntoInterface(out, event, log.Data); err != nil { if err := c.abi.UnpackIntoInterface(out, event, log.Data); err != nil {
@ -503,8 +516,12 @@ func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log)
// UnpackLogIntoMap unpacks a retrieved log into the provided map. // UnpackLogIntoMap unpacks a retrieved log into the provided map.
func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error { func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error {
// Anonymous events are not supported.
if len(log.Topics) == 0 {
return errNoEventSignature
}
if log.Topics[0] != c.abi.Events[event].ID { if log.Topics[0] != c.abi.Events[event].ID {
return fmt.Errorf("event signature mismatch") return errEventSignatureMismatch
} }
if len(log.Data) > 0 { if len(log.Data) > 0 {
if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil { if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {

View File

@ -186,6 +186,23 @@ func TestUnpackIndexedStringTyLogIntoMap(t *testing.T) {
unpackAndCheck(t, bc, expectedReceivedMap, mockLog) unpackAndCheck(t, bc, expectedReceivedMap, mockLog)
} }
func TestUnpackAnonymousLogIntoMap(t *testing.T) {
mockLog := newMockLog(nil, common.HexToHash("0x0"))
abiString := `[{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"received","type":"event"}]`
parsedAbi, _ := abi.JSON(strings.NewReader(abiString))
bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil)
var received map[string]interface{}
err := bc.UnpackLogIntoMap(received, "received", mockLog)
if err == nil {
t.Error("unpacking anonymous event is not supported")
}
if err.Error() != "no event signature" {
t.Errorf("expected error 'no event signature', got '%s'", err)
}
}
func TestUnpackIndexedSliceTyLogIntoMap(t *testing.T) { func TestUnpackIndexedSliceTyLogIntoMap(t *testing.T) {
sliceBytes, err := rlp.EncodeToBytes([]string{"name1", "name2", "name3", "name4"}) sliceBytes, err := rlp.EncodeToBytes([]string{"name1", "name2", "name3", "name4"})
if err != nil { if err != nil {

View File

@ -22,7 +22,6 @@ package bind
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"go/format" "go/format"
"regexp" "regexp"
@ -39,8 +38,6 @@ type Lang int
const ( const (
LangGo Lang = iota LangGo Lang = iota
LangJava
LangObjC
) )
func isKeyWord(arg string) bool { func isKeyWord(arg string) bool {
@ -221,11 +218,6 @@ func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string]
if evmABI.HasReceive() { if evmABI.HasReceive() {
receive = &tmplMethod{Original: evmABI.Receive} receive = &tmplMethod{Original: evmABI.Receive}
} }
// There is no easy way to pass arbitrary java objects to the Go side.
if len(structs) > 0 && lang == LangJava {
return "", errors.New("java binding for tuple arguments is not supported yet")
}
contracts[types[i]] = &tmplContract{ contracts[types[i]] = &tmplContract{
Type: capitalise(types[i]), Type: capitalise(types[i]),
InputABI: strings.ReplaceAll(strippedABI, "\"", "\\\""), InputABI: strings.ReplaceAll(strippedABI, "\"", "\\\""),
@ -298,8 +290,7 @@ func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string]
// bindType is a set of type binders that convert Solidity types to some supported // bindType is a set of type binders that convert Solidity types to some supported
// programming language types. // programming language types.
var bindType = map[Lang]func(kind abi.Type, structs map[string]*tmplStruct) string{ var bindType = map[Lang]func(kind abi.Type, structs map[string]*tmplStruct) string{
LangGo: bindTypeGo, LangGo: bindTypeGo,
LangJava: bindTypeJava,
} }
// bindBasicTypeGo converts basic solidity types(except array, slice and tuple) to Go ones. // bindBasicTypeGo converts basic solidity types(except array, slice and tuple) to Go ones.
@ -342,86 +333,10 @@ func bindTypeGo(kind abi.Type, structs map[string]*tmplStruct) string {
} }
} }
// bindBasicTypeJava converts basic solidity types(except array, slice and tuple) to Java ones.
func bindBasicTypeJava(kind abi.Type) string {
switch kind.T {
case abi.AddressTy:
return "Address"
case abi.IntTy, abi.UintTy:
// Note that uint and int (without digits) are also matched,
// these are size 256, and will translate to BigInt (the default).
parts := regexp.MustCompile(`(u)?int([0-9]*)`).FindStringSubmatch(kind.String())
if len(parts) != 3 {
return kind.String()
}
// All unsigned integers should be translated to BigInt since gomobile doesn't
// support them.
if parts[1] == "u" {
return "BigInt"
}
namedSize := map[string]string{
"8": "byte",
"16": "short",
"32": "int",
"64": "long",
}[parts[2]]
// default to BigInt
if namedSize == "" {
namedSize = "BigInt"
}
return namedSize
case abi.FixedBytesTy, abi.BytesTy:
return "byte[]"
case abi.BoolTy:
return "boolean"
case abi.StringTy:
return "String"
case abi.FunctionTy:
return "byte[24]"
default:
return kind.String()
}
}
// pluralizeJavaType explicitly converts multidimensional types to predefined
// types in go side.
func pluralizeJavaType(typ string) string {
switch typ {
case "boolean":
return "Bools"
case "String":
return "Strings"
case "Address":
return "Addresses"
case "byte[]":
return "Binaries"
case "BigInt":
return "BigInts"
}
return typ + "[]"
}
// bindTypeJava converts a Solidity type to a Java one. Since there is no clear mapping
// from all Solidity types to Java ones (e.g. uint17), those that cannot be exactly
// mapped will use an upscaled type (e.g. BigDecimal).
func bindTypeJava(kind abi.Type, structs map[string]*tmplStruct) string {
switch kind.T {
case abi.TupleTy:
return structs[kind.TupleRawName+kind.String()].Name
case abi.ArrayTy, abi.SliceTy:
return pluralizeJavaType(bindTypeJava(*kind.Elem, structs))
default:
return bindBasicTypeJava(kind)
}
}
// bindTopicType is a set of type binders that convert Solidity types to some // bindTopicType is a set of type binders that convert Solidity types to some
// supported programming language topic types. // supported programming language topic types.
var bindTopicType = map[Lang]func(kind abi.Type, structs map[string]*tmplStruct) string{ var bindTopicType = map[Lang]func(kind abi.Type, structs map[string]*tmplStruct) string{
LangGo: bindTopicTypeGo, LangGo: bindTopicTypeGo,
LangJava: bindTopicTypeJava,
} }
// bindTopicTypeGo converts a Solidity topic type to a Go one. It is almost the same // bindTopicTypeGo converts a Solidity topic type to a Go one. It is almost the same
@ -441,28 +356,10 @@ func bindTopicTypeGo(kind abi.Type, structs map[string]*tmplStruct) string {
return bound return bound
} }
// bindTopicTypeJava converts a Solidity topic type to a Java one. It is almost the same
// functionality as for simple types, but dynamic types get converted to hashes.
func bindTopicTypeJava(kind abi.Type, structs map[string]*tmplStruct) string {
bound := bindTypeJava(kind, structs)
// todo(rjl493456442) according solidity documentation, indexed event
// parameters that are not value types i.e. arrays and structs are not
// stored directly but instead a keccak256-hash of an encoding is stored.
//
// We only convert strings and bytes to hash, still need to deal with
// array(both fixed-size and dynamic-size) and struct.
if bound == "String" || bound == "byte[]" {
bound = "Hash"
}
return bound
}
// bindStructType is a set of type binders that convert Solidity tuple types to some supported // bindStructType is a set of type binders that convert Solidity tuple types to some supported
// programming language struct definition. // programming language struct definition.
var bindStructType = map[Lang]func(kind abi.Type, structs map[string]*tmplStruct) string{ var bindStructType = map[Lang]func(kind abi.Type, structs map[string]*tmplStruct) string{
LangGo: bindStructTypeGo, LangGo: bindStructTypeGo,
LangJava: bindStructTypeJava,
} }
// bindStructTypeGo converts a Solidity tuple type to a Go one and records the mapping // bindStructTypeGo converts a Solidity tuple type to a Go one and records the mapping
@ -511,74 +408,10 @@ func bindStructTypeGo(kind abi.Type, structs map[string]*tmplStruct) string {
} }
} }
// bindStructTypeJava converts a Solidity tuple type to a Java one and records the mapping
// in the given map.
// Notably, this function will resolve and record nested struct recursively.
func bindStructTypeJava(kind abi.Type, structs map[string]*tmplStruct) string {
switch kind.T {
case abi.TupleTy:
// We compose a raw struct name and a canonical parameter expression
// together here. The reason is before solidity v0.5.11, kind.TupleRawName
// is empty, so we use canonical parameter expression to distinguish
// different struct definition. From the consideration of backward
// compatibility, we concat these two together so that if kind.TupleRawName
// is not empty, it can have unique id.
id := kind.TupleRawName + kind.String()
if s, exist := structs[id]; exist {
return s.Name
}
var fields []*tmplField
for i, elem := range kind.TupleElems {
field := bindStructTypeJava(*elem, structs)
fields = append(fields, &tmplField{Type: field, Name: decapitalise(kind.TupleRawNames[i]), SolKind: *elem})
}
name := kind.TupleRawName
if name == "" {
name = fmt.Sprintf("Class%d", len(structs))
}
structs[id] = &tmplStruct{
Name: name,
Fields: fields,
}
return name
case abi.ArrayTy, abi.SliceTy:
return pluralizeJavaType(bindStructTypeJava(*kind.Elem, structs))
default:
return bindBasicTypeJava(kind)
}
}
// namedType is a set of functions that transform language specific types to // namedType is a set of functions that transform language specific types to
// named versions that may be used inside method names. // named versions that may be used inside method names.
var namedType = map[Lang]func(string, abi.Type) string{ var namedType = map[Lang]func(string, abi.Type) string{
LangGo: func(string, abi.Type) string { panic("this shouldn't be needed") }, LangGo: func(string, abi.Type) string { panic("this shouldn't be needed") },
LangJava: namedTypeJava,
}
// namedTypeJava converts some primitive data types to named variants that can
// be used as parts of method names.
func namedTypeJava(javaKind string, solKind abi.Type) string {
switch javaKind {
case "byte[]":
return "Binary"
case "boolean":
return "Bool"
default:
parts := regexp.MustCompile(`(u)?int([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(solKind.String())
if len(parts) != 4 {
return javaKind
}
switch parts[2] {
case "8", "16", "32", "64":
if parts[3] == "" {
return capitalise(fmt.Sprintf("%sint%s", parts[1], parts[2]))
}
return capitalise(fmt.Sprintf("%sint%ss", parts[1], parts[2]))
default:
return javaKind
}
}
} }
// alias returns an alias of the given string based on the aliasing rules // alias returns an alias of the given string based on the aliasing rules
@ -593,8 +426,7 @@ func alias(aliases map[string]string, n string) string {
// methodNormalizer is a name transformer that modifies Solidity method names to // methodNormalizer is a name transformer that modifies Solidity method names to
// conform to target language naming conventions. // conform to target language naming conventions.
var methodNormalizer = map[Lang]func(string) string{ var methodNormalizer = map[Lang]func(string) string{
LangGo: abi.ToCamelCase, LangGo: abi.ToCamelCase,
LangJava: decapitalise,
} }
// capitalise makes a camel-case string which starts with an upper case character. // capitalise makes a camel-case string which starts with an upper case character.

File diff suppressed because one or more lines are too long

View File

@ -75,8 +75,7 @@ type tmplStruct struct {
// tmplSource is language to template mapping containing all the supported // tmplSource is language to template mapping containing all the supported
// programming languages the package can generate to. // programming languages the package can generate to.
var tmplSource = map[Lang]string{ var tmplSource = map[Lang]string{
LangGo: tmplSourceGo, LangGo: tmplSourceGo,
LangJava: tmplSourceJava,
} }
// tmplSourceGo is the Go source template that the generated Go contract binding // tmplSourceGo is the Go source template that the generated Go contract binding
@ -110,6 +109,7 @@ var (
_ = common.Big1 _ = common.Big1
_ = types.BloomLookup _ = types.BloomLookup
_ = event.NewSubscription _ = event.NewSubscription
_ = abi.ConvertType
) )
{{$structs := .Structs}} {{$structs := .Structs}}
@ -268,11 +268,11 @@ var (
// bind{{.Type}} binds a generic wrapper to an already deployed contract. // bind{{.Type}} binds a generic wrapper to an already deployed contract.
func bind{{.Type}}(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { func bind{{.Type}}(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {
parsed, err := abi.JSON(strings.NewReader({{.Type}}ABI)) parsed, err := {{.Type}}MetaData.GetAbi()
if err != nil { if err != nil {
return nil, err return nil, err
} }
return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil
} }
// Call invokes the (constant) contract method with params as input values and // Call invokes the (constant) contract method with params as input values and
@ -569,140 +569,3 @@ var (
{{end}} {{end}}
{{end}} {{end}}
` `
// tmplSourceJava is the Java source template that the generated Java contract binding
// is based on.
const tmplSourceJava = `
// This file is an automatically generated Java binding. Do not modify as any
// change will likely be lost upon the next re-generation!
package {{.Package}};
import org.ethereum.geth.*;
import java.util.*;
{{$structs := .Structs}}
{{range $contract := .Contracts}}
{{if not .Library}}public {{end}}class {{.Type}} {
// ABI is the input ABI used to generate the binding from.
public final static String ABI = "{{.InputABI}}";
{{if $contract.FuncSigs}}
// {{.Type}}FuncSigs maps the 4-byte function signature to its string representation.
public final static Map<String, String> {{.Type}}FuncSigs;
static {
Hashtable<String, String> temp = new Hashtable<String, String>();
{{range $strsig, $binsig := .FuncSigs}}temp.put("{{$binsig}}", "{{$strsig}}");
{{end}}
{{.Type}}FuncSigs = Collections.unmodifiableMap(temp);
}
{{end}}
{{if .InputBin}}
// BYTECODE is the compiled bytecode used for deploying new contracts.
public final static String BYTECODE = "0x{{.InputBin}}";
// deploy deploys a new Ethereum contract, binding an instance of {{.Type}} to it.
public static {{.Type}} deploy(TransactOpts auth, EthereumClient client{{range .Constructor.Inputs}}, {{bindtype .Type $structs}} {{.Name}}{{end}}) throws Exception {
Interfaces args = Geth.newInterfaces({{(len .Constructor.Inputs)}});
String bytecode = BYTECODE;
{{if .Libraries}}
// "link" contract to dependent libraries by deploying them first.
{{range $pattern, $name := .Libraries}}
{{capitalise $name}} {{decapitalise $name}}Inst = {{capitalise $name}}.deploy(auth, client);
bytecode = bytecode.replace("__${{$pattern}}$__", {{decapitalise $name}}Inst.Address.getHex().substring(2));
{{end}}
{{end}}
{{range $index, $element := .Constructor.Inputs}}Interface arg{{$index}} = Geth.newInterface();arg{{$index}}.set{{namedtype (bindtype .Type $structs) .Type}}({{.Name}});args.set({{$index}},arg{{$index}});
{{end}}
return new {{.Type}}(Geth.deployContract(auth, ABI, Geth.decodeFromHex(bytecode), client, args));
}
// Internal constructor used by contract deployment.
private {{.Type}}(BoundContract deployment) {
this.Address = deployment.getAddress();
this.Deployer = deployment.getDeployer();
this.Contract = deployment;
}
{{end}}
// Ethereum address where this contract is located at.
public final Address Address;
// Ethereum transaction in which this contract was deployed (if known!).
public final Transaction Deployer;
// Contract instance bound to a blockchain address.
private final BoundContract Contract;
// Creates a new instance of {{.Type}}, bound to a specific deployed contract.
public {{.Type}}(Address address, EthereumClient client) throws Exception {
this(Geth.bindContract(address, ABI, client));
}
{{range .Calls}}
{{if gt (len .Normalized.Outputs) 1}}
// {{capitalise .Normalized.Name}}Results is the output of a call to {{.Normalized.Name}}.
public class {{capitalise .Normalized.Name}}Results {
{{range $index, $item := .Normalized.Outputs}}public {{bindtype .Type $structs}} {{if ne .Name ""}}{{.Name}}{{else}}Return{{$index}}{{end}};
{{end}}
}
{{end}}
// {{.Normalized.Name}} is a free data retrieval call binding the contract method 0x{{printf "%x" .Original.ID}}.
//
// Solidity: {{.Original.String}}
public {{if gt (len .Normalized.Outputs) 1}}{{capitalise .Normalized.Name}}Results{{else if eq (len .Normalized.Outputs) 0}}void{{else}}{{range .Normalized.Outputs}}{{bindtype .Type $structs}}{{end}}{{end}} {{.Normalized.Name}}(CallOpts opts{{range .Normalized.Inputs}}, {{bindtype .Type $structs}} {{.Name}}{{end}}) throws Exception {
Interfaces args = Geth.newInterfaces({{(len .Normalized.Inputs)}});
{{range $index, $item := .Normalized.Inputs}}Interface arg{{$index}} = Geth.newInterface();arg{{$index}}.set{{namedtype (bindtype .Type $structs) .Type}}({{.Name}});args.set({{$index}},arg{{$index}});
{{end}}
Interfaces results = Geth.newInterfaces({{(len .Normalized.Outputs)}});
{{range $index, $item := .Normalized.Outputs}}Interface result{{$index}} = Geth.newInterface(); result{{$index}}.setDefault{{namedtype (bindtype .Type $structs) .Type}}(); results.set({{$index}}, result{{$index}});
{{end}}
if (opts == null) {
opts = Geth.newCallOpts();
}
this.Contract.call(opts, results, "{{.Original.Name}}", args);
{{if gt (len .Normalized.Outputs) 1}}
{{capitalise .Normalized.Name}}Results result = new {{capitalise .Normalized.Name}}Results();
{{range $index, $item := .Normalized.Outputs}}result.{{if ne .Name ""}}{{.Name}}{{else}}Return{{$index}}{{end}} = results.get({{$index}}).get{{namedtype (bindtype .Type $structs) .Type}}();
{{end}}
return result;
{{else}}{{range .Normalized.Outputs}}return results.get(0).get{{namedtype (bindtype .Type $structs) .Type}}();{{end}}
{{end}}
}
{{end}}
{{range .Transacts}}
// {{.Normalized.Name}} is a paid mutator transaction binding the contract method 0x{{printf "%x" .Original.ID}}.
//
// Solidity: {{.Original.String}}
public Transaction {{.Normalized.Name}}(TransactOpts opts{{range .Normalized.Inputs}}, {{bindtype .Type $structs}} {{.Name}}{{end}}) throws Exception {
Interfaces args = Geth.newInterfaces({{(len .Normalized.Inputs)}});
{{range $index, $item := .Normalized.Inputs}}Interface arg{{$index}} = Geth.newInterface();arg{{$index}}.set{{namedtype (bindtype .Type $structs) .Type}}({{.Name}});args.set({{$index}},arg{{$index}});
{{end}}
return this.Contract.transact(opts, "{{.Original.Name}}" , args);
}
{{end}}
{{if .Fallback}}
// Fallback is a paid mutator transaction binding the contract fallback function.
//
// Solidity: {{.Fallback.Original.String}}
public Transaction Fallback(TransactOpts opts, byte[] calldata) throws Exception {
return this.Contract.rawTransact(opts, calldata);
}
{{end}}
{{if .Receive}}
// Receive is a paid mutator transaction binding the contract receive function.
//
// Solidity: {{.Receive.Original.String}}
public Transaction Receive(TransactOpts opts) throws Exception {
return this.Contract.rawTransact(opts, null);
}
{{end}}
}
{{end}}
`

View File

@ -23,7 +23,15 @@ import (
) )
var ( var (
errBadBool = errors.New("abi: improperly encoded boolean value") errBadBool = errors.New("abi: improperly encoded boolean value")
errBadUint8 = errors.New("abi: improperly encoded uint8 value")
errBadUint16 = errors.New("abi: improperly encoded uint16 value")
errBadUint32 = errors.New("abi: improperly encoded uint32 value")
errBadUint64 = errors.New("abi: improperly encoded uint64 value")
errBadInt8 = errors.New("abi: improperly encoded int8 value")
errBadInt16 = errors.New("abi: improperly encoded int16 value")
errBadInt32 = errors.New("abi: improperly encoded int32 value")
errBadInt64 = errors.New("abi: improperly encoded int64 value")
) )
// formatSliceString formats the reflection kind with the given slice size // formatSliceString formats the reflection kind with the given slice size

View File

@ -25,16 +25,19 @@ import (
) )
// ConvertType converts an interface of a runtime type into a interface of the // ConvertType converts an interface of a runtime type into a interface of the
// given type // given type, e.g. turn this code:
// e.g. turn //
// var fields []reflect.StructField // var fields []reflect.StructField
// fields = append(fields, reflect.StructField{ //
// Name: "X", // fields = append(fields, reflect.StructField{
// Type: reflect.TypeOf(new(big.Int)), // Name: "X",
// Tag: reflect.StructTag("json:\"" + "x" + "\""), // Type: reflect.TypeOf(new(big.Int)),
// } // Tag: reflect.StructTag("json:\"" + "x" + "\""),
// into // }
// type TupleT struct { X *big.Int } //
// into:
//
// type TupleT struct { X *big.Int }
func ConvertType(in interface{}, proto interface{}) interface{} { func ConvertType(in interface{}, proto interface{}) interface{} {
protoType := reflect.TypeOf(proto) protoType := reflect.TypeOf(proto)
if reflect.TypeOf(in).ConvertibleTo(protoType) { if reflect.TypeOf(in).ConvertibleTo(protoType) {
@ -170,11 +173,13 @@ func setStruct(dst, src reflect.Value) error {
} }
// mapArgNamesToStructFields maps a slice of argument names to struct fields. // mapArgNamesToStructFields maps a slice of argument names to struct fields.
// first round: for each Exportable field that contains a `abi:""` tag //
// and this field name exists in the given argument name list, pair them together. // first round: for each Exportable field that contains a `abi:""` tag and this field name
// second round: for each argument name that has not been already linked, // exists in the given argument name list, pair them together.
// find what variable is expected to be mapped into, if it exists and has not been //
// used, pair them. // second round: for each argument name that has not been already linked, find what
// variable is expected to be mapped into, if it exists and has not been used, pair them.
//
// Note this function assumes the given value is a struct value. // Note this function assumes the given value is a struct value.
func mapArgNamesToStructFields(argNames []string, value reflect.Value) (map[string]string, error) { func mapArgNamesToStructFields(argNames []string, value reflect.Value) (map[string]string, error) {
typ := value.Type() typ := value.Type()

View File

@ -154,6 +154,9 @@ func NewType(t string, internalType string, components []ArgumentMarshaling) (ty
if varSize == 0 { if varSize == 0 {
typ.T = BytesTy typ.T = BytesTy
} else { } else {
if varSize > 32 {
return Type{}, fmt.Errorf("unsupported arg type: %s", t)
}
typ.T = FixedBytesTy typ.T = FixedBytesTy
typ.Size = varSize typ.Size = varSize
} }

View File

@ -366,3 +366,10 @@ func TestGetTypeSize(t *testing.T) {
} }
} }
} }
func TestNewFixedBytesOver32(t *testing.T) {
_, err := NewType("bytes4096", "", nil)
if err == nil {
t.Errorf("fixed bytes with size over 32 is not spec'd")
}
}

View File

@ -19,6 +19,7 @@ package abi
import ( import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"math"
"math/big" "math/big"
"reflect" "reflect"
@ -33,43 +34,72 @@ var (
) )
// ReadInteger reads the integer based on its kind and returns the appropriate value. // ReadInteger reads the integer based on its kind and returns the appropriate value.
func ReadInteger(typ Type, b []byte) interface{} { func ReadInteger(typ Type, b []byte) (interface{}, error) {
ret := new(big.Int).SetBytes(b)
if typ.T == UintTy { if typ.T == UintTy {
u64, isu64 := ret.Uint64(), ret.IsUint64()
switch typ.Size { switch typ.Size {
case 8: case 8:
return b[len(b)-1] if !isu64 || u64 > math.MaxUint8 {
return nil, errBadUint8
}
return byte(u64), nil
case 16: case 16:
return binary.BigEndian.Uint16(b[len(b)-2:]) if !isu64 || u64 > math.MaxUint16 {
return nil, errBadUint16
}
return uint16(u64), nil
case 32: case 32:
return binary.BigEndian.Uint32(b[len(b)-4:]) if !isu64 || u64 > math.MaxUint32 {
return nil, errBadUint32
}
return uint32(u64), nil
case 64: case 64:
return binary.BigEndian.Uint64(b[len(b)-8:]) if !isu64 {
return nil, errBadUint64
}
return u64, nil
default: default:
// the only case left for unsigned integer is uint256. // the only case left for unsigned integer is uint256.
return new(big.Int).SetBytes(b) return ret, nil
} }
} }
// big.SetBytes can't tell if a number is negative or positive in itself.
// On EVM, if the returned number > max int256, it is negative.
// A number is > max int256 if the bit at position 255 is set.
if ret.Bit(255) == 1 {
ret.Add(MaxUint256, new(big.Int).Neg(ret))
ret.Add(ret, common.Big1)
ret.Neg(ret)
}
i64, isi64 := ret.Int64(), ret.IsInt64()
switch typ.Size { switch typ.Size {
case 8: case 8:
return int8(b[len(b)-1]) if !isi64 || i64 < math.MinInt8 || i64 > math.MaxInt8 {
return nil, errBadInt8
}
return int8(i64), nil
case 16: case 16:
return int16(binary.BigEndian.Uint16(b[len(b)-2:])) if !isi64 || i64 < math.MinInt16 || i64 > math.MaxInt16 {
return nil, errBadInt16
}
return int16(i64), nil
case 32: case 32:
return int32(binary.BigEndian.Uint32(b[len(b)-4:])) if !isi64 || i64 < math.MinInt32 || i64 > math.MaxInt32 {
return nil, errBadInt32
}
return int32(i64), nil
case 64: case 64:
return int64(binary.BigEndian.Uint64(b[len(b)-8:])) if !isi64 {
return nil, errBadInt64
}
return i64, nil
default: default:
// the only case left for integer is int256 // the only case left for integer is int256
// big.SetBytes can't tell if a number is negative or positive in itself.
// On EVM, if the returned number > max int256, it is negative. return ret, nil
// A number is > max int256 if the bit at position 255 is set.
ret := new(big.Int).SetBytes(b)
if ret.Bit(255) == 1 {
ret.Add(MaxUint256, new(big.Int).Neg(ret))
ret.Add(ret, common.Big1)
ret.Neg(ret)
}
return ret
} }
} }
@ -123,7 +153,7 @@ func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error)
return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size) return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size)
} }
if start+32*size > len(output) { if start+32*size > len(output) {
return nil, fmt.Errorf("abi: cannot marshal in to go array: offset %d would go over slice boundary (len=%d)", len(output), start+32*size) return nil, fmt.Errorf("abi: cannot marshal into go array: offset %d would go over slice boundary (len=%d)", len(output), start+32*size)
} }
// this value will become our slice or our array, depending on the type // this value will become our slice or our array, depending on the type
@ -162,6 +192,9 @@ func forTupleUnpack(t Type, output []byte) (interface{}, error) {
virtualArgs := 0 virtualArgs := 0
for index, elem := range t.TupleElems { for index, elem := range t.TupleElems {
marshalledValue, err := toGoType((index+virtualArgs)*32, *elem, output) marshalledValue, err := toGoType((index+virtualArgs)*32, *elem, output)
if err != nil {
return nil, err
}
if elem.T == ArrayTy && !isDynamicType(*elem) { if elem.T == ArrayTy && !isDynamicType(*elem) {
// If we have a static array, like [3]uint256, these are coded as // If we have a static array, like [3]uint256, these are coded as
// just like uint256,uint256,uint256. // just like uint256,uint256,uint256.
@ -179,9 +212,6 @@ func forTupleUnpack(t Type, output []byte) (interface{}, error) {
// coded as just like uint256,bool,uint256 // coded as just like uint256,bool,uint256
virtualArgs += getTypeSize(*elem)/32 - 1 virtualArgs += getTypeSize(*elem)/32 - 1
} }
if err != nil {
return nil, err
}
retval.Field(index).Set(reflect.ValueOf(marshalledValue)) retval.Field(index).Set(reflect.ValueOf(marshalledValue))
} }
return retval.Interface(), nil return retval.Interface(), nil
@ -234,7 +264,7 @@ func toGoType(index int, t Type, output []byte) (interface{}, error) {
case StringTy: // variable arrays are written at the end of the return bytes case StringTy: // variable arrays are written at the end of the return bytes
return string(output[begin : begin+length]), nil return string(output[begin : begin+length]), nil
case IntTy, UintTy: case IntTy, UintTy:
return ReadInteger(t, returnOutput), nil return ReadInteger(t, returnOutput)
case BoolTy: case BoolTy:
return readBool(returnOutput) return readBool(returnOutput)
case AddressTy: case AddressTy:

View File

@ -20,6 +20,7 @@ import (
"bytes" "bytes"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"math"
"math/big" "math/big"
"reflect" "reflect"
"strconv" "strconv"
@ -943,3 +944,164 @@ func TestOOMMaliciousInput(t *testing.T) {
} }
} }
} }
func TestPackAndUnpackIncompatibleNumber(t *testing.T) {
var encodeABI Arguments
uint256Ty, err := NewType("uint256", "", nil)
if err != nil {
panic(err)
}
encodeABI = Arguments{
{Type: uint256Ty},
}
maxU64, ok := new(big.Int).SetString(strconv.FormatUint(math.MaxUint64, 10), 10)
if !ok {
panic("bug")
}
maxU64Plus1 := new(big.Int).Add(maxU64, big.NewInt(1))
cases := []struct {
decodeType string
inputValue *big.Int
err error
expectValue interface{}
}{
{
decodeType: "uint8",
inputValue: big.NewInt(math.MaxUint8 + 1),
err: errBadUint8,
},
{
decodeType: "uint8",
inputValue: big.NewInt(math.MaxUint8),
err: nil,
expectValue: uint8(math.MaxUint8),
},
{
decodeType: "uint16",
inputValue: big.NewInt(math.MaxUint16 + 1),
err: errBadUint16,
},
{
decodeType: "uint16",
inputValue: big.NewInt(math.MaxUint16),
err: nil,
expectValue: uint16(math.MaxUint16),
},
{
decodeType: "uint32",
inputValue: big.NewInt(math.MaxUint32 + 1),
err: errBadUint32,
},
{
decodeType: "uint32",
inputValue: big.NewInt(math.MaxUint32),
err: nil,
expectValue: uint32(math.MaxUint32),
},
{
decodeType: "uint64",
inputValue: maxU64Plus1,
err: errBadUint64,
},
{
decodeType: "uint64",
inputValue: maxU64,
err: nil,
expectValue: uint64(math.MaxUint64),
},
{
decodeType: "uint256",
inputValue: maxU64Plus1,
err: nil,
expectValue: maxU64Plus1,
},
{
decodeType: "int8",
inputValue: big.NewInt(math.MaxInt8 + 1),
err: errBadInt8,
},
{
decodeType: "int8",
inputValue: big.NewInt(math.MinInt8 - 1),
err: errBadInt8,
},
{
decodeType: "int8",
inputValue: big.NewInt(math.MaxInt8),
err: nil,
expectValue: int8(math.MaxInt8),
},
{
decodeType: "int16",
inputValue: big.NewInt(math.MaxInt16 + 1),
err: errBadInt16,
},
{
decodeType: "int16",
inputValue: big.NewInt(math.MinInt16 - 1),
err: errBadInt16,
},
{
decodeType: "int16",
inputValue: big.NewInt(math.MaxInt16),
err: nil,
expectValue: int16(math.MaxInt16),
},
{
decodeType: "int32",
inputValue: big.NewInt(math.MaxInt32 + 1),
err: errBadInt32,
},
{
decodeType: "int32",
inputValue: big.NewInt(math.MinInt32 - 1),
err: errBadInt32,
},
{
decodeType: "int32",
inputValue: big.NewInt(math.MaxInt32),
err: nil,
expectValue: int32(math.MaxInt32),
},
{
decodeType: "int64",
inputValue: new(big.Int).Add(big.NewInt(math.MaxInt64), big.NewInt(1)),
err: errBadInt64,
},
{
decodeType: "int64",
inputValue: new(big.Int).Sub(big.NewInt(math.MinInt64), big.NewInt(1)),
err: errBadInt64,
},
{
decodeType: "int64",
inputValue: big.NewInt(math.MaxInt64),
err: nil,
expectValue: int64(math.MaxInt64),
},
}
for i, testCase := range cases {
packed, err := encodeABI.Pack(testCase.inputValue)
if err != nil {
panic(err)
}
ty, err := NewType(testCase.decodeType, "", nil)
if err != nil {
panic(err)
}
decodeABI := Arguments{
{Type: ty},
}
decoded, err := decodeABI.Unpack(packed)
if err != testCase.err {
t.Fatalf("Expected error %v, actual error %v. case %d", testCase.err, err, i)
}
if err != nil {
continue
}
if !reflect.DeepEqual(decoded[0], testCase.expectValue) {
t.Fatalf("Expected value %v, actual value %v", testCase.expectValue, decoded[0])
}
}
}

View File

@ -21,15 +21,14 @@ import "fmt"
// ResolveNameConflict returns the next available name for a given thing. // ResolveNameConflict returns the next available name for a given thing.
// This helper can be used for lots of purposes: // This helper can be used for lots of purposes:
// //
// - In solidity function overloading is supported, this function can fix // - In solidity function overloading is supported, this function can fix
// the name conflicts of overloaded functions. // the name conflicts of overloaded functions.
// - In golang binding generation, the parameter(in function, event, error, // - In golang binding generation, the parameter(in function, event, error,
// and struct definition) name will be converted to camelcase style which // and struct definition) name will be converted to camelcase style which
// may eventually lead to name conflicts. // may eventually lead to name conflicts.
// //
// Name conflicts are mostly resolved by adding number suffix. // Name conflicts are mostly resolved by adding number suffix. e.g. if the abi contains
// e.g. if the abi contains Methods send, send1 // Methods "send" and "send1", ResolveNameConflict would return "send2" for input "send".
// ResolveNameConflict would return send2 for input send.
func ResolveNameConflict(rawName string, used func(string) bool) string { func ResolveNameConflict(rawName string, used func(string) bool) string {
name := rawName name := rawName
ok := used(name) ok := used(name)

View File

@ -177,7 +177,8 @@ type Backend interface {
// safely used to calculate a signature from. // safely used to calculate a signature from.
// //
// The hash is calculated as // The hash is calculated as
// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}). //
// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
// //
// This gives context to the signed message and prevents signing of transactions. // This gives context to the signed message and prevents signing of transactions.
func TextHash(data []byte) []byte { func TextHash(data []byte) []byte {
@ -189,7 +190,8 @@ func TextHash(data []byte) []byte {
// safely used to calculate a signature from. // safely used to calculate a signature from.
// //
// The hash is calculated as // The hash is calculated as
// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}). //
// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
// //
// This gives context to the signed message and prevents signing of transactions. // This gives context to the signed message and prevents signing of transactions.
func TextAndHash(data []byte) ([]byte, string) { func TextAndHash(data []byte) ([]byte, string) {

View File

@ -46,7 +46,7 @@ var LegacyLedgerBaseDerivationPath = DerivationPath{0x80000000 + 44, 0x80000000
// The BIP-32 spec https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki // The BIP-32 spec https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
// defines derivation paths to be of the form: // defines derivation paths to be of the form:
// //
// m / purpose' / coin_type' / account' / change / address_index // m / purpose' / coin_type' / account' / change / address_index
// //
// The BIP-44 spec https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki // The BIP-44 spec https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
// defines that the `purpose` be 44' (or 0x8000002C) for crypto currencies, and // defines that the `purpose` be 44' (or 0x8000002C) for crypto currencies, and

View File

@ -27,7 +27,7 @@ import (
"sync" "sync"
"time" "time"
mapset "github.com/deckarep/golang-set" mapset "github.com/deckarep/golang-set/v2"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
@ -79,7 +79,7 @@ func newAccountCache(keydir string) (*accountCache, chan struct{}) {
keydir: keydir, keydir: keydir,
byAddr: make(map[common.Address][]accounts.Account), byAddr: make(map[common.Address][]accounts.Account),
notify: make(chan struct{}, 1), notify: make(chan struct{}, 1),
fileC: fileCache{all: mapset.NewThreadUnsafeSet()}, fileC: fileCache{all: mapset.NewThreadUnsafeSet[string]()},
} }
ac.watcher = newWatcher(ac) ac.watcher = newWatcher(ac)
return ac, ac.notify return ac, ac.notify
@ -146,6 +146,14 @@ func (ac *accountCache) deleteByFile(path string) {
} }
} }
// watcherStarted returns true if the watcher loop started running (even if it
// has since also ended).
func (ac *accountCache) watcherStarted() bool {
ac.mu.Lock()
defer ac.mu.Unlock()
return ac.watcher.running || ac.watcher.runEnded
}
func removeAccount(slice []accounts.Account, elem accounts.Account) []accounts.Account { func removeAccount(slice []accounts.Account, elem accounts.Account) []accounts.Account {
for i := range slice { for i := range slice {
if slice[i] == elem { if slice[i] == elem {
@ -275,16 +283,15 @@ func (ac *accountCache) scanAccounts() error {
// Process all the file diffs // Process all the file diffs
start := time.Now() start := time.Now()
for _, p := range creates.ToSlice() { for _, path := range creates.ToSlice() {
if a := readAccount(p.(string)); a != nil { if a := readAccount(path); a != nil {
ac.add(*a) ac.add(*a)
} }
} }
for _, p := range deletes.ToSlice() { for _, path := range deletes.ToSlice() {
ac.deleteByFile(p.(string)) ac.deleteByFile(path)
} }
for _, p := range updates.ToSlice() { for _, path := range updates.ToSlice() {
path := p.(string)
ac.deleteByFile(path) ac.deleteByFile(path)
if a := readAccount(path); a != nil { if a := readAccount(path); a != nil {
ac.add(*a) ac.add(*a)

View File

@ -50,6 +50,38 @@ var (
} }
) )
// waitWatcherStarts waits up to 1s for the keystore watcher to start.
func waitWatcherStart(ks *KeyStore) bool {
// On systems where file watch is not supported, just return "ok".
if !ks.cache.watcher.enabled() {
return true
}
// The watcher should start, and then exit.
for t0 := time.Now(); time.Since(t0) < 1*time.Second; time.Sleep(100 * time.Millisecond) {
if ks.cache.watcherStarted() {
return true
}
}
return false
}
func waitForAccounts(wantAccounts []accounts.Account, ks *KeyStore) error {
var list []accounts.Account
for t0 := time.Now(); time.Since(t0) < 5*time.Second; time.Sleep(200 * time.Millisecond) {
list = ks.Accounts()
if reflect.DeepEqual(list, wantAccounts) {
// ks should have also received change notifications
select {
case <-ks.changes:
default:
return fmt.Errorf("wasn't notified of new accounts")
}
return nil
}
}
return fmt.Errorf("\ngot %v\nwant %v", list, wantAccounts)
}
func TestWatchNewFile(t *testing.T) { func TestWatchNewFile(t *testing.T) {
t.Parallel() t.Parallel()
@ -57,8 +89,9 @@ func TestWatchNewFile(t *testing.T) {
// Ensure the watcher is started before adding any files. // Ensure the watcher is started before adding any files.
ks.Accounts() ks.Accounts()
time.Sleep(1000 * time.Millisecond) if !waitWatcherStart(ks) {
t.Fatal("keystore watcher didn't start in time")
}
// Move in the files. // Move in the files.
wantAccounts := make([]accounts.Account, len(cachetestAccounts)) wantAccounts := make([]accounts.Account, len(cachetestAccounts))
for i := range cachetestAccounts { for i := range cachetestAccounts {
@ -72,37 +105,24 @@ func TestWatchNewFile(t *testing.T) {
} }
// ks should see the accounts. // ks should see the accounts.
var list []accounts.Account if err := waitForAccounts(wantAccounts, ks); err != nil {
for d := 200 * time.Millisecond; d < 5*time.Second; d *= 2 { t.Error(err)
list = ks.Accounts()
if reflect.DeepEqual(list, wantAccounts) {
// ks should have also received change notifications
select {
case <-ks.changes:
default:
t.Fatalf("wasn't notified of new accounts")
}
return
}
time.Sleep(d)
} }
t.Errorf("got %s, want %s", spew.Sdump(list), spew.Sdump(wantAccounts))
} }
func TestWatchNoDir(t *testing.T) { func TestWatchNoDir(t *testing.T) {
t.Parallel() t.Parallel()
// Create ks but not the directory that it watches. // Create ks but not the directory that it watches.
rand.Seed(time.Now().UnixNano())
dir := filepath.Join(os.TempDir(), fmt.Sprintf("eth-keystore-watchnodir-test-%d-%d", os.Getpid(), rand.Int())) dir := filepath.Join(os.TempDir(), fmt.Sprintf("eth-keystore-watchnodir-test-%d-%d", os.Getpid(), rand.Int()))
ks := NewKeyStore(dir, LightScryptN, LightScryptP) ks := NewKeyStore(dir, LightScryptN, LightScryptP)
list := ks.Accounts() list := ks.Accounts()
if len(list) > 0 { if len(list) > 0 {
t.Error("initial account list not empty:", list) t.Error("initial account list not empty:", list)
} }
time.Sleep(100 * time.Millisecond) // The watcher should start, and then exit.
if !waitWatcherStart(ks) {
t.Fatal("keystore watcher didn't start in time")
}
// Create the directory and copy a key file into it. // Create the directory and copy a key file into it.
os.MkdirAll(dir, 0700) os.MkdirAll(dir, 0700)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
@ -295,31 +315,12 @@ func TestCacheFind(t *testing.T) {
} }
} }
func waitForAccounts(wantAccounts []accounts.Account, ks *KeyStore) error {
var list []accounts.Account
for d := 200 * time.Millisecond; d < 8*time.Second; d *= 2 {
list = ks.Accounts()
if reflect.DeepEqual(list, wantAccounts) {
// ks should have also received change notifications
select {
case <-ks.changes:
default:
return fmt.Errorf("wasn't notified of new accounts")
}
return nil
}
time.Sleep(d)
}
return fmt.Errorf("\ngot %v\nwant %v", list, wantAccounts)
}
// TestUpdatedKeyfileContents tests that updating the contents of a keystore file // TestUpdatedKeyfileContents tests that updating the contents of a keystore file
// is noticed by the watcher, and the account cache is updated accordingly // is noticed by the watcher, and the account cache is updated accordingly
func TestUpdatedKeyfileContents(t *testing.T) { func TestUpdatedKeyfileContents(t *testing.T) {
t.Parallel() t.Parallel()
// Create a temporary keystore to test with // Create a temporary keystore to test with
rand.Seed(time.Now().UnixNano())
dir := filepath.Join(os.TempDir(), fmt.Sprintf("eth-keystore-updatedkeyfilecontents-test-%d-%d", os.Getpid(), rand.Int())) dir := filepath.Join(os.TempDir(), fmt.Sprintf("eth-keystore-updatedkeyfilecontents-test-%d-%d", os.Getpid(), rand.Int()))
ks := NewKeyStore(dir, LightScryptN, LightScryptP) ks := NewKeyStore(dir, LightScryptN, LightScryptP)
@ -327,8 +328,9 @@ func TestUpdatedKeyfileContents(t *testing.T) {
if len(list) > 0 { if len(list) > 0 {
t.Error("initial account list not empty:", list) t.Error("initial account list not empty:", list)
} }
time.Sleep(100 * time.Millisecond) if !waitWatcherStart(ks) {
t.Fatal("keystore watcher didn't start in time")
}
// Create the directory and copy a key file into it. // Create the directory and copy a key file into it.
os.MkdirAll(dir, 0700) os.MkdirAll(dir, 0700)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
@ -346,9 +348,8 @@ func TestUpdatedKeyfileContents(t *testing.T) {
t.Error(err) t.Error(err)
return return
} }
// needed so that modTime of `file` is different to its current value after forceCopyFile // needed so that modTime of `file` is different to its current value after forceCopyFile
time.Sleep(1000 * time.Millisecond) time.Sleep(time.Second)
// Now replace file contents // Now replace file contents
if err := forceCopyFile(file, cachetestAccounts[1].URL.Path); err != nil { if err := forceCopyFile(file, cachetestAccounts[1].URL.Path); err != nil {
@ -364,7 +365,7 @@ func TestUpdatedKeyfileContents(t *testing.T) {
} }
// needed so that modTime of `file` is different to its current value after forceCopyFile // needed so that modTime of `file` is different to its current value after forceCopyFile
time.Sleep(1000 * time.Millisecond) time.Sleep(time.Second)
// Now replace file contents again // Now replace file contents again
if err := forceCopyFile(file, cachetestAccounts[2].URL.Path); err != nil { if err := forceCopyFile(file, cachetestAccounts[2].URL.Path); err != nil {
@ -380,7 +381,7 @@ func TestUpdatedKeyfileContents(t *testing.T) {
} }
// needed so that modTime of `file` is different to its current value after os.WriteFile // needed so that modTime of `file` is different to its current value after os.WriteFile
time.Sleep(1000 * time.Millisecond) time.Sleep(time.Second)
// Now replace file contents with crap // Now replace file contents with crap
if err := os.WriteFile(file, []byte("foo"), 0600); err != nil { if err := os.WriteFile(file, []byte("foo"), 0600); err != nil {

View File

@ -23,20 +23,20 @@ import (
"sync" "sync"
"time" "time"
mapset "github.com/deckarep/golang-set" mapset "github.com/deckarep/golang-set/v2"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
) )
// fileCache is a cache of files seen during scan of keystore. // fileCache is a cache of files seen during scan of keystore.
type fileCache struct { type fileCache struct {
all mapset.Set // Set of all files from the keystore folder all mapset.Set[string] // Set of all files from the keystore folder
lastMod time.Time // Last time instance when a file was modified lastMod time.Time // Last time instance when a file was modified
mu sync.Mutex mu sync.Mutex
} }
// scan performs a new scan on the given directory, compares against the already // scan performs a new scan on the given directory, compares against the already
// cached filenames, and returns file sets: creates, deletes, updates. // cached filenames, and returns file sets: creates, deletes, updates.
func (fc *fileCache) scan(keyDir string) (mapset.Set, mapset.Set, mapset.Set, error) { func (fc *fileCache) scan(keyDir string) (mapset.Set[string], mapset.Set[string], mapset.Set[string], error) {
t0 := time.Now() t0 := time.Now()
// List all the files from the keystore folder // List all the files from the keystore folder
@ -50,8 +50,8 @@ func (fc *fileCache) scan(keyDir string) (mapset.Set, mapset.Set, mapset.Set, er
defer fc.mu.Unlock() defer fc.mu.Unlock()
// Iterate all the files and gather their metadata // Iterate all the files and gather their metadata
all := mapset.NewThreadUnsafeSet() all := mapset.NewThreadUnsafeSet[string]()
mods := mapset.NewThreadUnsafeSet() mods := mapset.NewThreadUnsafeSet[string]()
var newLastMod time.Time var newLastMod time.Time
for _, fi := range files { for _, fi := range files {

View File

@ -498,6 +498,14 @@ func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (account
return a, nil return a, nil
} }
// isUpdating returns whether the event notification loop is running.
// This method is mainly meant for tests.
func (ks *KeyStore) isUpdating() bool {
ks.mu.RLock()
defer ks.mu.RUnlock()
return ks.updating
}
// zeroKey zeroes a private key in memory. // zeroKey zeroes a private key in memory.
func zeroKey(k *ecdsa.PrivateKey) { func zeroKey(k *ecdsa.PrivateKey) {
b := k.D.Bits() b := k.D.Bits()

View File

@ -113,6 +113,7 @@ func TestSignWithPassphrase(t *testing.T) {
} }
func TestTimedUnlock(t *testing.T) { func TestTimedUnlock(t *testing.T) {
t.Parallel()
_, ks := tmpKeyStore(t, true) _, ks := tmpKeyStore(t, true)
pass := "foo" pass := "foo"
@ -147,6 +148,7 @@ func TestTimedUnlock(t *testing.T) {
} }
func TestOverrideUnlock(t *testing.T) { func TestOverrideUnlock(t *testing.T) {
t.Parallel()
_, ks := tmpKeyStore(t, false) _, ks := tmpKeyStore(t, false)
pass := "foo" pass := "foo"
@ -187,6 +189,7 @@ func TestOverrideUnlock(t *testing.T) {
// This test should fail under -race if signing races the expiration goroutine. // This test should fail under -race if signing races the expiration goroutine.
func TestSignRace(t *testing.T) { func TestSignRace(t *testing.T) {
t.Parallel()
_, ks := tmpKeyStore(t, false) _, ks := tmpKeyStore(t, false)
// Create a test account. // Create a test account.
@ -211,19 +214,33 @@ func TestSignRace(t *testing.T) {
t.Errorf("Account did not lock within the timeout") t.Errorf("Account did not lock within the timeout")
} }
// waitForKsUpdating waits until the updating-status of the ks reaches the
// desired wantStatus.
// It waits for a maximum time of maxTime, and returns false if it does not
// finish in time
func waitForKsUpdating(t *testing.T, ks *KeyStore, wantStatus bool, maxTime time.Duration) bool {
t.Helper()
// Wait max 250 ms, then return false
for t0 := time.Now(); time.Since(t0) < maxTime; {
if ks.isUpdating() == wantStatus {
return true
}
time.Sleep(25 * time.Millisecond)
}
return false
}
// Tests that the wallet notifier loop starts and stops correctly based on the // Tests that the wallet notifier loop starts and stops correctly based on the
// addition and removal of wallet event subscriptions. // addition and removal of wallet event subscriptions.
func TestWalletNotifierLifecycle(t *testing.T) { func TestWalletNotifierLifecycle(t *testing.T) {
t.Parallel()
// Create a temporary keystore to test with // Create a temporary keystore to test with
_, ks := tmpKeyStore(t, false) _, ks := tmpKeyStore(t, false)
// Ensure that the notification updater is not running yet // Ensure that the notification updater is not running yet
time.Sleep(250 * time.Millisecond) time.Sleep(250 * time.Millisecond)
ks.mu.RLock()
updating := ks.updating
ks.mu.RUnlock()
if updating { if ks.isUpdating() {
t.Errorf("wallet notifier running without subscribers") t.Errorf("wallet notifier running without subscribers")
} }
// Subscribe to the wallet feed and ensure the updater boots up // Subscribe to the wallet feed and ensure the updater boots up
@ -233,38 +250,26 @@ func TestWalletNotifierLifecycle(t *testing.T) {
for i := 0; i < len(subs); i++ { for i := 0; i < len(subs); i++ {
// Create a new subscription // Create a new subscription
subs[i] = ks.Subscribe(updates) subs[i] = ks.Subscribe(updates)
if !waitForKsUpdating(t, ks, true, 250*time.Millisecond) {
// Ensure the notifier comes online
time.Sleep(250 * time.Millisecond)
ks.mu.RLock()
updating = ks.updating
ks.mu.RUnlock()
if !updating {
t.Errorf("sub %d: wallet notifier not running after subscription", i) t.Errorf("sub %d: wallet notifier not running after subscription", i)
} }
} }
// Unsubscribe and ensure the updater terminates eventually // Close all but one sub
for i := 0; i < len(subs); i++ { for i := 0; i < len(subs)-1; i++ {
// Close an existing subscription // Close an existing subscription
subs[i].Unsubscribe() subs[i].Unsubscribe()
// Ensure the notifier shuts down at and only at the last close
for k := 0; k < int(walletRefreshCycle/(250*time.Millisecond))+2; k++ {
ks.mu.RLock()
updating = ks.updating
ks.mu.RUnlock()
if i < len(subs)-1 && !updating {
t.Fatalf("sub %d: event notifier stopped prematurely", i)
}
if i == len(subs)-1 && !updating {
return
}
time.Sleep(250 * time.Millisecond)
}
} }
t.Errorf("wallet notifier didn't terminate after unsubscribe") // Check that it is still running
time.Sleep(250 * time.Millisecond)
if !ks.isUpdating() {
t.Fatal("event notifier stopped prematurely")
}
// Unsubscribe the last one and ensure the updater terminates eventually.
subs[len(subs)-1].Unsubscribe()
if !waitForKsUpdating(t, ks, false, 4*time.Second) {
t.Errorf("wallet notifier didn't terminate after unsubscribe")
}
} }
type walletEvent struct { type walletEvent struct {

View File

@ -23,25 +23,27 @@ import (
"time" "time"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/rjeczalik/notify" "github.com/fsnotify/fsnotify"
) )
type watcher struct { type watcher struct {
ac *accountCache ac *accountCache
starting bool running bool // set to true when runloop begins
running bool runEnded bool // set to true when runloop ends
ev chan notify.EventInfo starting bool // set to true prior to runloop starting
quit chan struct{} quit chan struct{}
} }
func newWatcher(ac *accountCache) *watcher { func newWatcher(ac *accountCache) *watcher {
return &watcher{ return &watcher{
ac: ac, ac: ac,
ev: make(chan notify.EventInfo, 10),
quit: make(chan struct{}), quit: make(chan struct{}),
} }
} }
// enabled returns false on systems not supported.
func (*watcher) enabled() bool { return true }
// starts the watcher loop in the background. // starts the watcher loop in the background.
// Start a watcher in the background if that's not already in progress. // Start a watcher in the background if that's not already in progress.
// The caller must hold w.ac.mu. // The caller must hold w.ac.mu.
@ -62,16 +64,24 @@ func (w *watcher) loop() {
w.ac.mu.Lock() w.ac.mu.Lock()
w.running = false w.running = false
w.starting = false w.starting = false
w.runEnded = true
w.ac.mu.Unlock() w.ac.mu.Unlock()
}() }()
logger := log.New("path", w.ac.keydir) logger := log.New("path", w.ac.keydir)
if err := notify.Watch(w.ac.keydir, w.ev, notify.All); err != nil { // Create new watcher.
logger.Trace("Failed to watch keystore folder", "err", err) watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Error("Failed to start filesystem watcher", "err", err)
return return
} }
defer notify.Stop(w.ev) defer watcher.Close()
logger.Trace("Started watching keystore folder") if err := watcher.Add(w.ac.keydir); err != nil {
logger.Warn("Failed to watch keystore folder", "err", err)
return
}
logger.Trace("Started watching keystore folder", "folder", w.ac.keydir)
defer logger.Trace("Stopped watching keystore folder") defer logger.Trace("Stopped watching keystore folder")
w.ac.mu.Lock() w.ac.mu.Lock()
@ -95,12 +105,24 @@ func (w *watcher) loop() {
select { select {
case <-w.quit: case <-w.quit:
return return
case <-w.ev: case _, ok := <-watcher.Events:
if !ok {
return
}
// Trigger the scan (with delay), if not already triggered // Trigger the scan (with delay), if not already triggered
if !rescanTriggered { if !rescanTriggered {
debounce.Reset(debounceDuration) debounce.Reset(debounceDuration)
rescanTriggered = true rescanTriggered = true
} }
// The fsnotify library does provide more granular event-info, it
// would be possible to refresh individual affected files instead
// of scheduling a full rescan. For most cases though, the
// full rescan is quick and obviously simplest.
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Info("Filsystem watcher error", "err", err)
case <-debounce.C: case <-debounce.C:
w.ac.scanAccounts() w.ac.scanAccounts()
rescanTriggered = false rescanTriggered = false

View File

@ -22,8 +22,14 @@
package keystore package keystore
type watcher struct{ running bool } type watcher struct {
running bool
runEnded bool
}
func newWatcher(*accountCache) *watcher { return new(watcher) } func newWatcher(*accountCache) *watcher { return new(watcher) }
func (*watcher) start() {} func (*watcher) start() {}
func (*watcher) close() {} func (*watcher) close() {}
// enabled returns false on systems not supported.
func (*watcher) enabled() bool { return false }

View File

@ -257,7 +257,7 @@ func merge(slice []Wallet, wallets ...Wallet) []Wallet {
return slice return slice
} }
// drop is the couterpart of merge, which looks up wallets from within the sorted // drop is the counterpart of merge, which looks up wallets from within the sorted
// cache and removes the ones specified. // cache and removes the ones specified.
func drop(slice []Wallet, wallets ...Wallet) []Wallet { func drop(slice []Wallet, wallets ...Wallet) []Wallet {
for _, wallet := range wallets { for _, wallet := range wallets {

View File

@ -99,8 +99,8 @@ const (
P1DeriveKeyFromCurrent = uint8(0x10) P1DeriveKeyFromCurrent = uint8(0x10)
statusP1WalletStatus = uint8(0x00) statusP1WalletStatus = uint8(0x00)
statusP1Path = uint8(0x01) statusP1Path = uint8(0x01)
signP1PrecomputedHash = uint8(0x01) signP1PrecomputedHash = uint8(0x00)
signP2OnlyBlock = uint8(0x81) signP2OnlyBlock = uint8(0x00)
exportP1Any = uint8(0x00) exportP1Any = uint8(0x00)
exportP2Pubkey = uint8(0x01) exportP2Pubkey = uint8(0x01)
) )
@ -879,6 +879,7 @@ func (s *Session) walletStatus() (*walletStatus, error) {
} }
// derivationPath fetches the wallet's current derivation path from the card. // derivationPath fetches the wallet's current derivation path from the card.
//
//lint:ignore U1000 needs to be added to the console interface //lint:ignore U1000 needs to be added to the console interface
func (s *Session) derivationPath() (accounts.DerivationPath, error) { func (s *Session) derivationPath() (accounts.DerivationPath, error) {
response, err := s.Channel.transmitEncrypted(claSCWallet, insStatus, statusP1Path, 0, nil) response, err := s.Channel.transmitEncrypted(claSCWallet, insStatus, statusP1Path, 0, nil)
@ -994,6 +995,7 @@ func (s *Session) derive(path accounts.DerivationPath) (accounts.Account, error)
} }
// keyExport contains information on an exported keypair. // keyExport contains information on an exported keypair.
//
//lint:ignore U1000 needs to be added to the console interface //lint:ignore U1000 needs to be added to the console interface
type keyExport struct { type keyExport struct {
PublicKey []byte `asn1:"tag:0"` PublicKey []byte `asn1:"tag:0"`
@ -1001,6 +1003,7 @@ type keyExport struct {
} }
// publicKey returns the public key for the current derivation path. // publicKey returns the public key for the current derivation path.
//
//lint:ignore U1000 needs to be added to the console interface //lint:ignore U1000 needs to be added to the console interface
func (s *Session) publicKey() ([]byte, error) { func (s *Session) publicKey() ([]byte, error) {
response, err := s.Channel.transmitEncrypted(claSCWallet, insExportKey, exportP1Any, exportP2Pubkey, nil) response, err := s.Channel.transmitEncrypted(claSCWallet, insExportKey, exportP1Any, exportP2Pubkey, nil)

View File

@ -92,10 +92,9 @@ func (u *URL) UnmarshalJSON(input []byte) error {
// Cmp compares x and y and returns: // Cmp compares x and y and returns:
// //
// -1 if x < y // -1 if x < y
// 0 if x == y // 0 if x == y
// +1 if x > y // +1 if x > y
//
func (u URL) Cmp(url URL) int { func (u URL) Cmp(url URL) int {
if u.Scheme == url.Scheme { if u.Scheme == url.Scheme {
return strings.Compare(u.Path, url.Path) return strings.Compare(u.Path, url.Path)

View File

@ -71,18 +71,28 @@ type Hub struct {
// NewLedgerHub creates a new hardware wallet manager for Ledger devices. // NewLedgerHub creates a new hardware wallet manager for Ledger devices.
func NewLedgerHub() (*Hub, error) { func NewLedgerHub() (*Hub, error) {
return newHub(LedgerScheme, 0x2c97, []uint16{ return newHub(LedgerScheme, 0x2c97, []uint16{
// Device definitions taken from
// https://github.com/LedgerHQ/ledger-live/blob/38012bc8899e0f07149ea9cfe7e64b2c146bc92b/libs/ledgerjs/packages/devices/src/index.ts
// Original product IDs // Original product IDs
0x0000, /* Ledger Blue */ 0x0000, /* Ledger Blue */
0x0001, /* Ledger Nano S */ 0x0001, /* Ledger Nano S */
0x0004, /* Ledger Nano X */ 0x0004, /* Ledger Nano X */
0x0005, /* Ledger Nano S Plus */
0x0006, /* Ledger Nano FTS */
// Upcoming product IDs: https://www.ledger.com/2019/05/17/windows-10-update-sunsetting-u2f-tunnel-transport-for-ledger-devices/
0x0015, /* HID + U2F + WebUSB Ledger Blue */ 0x0015, /* HID + U2F + WebUSB Ledger Blue */
0x1015, /* HID + U2F + WebUSB Ledger Nano S */ 0x1015, /* HID + U2F + WebUSB Ledger Nano S */
0x4015, /* HID + U2F + WebUSB Ledger Nano X */ 0x4015, /* HID + U2F + WebUSB Ledger Nano X */
0x5015, /* HID + U2F + WebUSB Ledger Nano S Plus */
0x6015, /* HID + U2F + WebUSB Ledger Nano FTS */
0x0011, /* HID + WebUSB Ledger Blue */ 0x0011, /* HID + WebUSB Ledger Blue */
0x1011, /* HID + WebUSB Ledger Nano S */ 0x1011, /* HID + WebUSB Ledger Nano S */
0x4011, /* HID + WebUSB Ledger Nano X */ 0x4011, /* HID + WebUSB Ledger Nano X */
0x5011, /* HID + WebUSB Ledger Nano S Plus */
0x6011, /* HID + WebUSB Ledger Nano FTS */
}, 0xffa0, 0, newLedgerDriver) }, 0xffa0, 0, newLedgerDriver)
} }

View File

@ -59,6 +59,8 @@ const (
ledgerP1InitTransactionData ledgerParam1 = 0x00 // First transaction data block for signing ledgerP1InitTransactionData ledgerParam1 = 0x00 // First transaction data block for signing
ledgerP1ContTransactionData ledgerParam1 = 0x80 // Subsequent transaction data block for signing ledgerP1ContTransactionData ledgerParam1 = 0x80 // Subsequent transaction data block for signing
ledgerP2DiscardAddressChainCode ledgerParam2 = 0x00 // Do not return the chain code along with the address ledgerP2DiscardAddressChainCode ledgerParam2 = 0x00 // Do not return the chain code along with the address
ledgerEip155Size int = 3 // Size of the EIP-155 chain_id,r,s in unsigned transactions
) )
// errLedgerReplyInvalidHeader is the error message returned by a Ledger data exchange // errLedgerReplyInvalidHeader is the error message returned by a Ledger data exchange
@ -195,18 +197,18 @@ func (w *ledgerDriver) SignTypedMessage(path accounts.DerivationPath, domainHash
// //
// The version retrieval protocol is defined as follows: // The version retrieval protocol is defined as follows:
// //
// CLA | INS | P1 | P2 | Lc | Le // CLA | INS | P1 | P2 | Lc | Le
// ----+-----+----+----+----+--- // ----+-----+----+----+----+---
// E0 | 06 | 00 | 00 | 00 | 04 // E0 | 06 | 00 | 00 | 00 | 04
// //
// With no input data, and the output data being: // With no input data, and the output data being:
// //
// Description | Length // Description | Length
// ---------------------------------------------------+-------- // ---------------------------------------------------+--------
// Flags 01: arbitrary data signature enabled by user | 1 byte // Flags 01: arbitrary data signature enabled by user | 1 byte
// Application major version | 1 byte // Application major version | 1 byte
// Application minor version | 1 byte // Application minor version | 1 byte
// Application patch version | 1 byte // Application patch version | 1 byte
func (w *ledgerDriver) ledgerVersion() ([3]byte, error) { func (w *ledgerDriver) ledgerVersion() ([3]byte, error) {
// Send the request and wait for the response // Send the request and wait for the response
reply, err := w.ledgerExchange(ledgerOpGetConfiguration, 0, 0, nil) reply, err := w.ledgerExchange(ledgerOpGetConfiguration, 0, 0, nil)
@ -227,32 +229,32 @@ func (w *ledgerDriver) ledgerVersion() ([3]byte, error) {
// //
// The address derivation protocol is defined as follows: // The address derivation protocol is defined as follows:
// //
// CLA | INS | P1 | P2 | Lc | Le // CLA | INS | P1 | P2 | Lc | Le
// ----+-----+----+----+-----+--- // ----+-----+----+----+-----+---
// E0 | 02 | 00 return address // E0 | 02 | 00 return address
// 01 display address and confirm before returning // 01 display address and confirm before returning
// | 00: do not return the chain code // | 00: do not return the chain code
// | 01: return the chain code // | 01: return the chain code
// | var | 00 // | var | 00
// //
// Where the input data is: // Where the input data is:
// //
// Description | Length // Description | Length
// -------------------------------------------------+-------- // -------------------------------------------------+--------
// Number of BIP 32 derivations to perform (max 10) | 1 byte // Number of BIP 32 derivations to perform (max 10) | 1 byte
// First derivation index (big endian) | 4 bytes // First derivation index (big endian) | 4 bytes
// ... | 4 bytes // ... | 4 bytes
// Last derivation index (big endian) | 4 bytes // Last derivation index (big endian) | 4 bytes
// //
// And the output data is: // And the output data is:
// //
// Description | Length // Description | Length
// ------------------------+------------------- // ------------------------+-------------------
// Public Key length | 1 byte // Public Key length | 1 byte
// Uncompressed Public Key | arbitrary // Uncompressed Public Key | arbitrary
// Ethereum address length | 1 byte // Ethereum address length | 1 byte
// Ethereum address | 40 bytes hex ascii // Ethereum address | 40 bytes hex ascii
// Chain code if requested | 32 bytes // Chain code if requested | 32 bytes
func (w *ledgerDriver) ledgerDerive(derivationPath []uint32) (common.Address, error) { func (w *ledgerDriver) ledgerDerive(derivationPath []uint32) (common.Address, error) {
// Flatten the derivation path into the Ledger request // Flatten the derivation path into the Ledger request
path := make([]byte, 1+4*len(derivationPath)) path := make([]byte, 1+4*len(derivationPath))
@ -290,35 +292,35 @@ func (w *ledgerDriver) ledgerDerive(derivationPath []uint32) (common.Address, er
// //
// The transaction signing protocol is defined as follows: // The transaction signing protocol is defined as follows:
// //
// CLA | INS | P1 | P2 | Lc | Le // CLA | INS | P1 | P2 | Lc | Le
// ----+-----+----+----+-----+--- // ----+-----+----+----+-----+---
// E0 | 04 | 00: first transaction data block // E0 | 04 | 00: first transaction data block
// 80: subsequent transaction data block // 80: subsequent transaction data block
// | 00 | variable | variable // | 00 | variable | variable
// //
// Where the input for the first transaction block (first 255 bytes) is: // Where the input for the first transaction block (first 255 bytes) is:
// //
// Description | Length // Description | Length
// -------------------------------------------------+---------- // -------------------------------------------------+----------
// Number of BIP 32 derivations to perform (max 10) | 1 byte // Number of BIP 32 derivations to perform (max 10) | 1 byte
// First derivation index (big endian) | 4 bytes // First derivation index (big endian) | 4 bytes
// ... | 4 bytes // ... | 4 bytes
// Last derivation index (big endian) | 4 bytes // Last derivation index (big endian) | 4 bytes
// RLP transaction chunk | arbitrary // RLP transaction chunk | arbitrary
// //
// And the input for subsequent transaction blocks (first 255 bytes) are: // And the input for subsequent transaction blocks (first 255 bytes) are:
// //
// Description | Length // Description | Length
// ----------------------+---------- // ----------------------+----------
// RLP transaction chunk | arbitrary // RLP transaction chunk | arbitrary
// //
// And the output data is: // And the output data is:
// //
// Description | Length // Description | Length
// ------------+--------- // ------------+---------
// signature V | 1 byte // signature V | 1 byte
// signature R | 32 bytes // signature R | 32 bytes
// signature S | 32 bytes // signature S | 32 bytes
func (w *ledgerDriver) ledgerSign(derivationPath []uint32, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) { func (w *ledgerDriver) ledgerSign(derivationPath []uint32, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) {
// Flatten the derivation path into the Ledger request // Flatten the derivation path into the Ledger request
path := make([]byte, 1+4*len(derivationPath)) path := make([]byte, 1+4*len(derivationPath))
@ -347,9 +349,15 @@ func (w *ledgerDriver) ledgerSign(derivationPath []uint32, tx *types.Transaction
op = ledgerP1InitTransactionData op = ledgerP1InitTransactionData
reply []byte reply []byte
) )
// Chunk size selection to mitigate an underlying RLP deserialization issue on the ledger app.
// https://github.com/LedgerHQ/app-ethereum/issues/409
chunk := 255
for ; len(payload)%chunk <= ledgerEip155Size; chunk-- {
}
for len(payload) > 0 { for len(payload) > 0 {
// Calculate the size of the next data chunk // Calculate the size of the next data chunk
chunk := 255
if chunk > len(payload) { if chunk > len(payload) {
chunk = len(payload) chunk = len(payload)
} }
@ -392,30 +400,28 @@ func (w *ledgerDriver) ledgerSign(derivationPath []uint32, tx *types.Transaction
// //
// The signing protocol is defined as follows: // The signing protocol is defined as follows:
// //
// CLA | INS | P1 | P2 | Lc | Le // CLA | INS | P1 | P2 | Lc | Le
// ----+-----+----+-----------------------------+-----+--- // ----+-----+----+-----------------------------+-----+---
// E0 | 0C | 00 | implementation version : 00 | variable | variable // E0 | 0C | 00 | implementation version : 00 | variable | variable
// //
// Where the input is: // Where the input is:
// //
// Description | Length // Description | Length
// -------------------------------------------------+---------- // -------------------------------------------------+----------
// Number of BIP 32 derivations to perform (max 10) | 1 byte // Number of BIP 32 derivations to perform (max 10) | 1 byte
// First derivation index (big endian) | 4 bytes // First derivation index (big endian) | 4 bytes
// ... | 4 bytes // ... | 4 bytes
// Last derivation index (big endian) | 4 bytes // Last derivation index (big endian) | 4 bytes
// domain hash | 32 bytes // domain hash | 32 bytes
// message hash | 32 bytes // message hash | 32 bytes
//
//
// //
// And the output data is: // And the output data is:
// //
// Description | Length // Description | Length
// ------------+--------- // ------------+---------
// signature V | 1 byte // signature V | 1 byte
// signature R | 32 bytes // signature R | 32 bytes
// signature S | 32 bytes // signature S | 32 bytes
func (w *ledgerDriver) ledgerSignTypedMessage(derivationPath []uint32, domainHash []byte, messageHash []byte) ([]byte, error) { func (w *ledgerDriver) ledgerSignTypedMessage(derivationPath []uint32, domainHash []byte, messageHash []byte) ([]byte, error) {
// Flatten the derivation path into the Ledger request // Flatten the derivation path into the Ledger request
path := make([]byte, 1+4*len(derivationPath)) path := make([]byte, 1+4*len(derivationPath))
@ -454,12 +460,12 @@ func (w *ledgerDriver) ledgerSignTypedMessage(derivationPath []uint32, domainHas
// //
// The common transport header is defined as follows: // The common transport header is defined as follows:
// //
// Description | Length // Description | Length
// --------------------------------------+---------- // --------------------------------------+----------
// Communication channel ID (big endian) | 2 bytes // Communication channel ID (big endian) | 2 bytes
// Command tag | 1 byte // Command tag | 1 byte
// Packet sequence index (big endian) | 2 bytes // Packet sequence index (big endian) | 2 bytes
// Payload | arbitrary // Payload | arbitrary
// //
// The Communication channel ID allows commands multiplexing over the same // The Communication channel ID allows commands multiplexing over the same
// physical link. It is not used for the time being, and should be set to 0101 // physical link. It is not used for the time being, and should be set to 0101
@ -473,15 +479,15 @@ func (w *ledgerDriver) ledgerSignTypedMessage(derivationPath []uint32, domainHas
// //
// APDU Command payloads are encoded as follows: // APDU Command payloads are encoded as follows:
// //
// Description | Length // Description | Length
// ----------------------------------- // -----------------------------------
// APDU length (big endian) | 2 bytes // APDU length (big endian) | 2 bytes
// APDU CLA | 1 byte // APDU CLA | 1 byte
// APDU INS | 1 byte // APDU INS | 1 byte
// APDU P1 | 1 byte // APDU P1 | 1 byte
// APDU P2 | 1 byte // APDU P2 | 1 byte
// APDU length | 1 byte // APDU length | 1 byte
// Optional APDU data | arbitrary // Optional APDU data | arbitrary
func (w *ledgerDriver) ledgerExchange(opcode ledgerOpcode, p1 ledgerParam1, p2 ledgerParam2, data []byte) ([]byte, error) { func (w *ledgerDriver) ledgerExchange(opcode ledgerOpcode, p1 ledgerParam1, p2 ledgerParam2, data []byte) ([]byte, error) {
// Construct the message payload, possibly split into multiple chunks // Construct the message payload, possibly split into multiple chunks
apdu := make([]byte, 2, 7+len(data)) apdu := make([]byte, 2, 7+len(data))

View File

@ -84,15 +84,15 @@ func (w *trezorDriver) Status() (string, error) {
// Open implements usbwallet.driver, attempting to initialize the connection to // Open implements usbwallet.driver, attempting to initialize the connection to
// the Trezor hardware wallet. Initializing the Trezor is a two or three phase operation: // the Trezor hardware wallet. Initializing the Trezor is a two or three phase operation:
// * The first phase is to initialize the connection and read the wallet's // - The first phase is to initialize the connection and read the wallet's
// features. This phase is invoked if the provided passphrase is empty. The // features. This phase is invoked if the provided passphrase is empty. The
// device will display the pinpad as a result and will return an appropriate // device will display the pinpad as a result and will return an appropriate
// error to notify the user that a second open phase is needed. // error to notify the user that a second open phase is needed.
// * The second phase is to unlock access to the Trezor, which is done by the // - The second phase is to unlock access to the Trezor, which is done by the
// user actually providing a passphrase mapping a keyboard keypad to the pin // user actually providing a passphrase mapping a keyboard keypad to the pin
// number of the user (shuffled according to the pinpad displayed). // number of the user (shuffled according to the pinpad displayed).
// * If needed the device will ask for passphrase which will require calling // - If needed the device will ask for passphrase which will require calling
// open again with the actual passphrase (3rd phase) // open again with the actual passphrase (3rd phase)
func (w *trezorDriver) Open(device io.ReadWriter, passphrase string) error { func (w *trezorDriver) Open(device io.ReadWriter, passphrase string) error {
w.device, w.failure = device, nil w.device, w.failure = device, nil

View File

@ -94,7 +94,7 @@ func (Failure_FailureType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_aaf30d059fdbc38d, []int{1, 0} return fileDescriptor_aaf30d059fdbc38d, []int{1, 0}
} }
//* // *
// Type of button request // Type of button request
type ButtonRequest_ButtonRequestType int32 type ButtonRequest_ButtonRequestType int32
@ -175,7 +175,7 @@ func (ButtonRequest_ButtonRequestType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_aaf30d059fdbc38d, []int{2, 0} return fileDescriptor_aaf30d059fdbc38d, []int{2, 0}
} }
//* // *
// Type of PIN request // Type of PIN request
type PinMatrixRequest_PinMatrixRequestType int32 type PinMatrixRequest_PinMatrixRequestType int32
@ -220,7 +220,7 @@ func (PinMatrixRequest_PinMatrixRequestType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_aaf30d059fdbc38d, []int{4, 0} return fileDescriptor_aaf30d059fdbc38d, []int{4, 0}
} }
//* // *
// Response: Success of the previous request // Response: Success of the previous request
// @end // @end
type Success struct { type Success struct {
@ -262,7 +262,7 @@ func (m *Success) GetMessage() string {
return "" return ""
} }
//* // *
// Response: Failure of the previous request // Response: Failure of the previous request
// @end // @end
type Failure struct { type Failure struct {
@ -312,7 +312,7 @@ func (m *Failure) GetMessage() string {
return "" return ""
} }
//* // *
// Response: Device is waiting for HW button press. // Response: Device is waiting for HW button press.
// @auxstart // @auxstart
// @next ButtonAck // @next ButtonAck
@ -363,7 +363,7 @@ func (m *ButtonRequest) GetData() string {
return "" return ""
} }
//* // *
// Request: Computer agrees to wait for HW button press // Request: Computer agrees to wait for HW button press
// @auxend // @auxend
type ButtonAck struct { type ButtonAck struct {
@ -397,7 +397,7 @@ func (m *ButtonAck) XXX_DiscardUnknown() {
var xxx_messageInfo_ButtonAck proto.InternalMessageInfo var xxx_messageInfo_ButtonAck proto.InternalMessageInfo
//* // *
// Response: Device is asking computer to show PIN matrix and awaits PIN encoded using this matrix scheme // Response: Device is asking computer to show PIN matrix and awaits PIN encoded using this matrix scheme
// @auxstart // @auxstart
// @next PinMatrixAck // @next PinMatrixAck
@ -440,7 +440,7 @@ func (m *PinMatrixRequest) GetType() PinMatrixRequest_PinMatrixRequestType {
return PinMatrixRequest_PinMatrixRequestType_Current return PinMatrixRequest_PinMatrixRequestType_Current
} }
//* // *
// Request: Computer responds with encoded PIN // Request: Computer responds with encoded PIN
// @auxend // @auxend
type PinMatrixAck struct { type PinMatrixAck struct {
@ -482,7 +482,7 @@ func (m *PinMatrixAck) GetPin() string {
return "" return ""
} }
//* // *
// Response: Device awaits encryption passphrase // Response: Device awaits encryption passphrase
// @auxstart // @auxstart
// @next PassphraseAck // @next PassphraseAck
@ -525,7 +525,7 @@ func (m *PassphraseRequest) GetOnDevice() bool {
return false return false
} }
//* // *
// Request: Send passphrase back // Request: Send passphrase back
// @next PassphraseStateRequest // @next PassphraseStateRequest
type PassphraseAck struct { type PassphraseAck struct {
@ -575,7 +575,7 @@ func (m *PassphraseAck) GetState() []byte {
return nil return nil
} }
//* // *
// Response: Device awaits passphrase state // Response: Device awaits passphrase state
// @next PassphraseStateAck // @next PassphraseStateAck
type PassphraseStateRequest struct { type PassphraseStateRequest struct {
@ -617,7 +617,7 @@ func (m *PassphraseStateRequest) GetState() []byte {
return nil return nil
} }
//* // *
// Request: Send passphrase state back // Request: Send passphrase state back
// @auxend // @auxend
type PassphraseStateAck struct { type PassphraseStateAck struct {
@ -651,7 +651,7 @@ func (m *PassphraseStateAck) XXX_DiscardUnknown() {
var xxx_messageInfo_PassphraseStateAck proto.InternalMessageInfo var xxx_messageInfo_PassphraseStateAck proto.InternalMessageInfo
//* // *
// Structure representing BIP32 (hierarchical deterministic) node // Structure representing BIP32 (hierarchical deterministic) node
// Used for imports of private key into the device and exporting public key out of device // Used for imports of private key into the device and exporting public key out of device
// @embed // @embed

View File

@ -21,7 +21,7 @@ var _ = math.Inf
// proto package needs to be updated. // proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
//* // *
// Request: Ask device for public key corresponding to address_n path // Request: Ask device for public key corresponding to address_n path
// @start // @start
// @next EthereumPublicKey // @next EthereumPublicKey
@ -73,7 +73,7 @@ func (m *EthereumGetPublicKey) GetShowDisplay() bool {
return false return false
} }
//* // *
// Response: Contains public key derived from device private seed // Response: Contains public key derived from device private seed
// @end // @end
type EthereumPublicKey struct { type EthereumPublicKey struct {
@ -123,7 +123,7 @@ func (m *EthereumPublicKey) GetXpub() string {
return "" return ""
} }
//* // *
// Request: Ask device for Ethereum address corresponding to address_n path // Request: Ask device for Ethereum address corresponding to address_n path
// @start // @start
// @next EthereumAddress // @next EthereumAddress
@ -175,7 +175,7 @@ func (m *EthereumGetAddress) GetShowDisplay() bool {
return false return false
} }
//* // *
// Response: Contains an Ethereum address derived from device private seed // Response: Contains an Ethereum address derived from device private seed
// @end // @end
type EthereumAddress struct { type EthereumAddress struct {
@ -225,7 +225,7 @@ func (m *EthereumAddress) GetAddressHex() string {
return "" return ""
} }
//* // *
// Request: Ask device to sign transaction // Request: Ask device to sign transaction
// All fields are optional from the protocol's point of view. Each field defaults to value `0` if missing. // All fields are optional from the protocol's point of view. Each field defaults to value `0` if missing.
// Note: the first at most 1024 bytes of data MUST be transmitted as part of this message. // Note: the first at most 1024 bytes of data MUST be transmitted as part of this message.
@ -351,7 +351,7 @@ func (m *EthereumSignTx) GetTxType() uint32 {
return 0 return 0
} }
//* // *
// Response: Device asks for more data from transaction payload, or returns the signature. // Response: Device asks for more data from transaction payload, or returns the signature.
// If data_length is set, device awaits that many more bytes of payload. // If data_length is set, device awaits that many more bytes of payload.
// Otherwise, the signature_* fields contain the computed transaction signature. All three fields will be present. // Otherwise, the signature_* fields contain the computed transaction signature. All three fields will be present.
@ -420,7 +420,7 @@ func (m *EthereumTxRequest) GetSignatureS() []byte {
return nil return nil
} }
//* // *
// Request: Transaction payload data. // Request: Transaction payload data.
// @next EthereumTxRequest // @next EthereumTxRequest
type EthereumTxAck struct { type EthereumTxAck struct {
@ -462,7 +462,7 @@ func (m *EthereumTxAck) GetDataChunk() []byte {
return nil return nil
} }
//* // *
// Request: Ask device to sign message // Request: Ask device to sign message
// @start // @start
// @next EthereumMessageSignature // @next EthereumMessageSignature
@ -514,7 +514,7 @@ func (m *EthereumSignMessage) GetMessage() []byte {
return nil return nil
} }
//* // *
// Response: Signed message // Response: Signed message
// @end // @end
type EthereumMessageSignature struct { type EthereumMessageSignature struct {
@ -572,7 +572,7 @@ func (m *EthereumMessageSignature) GetAddressHex() string {
return "" return ""
} }
//* // *
// Request: Ask device to verify message // Request: Ask device to verify message
// @start // @start
// @next Success // @next Success

View File

@ -21,7 +21,7 @@ var _ = math.Inf
// proto package needs to be updated. // proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
//* // *
// Structure representing passphrase source // Structure representing passphrase source
type ApplySettings_PassphraseSourceType int32 type ApplySettings_PassphraseSourceType int32
@ -66,7 +66,7 @@ func (ApplySettings_PassphraseSourceType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_0c720c20d27aa029, []int{4, 0} return fileDescriptor_0c720c20d27aa029, []int{4, 0}
} }
//* // *
// Type of recovery procedure. These should be used as bitmask, e.g., // Type of recovery procedure. These should be used as bitmask, e.g.,
// `RecoveryDeviceType_ScrambledWords | RecoveryDeviceType_Matrix` // `RecoveryDeviceType_ScrambledWords | RecoveryDeviceType_Matrix`
// listing every method supported by the host computer. // listing every method supported by the host computer.
@ -114,7 +114,7 @@ func (RecoveryDevice_RecoveryDeviceType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_0c720c20d27aa029, []int{17, 0} return fileDescriptor_0c720c20d27aa029, []int{17, 0}
} }
//* // *
// Type of Recovery Word request // Type of Recovery Word request
type WordRequest_WordRequestType int32 type WordRequest_WordRequestType int32
@ -159,7 +159,7 @@ func (WordRequest_WordRequestType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_0c720c20d27aa029, []int{18, 0} return fileDescriptor_0c720c20d27aa029, []int{18, 0}
} }
//* // *
// Request: Reset device to default state and ask for device details // Request: Reset device to default state and ask for device details
// @start // @start
// @next Features // @next Features
@ -210,7 +210,7 @@ func (m *Initialize) GetSkipPassphrase() bool {
return false return false
} }
//* // *
// Request: Ask for device details (no device reset) // Request: Ask for device details (no device reset)
// @start // @start
// @next Features // @next Features
@ -245,7 +245,7 @@ func (m *GetFeatures) XXX_DiscardUnknown() {
var xxx_messageInfo_GetFeatures proto.InternalMessageInfo var xxx_messageInfo_GetFeatures proto.InternalMessageInfo
//* // *
// Response: Reports various information about the device // Response: Reports various information about the device
// @end // @end
type Features struct { type Features struct {
@ -495,7 +495,7 @@ func (m *Features) GetNoBackup() bool {
return false return false
} }
//* // *
// Request: clear session (removes cached PIN, passphrase, etc). // Request: clear session (removes cached PIN, passphrase, etc).
// @start // @start
// @next Success // @next Success
@ -530,7 +530,7 @@ func (m *ClearSession) XXX_DiscardUnknown() {
var xxx_messageInfo_ClearSession proto.InternalMessageInfo var xxx_messageInfo_ClearSession proto.InternalMessageInfo
//* // *
// Request: change language and/or label of the device // Request: change language and/or label of the device
// @start // @start
// @next Success // @next Success
@ -622,7 +622,7 @@ func (m *ApplySettings) GetDisplayRotation() uint32 {
return 0 return 0
} }
//* // *
// Request: set flags of the device // Request: set flags of the device
// @start // @start
// @next Success // @next Success
@ -666,7 +666,7 @@ func (m *ApplyFlags) GetFlags() uint32 {
return 0 return 0
} }
//* // *
// Request: Starts workflow for setting/changing/removing the PIN // Request: Starts workflow for setting/changing/removing the PIN
// @start // @start
// @next Success // @next Success
@ -710,7 +710,7 @@ func (m *ChangePin) GetRemove() bool {
return false return false
} }
//* // *
// Request: Test if the device is alive, device sends back the message in Success response // Request: Test if the device is alive, device sends back the message in Success response
// @start // @start
// @next Success // @next Success
@ -777,7 +777,7 @@ func (m *Ping) GetPassphraseProtection() bool {
return false return false
} }
//* // *
// Request: Abort last operation that required user interaction // Request: Abort last operation that required user interaction
// @start // @start
// @next Failure // @next Failure
@ -812,7 +812,7 @@ func (m *Cancel) XXX_DiscardUnknown() {
var xxx_messageInfo_Cancel proto.InternalMessageInfo var xxx_messageInfo_Cancel proto.InternalMessageInfo
//* // *
// Request: Request a sample of random data generated by hardware RNG. May be used for testing. // Request: Request a sample of random data generated by hardware RNG. May be used for testing.
// @start // @start
// @next Entropy // @next Entropy
@ -856,7 +856,7 @@ func (m *GetEntropy) GetSize() uint32 {
return 0 return 0
} }
//* // *
// Response: Reply with random data generated by internal RNG // Response: Reply with random data generated by internal RNG
// @end // @end
type Entropy struct { type Entropy struct {
@ -898,7 +898,7 @@ func (m *Entropy) GetEntropy() []byte {
return nil return nil
} }
//* // *
// Request: Request device to wipe all sensitive data and settings // Request: Request device to wipe all sensitive data and settings
// @start // @start
// @next Success // @next Success
@ -934,7 +934,7 @@ func (m *WipeDevice) XXX_DiscardUnknown() {
var xxx_messageInfo_WipeDevice proto.InternalMessageInfo var xxx_messageInfo_WipeDevice proto.InternalMessageInfo
//* // *
// Request: Load seed and related internal settings from the computer // Request: Load seed and related internal settings from the computer
// @start // @start
// @next Success // @next Success
@ -1036,7 +1036,7 @@ func (m *LoadDevice) GetU2FCounter() uint32 {
return 0 return 0
} }
//* // *
// Request: Ask device to do initialization involving user interaction // Request: Ask device to do initialization involving user interaction
// @start // @start
// @next EntropyRequest // @next EntropyRequest
@ -1147,7 +1147,7 @@ func (m *ResetDevice) GetNoBackup() bool {
return false return false
} }
//* // *
// Request: Perform backup of the device seed if not backed up using ResetDevice // Request: Perform backup of the device seed if not backed up using ResetDevice
// @start // @start
// @next Success // @next Success
@ -1182,7 +1182,7 @@ func (m *BackupDevice) XXX_DiscardUnknown() {
var xxx_messageInfo_BackupDevice proto.InternalMessageInfo var xxx_messageInfo_BackupDevice proto.InternalMessageInfo
//* // *
// Response: Ask for additional entropy from host computer // Response: Ask for additional entropy from host computer
// @next EntropyAck // @next EntropyAck
type EntropyRequest struct { type EntropyRequest struct {
@ -1216,7 +1216,7 @@ func (m *EntropyRequest) XXX_DiscardUnknown() {
var xxx_messageInfo_EntropyRequest proto.InternalMessageInfo var xxx_messageInfo_EntropyRequest proto.InternalMessageInfo
//* // *
// Request: Provide additional entropy for seed generation function // Request: Provide additional entropy for seed generation function
// @next Success // @next Success
type EntropyAck struct { type EntropyAck struct {
@ -1258,7 +1258,7 @@ func (m *EntropyAck) GetEntropy() []byte {
return nil return nil
} }
//* // *
// Request: Start recovery workflow asking user for specific words of mnemonic // Request: Start recovery workflow asking user for specific words of mnemonic
// Used to recovery device safely even on untrusted computer. // Used to recovery device safely even on untrusted computer.
// @start // @start
@ -1369,7 +1369,7 @@ func (m *RecoveryDevice) GetDryRun() bool {
return false return false
} }
//* // *
// Response: Device is waiting for user to enter word of the mnemonic // Response: Device is waiting for user to enter word of the mnemonic
// Its position is shown only on device's internal display. // Its position is shown only on device's internal display.
// @next WordAck // @next WordAck
@ -1412,7 +1412,7 @@ func (m *WordRequest) GetType() WordRequest_WordRequestType {
return WordRequest_WordRequestType_Plain return WordRequest_WordRequestType_Plain
} }
//* // *
// Request: Computer replies with word from the mnemonic // Request: Computer replies with word from the mnemonic
// @next WordRequest // @next WordRequest
// @next Success // @next Success
@ -1456,7 +1456,7 @@ func (m *WordAck) GetWord() string {
return "" return ""
} }
//* // *
// Request: Set U2F counter // Request: Set U2F counter
// @start // @start
// @next Success // @next Success

View File

@ -22,7 +22,7 @@ var _ = math.Inf
// proto package needs to be updated. // proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
//* // *
// Mapping between TREZOR wire identifier (uint) and a protobuf message // Mapping between TREZOR wire identifier (uint) and a protobuf message
type MessageType int32 type MessageType int32

View File

@ -26,7 +26,7 @@ for:
- go run build/ci.go lint - go run build/ci.go lint
- go run build/ci.go install -dlgo - go run build/ci.go install -dlgo
test_script: test_script:
- go run build/ci.go test -dlgo -coverage - go run build/ci.go test -dlgo
# linux/386 is disabled. # linux/386 is disabled.
- matrix: - matrix:
@ -54,4 +54,4 @@ for:
- go run build/ci.go archive -arch %GETH_ARCH% -type zip -signer WINDOWS_SIGNING_KEY -upload gethstore/builds - go run build/ci.go archive -arch %GETH_ARCH% -type zip -signer WINDOWS_SIGNING_KEY -upload gethstore/builds
- go run build/ci.go nsis -arch %GETH_ARCH% -signer WINDOWS_SIGNING_KEY -upload gethstore/builds - go run build/ci.go nsis -arch %GETH_ARCH% -signer WINDOWS_SIGNING_KEY -upload gethstore/builds
test_script: test_script:
- go run build/ci.go test -dlgo -arch %GETH_ARCH% -cc %GETH_CC% -coverage - go run build/ci.go test -dlgo -arch %GETH_ARCH% -cc %GETH_CC%

View File

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package beacon package engine
import ( import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
@ -74,12 +74,12 @@ var (
// - newPayloadV1: if the payload was accepted, but not processed (side chain) // - newPayloadV1: if the payload was accepted, but not processed (side chain)
ACCEPTED = "ACCEPTED" ACCEPTED = "ACCEPTED"
INVALIDBLOCKHASH = "INVALID_BLOCK_HASH"
GenericServerError = &EngineAPIError{code: -32000, msg: "Server error"} GenericServerError = &EngineAPIError{code: -32000, msg: "Server error"}
UnknownPayload = &EngineAPIError{code: -38001, msg: "Unknown payload"} UnknownPayload = &EngineAPIError{code: -38001, msg: "Unknown payload"}
InvalidForkChoiceState = &EngineAPIError{code: -38002, msg: "Invalid forkchoice state"} InvalidForkChoiceState = &EngineAPIError{code: -38002, msg: "Invalid forkchoice state"}
InvalidPayloadAttributes = &EngineAPIError{code: -38003, msg: "Invalid payload attributes"} InvalidPayloadAttributes = &EngineAPIError{code: -38003, msg: "Invalid payload attributes"}
TooLargeRequest = &EngineAPIError{code: -38004, msg: "Too large request"}
InvalidParams = &EngineAPIError{code: -32602, msg: "Invalid parameters"}
STATUS_INVALID = ForkChoiceResponse{PayloadStatus: PayloadStatusV1{Status: INVALID}, PayloadID: nil} STATUS_INVALID = ForkChoiceResponse{PayloadStatus: PayloadStatusV1{Status: INVALID}, PayloadID: nil}
STATUS_SYNCING = ForkChoiceResponse{PayloadStatus: PayloadStatusV1{Status: SYNCING}, PayloadID: nil} STATUS_SYNCING = ForkChoiceResponse{PayloadStatus: PayloadStatusV1{Status: SYNCING}, PayloadID: nil}

View File

@ -0,0 +1,60 @@
// Code generated by github.com/fjl/gencodec. DO NOT EDIT.
package engine
import (
"encoding/json"
"errors"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
)
var _ = (*payloadAttributesMarshaling)(nil)
// MarshalJSON marshals as JSON.
func (p PayloadAttributes) MarshalJSON() ([]byte, error) {
type PayloadAttributes struct {
Timestamp hexutil.Uint64 `json:"timestamp" gencodec:"required"`
Random common.Hash `json:"prevRandao" gencodec:"required"`
SuggestedFeeRecipient common.Address `json:"suggestedFeeRecipient" gencodec:"required"`
Withdrawals []*types.Withdrawal `json:"withdrawals"`
}
var enc PayloadAttributes
enc.Timestamp = hexutil.Uint64(p.Timestamp)
enc.Random = p.Random
enc.SuggestedFeeRecipient = p.SuggestedFeeRecipient
enc.Withdrawals = p.Withdrawals
return json.Marshal(&enc)
}
// UnmarshalJSON unmarshals from JSON.
func (p *PayloadAttributes) UnmarshalJSON(input []byte) error {
type PayloadAttributes struct {
Timestamp *hexutil.Uint64 `json:"timestamp" gencodec:"required"`
Random *common.Hash `json:"prevRandao" gencodec:"required"`
SuggestedFeeRecipient *common.Address `json:"suggestedFeeRecipient" gencodec:"required"`
Withdrawals []*types.Withdrawal `json:"withdrawals"`
}
var dec PayloadAttributes
if err := json.Unmarshal(input, &dec); err != nil {
return err
}
if dec.Timestamp == nil {
return errors.New("missing required field 'timestamp' for PayloadAttributes")
}
p.Timestamp = uint64(*dec.Timestamp)
if dec.Random == nil {
return errors.New("missing required field 'prevRandao' for PayloadAttributes")
}
p.Random = *dec.Random
if dec.SuggestedFeeRecipient == nil {
return errors.New("missing required field 'suggestedFeeRecipient' for PayloadAttributes")
}
p.SuggestedFeeRecipient = *dec.SuggestedFeeRecipient
if dec.Withdrawals != nil {
p.Withdrawals = dec.Withdrawals
}
return nil
}

View File

@ -1,6 +1,6 @@
// Code generated by github.com/fjl/gencodec. DO NOT EDIT. // Code generated by github.com/fjl/gencodec. DO NOT EDIT.
package beacon package engine
import ( import (
"encoding/json" "encoding/json"
@ -9,29 +9,31 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
) )
var _ = (*executableDataMarshaling)(nil) var _ = (*executableDataMarshaling)(nil)
// MarshalJSON marshals as JSON. // MarshalJSON marshals as JSON.
func (e ExecutableDataV1) MarshalJSON() ([]byte, error) { func (e ExecutableData) MarshalJSON() ([]byte, error) {
type ExecutableDataV1 struct { type ExecutableData struct {
ParentHash common.Hash `json:"parentHash" gencodec:"required"` ParentHash common.Hash `json:"parentHash" gencodec:"required"`
FeeRecipient common.Address `json:"feeRecipient" gencodec:"required"` FeeRecipient common.Address `json:"feeRecipient" gencodec:"required"`
StateRoot common.Hash `json:"stateRoot" gencodec:"required"` StateRoot common.Hash `json:"stateRoot" gencodec:"required"`
ReceiptsRoot common.Hash `json:"receiptsRoot" gencodec:"required"` ReceiptsRoot common.Hash `json:"receiptsRoot" gencodec:"required"`
LogsBloom hexutil.Bytes `json:"logsBloom" gencodec:"required"` LogsBloom hexutil.Bytes `json:"logsBloom" gencodec:"required"`
Random common.Hash `json:"prevRandao" gencodec:"required"` Random common.Hash `json:"prevRandao" gencodec:"required"`
Number hexutil.Uint64 `json:"blockNumber" gencodec:"required"` Number hexutil.Uint64 `json:"blockNumber" gencodec:"required"`
GasLimit hexutil.Uint64 `json:"gasLimit" gencodec:"required"` GasLimit hexutil.Uint64 `json:"gasLimit" gencodec:"required"`
GasUsed hexutil.Uint64 `json:"gasUsed" gencodec:"required"` GasUsed hexutil.Uint64 `json:"gasUsed" gencodec:"required"`
Timestamp hexutil.Uint64 `json:"timestamp" gencodec:"required"` Timestamp hexutil.Uint64 `json:"timestamp" gencodec:"required"`
ExtraData hexutil.Bytes `json:"extraData" gencodec:"required"` ExtraData hexutil.Bytes `json:"extraData" gencodec:"required"`
BaseFeePerGas *hexutil.Big `json:"baseFeePerGas" gencodec:"required"` BaseFeePerGas *hexutil.Big `json:"baseFeePerGas" gencodec:"required"`
BlockHash common.Hash `json:"blockHash" gencodec:"required"` BlockHash common.Hash `json:"blockHash" gencodec:"required"`
Transactions []hexutil.Bytes `json:"transactions" gencodec:"required"` Transactions []hexutil.Bytes `json:"transactions" gencodec:"required"`
Withdrawals []*types.Withdrawal `json:"withdrawals"`
} }
var enc ExecutableDataV1 var enc ExecutableData
enc.ParentHash = e.ParentHash enc.ParentHash = e.ParentHash
enc.FeeRecipient = e.FeeRecipient enc.FeeRecipient = e.FeeRecipient
enc.StateRoot = e.StateRoot enc.StateRoot = e.StateRoot
@ -51,89 +53,94 @@ func (e ExecutableDataV1) MarshalJSON() ([]byte, error) {
enc.Transactions[k] = v enc.Transactions[k] = v
} }
} }
enc.Withdrawals = e.Withdrawals
return json.Marshal(&enc) return json.Marshal(&enc)
} }
// UnmarshalJSON unmarshals from JSON. // UnmarshalJSON unmarshals from JSON.
func (e *ExecutableDataV1) UnmarshalJSON(input []byte) error { func (e *ExecutableData) UnmarshalJSON(input []byte) error {
type ExecutableDataV1 struct { type ExecutableData struct {
ParentHash *common.Hash `json:"parentHash" gencodec:"required"` ParentHash *common.Hash `json:"parentHash" gencodec:"required"`
FeeRecipient *common.Address `json:"feeRecipient" gencodec:"required"` FeeRecipient *common.Address `json:"feeRecipient" gencodec:"required"`
StateRoot *common.Hash `json:"stateRoot" gencodec:"required"` StateRoot *common.Hash `json:"stateRoot" gencodec:"required"`
ReceiptsRoot *common.Hash `json:"receiptsRoot" gencodec:"required"` ReceiptsRoot *common.Hash `json:"receiptsRoot" gencodec:"required"`
LogsBloom *hexutil.Bytes `json:"logsBloom" gencodec:"required"` LogsBloom *hexutil.Bytes `json:"logsBloom" gencodec:"required"`
Random *common.Hash `json:"prevRandao" gencodec:"required"` Random *common.Hash `json:"prevRandao" gencodec:"required"`
Number *hexutil.Uint64 `json:"blockNumber" gencodec:"required"` Number *hexutil.Uint64 `json:"blockNumber" gencodec:"required"`
GasLimit *hexutil.Uint64 `json:"gasLimit" gencodec:"required"` GasLimit *hexutil.Uint64 `json:"gasLimit" gencodec:"required"`
GasUsed *hexutil.Uint64 `json:"gasUsed" gencodec:"required"` GasUsed *hexutil.Uint64 `json:"gasUsed" gencodec:"required"`
Timestamp *hexutil.Uint64 `json:"timestamp" gencodec:"required"` Timestamp *hexutil.Uint64 `json:"timestamp" gencodec:"required"`
ExtraData *hexutil.Bytes `json:"extraData" gencodec:"required"` ExtraData *hexutil.Bytes `json:"extraData" gencodec:"required"`
BaseFeePerGas *hexutil.Big `json:"baseFeePerGas" gencodec:"required"` BaseFeePerGas *hexutil.Big `json:"baseFeePerGas" gencodec:"required"`
BlockHash *common.Hash `json:"blockHash" gencodec:"required"` BlockHash *common.Hash `json:"blockHash" gencodec:"required"`
Transactions []hexutil.Bytes `json:"transactions" gencodec:"required"` Transactions []hexutil.Bytes `json:"transactions" gencodec:"required"`
Withdrawals []*types.Withdrawal `json:"withdrawals"`
} }
var dec ExecutableDataV1 var dec ExecutableData
if err := json.Unmarshal(input, &dec); err != nil { if err := json.Unmarshal(input, &dec); err != nil {
return err return err
} }
if dec.ParentHash == nil { if dec.ParentHash == nil {
return errors.New("missing required field 'parentHash' for ExecutableDataV1") return errors.New("missing required field 'parentHash' for ExecutableData")
} }
e.ParentHash = *dec.ParentHash e.ParentHash = *dec.ParentHash
if dec.FeeRecipient == nil { if dec.FeeRecipient == nil {
return errors.New("missing required field 'feeRecipient' for ExecutableDataV1") return errors.New("missing required field 'feeRecipient' for ExecutableData")
} }
e.FeeRecipient = *dec.FeeRecipient e.FeeRecipient = *dec.FeeRecipient
if dec.StateRoot == nil { if dec.StateRoot == nil {
return errors.New("missing required field 'stateRoot' for ExecutableDataV1") return errors.New("missing required field 'stateRoot' for ExecutableData")
} }
e.StateRoot = *dec.StateRoot e.StateRoot = *dec.StateRoot
if dec.ReceiptsRoot == nil { if dec.ReceiptsRoot == nil {
return errors.New("missing required field 'receiptsRoot' for ExecutableDataV1") return errors.New("missing required field 'receiptsRoot' for ExecutableData")
} }
e.ReceiptsRoot = *dec.ReceiptsRoot e.ReceiptsRoot = *dec.ReceiptsRoot
if dec.LogsBloom == nil { if dec.LogsBloom == nil {
return errors.New("missing required field 'logsBloom' for ExecutableDataV1") return errors.New("missing required field 'logsBloom' for ExecutableData")
} }
e.LogsBloom = *dec.LogsBloom e.LogsBloom = *dec.LogsBloom
if dec.Random == nil { if dec.Random == nil {
return errors.New("missing required field 'prevRandao' for ExecutableDataV1") return errors.New("missing required field 'prevRandao' for ExecutableData")
} }
e.Random = *dec.Random e.Random = *dec.Random
if dec.Number == nil { if dec.Number == nil {
return errors.New("missing required field 'blockNumber' for ExecutableDataV1") return errors.New("missing required field 'blockNumber' for ExecutableData")
} }
e.Number = uint64(*dec.Number) e.Number = uint64(*dec.Number)
if dec.GasLimit == nil { if dec.GasLimit == nil {
return errors.New("missing required field 'gasLimit' for ExecutableDataV1") return errors.New("missing required field 'gasLimit' for ExecutableData")
} }
e.GasLimit = uint64(*dec.GasLimit) e.GasLimit = uint64(*dec.GasLimit)
if dec.GasUsed == nil { if dec.GasUsed == nil {
return errors.New("missing required field 'gasUsed' for ExecutableDataV1") return errors.New("missing required field 'gasUsed' for ExecutableData")
} }
e.GasUsed = uint64(*dec.GasUsed) e.GasUsed = uint64(*dec.GasUsed)
if dec.Timestamp == nil { if dec.Timestamp == nil {
return errors.New("missing required field 'timestamp' for ExecutableDataV1") return errors.New("missing required field 'timestamp' for ExecutableData")
} }
e.Timestamp = uint64(*dec.Timestamp) e.Timestamp = uint64(*dec.Timestamp)
if dec.ExtraData == nil { if dec.ExtraData == nil {
return errors.New("missing required field 'extraData' for ExecutableDataV1") return errors.New("missing required field 'extraData' for ExecutableData")
} }
e.ExtraData = *dec.ExtraData e.ExtraData = *dec.ExtraData
if dec.BaseFeePerGas == nil { if dec.BaseFeePerGas == nil {
return errors.New("missing required field 'baseFeePerGas' for ExecutableDataV1") return errors.New("missing required field 'baseFeePerGas' for ExecutableData")
} }
e.BaseFeePerGas = (*big.Int)(dec.BaseFeePerGas) e.BaseFeePerGas = (*big.Int)(dec.BaseFeePerGas)
if dec.BlockHash == nil { if dec.BlockHash == nil {
return errors.New("missing required field 'blockHash' for ExecutableDataV1") return errors.New("missing required field 'blockHash' for ExecutableData")
} }
e.BlockHash = *dec.BlockHash e.BlockHash = *dec.BlockHash
if dec.Transactions == nil { if dec.Transactions == nil {
return errors.New("missing required field 'transactions' for ExecutableDataV1") return errors.New("missing required field 'transactions' for ExecutableData")
} }
e.Transactions = make([][]byte, len(dec.Transactions)) e.Transactions = make([][]byte, len(dec.Transactions))
for k, v := range dec.Transactions { for k, v := range dec.Transactions {
e.Transactions[k] = v e.Transactions[k] = v
} }
if dec.Withdrawals != nil {
e.Withdrawals = dec.Withdrawals
}
return nil return nil
} }

46
beacon/engine/gen_epe.go Normal file
View File

@ -0,0 +1,46 @@
// Code generated by github.com/fjl/gencodec. DO NOT EDIT.
package engine
import (
"encoding/json"
"errors"
"math/big"
"github.com/ethereum/go-ethereum/common/hexutil"
)
var _ = (*executionPayloadEnvelopeMarshaling)(nil)
// MarshalJSON marshals as JSON.
func (e ExecutionPayloadEnvelope) MarshalJSON() ([]byte, error) {
type ExecutionPayloadEnvelope struct {
ExecutionPayload *ExecutableData `json:"executionPayload" gencodec:"required"`
BlockValue *hexutil.Big `json:"blockValue" gencodec:"required"`
}
var enc ExecutionPayloadEnvelope
enc.ExecutionPayload = e.ExecutionPayload
enc.BlockValue = (*hexutil.Big)(e.BlockValue)
return json.Marshal(&enc)
}
// UnmarshalJSON unmarshals from JSON.
func (e *ExecutionPayloadEnvelope) UnmarshalJSON(input []byte) error {
type ExecutionPayloadEnvelope struct {
ExecutionPayload *ExecutableData `json:"executionPayload" gencodec:"required"`
BlockValue *hexutil.Big `json:"blockValue" gencodec:"required"`
}
var dec ExecutionPayloadEnvelope
if err := json.Unmarshal(input, &dec); err != nil {
return err
}
if dec.ExecutionPayload == nil {
return errors.New("missing required field 'executionPayload' for ExecutionPayloadEnvelope")
}
e.ExecutionPayload = dec.ExecutionPayload
if dec.BlockValue == nil {
return errors.New("missing required field 'blockValue' for ExecutionPayloadEnvelope")
}
e.BlockValue = (*big.Int)(dec.BlockValue)
return nil
}

View File

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package beacon package engine
import ( import (
"fmt" "fmt"
@ -26,38 +26,41 @@ import (
"github.com/ethereum/go-ethereum/trie" "github.com/ethereum/go-ethereum/trie"
) )
//go:generate go run github.com/fjl/gencodec -type PayloadAttributesV1 -field-override payloadAttributesMarshaling -out gen_blockparams.go //go:generate go run github.com/fjl/gencodec -type PayloadAttributes -field-override payloadAttributesMarshaling -out gen_blockparams.go
// PayloadAttributesV1 structure described at https://github.com/ethereum/execution-apis/pull/74 // PayloadAttributes describes the environment context in which a block should
type PayloadAttributesV1 struct { // be built.
Timestamp uint64 `json:"timestamp" gencodec:"required"` type PayloadAttributes struct {
Random common.Hash `json:"prevRandao" gencodec:"required"` Timestamp uint64 `json:"timestamp" gencodec:"required"`
SuggestedFeeRecipient common.Address `json:"suggestedFeeRecipient" gencodec:"required"` Random common.Hash `json:"prevRandao" gencodec:"required"`
SuggestedFeeRecipient common.Address `json:"suggestedFeeRecipient" gencodec:"required"`
Withdrawals []*types.Withdrawal `json:"withdrawals"`
} }
// JSON type overrides for PayloadAttributesV1. // JSON type overrides for PayloadAttributes.
type payloadAttributesMarshaling struct { type payloadAttributesMarshaling struct {
Timestamp hexutil.Uint64 Timestamp hexutil.Uint64
} }
//go:generate go run github.com/fjl/gencodec -type ExecutableDataV1 -field-override executableDataMarshaling -out gen_ed.go //go:generate go run github.com/fjl/gencodec -type ExecutableData -field-override executableDataMarshaling -out gen_ed.go
// ExecutableDataV1 structure described at https://github.com/ethereum/execution-apis/tree/main/src/engine/specification.md // ExecutableData is the data necessary to execute an EL payload.
type ExecutableDataV1 struct { type ExecutableData struct {
ParentHash common.Hash `json:"parentHash" gencodec:"required"` ParentHash common.Hash `json:"parentHash" gencodec:"required"`
FeeRecipient common.Address `json:"feeRecipient" gencodec:"required"` FeeRecipient common.Address `json:"feeRecipient" gencodec:"required"`
StateRoot common.Hash `json:"stateRoot" gencodec:"required"` StateRoot common.Hash `json:"stateRoot" gencodec:"required"`
ReceiptsRoot common.Hash `json:"receiptsRoot" gencodec:"required"` ReceiptsRoot common.Hash `json:"receiptsRoot" gencodec:"required"`
LogsBloom []byte `json:"logsBloom" gencodec:"required"` LogsBloom []byte `json:"logsBloom" gencodec:"required"`
Random common.Hash `json:"prevRandao" gencodec:"required"` Random common.Hash `json:"prevRandao" gencodec:"required"`
Number uint64 `json:"blockNumber" gencodec:"required"` Number uint64 `json:"blockNumber" gencodec:"required"`
GasLimit uint64 `json:"gasLimit" gencodec:"required"` GasLimit uint64 `json:"gasLimit" gencodec:"required"`
GasUsed uint64 `json:"gasUsed" gencodec:"required"` GasUsed uint64 `json:"gasUsed" gencodec:"required"`
Timestamp uint64 `json:"timestamp" gencodec:"required"` Timestamp uint64 `json:"timestamp" gencodec:"required"`
ExtraData []byte `json:"extraData" gencodec:"required"` ExtraData []byte `json:"extraData" gencodec:"required"`
BaseFeePerGas *big.Int `json:"baseFeePerGas" gencodec:"required"` BaseFeePerGas *big.Int `json:"baseFeePerGas" gencodec:"required"`
BlockHash common.Hash `json:"blockHash" gencodec:"required"` BlockHash common.Hash `json:"blockHash" gencodec:"required"`
Transactions [][]byte `json:"transactions" gencodec:"required"` Transactions [][]byte `json:"transactions" gencodec:"required"`
Withdrawals []*types.Withdrawal `json:"withdrawals"`
} }
// JSON type overrides for executableData. // JSON type overrides for executableData.
@ -72,6 +75,18 @@ type executableDataMarshaling struct {
Transactions []hexutil.Bytes Transactions []hexutil.Bytes
} }
//go:generate go run github.com/fjl/gencodec -type ExecutionPayloadEnvelope -field-override executionPayloadEnvelopeMarshaling -out gen_epe.go
type ExecutionPayloadEnvelope struct {
ExecutionPayload *ExecutableData `json:"executionPayload" gencodec:"required"`
BlockValue *big.Int `json:"blockValue" gencodec:"required"`
}
// JSON type overrides for ExecutionPayloadEnvelope.
type executionPayloadEnvelopeMarshaling struct {
BlockValue *hexutil.Big
}
type PayloadStatusV1 struct { type PayloadStatusV1 struct {
Status string `json:"status"` Status string `json:"status"`
LatestValidHash *common.Hash `json:"latestValidHash"` LatestValidHash *common.Hash `json:"latestValidHash"`
@ -136,11 +151,15 @@ func decodeTransactions(enc [][]byte) ([]*types.Transaction, error) {
// ExecutableDataToBlock constructs a block from executable data. // ExecutableDataToBlock constructs a block from executable data.
// It verifies that the following fields: // It verifies that the following fields:
// len(extraData) <= 32 //
// uncleHash = emptyUncleHash // len(extraData) <= 32
// difficulty = 0 // uncleHash = emptyUncleHash
// and that the blockhash of the constructed block matches the parameters. // difficulty = 0
func ExecutableDataToBlock(params ExecutableDataV1) (*types.Block, error) { //
// and that the blockhash of the constructed block matches the parameters. Nil
// Withdrawals value will propagate through the returned block. Empty
// Withdrawals value must be passed via non-nil, length 0 value in params.
func ExecutableDataToBlock(params ExecutableData) (*types.Block, error) {
txs, err := decodeTransactions(params.Transactions) txs, err := decodeTransactions(params.Transactions)
if err != nil { if err != nil {
return nil, err return nil, err
@ -155,34 +174,43 @@ func ExecutableDataToBlock(params ExecutableDataV1) (*types.Block, error) {
if params.BaseFeePerGas != nil && (params.BaseFeePerGas.Sign() == -1 || params.BaseFeePerGas.BitLen() > 256) { if params.BaseFeePerGas != nil && (params.BaseFeePerGas.Sign() == -1 || params.BaseFeePerGas.BitLen() > 256) {
return nil, fmt.Errorf("invalid baseFeePerGas: %v", params.BaseFeePerGas) return nil, fmt.Errorf("invalid baseFeePerGas: %v", params.BaseFeePerGas)
} }
header := &types.Header{ // Only set withdrawalsRoot if it is non-nil. This allows CLs to use
ParentHash: params.ParentHash, // ExecutableData before withdrawals are enabled by marshaling
UncleHash: types.EmptyUncleHash, // Withdrawals as the json null value.
Coinbase: params.FeeRecipient, var withdrawalsRoot *common.Hash
Root: params.StateRoot, if params.Withdrawals != nil {
TxHash: types.DeriveSha(types.Transactions(txs), trie.NewStackTrie(nil)), h := types.DeriveSha(types.Withdrawals(params.Withdrawals), trie.NewStackTrie(nil))
ReceiptHash: params.ReceiptsRoot, withdrawalsRoot = &h
Bloom: types.BytesToBloom(params.LogsBloom),
Difficulty: common.Big0,
Number: new(big.Int).SetUint64(params.Number),
GasLimit: params.GasLimit,
GasUsed: params.GasUsed,
Time: params.Timestamp,
BaseFee: params.BaseFeePerGas,
Extra: params.ExtraData,
MixDigest: params.Random,
} }
block := types.NewBlockWithHeader(header).WithBody(txs, nil /* uncles */) header := &types.Header{
ParentHash: params.ParentHash,
UncleHash: types.EmptyUncleHash,
Coinbase: params.FeeRecipient,
Root: params.StateRoot,
TxHash: types.DeriveSha(types.Transactions(txs), trie.NewStackTrie(nil)),
ReceiptHash: params.ReceiptsRoot,
Bloom: types.BytesToBloom(params.LogsBloom),
Difficulty: common.Big0,
Number: new(big.Int).SetUint64(params.Number),
GasLimit: params.GasLimit,
GasUsed: params.GasUsed,
Time: params.Timestamp,
BaseFee: params.BaseFeePerGas,
Extra: params.ExtraData,
MixDigest: params.Random,
WithdrawalsHash: withdrawalsRoot,
}
block := types.NewBlockWithHeader(header).WithBody(txs, nil /* uncles */).WithWithdrawals(params.Withdrawals)
if block.Hash() != params.BlockHash { if block.Hash() != params.BlockHash {
return nil, fmt.Errorf("blockhash mismatch, want %x, got %x", params.BlockHash, block.Hash()) return nil, fmt.Errorf("blockhash mismatch, want %x, got %x", params.BlockHash, block.Hash())
} }
return block, nil return block, nil
} }
// BlockToExecutableData constructs the executableDataV1 structure by filling the // BlockToExecutableData constructs the ExecutableData structure by filling the
// fields from the given block. It assumes the given block is post-merge block. // fields from the given block. It assumes the given block is post-merge block.
func BlockToExecutableData(block *types.Block) *ExecutableDataV1 { func BlockToExecutableData(block *types.Block, fees *big.Int) *ExecutionPayloadEnvelope {
return &ExecutableDataV1{ data := &ExecutableData{
BlockHash: block.Hash(), BlockHash: block.Hash(),
ParentHash: block.ParentHash(), ParentHash: block.ParentHash(),
FeeRecipient: block.Coinbase(), FeeRecipient: block.Coinbase(),
@ -197,5 +225,13 @@ func BlockToExecutableData(block *types.Block) *ExecutableDataV1 {
Transactions: encodeTransactions(block.Transactions()), Transactions: encodeTransactions(block.Transactions()),
Random: block.MixDigest(), Random: block.MixDigest(),
ExtraData: block.Extra(), ExtraData: block.Extra(),
Withdrawals: block.Withdrawals(),
} }
return &ExecutionPayloadEnvelope{ExecutionPayload: data, BlockValue: fees}
}
// ExecutionPayloadBodyV1 is used in the response to GetPayloadBodiesByHashV1 and GetPayloadBodiesByRangeV1
type ExecutionPayloadBodyV1 struct {
TransactionData []hexutil.Bytes `json:"transactions"`
Withdrawals []*types.Withdrawal `json:"withdrawals"`
} }

View File

@ -1,38 +1,46 @@
# This file contains sha256 checksums of optional build dependencies. # This file contains sha256 checksums of optional build dependencies.
9920d3306a1ac536cdd2c796d6cb3c54bc559c226fc3cc39c32f1e0bd7f50d2a go1.18.5.src.tar.gz e447b498cde50215c4f7619e5124b0fc4e25fb5d16ea47271c47f278e7aa763a go1.20.3.src.tar.gz
828eeca8b5abea3e56921df8fa4b1101380a5ebcfee10acbc8ffe7ec0bf5876b go1.18.5.darwin-amd64.tar.gz c1e1161d6d859deb576e6cfabeb40e3d042ceb1c6f444f617c3c9d76269c3565 go1.20.3.darwin-amd64.tar.gz
923a377c6fc9a2c789f5db61c24b8f64133f7889056897449891f256af34065f go1.18.5.darwin-arm64.tar.gz 86b0ed0f2b2df50fa8036eea875d1cf2d76cefdacf247c44639a1464b7e36b95 go1.20.3.darwin-arm64.tar.gz
c3d90264a706e2d88cfb44126dc6f0d008a48f00732e04bc377cea1a2b716a7c go1.18.5.freebsd-386.tar.gz 340e80abd047c597fdc0f50a6cc59617f06c297d62f7fc77f4a0164e2da6f7aa go1.20.3.freebsd-386.tar.gz
0de23843c568d388bc0f0e390a8966938cccaae0d74b698325f7175bac04e0c6 go1.18.5.freebsd-amd64.tar.gz 2169fcd8b6c94c5fbe07c0b470ccfb6001d343f6548ad49f3d9ab78e3b5753c7 go1.20.3.freebsd-amd64.tar.gz
0c44f85d146c6f98c34e8ff436a42af22e90e36fe232d3d9d3101f23fd61362b go1.18.5.linux-386.tar.gz e12384311403f1389d14cc1c1295bfb4e0dd5ab919403b80da429f671a223507 go1.20.3.linux-386.tar.gz
9e5de37f9c49942c601b191ac5fba404b868bfc21d446d6960acc12283d6e5f2 go1.18.5.linux-amd64.tar.gz 979694c2c25c735755bf26f4f45e19e64e4811d661dd07b8c010f7a8e18adfca go1.20.3.linux-amd64.tar.gz
006f6622718212363fa1ff004a6ab4d87bbbe772ec5631bab7cac10be346e4f1 go1.18.5.linux-arm64.tar.gz eb186529f13f901e7a2c4438a05c2cd90d74706aaa0a888469b2a4a617b6ee54 go1.20.3.linux-arm64.tar.gz
d5ac34ac5f060a5274319aa04b7b11e41b123bd7887d64efb5f44ead236957af go1.18.5.linux-armv6l.tar.gz b421e90469a83671641f81b6e20df6500f033e9523e89cbe7b7223704dd1035c go1.20.3.linux-armv6l.tar.gz
2e37fb9c7cbaedd4e729492d658aa4cde821fc94117391a8105c13b25ca1c84b go1.18.5.linux-ppc64le.tar.gz 943c89aa1624ea544a022b31e3d6e16a037200e436370bdd5fd67f3fa60be282 go1.20.3.linux-ppc64le.tar.gz
e3d536e7873639f85353e892444f83b14cb6670603961f215986ae8e28e8e07a go1.18.5.linux-s390x.tar.gz 126cf823a5634ef2544b866db107b9d351d3ea70d9e240b0bdcfb46f4dcae54b go1.20.3.linux-s390x.tar.gz
7b3142ec0c5db991e7f73a231662a92429b90ee151fe47557acb566d8d9ae4d3 go1.18.5.windows-386.zip 37e9146e1f9d681cfcaa6fee6c7b890c44c64bc50228c9588f3c4231346d33bd go1.20.3.windows-386.zip
73753620602d4b4469770040c53db55e5dd6af2ad07ecc18f71f164c3224eaad go1.18.5.windows-amd64.zip 143a2837821c7dbacf7744cbb1a8421c1f48307c6fdfaeffc5f8c2f69e1b7932 go1.20.3.windows-amd64.zip
4d154626affff12ef73ea1017af0e5b52dbc839ef92f6f9e76cf4f71278a5744 go1.18.5.windows-arm64.zip 158cb159e00bc979f473e0f5b5a561613129c5e51067967b72b8e072e5a4db81 go1.20.3.windows-arm64.zip
658078aaaf7608693f37c4cf1380b2af418ab8b2d23fdb33e7e2d4339328590e golangci-lint-1.46.2-darwin-amd64.tar.gz fba08acc4027f69f07cef48fbff70b8a7ecdfaa1c2aba9ad3fb31d60d9f5d4bc golangci-lint-1.51.1-darwin-amd64.tar.gz
81f9b4afd62ec5e612ef8bc3b1d612a88b56ff289874831845cdad394427385f golangci-lint-1.46.2-darwin-arm64.tar.gz 75b8f0ff3a4e68147156be4161a49d4576f1be37a0b506473f8c482140c1e7f2 golangci-lint-1.51.1-darwin-arm64.tar.gz
943486e703e62ec55ecd90caeb22bcd39f8cc3962a93eec18c06b7bae12cb46f golangci-lint-1.46.2-freebsd-386.tar.gz e06b3459aaed356e1667580be00b05f41f3b2e29685d12cdee571c23e1edb414 golangci-lint-1.51.1-freebsd-386.tar.gz
a75dd9ba7e08e8315c411697171db5375c0f6a1ece9e6fbeb9e9a4386822e17d golangci-lint-1.46.2-freebsd-amd64.tar.gz 623ce2d0fa4d35cc2e8d69fa7334227ab592380962a13b4d9cdc77cf41db2008 golangci-lint-1.51.1-freebsd-amd64.tar.gz
83eedca1af72e8be055a1235177eb1b33524fbf08bec5730df2e6c3efade2b23 golangci-lint-1.46.2-freebsd-armv6.tar.gz 131365feb0584cc2736c43192fa673ca50e5b6b765456990cb379ecfb787e568 golangci-lint-1.51.1-freebsd-armv6.tar.gz
513d276c490de6f82baa01f9346d8d78b385f2ae97608f42f05d1f0f1314cd54 golangci-lint-1.46.2-freebsd-armv7.tar.gz 98fb627927cbb654f5bf85dcffc5f646666b2ce96ea0fed977c9fb28abd51532 golangci-lint-1.51.1-freebsd-armv7.tar.gz
461a60016d516c69d406dc3e2d4957b722dbe684b7085dfac4802d0f84409e27 golangci-lint-1.46.2-linux-386.tar.gz b36a99702fa762c15840261bc0fb41b4b1b16b8b19b8c0941bae98c85bb0f8b8 golangci-lint-1.51.1-linux-386.tar.gz
242cd4f2d6ac0556e315192e8555784d13da5d1874e51304711570769c4f2b9b golangci-lint-1.46.2-linux-amd64.tar.gz 17aeb26c76820c22efa0e1838b0ab93e90cfedef43fbfc9a2f33f27eb9e5e070 golangci-lint-1.51.1-linux-amd64.tar.gz
ff5448ada2b3982581984d64b0dec614dba0a3ea4cab2d6a343c77927fc89f7e golangci-lint-1.46.2-linux-arm64.tar.gz 9744bc34e7b8d82ca788b667bfb7155a39b4be9aef43bf9f10318b1372cea338 golangci-lint-1.51.1-linux-arm64.tar.gz
177f5210ef04aee282bfbc6ec519d36af5fb7d2b2c8d3f4ea5e59fdba71b0a27 golangci-lint-1.46.2-linux-armv6.tar.gz 0dda8dbeb2ff7455a044ec8e347f2fc6d655d2e99d281b3b95e88167031c673d golangci-lint-1.51.1-linux-armv6.tar.gz
10dd512a36ee978a1009edbca3ba3af410f0fda8df4d85f0e4793a24213870cc golangci-lint-1.46.2-linux-armv7.tar.gz 0512f311b11d43b8b22989d929f0fe8a2e1e5ebe497f1eb0ff73a0fc3d188fd1 golangci-lint-1.51.1-linux-armv7.tar.gz
67779fa517c688c9db1090c3c456117d95c6b92979c623fe8cce8fb84251f21e golangci-lint-1.46.2-linux-mips64.tar.gz d767108dcf84a8eaa844df3454cb0f75a492f4e7102ecc2b0a3545cfe073a566 golangci-lint-1.51.1-linux-loong64.tar.gz
c085f0f57bdccbb2c902a41b72ce210a3dfff16ca856789374745ab52004b6ee golangci-lint-1.46.2-linux-mips64le.tar.gz 3bd56c54daec16585b2668e0dfabb27af2c2b38cc0fdb46923e2521e1634846b golangci-lint-1.51.1-linux-mips64.tar.gz
abecef6421499248e58ed75d2938bc12b4b1f98b057f25060680b77bb51a881e golangci-lint-1.46.2-linux-ppc64le.tar.gz f72f5adfa2219e15d2414c9a2966f86e74556cf17a85c727a7fb7770a16cf814 golangci-lint-1.51.1-linux-mips64le.tar.gz
134843a8f5c5c182c11979ea75f5866945d54757b2a04f3e5e04a0cf4fbf3a39 golangci-lint-1.46.2-linux-riscv64.tar.gz e605521dac98096d8737e1997c954f41f1d0d8275b8731f62783d410c23574b9 golangci-lint-1.51.1-linux-ppc64le.tar.gz
9fe21a9476567aafe7a2e1a926b9641a39f920d4c0ea8eda9d968bc6136337f9 golangci-lint-1.46.2-linux-s390x.tar.gz 2f683217b814339e74d61ca700922d8407f15addd6d4c5e8b156fbab79f26a87 golangci-lint-1.51.1-linux-riscv64.tar.gz
b48a421ec12a43f8fc8f977b9cf7d4a1ea1c4b97f803a238de7d3ce4ab23a84b golangci-lint-1.46.2-windows-386.zip d98528292b65971a3594e5880530e7624597dc9806fcfccdfbe39be411713d63 golangci-lint-1.51.1-linux-s390x.tar.gz
604acc1378a566abb0eac799362f3a37b7fcb5fa2268aeb2d5d954c829367301 golangci-lint-1.46.2-windows-amd64.zip 9bb2d0fe9e692ed0aea4f2537e3e6862b2f6768fe2849a84f4a6ad09da9fd971 golangci-lint-1.51.1-netbsd-386.tar.gz
927def10db073da9687594072e6a3d9c891f67fa897105a2cfd715e018e7386c golangci-lint-1.46.2-windows-arm64.zip 34cafdcd11ae73ae88d66c33eb8449f5c976fc3e37b44774dbe9c71caa95e592 golangci-lint-1.51.1-netbsd-amd64.tar.gz
729b76ed1d8b4e2612e38772b211503cb940e00a137bbaace1aa066f7c943737 golangci-lint-1.46.2-windows-armv6.zip f8b4e1e47ac17caafe8a5f32f975a2b6a7cb14c27c0f73c1fb15c20ca91c2e03 golangci-lint-1.51.1-netbsd-armv6.tar.gz
ea27c86d91e0b245ecbcfbf6cdb4ac0522d4bc6dca56bba02ea1bc77ad2917ac golangci-lint-1.46.2-windows-armv7.zip c4f58b7e227b9fd41f0e9310dc83f4a4e7d026598e2f6e95b78761081a6d9bd2 golangci-lint-1.51.1-netbsd-armv7.tar.gz
6710e2f5375dc75521c1a17980a6cbbe6ff76c2f8b852964a8af558899a97cf5 golangci-lint-1.51.1-windows-386.zip
722d7b87b9cdda0a3835d5030b3fc5385c2eba4c107f63f6391cfb2ac35f051d golangci-lint-1.51.1-windows-amd64.zip
eb57f9bcb56646f2e3d6ccaf02ec227815fb05077b2e0b1bf9e755805acdc2b9 golangci-lint-1.51.1-windows-arm64.zip
bce02f7232723cb727755ee11f168a700a00896a25d37f87c4b173bce55596b4 golangci-lint-1.51.1-windows-armv6.zip
cf6403f84707ce8c98664736772271bc8874f2e760c2fd0f00cf3e85963507e9 golangci-lint-1.51.1-windows-armv7.zip
# This is the builder on PPA that will build Go itself (inception-y), don't modify!
d7f0013f82e6d7f862cc6cb5c8cdb48eef5f2e239b35baa97e2f1a7466043767 go1.19.6.src.tar.gz

View File

@ -24,24 +24,20 @@ Usage: go run build/ci.go <command> <command flags/arguments>
Available commands are: Available commands are:
install [ -arch architecture ] [ -cc compiler ] [ packages... ] -- builds packages and executables install [ -arch architecture ] [ -cc compiler ] [ packages... ] -- builds packages and executables
test [ -coverage ] [ packages... ] -- runs the tests test [ -coverage ] [ packages... ] -- runs the tests
lint -- runs certain pre-selected linters lint -- runs certain pre-selected linters
archive [ -arch architecture ] [ -type zip|tar ] [ -signer key-envvar ] [ -signify key-envvar ] [ -upload dest ] -- archives build artifacts archive [ -arch architecture ] [ -type zip|tar ] [ -signer key-envvar ] [ -signify key-envvar ] [ -upload dest ] -- archives build artifacts
importkeys -- imports signing keys from env importkeys -- imports signing keys from env
debsrc [ -signer key-id ] [ -upload dest ] -- creates a debian source package debsrc [ -signer key-id ] [ -upload dest ] -- creates a debian source package
nsis -- creates a Windows NSIS installer nsis -- creates a Windows NSIS installer
aar [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ] -- creates an Android archive purge [ -store blobstore ] [ -days threshold ] -- purges old archives from the blobstore
xcode [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ] -- creates an iOS XCode framework
purge [ -store blobstore ] [ -days threshold ] -- purges old archives from the blobstore
For all commands, -n prevents execution of external programs (dry run mode). For all commands, -n prevents execution of external programs (dry run mode).
*/ */
package main package main
import ( import (
"bufio"
"bytes" "bytes"
"encoding/base64" "encoding/base64"
"flag" "flag"
@ -51,7 +47,6 @@ import (
"os/exec" "os/exec"
"path" "path"
"path/filepath" "path/filepath"
"regexp"
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
@ -78,7 +73,6 @@ var (
executablePath("bootnode"), executablePath("bootnode"),
executablePath("evm"), executablePath("evm"),
executablePath("geth"), executablePath("geth"),
executablePath("puppeth"),
executablePath("rlpdump"), executablePath("rlpdump"),
executablePath("clef"), executablePath("clef"),
} }
@ -101,10 +95,6 @@ var (
BinaryName: "geth", BinaryName: "geth",
Description: "Ethereum CLI client.", Description: "Ethereum CLI client.",
}, },
{
BinaryName: "puppeth",
Description: "Ethereum private network manager.",
},
{ {
BinaryName: "rlpdump", BinaryName: "rlpdump",
Description: "Developer utility tool that prints RLP structures.", Description: "Developer utility tool that prints RLP structures.",
@ -130,15 +120,15 @@ var (
// Distros for which packages are created. // Distros for which packages are created.
// Note: vivid is unsupported because there is no golang-1.6 package for it. // Note: vivid is unsupported because there is no golang-1.6 package for it.
// Note: the following Ubuntu releases have been officially deprecated on Launchpad: // Note: the following Ubuntu releases have been officially deprecated on Launchpad:
// wily, yakkety, zesty, artful, cosmic, disco, eoan, groovy, hirsuite // wily, yakkety, zesty, artful, cosmic, disco, eoan, groovy, hirsuite, impish
debDistroGoBoots = map[string]string{ debDistroGoBoots = map[string]string{
"trusty": "golang-1.11", // EOL: 04/2024 "trusty": "golang-1.11", // EOL: 04/2024
"xenial": "golang-go", // EOL: 04/2026 "xenial": "golang-go", // EOL: 04/2026
"bionic": "golang-go", // EOL: 04/2028 "bionic": "golang-go", // EOL: 04/2028
"focal": "golang-go", // EOL: 04/2030 "focal": "golang-go", // EOL: 04/2030
"impish": "golang-go", // EOL: 07/2022 "jammy": "golang-go", // EOL: 04/2032
"jammy": "golang-go", // EOL: 04/2032 "kinetic": "golang-go", // EOL: 07/2023
//"kinetic": "golang-go", // EOL: 07/2023 "lunar": "golang-go", // EOL: 01/2024
} }
debGoBootPaths = map[string]string{ debGoBootPaths = map[string]string{
@ -146,10 +136,18 @@ var (
"golang-go": "/usr/lib/go", "golang-go": "/usr/lib/go",
} }
// This is the version of go that will be downloaded by // This is the version of Go that will be downloaded by
// //
// go run ci.go install -dlgo // go run ci.go install -dlgo
dlgoVersion = "1.18.5" dlgoVersion = "1.20.3"
// This is the version of Go that will be used to bootstrap the PPA builder.
//
// This version is fine to be old and full of security holes, we just use it
// to build the latest Go. Don't change it. If it ever becomes insufficient,
// we need to switch over to a recursive builder to jumpt across supported
// versions.
gobootVersion = "1.19.6"
) )
var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin")) var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
@ -185,10 +183,6 @@ func main() {
doDebianSource(os.Args[2:]) doDebianSource(os.Args[2:])
case "nsis": case "nsis":
doWindowsInstaller(os.Args[2:]) doWindowsInstaller(os.Args[2:])
case "aar":
doAndroidArchive(os.Args[2:])
case "xcode":
doXCodeFramework(os.Args[2:])
case "purge": case "purge":
doPurge(os.Args[2:]) doPurge(os.Args[2:])
default: default:
@ -255,8 +249,8 @@ func doInstall(cmdline []string) {
func buildFlags(env build.Environment, staticLinking bool, buildTags []string) (flags []string) { func buildFlags(env build.Environment, staticLinking bool, buildTags []string) (flags []string) {
var ld []string var ld []string
if env.Commit != "" { if env.Commit != "" {
ld = append(ld, "-X", "main.gitCommit="+env.Commit) ld = append(ld, "-X", "github.com/ethereum/go-ethereum/internal/version.gitCommit="+env.Commit)
ld = append(ld, "-X", "main.gitDate="+env.Date) ld = append(ld, "-X", "github.com/ethereum/go-ethereum/internal/version.gitDate="+env.Date)
} }
// Strip DWARF on darwin. This used to be required for certain things, // Strip DWARF on darwin. This used to be required for certain things,
// and there is no downside to this, so we just keep doing it. // and there is no downside to this, so we just keep doing it.
@ -347,7 +341,7 @@ func doLint(cmdline []string) {
// downloadLinter downloads and unpacks golangci-lint. // downloadLinter downloads and unpacks golangci-lint.
func downloadLinter(cachedir string) string { func downloadLinter(cachedir string) string {
const version = "1.46.2" const version = "1.51.1"
csdb := build.MustLoadChecksums("build/checksums.txt") csdb := build.MustLoadChecksums("build/checksums.txt")
arch := runtime.GOARCH arch := runtime.GOARCH
@ -471,10 +465,6 @@ func maybeSkipArchive(env build.Environment) {
log.Printf("skipping archive creation because this is a PR build") log.Printf("skipping archive creation because this is a PR build")
os.Exit(0) os.Exit(0)
} }
if env.IsCronJob {
log.Printf("skipping archive creation because this is a cron job")
os.Exit(0)
}
if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") { if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
log.Printf("skipping archive creation because branch %q, tag %q is not on the inclusion list", env.Branch, env.Tag) log.Printf("skipping archive creation because branch %q, tag %q is not on the inclusion list", env.Branch, env.Tag)
os.Exit(0) os.Exit(0)
@ -669,10 +659,11 @@ func doDebianSource(cmdline []string) {
gpg.Stdin = bytes.NewReader(key) gpg.Stdin = bytes.NewReader(key)
build.MustRun(gpg) build.MustRun(gpg)
} }
// Download and verify the Go source packages.
// Download and verify the Go source package. var (
gobundle := downloadGoSources(*cachedir) gobootbundle = downloadGoBootstrapSources(*cachedir)
gobundle = downloadGoSources(*cachedir)
)
// Download all the dependencies needed to build the sources and run the ci script // Download all the dependencies needed to build the sources and run the ci script
srcdepfetch := tc.Go("mod", "download") srcdepfetch := tc.Go("mod", "download")
srcdepfetch.Env = append(srcdepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath")) srcdepfetch.Env = append(srcdepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath"))
@ -689,12 +680,19 @@ func doDebianSource(cmdline []string) {
meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables) meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
pkgdir := stageDebianSource(*workdir, meta) pkgdir := stageDebianSource(*workdir, meta)
// Add Go source code // Add bootstrapper Go source code
if err := build.ExtractArchive(gobootbundle, pkgdir); err != nil {
log.Fatalf("Failed to extract bootstrapper Go sources: %v", err)
}
if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".goboot")); err != nil {
log.Fatalf("Failed to rename bootstrapper Go source folder: %v", err)
}
// Add builder Go source code
if err := build.ExtractArchive(gobundle, pkgdir); err != nil { if err := build.ExtractArchive(gobundle, pkgdir); err != nil {
log.Fatalf("Failed to extract Go sources: %v", err) log.Fatalf("Failed to extract builder Go sources: %v", err)
} }
if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil { if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil {
log.Fatalf("Failed to rename Go source folder: %v", err) log.Fatalf("Failed to rename builder Go source folder: %v", err)
} }
// Add all dependency modules in compressed form // Add all dependency modules in compressed form
os.MkdirAll(filepath.Join(pkgdir, ".mod", "cache"), 0755) os.MkdirAll(filepath.Join(pkgdir, ".mod", "cache"), 0755)
@ -723,6 +721,19 @@ func doDebianSource(cmdline []string) {
} }
} }
// downloadGoBootstrapSources downloads the Go source tarball that will be used
// to bootstrap the builder Go.
func downloadGoBootstrapSources(cachedir string) string {
csdb := build.MustLoadChecksums("build/checksums.txt")
file := fmt.Sprintf("go%s.src.tar.gz", gobootVersion)
url := "https://dl.google.com/go/" + file
dst := filepath.Join(cachedir, file)
if err := csdb.DownloadFile(url, dst); err != nil {
log.Fatal(err)
}
return dst
}
// downloadGoSources downloads the Go source tarball. // downloadGoSources downloads the Go source tarball.
func downloadGoSources(cachedir string) string { func downloadGoSources(cachedir string) string {
csdb := build.MustLoadChecksums("build/checksums.txt") csdb := build.MustLoadChecksums("build/checksums.txt")
@ -982,7 +993,10 @@ func doWindowsInstaller(cmdline []string) {
if env.Commit != "" { if env.Commit != "" {
version[2] += "-" + env.Commit[:8] version[2] += "-" + env.Commit[:8]
} }
installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe") installer, err := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
if err != nil {
log.Fatalf("Failed to convert installer file path: %v", err)
}
build.MustRunCommand("makensis.exe", build.MustRunCommand("makensis.exe",
"/DOUTPUTFILE="+installer, "/DOUTPUTFILE="+installer,
"/DMAJORVERSION="+version[0], "/DMAJORVERSION="+version[0],
@ -997,236 +1011,6 @@ func doWindowsInstaller(cmdline []string) {
} }
} }
// Android archives
func doAndroidArchive(cmdline []string) {
var (
local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
signify = flag.String("signify", "", `Environment variable holding the signify signing key (e.g. ANDROID_SIGNIFY_KEY)`)
deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
)
flag.CommandLine.Parse(cmdline)
env := build.Env()
tc := new(build.GoToolchain)
// Sanity check that the SDK and NDK are installed and set
if os.Getenv("ANDROID_HOME") == "" {
log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
}
// Build gomobile.
install := tc.Install(GOBIN, "golang.org/x/mobile/cmd/gomobile@latest", "golang.org/x/mobile/cmd/gobind@latest")
install.Env = append(install.Env)
build.MustRun(install)
// Ensure all dependencies are available. This is required to make
// gomobile bind work because it expects go.sum to contain all checksums.
build.MustRun(tc.Go("mod", "download"))
// Build the Android archive and Maven resources
build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
if *local {
// If we're building locally, copy bundle to build dir and skip Maven
os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
os.Rename("geth-sources.jar", filepath.Join(GOBIN, "geth-sources.jar"))
return
}
meta := newMavenMetadata(env)
build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
// Skip Maven deploy and Azure upload for PR builds
maybeSkipArchive(env)
// Sign and upload the archive to Azure
archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar"
os.Rename("geth.aar", archive)
if err := archiveUpload(archive, *upload, *signer, *signify); err != nil {
log.Fatal(err)
}
// Sign and upload all the artifacts to Maven Central
os.Rename(archive, meta.Package+".aar")
if *signer != "" && *deploy != "" {
// Import the signing key into the local GPG instance
key := getenvBase64(*signer)
gpg := exec.Command("gpg", "--import")
gpg.Stdin = bytes.NewReader(key)
build.MustRun(gpg)
keyID, err := build.PGPKeyID(string(key))
if err != nil {
log.Fatal(err)
}
// Upload the artifacts to Sonatype and/or Maven Central
repo := *deploy + "/service/local/staging/deploy/maven2"
if meta.Develop {
repo = *deploy + "/content/repositories/snapshots"
}
build.MustRunCommand("mvn", "gpg:sign-and-deploy-file", "-e", "-X",
"-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
"-Dgpg.keyname="+keyID,
"-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
}
}
func gomobileTool(subcmd string, args ...string) *exec.Cmd {
cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
cmd.Args = append(cmd.Args, args...)
cmd.Env = []string{
"PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"),
}
for _, e := range os.Environ() {
if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") || strings.HasPrefix(e, "GOBIN=") {
continue
}
cmd.Env = append(cmd.Env, e)
}
cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
return cmd
}
type mavenMetadata struct {
Version string
Package string
Develop bool
Contributors []mavenContributor
}
type mavenContributor struct {
Name string
Email string
}
func newMavenMetadata(env build.Environment) mavenMetadata {
// Collect the list of authors from the repo root
contribs := []mavenContributor{}
if authors, err := os.Open("AUTHORS"); err == nil {
defer authors.Close()
scanner := bufio.NewScanner(authors)
for scanner.Scan() {
// Skip any whitespace from the authors list
line := strings.TrimSpace(scanner.Text())
if line == "" || line[0] == '#' {
continue
}
// Split the author and insert as a contributor
re := regexp.MustCompile("([^<]+) <(.+)>")
parts := re.FindStringSubmatch(line)
if len(parts) == 3 {
contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
}
}
}
// Render the version and package strings
version := params.Version
if isUnstableBuild(env) {
version += "-SNAPSHOT"
}
return mavenMetadata{
Version: version,
Package: "geth-" + version,
Develop: isUnstableBuild(env),
Contributors: contribs,
}
}
// XCode frameworks
func doXCodeFramework(cmdline []string) {
var (
local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
signify = flag.String("signify", "", `Environment variable holding the signify signing key (e.g. IOS_SIGNIFY_KEY)`)
deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
)
flag.CommandLine.Parse(cmdline)
env := build.Env()
tc := new(build.GoToolchain)
// Build gomobile.
build.MustRun(tc.Install(GOBIN, "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
// Build the iOS XCode framework
bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
if *local {
// If we're building locally, use the build folder and stop afterwards
bind.Dir = GOBIN
build.MustRun(bind)
return
}
// Create the archive.
maybeSkipArchive(env)
archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
if err := os.MkdirAll(archive, 0755); err != nil {
log.Fatal(err)
}
bind.Dir, _ = filepath.Abs(archive)
build.MustRun(bind)
build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
// Sign and upload the framework to Azure
if err := archiveUpload(archive+".tar.gz", *upload, *signer, *signify); err != nil {
log.Fatal(err)
}
// Prepare and upload a PodSpec to CocoaPods
if *deploy != "" {
meta := newPodMetadata(env, archive)
build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings")
}
}
type podMetadata struct {
Version string
Commit string
Archive string
Contributors []podContributor
}
type podContributor struct {
Name string
Email string
}
func newPodMetadata(env build.Environment, archive string) podMetadata {
// Collect the list of authors from the repo root
contribs := []podContributor{}
if authors, err := os.Open("AUTHORS"); err == nil {
defer authors.Close()
scanner := bufio.NewScanner(authors)
for scanner.Scan() {
// Skip any whitespace from the authors list
line := strings.TrimSpace(scanner.Text())
if line == "" || line[0] == '#' {
continue
}
// Split the author and insert as a contributor
re := regexp.MustCompile("([^<]+) <(.+)>")
parts := re.FindStringSubmatch(line)
if len(parts) == 3 {
contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
}
}
}
version := params.Version
if isUnstableBuild(env) {
version += "-unstable." + env.Buildnum
}
return podMetadata{
Archive: archive,
Version: version,
Commit: env.Commit,
Contributors: contribs,
}
}
// Binary distribution cleanups // Binary distribution cleanups
func doPurge(cmdline []string) { func doPurge(cmdline []string) {

View File

@ -16,7 +16,11 @@ override_dh_auto_build:
# We can't download a fresh Go within Launchpad, so we're shipping and building # We can't download a fresh Go within Launchpad, so we're shipping and building
# one on the fly. However, we can't build it inside the go-ethereum folder as # one on the fly. However, we can't build it inside the go-ethereum folder as
# bootstrapping clashes with go modules, so build in a sibling folder. # bootstrapping clashes with go modules, so build in a sibling folder.
(mv .go ../ && cd ../.go/src && ./make.bash) #
# We're also shipping the bootstrapper as of Go 1.20 as it had minimum version
# requirements opposed to older versions of Go.
(mv .goboot ../ && cd ../.goboot/src && ./make.bash)
(mv .go ../ && cd ../.go/src && GOROOT_BOOTSTRAP=`pwd`/../../.goboot ./make.bash)
# We can't download external go modules within Launchpad, so we're shipping the # We can't download external go modules within Launchpad, so we're shipping the
# entire dependency source cache with go-ethereum. # entire dependency source cache with go-ethereum.

View File

@ -1,57 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.ethereum</groupId>
<artifactId>geth</artifactId>
<version>{{.Version}}</version>
<packaging>aar</packaging>
<name>Android Ethereum Client</name>
<description>Android port of the go-ethereum libraries and node</description>
<url>https://github.com/ethereum/go-ethereum</url>
<inceptionYear>2015</inceptionYear>
<licenses>
<license>
<name>GNU Lesser General Public License, Version 3.0</name>
<url>https://www.gnu.org/licenses/lgpl-3.0.en.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<organization>
<name>Ethereum</name>
<url>https://ethereum.org</url>
</organization>
<developers>
<developer>
<id>karalabe</id>
<name>Péter Szilágyi</name>
<email>peterke@gmail.com</email>
<url>https://github.com/karalabe</url>
<properties>
<picUrl>https://www.gravatar.com/avatar/2ecbf0f5b4b79eebf8c193e5d324357f?s=256</picUrl>
</properties>
</developer>
</developers>
<contributors>{{range .Contributors}}
<contributor>
<name>{{.Name}}</name>
<email>{{.Email}}</email>
</contributor>{{end}}
</contributors>
<issueManagement>
<system>GitHub Issues</system>
<url>https://github.com/ethereum/go-ethereum/issues/</url>
</issueManagement>
<scm>
<url>https://github.com/ethereum/go-ethereum</url>
</scm>
</project>

View File

@ -1,24 +0,0 @@
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<servers>
<server>
<id>ossrh</id>
<username>${env.ANDROID_SONATYPE_USERNAME}</username>
<password>${env.ANDROID_SONATYPE_PASSWORD}</password>
</server>
</servers>
<profiles>
<profile>
<id>ossrh</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<gpg.executable>gpg</gpg.executable>
<gpg.passphrase></gpg.passphrase>
</properties>
</profile>
</profiles>
</settings>

View File

@ -1,22 +0,0 @@
Pod::Spec.new do |spec|
spec.name = 'Geth'
spec.version = '{{.Version}}'
spec.license = { :type => 'GNU Lesser General Public License, Version 3.0' }
spec.homepage = 'https://github.com/ethereum/go-ethereum'
spec.authors = { {{range .Contributors}}
'{{.Name}}' => '{{.Email}}',{{end}}
}
spec.summary = 'iOS Ethereum Client'
spec.source = { :git => 'https://github.com/ethereum/go-ethereum.git', :commit => '{{.Commit}}' }
spec.platform = :ios
spec.ios.deployment_target = '9.0'
spec.ios.vendored_frameworks = 'Frameworks/Geth.framework'
spec.prepare_command = <<-CMD
curl https://gethstore.blob.core.windows.net/builds/{{.Archive}}.tar.gz | tar -xvz
mkdir Frameworks
mv {{.Archive}}/Geth.framework Frameworks
rm -rf {{.Archive}}
CMD
end

View File

@ -24,8 +24,4 @@ import (
_ "github.com/fjl/gencodec" _ "github.com/fjl/gencodec"
_ "github.com/golang/protobuf/protoc-gen-go" _ "github.com/golang/protobuf/protoc-gen-go"
_ "golang.org/x/tools/cmd/stringer" _ "golang.org/x/tools/cmd/stringer"
// Tool imports for mobile build.
_ "golang.org/x/mobile/cmd/gobind"
_ "golang.org/x/mobile/cmd/gomobile"
) )

View File

@ -342,7 +342,10 @@ func isGenerated(file string) bool {
} }
defer fd.Close() defer fd.Close()
buf := make([]byte, 2048) buf := make([]byte, 2048)
n, _ := fd.Read(buf) n, err := fd.Read(buf)
if err != nil {
return false
}
buf = buf[:n] buf = buf[:n]
for _, l := range bytes.Split(buf, []byte("\n")) { for _, l := range bytes.Split(buf, []byte("\n")) {
if bytes.HasPrefix(l, []byte("// Code generated")) { if bytes.HasPrefix(l, []byte("// Code generated")) {

View File

@ -33,14 +33,6 @@ import (
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
) )
var (
// Git SHA1 commit hash of the release (set via linker flags)
gitCommit = ""
gitDate = ""
app *cli.App
)
var ( var (
// Flags needed by abigen // Flags needed by abigen
abiFlag = &cli.StringFlag{ abiFlag = &cli.StringFlag{
@ -73,7 +65,7 @@ var (
} }
langFlag = &cli.StringFlag{ langFlag = &cli.StringFlag{
Name: "lang", Name: "lang",
Usage: "Destination language for the bindings (go, java, objc)", Usage: "Destination language for the bindings (go)",
Value: "go", Value: "go",
} }
aliasFlag = &cli.StringFlag{ aliasFlag = &cli.StringFlag{
@ -82,8 +74,9 @@ var (
} }
) )
var app = flags.NewApp("Ethereum ABI wrapper code generator")
func init() { func init() {
app = flags.NewApp(gitCommit, gitDate, "ethereum checkpoint helper tool")
app.Name = "abigen" app.Name = "abigen"
app.Flags = []cli.Flag{ app.Flags = []cli.Flag{
abiFlag, abiFlag,
@ -109,11 +102,6 @@ func abigen(c *cli.Context) error {
switch c.String(langFlag.Name) { switch c.String(langFlag.Name) {
case "go": case "go":
lang = bind.LangGo lang = bind.LangGo
case "java":
lang = bind.LangJava
case "objc":
lang = bind.LangObjC
utils.Fatalf("Objc binding generation is uncompleted")
default: default:
utils.Fatalf("Unsupported destination language \"%s\" (--lang)", c.String(langFlag.Name)) utils.Fatalf("Unsupported destination language \"%s\" (--lang)", c.String(langFlag.Name))
} }
@ -161,9 +149,12 @@ func abigen(c *cli.Context) error {
types = append(types, kind) types = append(types, kind)
} else { } else {
// Generate the list of types to exclude from binding // Generate the list of types to exclude from binding
exclude := make(map[string]bool) var exclude *nameFilter
for _, kind := range strings.Split(c.String(excFlag.Name), ",") { if c.IsSet(excFlag.Name) {
exclude[strings.ToLower(kind)] = true var err error
if exclude, err = newNameFilter(strings.Split(c.String(excFlag.Name), ",")...); err != nil {
utils.Fatalf("Failed to parse excludes: %v", err)
}
} }
var contracts map[string]*compiler.Contract var contracts map[string]*compiler.Contract
@ -188,7 +179,11 @@ func abigen(c *cli.Context) error {
} }
// Gather all non-excluded contract for binding // Gather all non-excluded contract for binding
for name, contract := range contracts { for name, contract := range contracts {
if exclude[strings.ToLower(name)] { // fully qualified name is of the form <solFilePath>:<type>
nameParts := strings.Split(name, ":")
typeName := nameParts[len(nameParts)-1]
if exclude != nil && exclude.Matches(name) {
fmt.Fprintf(os.Stderr, "excluding: %v\n", name)
continue continue
} }
abi, err := json.Marshal(contract.Info.AbiDefinition) // Flatten the compiler parse abi, err := json.Marshal(contract.Info.AbiDefinition) // Flatten the compiler parse
@ -198,15 +193,14 @@ func abigen(c *cli.Context) error {
abis = append(abis, string(abi)) abis = append(abis, string(abi))
bins = append(bins, contract.Code) bins = append(bins, contract.Code)
sigs = append(sigs, contract.Hashes) sigs = append(sigs, contract.Hashes)
nameParts := strings.Split(name, ":") types = append(types, typeName)
types = append(types, nameParts[len(nameParts)-1])
// Derive the library placeholder which is a 34 character prefix of the // Derive the library placeholder which is a 34 character prefix of the
// hex encoding of the keccak256 hash of the fully qualified library name. // hex encoding of the keccak256 hash of the fully qualified library name.
// Note that the fully qualified library name is the path of its source // Note that the fully qualified library name is the path of its source
// file and the library name separated by ":". // file and the library name separated by ":".
libPattern := crypto.Keccak256Hash([]byte(name)).String()[2:36] // the first 2 chars are 0x libPattern := crypto.Keccak256Hash([]byte(name)).String()[2:36] // the first 2 chars are 0x
libs[libPattern] = nameParts[len(nameParts)-1] libs[libPattern] = typeName
} }
} }
// Extract all aliases from the flags // Extract all aliases from the flags

58
cmd/abigen/namefilter.go Normal file
View File

@ -0,0 +1,58 @@
package main
import (
"fmt"
"strings"
)
type nameFilter struct {
fulls map[string]bool // path/to/contract.sol:Type
files map[string]bool // path/to/contract.sol:*
types map[string]bool // *:Type
}
func newNameFilter(patterns ...string) (*nameFilter, error) {
f := &nameFilter{
fulls: make(map[string]bool),
files: make(map[string]bool),
types: make(map[string]bool),
}
for _, pattern := range patterns {
if err := f.add(pattern); err != nil {
return nil, err
}
}
return f, nil
}
func (f *nameFilter) add(pattern string) error {
ft := strings.Split(pattern, ":")
if len(ft) != 2 {
// filenames and types must not include ':' symbol
return fmt.Errorf("invalid pattern: %s", pattern)
}
file, typ := ft[0], ft[1]
if file == "*" {
f.types[typ] = true
return nil
} else if typ == "*" {
f.files[file] = true
return nil
}
f.fulls[pattern] = true
return nil
}
func (f *nameFilter) Matches(name string) bool {
ft := strings.Split(name, ":")
if len(ft) != 2 {
// If contract names are always of the fully-qualified form
// <filePath>:<type>, then this case will never happen.
return false
}
file, typ := ft[0], ft[1]
// full paths > file paths > types
return f.fulls[name] || f.files[file] || f.types[typ]
}

View File

@ -0,0 +1,38 @@
package main
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNameFilter(t *testing.T) {
_, err := newNameFilter("Foo")
require.Error(t, err)
_, err = newNameFilter("too/many:colons:Foo")
require.Error(t, err)
f, err := newNameFilter("a/path:A", "*:B", "c/path:*")
require.NoError(t, err)
for _, tt := range []struct {
name string
match bool
}{
{"a/path:A", true},
{"unknown/path:A", false},
{"a/path:X", false},
{"unknown/path:X", false},
{"any/path:B", true},
{"c/path:X", true},
{"c/path:foo:B", false},
} {
match := f.Matches(tt.name)
if tt.match {
assert.True(t, match, "expected match")
} else {
assert.False(t, match, "expected no match")
}
}
}

View File

@ -40,7 +40,7 @@ func main() {
writeAddr = flag.Bool("writeaddress", false, "write out the node's public key and quit") writeAddr = flag.Bool("writeaddress", false, "write out the node's public key and quit")
nodeKeyFile = flag.String("nodekey", "", "private key filename") nodeKeyFile = flag.String("nodekey", "", "private key filename")
nodeKeyHex = flag.String("nodekeyhex", "", "private key as hex (for testing)") nodeKeyHex = flag.String("nodekeyhex", "", "private key as hex (for testing)")
natdesc = flag.String("nat", "none", "port mapping mechanism (any|none|upnp|pmp|extip:<IP>)") natdesc = flag.String("nat", "none", "port mapping mechanism (any|none|upnp|pmp|pmp:<IP>|extip:<IP>)")
netrestrict = flag.String("netrestrict", "", "restrict network communication to the given IP networks (CIDR masks)") netrestrict = flag.String("netrestrict", "", "restrict network communication to the given IP networks (CIDR masks)")
runv5 = flag.Bool("v5", false, "run a v5 topic discovery bootnode") runv5 = flag.Bool("v5", false, "run a v5 topic discovery bootnode")
verbosity = flag.Int("verbosity", int(log.LvlInfo), "log verbosity (0-5)") verbosity = flag.Int("verbosity", int(log.LvlInfo), "log verbosity (0-5)")

View File

@ -46,7 +46,7 @@ Deploy checkpoint oracle contract. `--signers` indicates the specified trusted s
checkpoint-admin deploy --rpc <NODE_RPC_ENDPOINT> --clef <CLEF_ENDPOINT> --signer <SIGNER_TO_SIGN_TX> --signers <TRUSTED_SIGNER_LIST> --threshold 1 checkpoint-admin deploy --rpc <NODE_RPC_ENDPOINT> --clef <CLEF_ENDPOINT> --signer <SIGNER_TO_SIGN_TX> --signers <TRUSTED_SIGNER_LIST> --threshold 1
``` ```
It is worth noting that checkpoint-admin only supports clef as a signer for transactions and plain text(checkpoint). For more clef usage, please see the clef [tutorial](https://geth.ethereum.org/docs/clef/tutorial) . It is worth noting that checkpoint-admin only supports clef as a signer for transactions and plain text(checkpoint). For more clef usage, please see the clef [tutorial](https://geth.ethereum.org/docs/tools/clef/tutorial) .
#### Sign #### Sign
@ -86,7 +86,7 @@ checkpoint-admin status --rpc <NODE_RPC_ENDPOINT>
### Enable checkpoint oracle in your private network ### Enable checkpoint oracle in your private network
Currently, only the Ethereum mainnet and the default supported test networks (ropsten, rinkeby, goerli) activate this feature. If you want to activate this feature in your private network, you can overwrite the relevant checkpoint oracle settings through the configuration file after deploying the oracle contract. Currently, only the Ethereum mainnet and the default supported test networks (rinkeby, goerli) activate this feature. If you want to activate this feature in your private network, you can overwrite the relevant checkpoint oracle settings through the configuration file after deploying the oracle contract.
* Get your node configuration file `geth dumpconfig OTHER_COMMAND_LINE_OPTIONS > config.toml` * Get your node configuration file `geth dumpconfig OTHER_COMMAND_LINE_OPTIONS > config.toml`
* Edit the configuration file and add the following information * Edit the configuration file and add the following information

View File

@ -28,16 +28,9 @@ import (
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
) )
var ( var app = flags.NewApp("ethereum checkpoint helper tool")
// Git SHA1 commit hash of the release (set via linker flags)
gitCommit = ""
gitDate = ""
app *cli.App
)
func init() { func init() {
app = flags.NewApp(gitCommit, gitDate, "ethereum checkpoint helper tool")
app.Commands = []*cli.Command{ app.Commands = []*cli.Command{
commandStatus, commandStatus,
commandDeploy, commandDeploy,

View File

@ -29,7 +29,7 @@ GLOBAL OPTIONS:
--loglevel value log level to emit to the screen (default: 4) --loglevel value log level to emit to the screen (default: 4)
--keystore value Directory for the keystore (default: "$HOME/.ethereum/keystore") --keystore value Directory for the keystore (default: "$HOME/.ethereum/keystore")
--configdir value Directory for Clef configuration (default: "$HOME/.clef") --configdir value Directory for Clef configuration (default: "$HOME/.clef")
--chainid value Chain id to use for signing (1=mainnet, 3=Ropsten, 4=Rinkeby, 5=Goerli) (default: 1) --chainid value Chain id to use for signing (1=mainnet, 4=Rinkeby, 5=Goerli) (default: 1)
--lightkdf Reduce key-derivation RAM & CPU usage at some expense of KDF strength --lightkdf Reduce key-derivation RAM & CPU usage at some expense of KDF strength
--nousb Disables monitoring for and managing USB hardware wallets --nousb Disables monitoring for and managing USB hardware wallets
--pcscdpath value Path to the smartcard daemon (pcscd) socket file (default: "/run/pcscd/pcscd.comm") --pcscdpath value Path to the smartcard daemon (pcscd) socket file (default: "/run/pcscd/pcscd.comm")

117
cmd/clef/consolecmd_test.go Normal file
View File

@ -0,0 +1,117 @@
// Copyright 2022 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// TestImportRaw tests clef --importraw
func TestImportRaw(t *testing.T) {
keyPath := filepath.Join(os.TempDir(), fmt.Sprintf("%v-tempkey.test", t.Name()))
os.WriteFile(keyPath, []byte("0102030405060708090a0102030405060708090a0102030405060708090a0102"), 0777)
t.Cleanup(func() { os.Remove(keyPath) })
t.Parallel()
t.Run("happy-path", func(t *testing.T) {
// Run clef importraw
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath)
clef.input("myverylongpassword").input("myverylongpassword")
if out := string(clef.Output()); !strings.Contains(out,
"Key imported:\n Address 0x9160DC9105f7De5dC5E7f3d97ef11DA47269BdA6") {
t.Logf("Output\n%v", out)
t.Error("Failure")
}
})
// tests clef --importraw with mismatched passwords.
t.Run("pw-mismatch", func(t *testing.T) {
// Run clef importraw
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath)
clef.input("myverylongpassword1").input("myverylongpassword2").WaitExit()
if have, want := clef.StderrText(), "Passwords do not match\n"; have != want {
t.Errorf("have %q, want %q", have, want)
}
})
// tests clef --importraw with a too short password.
t.Run("short-pw", func(t *testing.T) {
// Run clef importraw
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath)
clef.input("shorty").input("shorty").WaitExit()
if have, want := clef.StderrText(),
"password requirements not met: password too short (<10 characters)\n"; have != want {
t.Errorf("have %q, want %q", have, want)
}
})
}
// TestListAccounts tests clef --list-accounts
func TestListAccounts(t *testing.T) {
keyPath := filepath.Join(os.TempDir(), fmt.Sprintf("%v-tempkey.test", t.Name()))
os.WriteFile(keyPath, []byte("0102030405060708090a0102030405060708090a0102030405060708090a0102"), 0777)
t.Cleanup(func() { os.Remove(keyPath) })
t.Parallel()
t.Run("no-accounts", func(t *testing.T) {
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "list-accounts")
if out := string(clef.Output()); !strings.Contains(out, "The keystore is empty.") {
t.Logf("Output\n%v", out)
t.Error("Failure")
}
})
t.Run("one-account", func(t *testing.T) {
// First, we need to import
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath)
clef.input("myverylongpassword").input("myverylongpassword").WaitExit()
// Secondly, do a listing, using the same datadir
clef = runWithKeystore(t, clef.Datadir, "--suppress-bootwarn", "--lightkdf", "list-accounts")
if out := string(clef.Output()); !strings.Contains(out, "0x9160DC9105f7De5dC5E7f3d97ef11DA47269BdA6 (keystore:") {
t.Logf("Output\n%v", out)
t.Error("Failure")
}
})
}
// TestListWallets tests clef --list-wallets
func TestListWallets(t *testing.T) {
keyPath := filepath.Join(os.TempDir(), fmt.Sprintf("%v-tempkey.test", t.Name()))
os.WriteFile(keyPath, []byte("0102030405060708090a0102030405060708090a0102030405060708090a0102"), 0777)
t.Cleanup(func() { os.Remove(keyPath) })
t.Parallel()
t.Run("no-accounts", func(t *testing.T) {
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "list-wallets")
if out := string(clef.Output()); !strings.Contains(out, "There are no wallets.") {
t.Logf("Output\n%v", out)
t.Error("Failure")
}
})
t.Run("one-account", func(t *testing.T) {
// First, we need to import
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath)
clef.input("myverylongpassword").input("myverylongpassword").WaitExit()
// Secondly, do a listing, using the same datadir
clef = runWithKeystore(t, clef.Datadir, "--suppress-bootwarn", "--lightkdf", "list-wallets")
if out := string(clef.Output()); !strings.Contains(out, "Account 0: 0x9160DC9105f7De5dC5E7f3d97ef11DA47269BdA6") {
t.Logf("Output\n%v", out)
t.Error("Failure")
}
})
}

View File

@ -23,6 +23,7 @@ import (
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"math/big" "math/big"
@ -74,7 +75,7 @@ PURPOSE. See the GNU General Public License for more details.
var ( var (
logLevelFlag = &cli.IntFlag{ logLevelFlag = &cli.IntFlag{
Name: "loglevel", Name: "loglevel",
Value: 4, Value: 3,
Usage: "log level to emit to the screen", Usage: "log level to emit to the screen",
} }
advancedMode = &cli.BoolFlag{ advancedMode = &cli.BoolFlag{
@ -98,7 +99,7 @@ var (
chainIdFlag = &cli.Int64Flag{ chainIdFlag = &cli.Int64Flag{
Name: "chainid", Name: "chainid",
Value: params.MainnetChainConfig.ChainID.Int64(), Value: params.MainnetChainConfig.ChainID.Int64(),
Usage: "Chain id to use for signing (1=mainnet, 3=Ropsten, 4=Rinkeby, 5=Goerli)", Usage: "Chain id to use for signing (1=mainnet, 4=Rinkeby, 5=Goerli)",
} }
rpcPortFlag = &cli.IntFlag{ rpcPortFlag = &cli.IntFlag{
Name: "http.port", Name: "http.port",
@ -203,25 +204,61 @@ The delpw command removes a password for a given address (keyfile).
}, },
Description: ` Description: `
The newaccount command creates a new keystore-backed account. It is a convenience-method The newaccount command creates a new keystore-backed account. It is a convenience-method
which can be used in lieu of an external UI.`, which can be used in lieu of an external UI.
} `}
gendocCommand = &cli.Command{ gendocCommand = &cli.Command{
Action: GenDoc, Action: GenDoc,
Name: "gendoc", Name: "gendoc",
Usage: "Generate documentation about json-rpc format", Usage: "Generate documentation about json-rpc format",
Description: ` Description: `
The gendoc generates example structures of the json-rpc communication types. The gendoc generates example structures of the json-rpc communication types.
`}
listAccountsCommand = &cli.Command{
Action: listAccounts,
Name: "list-accounts",
Usage: "List accounts in the keystore",
Flags: []cli.Flag{
logLevelFlag,
keystoreFlag,
utils.LightKDFFlag,
acceptFlag,
},
Description: `
Lists the accounts in the keystore.
`}
listWalletsCommand = &cli.Command{
Action: listWallets,
Name: "list-wallets",
Usage: "List wallets known to Clef",
Flags: []cli.Flag{
logLevelFlag,
keystoreFlag,
utils.LightKDFFlag,
acceptFlag,
},
Description: `
Lists the wallets known to Clef.
`}
importRawCommand = &cli.Command{
Action: accountImport,
Name: "importraw",
Usage: "Import a hex-encoded private key.",
ArgsUsage: "<keyfile>",
Flags: []cli.Flag{
logLevelFlag,
keystoreFlag,
utils.LightKDFFlag,
acceptFlag,
},
Description: `
Imports an unencrypted private key from <keyfile> and creates a new account.
Prints the address.
The keyfile is assumed to contain an unencrypted private key in hexadecimal format.
The account is saved in encrypted format, you are prompted for a password.
`} `}
) )
var ( var app = flags.NewApp("Manage Ethereum account operations")
// Git SHA1 commit hash of the release (set via linker flags)
gitCommit = ""
gitDate = ""
app = flags.NewApp(gitCommit, gitDate, "Manage Ethereum account operations")
)
func init() { func init() {
app.Name = "Clef" app.Name = "Clef"
@ -254,7 +291,10 @@ func init() {
setCredentialCommand, setCredentialCommand,
delCredentialCommand, delCredentialCommand,
newAccountCommand, newAccountCommand,
importRawCommand,
gendocCommand, gendocCommand,
listAccountsCommand,
listWalletsCommand,
} }
} }
@ -357,6 +397,22 @@ func attestFile(ctx *cli.Context) error {
return nil return nil
} }
func initInternalApi(c *cli.Context) (*core.UIServerAPI, core.UIClientAPI, error) {
if err := initialize(c); err != nil {
return nil, nil, err
}
var (
ui = core.NewCommandlineUI()
pwStorage storage.Storage = &storage.NoStorage{}
ksLoc = c.String(keystoreFlag.Name)
lightKdf = c.Bool(utils.LightKDFFlag.Name)
)
am := core.StartClefAccountManager(ksLoc, true, lightKdf, "")
api := core.NewSignerAPI(am, 0, true, ui, nil, false, pwStorage)
internalApi := core.NewUIServerAPI(api)
return internalApi, ui, nil
}
func setCredential(ctx *cli.Context) error { func setCredential(ctx *cli.Context) error {
if ctx.NArg() < 1 { if ctx.NArg() < 1 {
utils.Fatalf("This command requires an address to be passed as an argument") utils.Fatalf("This command requires an address to be passed as an argument")
@ -415,31 +471,6 @@ func removeCredential(ctx *cli.Context) error {
return nil return nil
} }
func newAccount(c *cli.Context) error {
if err := initialize(c); err != nil {
return err
}
// The newaccount is meant for users using the CLI, since 'real' external
// UIs can use the UI-api instead. So we'll just use the native CLI UI here.
var (
ui = core.NewCommandlineUI()
pwStorage storage.Storage = &storage.NoStorage{}
ksLoc = c.String(keystoreFlag.Name)
lightKdf = c.Bool(utils.LightKDFFlag.Name)
)
log.Info("Starting clef", "keystore", ksLoc, "light-kdf", lightKdf)
am := core.StartClefAccountManager(ksLoc, true, lightKdf, "")
// This gives is us access to the external API
apiImpl := core.NewSignerAPI(am, 0, true, ui, nil, false, pwStorage)
// This gives us access to the internal API
internalApi := core.NewUIServerAPI(apiImpl)
addr, err := internalApi.New(context.Background())
if err == nil {
fmt.Printf("Generated account %v\n", addr.String())
}
return err
}
func initialize(c *cli.Context) error { func initialize(c *cli.Context) error {
// Set up the logger to print everything // Set up the logger to print everything
logOutput := os.Stdout logOutput := os.Stdout
@ -465,6 +496,108 @@ func initialize(c *cli.Context) error {
return nil return nil
} }
func newAccount(c *cli.Context) error {
internalApi, _, err := initInternalApi(c)
if err != nil {
return err
}
addr, err := internalApi.New(context.Background())
if err == nil {
fmt.Printf("Generated account %v\n", addr.String())
}
return err
}
func listAccounts(c *cli.Context) error {
internalApi, _, err := initInternalApi(c)
if err != nil {
return err
}
accs, err := internalApi.ListAccounts(context.Background())
if err != nil {
return err
}
if len(accs) == 0 {
fmt.Println("\nThe keystore is empty.")
}
fmt.Println()
for _, account := range accs {
fmt.Printf("%v (%v)\n", account.Address, account.URL)
}
return err
}
func listWallets(c *cli.Context) error {
internalApi, _, err := initInternalApi(c)
if err != nil {
return err
}
wallets := internalApi.ListWallets()
if len(wallets) == 0 {
fmt.Println("\nThere are no wallets.")
}
fmt.Println()
for i, wallet := range wallets {
fmt.Printf("- Wallet %d at %v (%v %v)\n", i, wallet.URL, wallet.Status, wallet.Failure)
for j, acc := range wallet.Accounts {
fmt.Printf(" -Account %d: %v (%v)\n", j, acc.Address, acc.URL)
}
fmt.Println()
}
return nil
}
// accountImport imports a raw hexadecimal private key via CLI.
func accountImport(c *cli.Context) error {
if c.Args().Len() != 1 {
return errors.New("<keyfile> must be given as first argument.")
}
internalApi, ui, err := initInternalApi(c)
if err != nil {
return err
}
pKey, err := crypto.LoadECDSA(c.Args().First())
if err != nil {
return err
}
readPw := func(prompt string) (string, error) {
resp, err := ui.OnInputRequired(core.UserInputRequest{
Title: "Password",
Prompt: prompt,
IsPassword: true,
})
if err != nil {
return "", err
}
return resp.Text, nil
}
first, err := readPw("Please enter a password for the imported account")
if err != nil {
return err
}
second, err := readPw("Please repeat the password you just entered")
if err != nil {
return err
}
if first != second {
return errors.New("Passwords do not match")
}
acc, err := internalApi.ImportRawKey(hex.EncodeToString(crypto.FromECDSA(pKey)), first)
if err != nil {
return err
}
ui.ShowInfo(fmt.Sprintf(`Key imported:
Address %v
Keystore file: %v
The key is now encrypted; losing the password will result in permanently losing
access to the key and all associated funds!
Make sure to backup keystore and passwords in a safe location.`,
acc.Address, acc.URL.Path))
return nil
}
// ipcEndpoint resolves an IPC endpoint based on a configured value, taking into // ipcEndpoint resolves an IPC endpoint based on a configured value, taking into
// account the set data folders as well as the designated platform we're currently // account the set data folders as well as the designated platform we're currently
// running on. // running on.
@ -574,6 +707,7 @@ func signer(c *cli.Context) error {
// it with the UI. // it with the UI.
ui.RegisterUIServer(core.NewUIServerAPI(apiImpl)) ui.RegisterUIServer(core.NewUIServerAPI(apiImpl))
api = apiImpl api = apiImpl
// Audit logging // Audit logging
if logfile := c.String(auditLogFlag.Name); logfile != "" { if logfile := c.String(auditLogFlag.Name); logfile != "" {
api, err = core.NewAuditLogger(logfile, api) api, err = core.NewAuditLogger(logfile, api)
@ -635,7 +769,6 @@ func signer(c *cli.Context) error {
log.Info("IPC endpoint closed", "url", ipcapiURL) log.Info("IPC endpoint closed", "url", ipcapiURL)
}() }()
} }
if c.Bool(testFlag.Name) { if c.Bool(testFlag.Name) {
log.Info("Performing UI test") log.Info("Performing UI test")
go testExternalUI(apiImpl) go testExternalUI(apiImpl)
@ -646,8 +779,7 @@ func signer(c *cli.Context) error {
"extapi_version": core.ExternalAPIVersion, "extapi_version": core.ExternalAPIVersion,
"extapi_http": extapiURL, "extapi_http": extapiURL,
"extapi_ipc": ipcapiURL, "extapi_ipc": ipcapiURL,
}, }})
})
abortChan := make(chan os.Signal, 1) abortChan := make(chan os.Signal, 1)
signal.Notify(abortChan, os.Interrupt) signal.Notify(abortChan, os.Interrupt)

109
cmd/clef/run_test.go Normal file
View File

@ -0,0 +1,109 @@
// Copyright 2022 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"fmt"
"os"
"testing"
"github.com/docker/docker/pkg/reexec"
"github.com/ethereum/go-ethereum/internal/cmdtest"
)
const registeredName = "clef-test"
type testproc struct {
*cmdtest.TestCmd
// template variables for expect
Datadir string
Etherbase string
}
func init() {
reexec.Register(registeredName, func() {
if err := app.Run(os.Args); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
os.Exit(0)
})
}
func TestMain(m *testing.M) {
// check if we have been reexec'd
if reexec.Init() {
return
}
os.Exit(m.Run())
}
// runClef spawns clef with the given command line args and adds keystore arg.
// This method creates a temporary keystore folder which will be removed after
// the test exits.
func runClef(t *testing.T, args ...string) *testproc {
ddir, err := os.MkdirTemp("", "cleftest-*")
if err != nil {
return nil
}
t.Cleanup(func() {
os.RemoveAll(ddir)
})
return runWithKeystore(t, ddir, args...)
}
// runWithKeystore spawns clef with the given command line args and adds keystore arg.
// This method does _not_ create the keystore folder, but it _does_ add the arg
// to the args.
func runWithKeystore(t *testing.T, keystore string, args ...string) *testproc {
args = append([]string{"--keystore", keystore}, args...)
tt := &testproc{Datadir: keystore}
tt.TestCmd = cmdtest.NewTestCmd(t, tt)
// Boot "clef". This actually runs the test binary but the TestMain
// function will prevent any tests from running.
tt.Run(registeredName, args...)
return tt
}
func (proc *testproc) input(text string) *testproc {
proc.TestCmd.InputLine(text)
return proc
}
/*
// waitForEndpoint waits for the rpc endpoint to appear, or
// aborts after 3 seconds.
func (proc *testproc) waitForEndpoint(t *testing.T) *testproc {
t.Helper()
timeout := 3 * time.Second
ipc := filepath.Join(proc.Datadir, "clef.ipc")
start := time.Now()
for time.Since(start) < timeout {
if _, err := os.Stat(ipc); !errors.Is(err, os.ErrNotExist) {
t.Logf("endpoint %v opened", ipc)
return proc
}
time.Sleep(200 * time.Millisecond)
}
t.Logf("stderr: \n%v", proc.StderrText())
t.Logf("stdout: \n%v", proc.Output())
t.Fatal("endpoint", ipc, "did not open within", timeout)
return proc
}
*/

View File

@ -44,7 +44,7 @@ set to standard output. The following filters are supported:
- `-limit <N>` limits the output set to N entries, taking the top N nodes by score - `-limit <N>` limits the output set to N entries, taking the top N nodes by score
- `-ip <CIDR>` filters nodes by IP subnet - `-ip <CIDR>` filters nodes by IP subnet
- `-min-age <duration>` filters nodes by 'first seen' time - `-min-age <duration>` filters nodes by 'first seen' time
- `-eth-network <mainnet/rinkeby/goerli/ropsten>` filters nodes by "eth" ENR entry - `-eth-network <mainnet/rinkeby/goerli/sepolia>` filters nodes by "eth" ENR entry
- `-les-server` filters nodes by LES server support - `-les-server` filters nodes by LES server support
- `-snap` filters nodes by snap protocol support - `-snap` filters nodes by snap protocol support
@ -135,6 +135,6 @@ replacing `<enode>` with the enode of the geth node:
``` ```
[eth]: https://github.com/ethereum/devp2p/blob/master/caps/eth.md [eth]: https://github.com/ethereum/devp2p/blob/master/caps/eth.md
[dns-tutorial]: https://geth.ethereum.org/docs/developers/dns-discovery-setup [dns-tutorial]: https://geth.ethereum.org/docs/developers/geth-developer/dns-discovery-setup
[discv4]: https://github.com/ethereum/devp2p/tree/master/discv4.md [discv4]: https://github.com/ethereum/devp2p/tree/master/discv4.md
[discv5]: https://github.com/ethereum/devp2p/tree/master/discv5/discv5.md [discv5]: https://github.com/ethereum/devp2p/tree/master/discv5/discv5.md

View File

@ -17,6 +17,8 @@
package main package main
import ( import (
"sync"
"sync/atomic"
"time" "time"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
@ -34,8 +36,17 @@ type crawler struct {
// settings // settings
revalidateInterval time.Duration revalidateInterval time.Duration
mu sync.RWMutex
} }
const (
nodeRemoved = iota
nodeSkipRecent
nodeSkipIncompat
nodeAdded
nodeUpdated
)
type resolver interface { type resolver interface {
RequestENR(*enode.Node) (*enode.Node, error) RequestENR(*enode.Node) (*enode.Node, error)
} }
@ -59,23 +70,59 @@ func newCrawler(input nodeSet, disc resolver, iters ...enode.Iterator) *crawler
return c return c
} }
func (c *crawler) run(timeout time.Duration) nodeSet { func (c *crawler) run(timeout time.Duration, nthreads int) nodeSet {
var ( var (
timeoutTimer = time.NewTimer(timeout) timeoutTimer = time.NewTimer(timeout)
timeoutCh <-chan time.Time timeoutCh <-chan time.Time
statusTicker = time.NewTicker(time.Second * 8)
doneCh = make(chan enode.Iterator, len(c.iters)) doneCh = make(chan enode.Iterator, len(c.iters))
liveIters = len(c.iters) liveIters = len(c.iters)
) )
if nthreads < 1 {
nthreads = 1
}
defer timeoutTimer.Stop() defer timeoutTimer.Stop()
defer statusTicker.Stop()
for _, it := range c.iters { for _, it := range c.iters {
go c.runIterator(doneCh, it) go c.runIterator(doneCh, it)
} }
var (
added uint64
updated uint64
skipped uint64
recent uint64
removed uint64
wg sync.WaitGroup
)
wg.Add(nthreads)
for i := 0; i < nthreads; i++ {
go func() {
defer wg.Done()
for {
select {
case n := <-c.ch:
switch c.updateNode(n) {
case nodeSkipIncompat:
atomic.AddUint64(&skipped, 1)
case nodeSkipRecent:
atomic.AddUint64(&recent, 1)
case nodeRemoved:
atomic.AddUint64(&removed, 1)
case nodeAdded:
atomic.AddUint64(&added, 1)
default:
atomic.AddUint64(&updated, 1)
}
case <-c.closed:
return
}
}
}()
}
loop: loop:
for { for {
select { select {
case n := <-c.ch:
c.updateNode(n)
case it := <-doneCh: case it := <-doneCh:
if it == c.inputIter { if it == c.inputIter {
// Enable timeout when we're done revalidating the input nodes. // Enable timeout when we're done revalidating the input nodes.
@ -89,6 +136,13 @@ loop:
} }
case <-timeoutCh: case <-timeoutCh:
break loop break loop
case <-statusTicker.C:
log.Info("Crawling in progress",
"added", atomic.LoadUint64(&added),
"updated", atomic.LoadUint64(&updated),
"removed", atomic.LoadUint64(&removed),
"ignored(recent)", atomic.LoadUint64(&recent),
"ignored(incompatible)", atomic.LoadUint64(&skipped))
} }
} }
@ -99,6 +153,7 @@ loop:
for ; liveIters > 0; liveIters-- { for ; liveIters > 0; liveIters-- {
<-doneCh <-doneCh
} }
wg.Wait()
return c.output return c.output
} }
@ -113,22 +168,26 @@ func (c *crawler) runIterator(done chan<- enode.Iterator, it enode.Iterator) {
} }
} }
func (c *crawler) updateNode(n *enode.Node) { // updateNode updates the info about the given node, and returns a status
// about what changed
func (c *crawler) updateNode(n *enode.Node) int {
c.mu.RLock()
node, ok := c.output[n.ID()] node, ok := c.output[n.ID()]
c.mu.RUnlock()
// Skip validation of recently-seen nodes. // Skip validation of recently-seen nodes.
if ok && time.Since(node.LastCheck) < c.revalidateInterval { if ok && time.Since(node.LastCheck) < c.revalidateInterval {
return return nodeSkipRecent
} }
// Request the node record. // Request the node record.
nn, err := c.disc.RequestENR(n) status := nodeUpdated
node.LastCheck = truncNow() node.LastCheck = truncNow()
if err != nil { if nn, err := c.disc.RequestENR(n); err != nil {
if node.Score == 0 { if node.Score == 0 {
// Node doesn't implement EIP-868. // Node doesn't implement EIP-868.
log.Debug("Skipping node", "id", n.ID()) log.Debug("Skipping node", "id", n.ID())
return return nodeSkipIncompat
} }
node.Score /= 2 node.Score /= 2
} else { } else {
@ -137,18 +196,21 @@ func (c *crawler) updateNode(n *enode.Node) {
node.Score++ node.Score++
if node.FirstResponse.IsZero() { if node.FirstResponse.IsZero() {
node.FirstResponse = node.LastCheck node.FirstResponse = node.LastCheck
status = nodeAdded
} }
node.LastResponse = node.LastCheck node.LastResponse = node.LastCheck
} }
// Store/update node in output set. // Store/update node in output set.
c.mu.Lock()
defer c.mu.Unlock()
if node.Score <= 0 { if node.Score <= 0 {
log.Info("Removing node", "id", n.ID()) log.Debug("Removing node", "id", n.ID())
delete(c.output, n.ID()) delete(c.output, n.ID())
} else { return nodeRemoved
log.Info("Updating node", "id", n.ID(), "seq", n.Seq(), "score", node.Score)
c.output[n.ID()] = node
} }
log.Debug("Updating node", "id", n.ID(), "seq", n.Seq(), "score", node.Score)
c.output[n.ID()] = node
return status
} }
func truncNow() time.Time { func truncNow() time.Time {

View File

@ -19,6 +19,7 @@ package main
import ( import (
"fmt" "fmt"
"net" "net"
"strconv"
"strings" "strings"
"time" "time"
@ -50,34 +51,34 @@ var (
Usage: "Sends ping to a node", Usage: "Sends ping to a node",
Action: discv4Ping, Action: discv4Ping,
ArgsUsage: "<node>", ArgsUsage: "<node>",
Flags: v4NodeFlags, Flags: discoveryNodeFlags,
} }
discv4RequestRecordCommand = &cli.Command{ discv4RequestRecordCommand = &cli.Command{
Name: "requestenr", Name: "requestenr",
Usage: "Requests a node record using EIP-868 enrRequest", Usage: "Requests a node record using EIP-868 enrRequest",
Action: discv4RequestRecord, Action: discv4RequestRecord,
ArgsUsage: "<node>", ArgsUsage: "<node>",
Flags: v4NodeFlags, Flags: discoveryNodeFlags,
} }
discv4ResolveCommand = &cli.Command{ discv4ResolveCommand = &cli.Command{
Name: "resolve", Name: "resolve",
Usage: "Finds a node in the DHT", Usage: "Finds a node in the DHT",
Action: discv4Resolve, Action: discv4Resolve,
ArgsUsage: "<node>", ArgsUsage: "<node>",
Flags: v4NodeFlags, Flags: discoveryNodeFlags,
} }
discv4ResolveJSONCommand = &cli.Command{ discv4ResolveJSONCommand = &cli.Command{
Name: "resolve-json", Name: "resolve-json",
Usage: "Re-resolves nodes in a nodes.json file", Usage: "Re-resolves nodes in a nodes.json file",
Action: discv4ResolveJSON, Action: discv4ResolveJSON,
Flags: v4NodeFlags, Flags: discoveryNodeFlags,
ArgsUsage: "<nodes.json file>", ArgsUsage: "<nodes.json file>",
} }
discv4CrawlCommand = &cli.Command{ discv4CrawlCommand = &cli.Command{
Name: "crawl", Name: "crawl",
Usage: "Updates a nodes.json file with random nodes found in the DHT", Usage: "Updates a nodes.json file with random nodes found in the DHT",
Action: discv4Crawl, Action: discv4Crawl,
Flags: flags.Merge(v4NodeFlags, []cli.Flag{crawlTimeoutFlag}), Flags: flags.Merge(discoveryNodeFlags, []cli.Flag{crawlTimeoutFlag, crawlParallelismFlag}),
} }
discv4TestCommand = &cli.Command{ discv4TestCommand = &cli.Command{
Name: "test", Name: "test",
@ -110,11 +111,20 @@ var (
Name: "addr", Name: "addr",
Usage: "Listening address", Usage: "Listening address",
} }
extAddrFlag = &cli.StringFlag{
Name: "extaddr",
Usage: "UDP endpoint announced in ENR. You can provide a bare IP address or IP:port as the value of this flag.",
}
crawlTimeoutFlag = &cli.DurationFlag{ crawlTimeoutFlag = &cli.DurationFlag{
Name: "timeout", Name: "timeout",
Usage: "Time limit for the crawl.", Usage: "Time limit for the crawl.",
Value: 30 * time.Minute, Value: 30 * time.Minute,
} }
crawlParallelismFlag = &cli.IntFlag{
Name: "parallel",
Usage: "How many parallel discoveries to attempt.",
Value: 16,
}
remoteEnodeFlag = &cli.StringFlag{ remoteEnodeFlag = &cli.StringFlag{
Name: "remote", Name: "remote",
Usage: "Enode of the remote node under test", Usage: "Enode of the remote node under test",
@ -122,11 +132,12 @@ var (
} }
) )
var v4NodeFlags = []cli.Flag{ var discoveryNodeFlags = []cli.Flag{
bootnodesFlag, bootnodesFlag,
nodekeyFlag, nodekeyFlag,
nodedbFlag, nodedbFlag,
listenAddrFlag, listenAddrFlag,
extAddrFlag,
} }
func discv4Ping(ctx *cli.Context) error { func discv4Ping(ctx *cli.Context) error {
@ -189,7 +200,7 @@ func discv4ResolveJSON(ctx *cli.Context) error {
defer disc.Close() defer disc.Close()
c := newCrawler(inputSet, disc, enode.IterNodes(nodeargs)) c := newCrawler(inputSet, disc, enode.IterNodes(nodeargs))
c.revalidateInterval = 0 c.revalidateInterval = 0
output := c.run(0) output := c.run(0, 1)
writeNodesJSON(nodesFile, output) writeNodesJSON(nodesFile, output)
return nil return nil
} }
@ -208,7 +219,7 @@ func discv4Crawl(ctx *cli.Context) error {
defer disc.Close() defer disc.Close()
c := newCrawler(inputSet, disc, disc.RandomNodes()) c := newCrawler(inputSet, disc, disc.RandomNodes())
c.revalidateInterval = 10 * time.Minute c.revalidateInterval = 10 * time.Minute
output := c.run(ctx.Duration(crawlTimeoutFlag.Name)) output := c.run(ctx.Duration(crawlTimeoutFlag.Name), ctx.Int(crawlParallelismFlag.Name))
writeNodesJSON(nodesFile, output) writeNodesJSON(nodesFile, output)
return nil return nil
} }
@ -228,7 +239,7 @@ func discv4Test(ctx *cli.Context) error {
// startV4 starts an ephemeral discovery V4 node. // startV4 starts an ephemeral discovery V4 node.
func startV4(ctx *cli.Context) *discover.UDPv4 { func startV4(ctx *cli.Context) *discover.UDPv4 {
ln, config := makeDiscoveryConfig(ctx) ln, config := makeDiscoveryConfig(ctx)
socket := listen(ln, ctx.String(listenAddrFlag.Name)) socket := listen(ctx, ln)
disc, err := discover.ListenV4(socket, ln, config) disc, err := discover.ListenV4(socket, ln, config)
if err != nil { if err != nil {
exit(err) exit(err)
@ -266,7 +277,28 @@ func makeDiscoveryConfig(ctx *cli.Context) (*enode.LocalNode, discover.Config) {
return ln, cfg return ln, cfg
} }
func listen(ln *enode.LocalNode, addr string) *net.UDPConn { func parseExtAddr(spec string) (ip net.IP, port int, ok bool) {
ip = net.ParseIP(spec)
if ip != nil {
return ip, 0, true
}
host, portstr, err := net.SplitHostPort(spec)
if err != nil {
return nil, 0, false
}
ip = net.ParseIP(host)
if ip == nil {
return nil, 0, false
}
port, err = strconv.Atoi(portstr)
if err != nil {
return nil, 0, false
}
return ip, port, true
}
func listen(ctx *cli.Context, ln *enode.LocalNode) *net.UDPConn {
addr := ctx.String(listenAddrFlag.Name)
if addr == "" { if addr == "" {
addr = "0.0.0.0:0" addr = "0.0.0.0:0"
} }
@ -274,6 +306,8 @@ func listen(ln *enode.LocalNode, addr string) *net.UDPConn {
if err != nil { if err != nil {
exit(err) exit(err)
} }
// Configure UDP endpoint in ENR from listener address.
usocket := socket.(*net.UDPConn) usocket := socket.(*net.UDPConn)
uaddr := socket.LocalAddr().(*net.UDPAddr) uaddr := socket.LocalAddr().(*net.UDPAddr)
if uaddr.IP.IsUnspecified() { if uaddr.IP.IsUnspecified() {
@ -282,6 +316,22 @@ func listen(ln *enode.LocalNode, addr string) *net.UDPConn {
ln.SetFallbackIP(uaddr.IP) ln.SetFallbackIP(uaddr.IP)
} }
ln.SetFallbackUDP(uaddr.Port) ln.SetFallbackUDP(uaddr.Port)
// If an ENR endpoint is set explicitly on the command-line, override
// the information from the listening address. Note this is careful not
// to set the UDP port if the external address doesn't have it.
extAddr := ctx.String(extAddrFlag.Name)
if extAddr != "" {
ip, port, ok := parseExtAddr(extAddr)
if !ok {
exit(fmt.Errorf("-%s: invalid external address %q", extAddrFlag.Name, extAddr))
}
ln.SetStaticIP(ip)
if port != 0 {
ln.SetFallbackUDP(port)
}
}
return usocket return usocket
} }

View File

@ -22,6 +22,7 @@ import (
"github.com/ethereum/go-ethereum/cmd/devp2p/internal/v5test" "github.com/ethereum/go-ethereum/cmd/devp2p/internal/v5test"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/internal/flags"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/discover"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
) )
@ -42,18 +43,21 @@ var (
Name: "ping", Name: "ping",
Usage: "Sends ping to a node", Usage: "Sends ping to a node",
Action: discv5Ping, Action: discv5Ping,
Flags: discoveryNodeFlags,
} }
discv5ResolveCommand = &cli.Command{ discv5ResolveCommand = &cli.Command{
Name: "resolve", Name: "resolve",
Usage: "Finds a node in the DHT", Usage: "Finds a node in the DHT",
Action: discv5Resolve, Action: discv5Resolve,
Flags: []cli.Flag{bootnodesFlag}, Flags: discoveryNodeFlags,
} }
discv5CrawlCommand = &cli.Command{ discv5CrawlCommand = &cli.Command{
Name: "crawl", Name: "crawl",
Usage: "Updates a nodes.json file with random nodes found in the DHT", Usage: "Updates a nodes.json file with random nodes found in the DHT",
Action: discv5Crawl, Action: discv5Crawl,
Flags: []cli.Flag{bootnodesFlag, crawlTimeoutFlag}, Flags: flags.Merge(discoveryNodeFlags, []cli.Flag{
crawlTimeoutFlag,
}),
} }
discv5TestCommand = &cli.Command{ discv5TestCommand = &cli.Command{
Name: "test", Name: "test",
@ -70,12 +74,7 @@ var (
Name: "listen", Name: "listen",
Usage: "Runs a node", Usage: "Runs a node",
Action: discv5Listen, Action: discv5Listen,
Flags: []cli.Flag{ Flags: discoveryNodeFlags,
bootnodesFlag,
nodekeyFlag,
nodedbFlag,
listenAddrFlag,
},
} }
) )
@ -111,7 +110,7 @@ func discv5Crawl(ctx *cli.Context) error {
defer disc.Close() defer disc.Close()
c := newCrawler(inputSet, disc, disc.RandomNodes()) c := newCrawler(inputSet, disc, disc.RandomNodes())
c.revalidateInterval = 10 * time.Minute c.revalidateInterval = 10 * time.Minute
output := c.run(ctx.Duration(crawlTimeoutFlag.Name)) output := c.run(ctx.Duration(crawlTimeoutFlag.Name), ctx.Int(crawlParallelismFlag.Name))
writeNodesJSON(nodesFile, output) writeNodesJSON(nodesFile, output)
return nil return nil
} }
@ -137,7 +136,7 @@ func discv5Listen(ctx *cli.Context) error {
// startV5 starts an ephemeral discovery v5 node. // startV5 starts an ephemeral discovery v5 node.
func startV5(ctx *cli.Context) *discover.UDPv5 { func startV5(ctx *cli.Context) *discover.UDPv5 {
ln, config := makeDiscoveryConfig(ctx) ln, config := makeDiscoveryConfig(ctx)
socket := listen(ln, ctx.String(listenAddrFlag.Name)) socket := listen(ctx, ln)
disc, err := discover.ListenV5(socket, ln, config) disc, err := discover.ListenV5(socket, ln, config)
if err != nil { if err != nil {
exit(err) exit(err)

View File

@ -126,11 +126,16 @@ func (c *cloudflareClient) uploadRecords(name string, records map[string]string)
} }
// Iterate over the new records and inject anything missing. // Iterate over the new records and inject anything missing.
log.Info("Updating DNS entries")
created := 0
updated := 0
skipped := 0
for path, val := range records { for path, val := range records {
old, exists := existing[path] old, exists := existing[path]
if !exists { if !exists {
// Entry is unknown, push a new one to Cloudflare. // Entry is unknown, push a new one to Cloudflare.
log.Info(fmt.Sprintf("Creating %s = %q", path, val)) log.Debug(fmt.Sprintf("Creating %s = %q", path, val))
created++
ttl := rootTTL ttl := rootTTL
if path != name { if path != name {
ttl = treeNodeTTLCloudflare // Max TTL permitted by Cloudflare ttl = treeNodeTTLCloudflare // Max TTL permitted by Cloudflare
@ -140,26 +145,32 @@ func (c *cloudflareClient) uploadRecords(name string, records map[string]string)
} else if old.Content != val { } else if old.Content != val {
// Entry already exists, only change its content. // Entry already exists, only change its content.
log.Info(fmt.Sprintf("Updating %s from %q to %q", path, old.Content, val)) log.Info(fmt.Sprintf("Updating %s from %q to %q", path, old.Content, val))
updated++
old.Content = val old.Content = val
err = c.UpdateDNSRecord(context.Background(), c.zoneID, old.ID, old) err = c.UpdateDNSRecord(context.Background(), c.zoneID, old.ID, old)
} else { } else {
skipped++
log.Debug(fmt.Sprintf("Skipping %s = %q", path, val)) log.Debug(fmt.Sprintf("Skipping %s = %q", path, val))
} }
if err != nil { if err != nil {
return fmt.Errorf("failed to publish %s: %v", path, err) return fmt.Errorf("failed to publish %s: %v", path, err)
} }
} }
log.Info("Updated DNS entries", "new", created, "updated", updated, "untouched", skipped)
// Iterate over the old records and delete anything stale. // Iterate over the old records and delete anything stale.
deleted := 0
log.Info("Deleting stale DNS entries")
for path, entry := range existing { for path, entry := range existing {
if _, ok := records[path]; ok { if _, ok := records[path]; ok {
continue continue
} }
// Stale entry, nuke it. // Stale entry, nuke it.
log.Info(fmt.Sprintf("Deleting %s = %q", path, entry.Content)) log.Debug(fmt.Sprintf("Deleting %s = %q", path, entry.Content))
deleted++
if err := c.DeleteDNSRecord(context.Background(), c.zoneID, entry.ID); err != nil { if err := c.DeleteDNSRecord(context.Background(), c.zoneID, entry.ID); err != nil {
return fmt.Errorf("failed to delete %s: %v", path, err) return fmt.Errorf("failed to delete %s: %v", path, err)
} }
} }
log.Info("Deleted stale DNS entries", "count", deleted)
return nil return nil
} }

View File

@ -221,7 +221,13 @@ func (c *route53Client) computeChanges(name string, records map[string]string, e
} }
records = lrecords records = lrecords
var changes []types.Change var (
changes []types.Change
inserts int
upserts int
skips int
)
for path, newValue := range records { for path, newValue := range records {
prevRecords, exists := existing[path] prevRecords, exists := existing[path]
prevValue := strings.Join(prevRecords.values, "") prevValue := strings.Join(prevRecords.values, "")
@ -237,20 +243,30 @@ func (c *route53Client) computeChanges(name string, records map[string]string, e
if !exists { if !exists {
// Entry is unknown, push a new one // Entry is unknown, push a new one
log.Info(fmt.Sprintf("Creating %s = %s", path, newValue)) log.Debug(fmt.Sprintf("Creating %s = %s", path, newValue))
changes = append(changes, newTXTChange("CREATE", path, ttl, newValue)) changes = append(changes, newTXTChange("CREATE", path, ttl, newValue))
inserts++
} else if prevValue != newValue || prevRecords.ttl != ttl { } else if prevValue != newValue || prevRecords.ttl != ttl {
// Entry already exists, only change its content. // Entry already exists, only change its content.
log.Info(fmt.Sprintf("Updating %s from %s to %s", path, prevValue, newValue)) log.Info(fmt.Sprintf("Updating %s from %s to %s", path, prevValue, newValue))
changes = append(changes, newTXTChange("UPSERT", path, ttl, newValue)) changes = append(changes, newTXTChange("UPSERT", path, ttl, newValue))
upserts++
} else { } else {
log.Debug(fmt.Sprintf("Skipping %s = %s", path, newValue)) log.Debug(fmt.Sprintf("Skipping %s = %s", path, newValue))
skips++
} }
} }
// Iterate over the old records and delete anything stale. // Iterate over the old records and delete anything stale.
changes = append(changes, makeDeletionChanges(existing, records)...) deletions := makeDeletionChanges(existing, records)
changes = append(changes, deletions...)
log.Info("Computed DNS changes",
"changes", len(changes),
"inserts", inserts,
"skips", skips,
"deleted", len(deletions),
"upserts", upserts)
// Ensure changes are in the correct order. // Ensure changes are in the correct order.
sortChanges(changes) sortChanges(changes)
return changes return changes
@ -263,7 +279,7 @@ func makeDeletionChanges(records map[string]recordSet, keep map[string]string) [
if _, ok := keep[path]; ok { if _, ok := keep[path]; ok {
continue continue
} }
log.Info(fmt.Sprintf("Deleting %s = %s", path, strings.Join(set.values, ""))) log.Debug(fmt.Sprintf("Deleting %s = %s", path, strings.Join(set.values, "")))
changes = append(changes, newTXTChange("DELETE", path, set.ttl, set.values...)) changes = append(changes, newTXTChange("DELETE", path, set.ttl, set.values...))
} }
return changes return changes
@ -329,8 +345,9 @@ func (c *route53Client) collectRecords(name string) (map[string]recordSet, error
var req route53.ListResourceRecordSetsInput var req route53.ListResourceRecordSetsInput
req.HostedZoneId = &c.zoneID req.HostedZoneId = &c.zoneID
existing := make(map[string]recordSet) existing := make(map[string]recordSet)
log.Info("Loading existing TXT records", "name", name, "zone", c.zoneID)
for page := 0; ; page++ { for page := 0; ; page++ {
log.Info("Loading existing TXT records", "name", name, "zone", c.zoneID, "page", page) log.Debug("Loading existing TXT records", "name", name, "zone", c.zoneID, "page", page)
resp, err := c.api.ListResourceRecordSets(context.TODO(), &req) resp, err := c.api.ListResourceRecordSets(context.TODO(), &req)
if err != nil { if err != nil {
return existing, err return existing, err
@ -360,7 +377,7 @@ func (c *route53Client) collectRecords(name string) (map[string]recordSet, error
req.StartRecordName = resp.NextRecordName req.StartRecordName = resp.NextRecordName
req.StartRecordType = resp.NextRecordType req.StartRecordType = resp.NextRecordType
} }
log.Info("Loaded existing TXT records", "name", name, "zone", c.zoneID, "records", len(existing))
return existing, nil return existing, nil
} }

View File

@ -76,7 +76,7 @@ func (c *Chain) RootAt(height int) common.Hash {
// ForkID gets the fork id of the chain. // ForkID gets the fork id of the chain.
func (c *Chain) ForkID() forkid.ID { func (c *Chain) ForkID() forkid.ID {
return forkid.NewID(c.chainConfig, c.blocks[0].Hash(), uint64(c.Len())) return forkid.NewID(c.chainConfig, c.blocks[0].Hash(), uint64(c.Len()), c.blocks[0].Time())
} }
// Shorten returns a copy chain of a desired height from the imported // Shorten returns a copy chain of a desired height from the imported

View File

@ -63,8 +63,9 @@ func (s *Suite) dial() (*Conn, error) {
conn.caps = []p2p.Cap{ conn.caps = []p2p.Cap{
{Name: "eth", Version: 66}, {Name: "eth", Version: 66},
{Name: "eth", Version: 67}, {Name: "eth", Version: 67},
{Name: "eth", Version: 68},
} }
conn.ourHighestProtoVersion = 67 conn.ourHighestProtoVersion = 68
return &conn, nil return &conn, nil
} }
@ -357,9 +358,15 @@ func (s *Suite) waitAnnounce(conn *Conn, blockAnnouncement *NewBlock) error {
return fmt.Errorf("wrong block hash in announcement: expected %v, got %v", blockAnnouncement.Block.Hash(), hashes[0].Hash) return fmt.Errorf("wrong block hash in announcement: expected %v, got %v", blockAnnouncement.Block.Hash(), hashes[0].Hash)
} }
return nil return nil
case *NewPooledTransactionHashes:
// ignore tx announcements from previous tests // ignore tx announcements from previous tests
case *NewPooledTransactionHashes66:
continue continue
case *NewPooledTransactionHashes:
continue
case *Transactions:
continue
default: default:
return fmt.Errorf("unexpected: %s", pretty.Sdump(msg)) return fmt.Errorf("unexpected: %s", pretty.Sdump(msg))
} }

View File

@ -23,6 +23,7 @@ import (
"math/rand" "math/rand"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth/protocols/snap" "github.com/ethereum/go-ethereum/eth/protocols/snap"
"github.com/ethereum/go-ethereum/internal/utesting" "github.com/ethereum/go-ethereum/internal/utesting"
@ -90,7 +91,7 @@ func (s *Suite) TestSnapGetAccountRange(t *utesting.T) {
{4000, s.chain.RootAt(0), zero, ffHash, 0, zero, zero}, {4000, s.chain.RootAt(0), zero, ffHash, 0, zero, zero},
// A 127 block old stateroot, expected to be served // A 127 block old stateroot, expected to be served
{4000, s.chain.RootAt(999 - 127), zero, ffHash, 77, firstKey, common.HexToHash("0xe4c6fdef5dd4e789a2612390806ee840b8ec0fe52548f8b4efe41abb20c37aac")}, {4000, s.chain.RootAt(999 - 127), zero, ffHash, 77, firstKey, common.HexToHash("0xe4c6fdef5dd4e789a2612390806ee840b8ec0fe52548f8b4efe41abb20c37aac")},
// A root which is not actually an account root, but a storage orot // A root which is not actually an account root, but a storage root
{4000, storageRoot, zero, ffHash, 0, zero, zero}, {4000, storageRoot, zero, ffHash, 0, zero, zero},
// And some non-sensical requests // And some non-sensical requests
@ -121,7 +122,7 @@ type stRangesTest struct {
expSlots int expSlots int
} }
// TestSnapGetStorageRange various forms of GetStorageRanges requests. // TestSnapGetStorageRanges various forms of GetStorageRanges requests.
func (s *Suite) TestSnapGetStorageRanges(t *utesting.T) { func (s *Suite) TestSnapGetStorageRanges(t *utesting.T) {
var ( var (
ffHash = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") ffHash = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
@ -210,13 +211,6 @@ type byteCodesTest struct {
expHashes int expHashes int
} }
var (
// emptyRoot is the known root hash of an empty trie.
emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
// emptyCode is the known hash of the empty EVM bytecode.
emptyCode = common.HexToHash("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470")
)
// TestSnapGetByteCodes various forms of GetByteCodes requests. // TestSnapGetByteCodes various forms of GetByteCodes requests.
func (s *Suite) TestSnapGetByteCodes(t *utesting.T) { func (s *Suite) TestSnapGetByteCodes(t *utesting.T) {
// The halfchain import should yield these bytecodes // The halfchain import should yield these bytecodes
@ -263,15 +257,15 @@ func (s *Suite) TestSnapGetByteCodes(t *utesting.T) {
}, },
// Empties // Empties
{ {
nBytes: 10000, hashes: []common.Hash{emptyRoot}, nBytes: 10000, hashes: []common.Hash{types.EmptyRootHash},
expHashes: 0, expHashes: 0,
}, },
{ {
nBytes: 10000, hashes: []common.Hash{emptyCode}, nBytes: 10000, hashes: []common.Hash{types.EmptyCodeHash},
expHashes: 1, expHashes: 1,
}, },
{ {
nBytes: 10000, hashes: []common.Hash{emptyCode, emptyCode, emptyCode}, nBytes: 10000, hashes: []common.Hash{types.EmptyCodeHash, types.EmptyCodeHash, types.EmptyCodeHash},
expHashes: 3, expHashes: 3,
}, },
// The existing bytecodes // The existing bytecodes
@ -363,7 +357,7 @@ func (s *Suite) TestSnapTrieNodes(t *utesting.T) {
for i := 1; i <= 65; i++ { for i := 1; i <= 65; i++ {
accPaths = append(accPaths, pathTo(i)) accPaths = append(accPaths, pathTo(i))
} }
empty := emptyCode empty := types.EmptyCodeHash
for i, tc := range []trieNodesTest{ for i, tc := range []trieNodesTest{
{ {
root: s.chain.RootAt(999), root: s.chain.RootAt(999),
@ -406,8 +400,10 @@ func (s *Suite) TestSnapTrieNodes(t *utesting.T) {
{[]byte{0}}, {[]byte{0}},
{[]byte{1}, []byte{0}}, {[]byte{1}, []byte{0}},
}, },
nBytes: 5000, nBytes: 5000,
expHashes: []common.Hash{}, expHashes: []common.Hash{
common.HexToHash("0x1ee1bb2fbac4d46eab331f3e8551e18a0805d084ed54647883aa552809ca968d"),
},
}, },
{ {
// The leaf is only a couple of levels down, so the continued trie traversal causes lookup failures. // The leaf is only a couple of levels down, so the continued trie traversal causes lookup failures.
@ -437,7 +433,35 @@ func (s *Suite) TestSnapTrieNodes(t *utesting.T) {
common.HexToHash("0xbcefee69b37cca1f5bf3a48aebe08b35f2ea1864fa958bb0723d909a0e0d28d8"), common.HexToHash("0xbcefee69b37cca1f5bf3a48aebe08b35f2ea1864fa958bb0723d909a0e0d28d8"),
}, },
}, },
} { {
/*
A test against this account, requesting trie nodes for the storage trie
{
"balance": "0",
"nonce": 1,
"root": "0xbe3d75a1729be157e79c3b77f00206db4d54e3ea14375a015451c88ec067c790",
"codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",
"storage": {
"0x405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace": "02",
"0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6": "01",
"0xc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b": "03"
},
"key": "0xf493f79c43bd747129a226ad42529885a4b108aba6046b2d12071695a6627844"
}
*/
root: s.chain.RootAt(999),
paths: []snap.TrieNodePathSet{
{
common.FromHex("0xf493f79c43bd747129a226ad42529885a4b108aba6046b2d12071695a6627844"),
[]byte{0},
},
},
nBytes: 5000,
expHashes: []common.Hash{
common.HexToHash("0xbe3d75a1729be157e79c3b77f00206db4d54e3ea14375a015451c88ec067c790"),
},
},
}[7:] {
tc := tc tc := tc
if err := s.snapGetTrieNodes(t, &tc); err != nil { if err := s.snapGetTrieNodes(t, &tc); err != nil {
t.Errorf("test %d \n #hashes %x\n root: %#x\n bytes: %d\nfailed: %v", i, len(tc.expHashes), tc.root, tc.nBytes, err) t.Errorf("test %d \n #hashes %x\n root: %#x\n bytes: %d\nfailed: %v", i, len(tc.expHashes), tc.root, tc.nBytes, err)

View File

@ -510,17 +510,18 @@ func (s *Suite) TestNewPooledTxs(t *utesting.T) {
} }
// generate 50 txs // generate 50 txs
hashMap, _, err := generateTxs(s, 50) _, txs, err := generateTxs(s, 50)
if err != nil { if err != nil {
t.Fatalf("failed to generate transactions: %v", err) t.Fatalf("failed to generate transactions: %v", err)
} }
hashes := make([]common.Hash, len(txs))
// create new pooled tx hashes announcement types := make([]byte, len(txs))
hashes := make([]common.Hash, 0) sizes := make([]uint32, len(txs))
for _, hash := range hashMap { for i, tx := range txs {
hashes = append(hashes, hash) hashes[i] = tx.Hash()
types[i] = tx.Type()
sizes[i] = uint32(tx.Size())
} }
announce := NewPooledTransactionHashes(hashes)
// send announcement // send announcement
conn, err := s.dial() conn, err := s.dial()
@ -531,7 +532,13 @@ func (s *Suite) TestNewPooledTxs(t *utesting.T) {
if err = conn.peer(s.chain, nil); err != nil { if err = conn.peer(s.chain, nil); err != nil {
t.Fatalf("peering failed: %v", err) t.Fatalf("peering failed: %v", err)
} }
if err = conn.Write(announce); err != nil {
var ann Message = NewPooledTransactionHashes{Types: types, Sizes: sizes, Hashes: hashes}
if conn.negotiatedProtoVersion < eth.ETH68 {
ann = NewPooledTransactionHashes66(hashes)
}
err = conn.Write(ann)
if err != nil {
t.Fatalf("failed to write to connection: %v", err) t.Fatalf("failed to write to connection: %v", err)
} }
@ -544,9 +551,15 @@ func (s *Suite) TestNewPooledTxs(t *utesting.T) {
t.Fatalf("unexpected number of txs requested: wanted %d, got %d", len(hashes), len(msg.GetPooledTransactionsPacket)) t.Fatalf("unexpected number of txs requested: wanted %d, got %d", len(hashes), len(msg.GetPooledTransactionsPacket))
} }
return return
// ignore propagated txs from previous tests // ignore propagated txs from previous tests
case *NewPooledTransactionHashes66:
continue
case *NewPooledTransactionHashes: case *NewPooledTransactionHashes:
continue continue
case *Transactions:
continue
// ignore block announcements from previous tests // ignore block announcements from previous tests
case *NewBlockHashes: case *NewBlockHashes:
continue continue

View File

@ -29,7 +29,7 @@ import (
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
) )
//var faucetAddr = common.HexToAddress("0x71562b71999873DB5b286dF957af199Ec94617F7") // var faucetAddr = common.HexToAddress("0x71562b71999873DB5b286dF957af199Ec94617F7")
var faucetKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") var faucetKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
func (s *Suite) sendSuccessfulTxs(t *utesting.T) error { func (s *Suite) sendSuccessfulTxs(t *utesting.T) error {
@ -95,7 +95,7 @@ func sendSuccessfulTx(s *Suite, tx *types.Transaction, prevTx *types.Transaction
} }
} }
return fmt.Errorf("missing transaction: got %v missing %v", recTxs, tx.Hash()) return fmt.Errorf("missing transaction: got %v missing %v", recTxs, tx.Hash())
case *NewPooledTransactionHashes: case *NewPooledTransactionHashes66:
txHashes := *msg txHashes := *msg
// if you receive an old tx propagation, read from connection again // if you receive an old tx propagation, read from connection again
if len(txHashes) == 1 && prevTx != nil { if len(txHashes) == 1 && prevTx != nil {
@ -110,6 +110,34 @@ func sendSuccessfulTx(s *Suite, tx *types.Transaction, prevTx *types.Transaction
} }
} }
return fmt.Errorf("missing transaction announcement: got %v missing %v", txHashes, tx.Hash()) return fmt.Errorf("missing transaction announcement: got %v missing %v", txHashes, tx.Hash())
case *NewPooledTransactionHashes:
txHashes := msg.Hashes
if len(txHashes) != len(msg.Sizes) {
return fmt.Errorf("invalid msg size lengths: hashes: %v sizes: %v", len(txHashes), len(msg.Sizes))
}
if len(txHashes) != len(msg.Types) {
return fmt.Errorf("invalid msg type lengths: hashes: %v types: %v", len(txHashes), len(msg.Types))
}
// if you receive an old tx propagation, read from connection again
if len(txHashes) == 1 && prevTx != nil {
if txHashes[0] == prevTx.Hash() {
continue
}
}
for index, gotHash := range txHashes {
if gotHash == tx.Hash() {
if msg.Sizes[index] != uint32(tx.Size()) {
return fmt.Errorf("invalid tx size: got %v want %v", msg.Sizes[index], tx.Size())
}
if msg.Types[index] != tx.Type() {
return fmt.Errorf("invalid tx type: got %v want %v", msg.Types[index], tx.Type())
}
// Ok
return nil
}
}
return fmt.Errorf("missing transaction announcement: got %v missing %v", txHashes, tx.Hash())
default: default:
return fmt.Errorf("unexpected message in sendSuccessfulTx: %s", pretty.Sdump(msg)) return fmt.Errorf("unexpected message in sendSuccessfulTx: %s", pretty.Sdump(msg))
} }
@ -192,17 +220,19 @@ func sendMultipleSuccessfulTxs(t *utesting.T, s *Suite, txs []*types.Transaction
nonce = txs[len(txs)-1].Nonce() nonce = txs[len(txs)-1].Nonce()
// Wait for the transaction announcement(s) and make sure all sent txs are being propagated. // Wait for the transaction announcement(s) and make sure all sent txs are being propagated.
// all txs should be announced within 3 announcements. // all txs should be announced within a couple announcements.
recvHashes := make([]common.Hash, 0) recvHashes := make([]common.Hash, 0)
for i := 0; i < 3; i++ { for i := 0; i < 20; i++ {
switch msg := recvConn.readAndServe(s.chain, timeout).(type) { switch msg := recvConn.readAndServe(s.chain, timeout).(type) {
case *Transactions: case *Transactions:
for _, tx := range *msg { for _, tx := range *msg {
recvHashes = append(recvHashes, tx.Hash()) recvHashes = append(recvHashes, tx.Hash())
} }
case *NewPooledTransactionHashes: case *NewPooledTransactionHashes66:
recvHashes = append(recvHashes, *msg...) recvHashes = append(recvHashes, *msg...)
case *NewPooledTransactionHashes:
recvHashes = append(recvHashes, msg.Hashes...)
default: default:
if !strings.Contains(pretty.Sdump(msg), "i/o timeout") { if !strings.Contains(pretty.Sdump(msg), "i/o timeout") {
return fmt.Errorf("unexpected message while waiting to receive txs: %s", pretty.Sdump(msg)) return fmt.Errorf("unexpected message while waiting to receive txs: %s", pretty.Sdump(msg))
@ -246,11 +276,16 @@ func checkMaliciousTxPropagation(s *Suite, txs []*types.Transaction, conn *Conn)
if len(badTxs) > 0 { if len(badTxs) > 0 {
return fmt.Errorf("received %d bad txs: \n%v", len(badTxs), badTxs) return fmt.Errorf("received %d bad txs: \n%v", len(badTxs), badTxs)
} }
case *NewPooledTransactionHashes: case *NewPooledTransactionHashes66:
badTxs, _ := compareReceivedTxs(*msg, txs) badTxs, _ := compareReceivedTxs(*msg, txs)
if len(badTxs) > 0 { if len(badTxs) > 0 {
return fmt.Errorf("received %d bad txs: \n%v", len(badTxs), badTxs) return fmt.Errorf("received %d bad txs: \n%v", len(badTxs), badTxs)
} }
case *NewPooledTransactionHashes:
badTxs, _ := compareReceivedTxs(msg.Hashes, txs)
if len(badTxs) > 0 {
return fmt.Errorf("received %d bad txs: \n%v", len(badTxs), badTxs)
}
case *Error: case *Error:
// Transaction should not be announced -> wait for timeout // Transaction should not be announced -> wait for timeout
return nil return nil

View File

@ -126,8 +126,14 @@ type NewBlock eth.NewBlockPacket
func (msg NewBlock) Code() int { return 23 } func (msg NewBlock) Code() int { return 23 }
func (msg NewBlock) ReqID() uint64 { return 0 } func (msg NewBlock) ReqID() uint64 { return 0 }
// NewPooledTransactionHashes66 is the network packet for the tx hash propagation message.
type NewPooledTransactionHashes66 eth.NewPooledTransactionHashesPacket66
func (msg NewPooledTransactionHashes66) Code() int { return 24 }
func (msg NewPooledTransactionHashes66) ReqID() uint64 { return 0 }
// NewPooledTransactionHashes is the network packet for the tx hash propagation message. // NewPooledTransactionHashes is the network packet for the tx hash propagation message.
type NewPooledTransactionHashes eth.NewPooledTransactionHashesPacket type NewPooledTransactionHashes eth.NewPooledTransactionHashesPacket68
func (msg NewPooledTransactionHashes) Code() int { return 24 } func (msg NewPooledTransactionHashes) Code() int { return 24 }
func (msg NewPooledTransactionHashes) ReqID() uint64 { return 0 } func (msg NewPooledTransactionHashes) ReqID() uint64 { return 0 }
@ -202,8 +208,13 @@ func (c *Conn) Read() Message {
msg = new(NewBlockHashes) msg = new(NewBlockHashes)
case (Transactions{}).Code(): case (Transactions{}).Code():
msg = new(Transactions) msg = new(Transactions)
case (NewPooledTransactionHashes{}).Code(): case (NewPooledTransactionHashes66{}).Code():
msg = new(NewPooledTransactionHashes) // Try decoding to eth68
ethMsg := new(NewPooledTransactionHashes)
if err := rlp.DecodeBytes(rawData, ethMsg); err == nil {
return ethMsg
}
msg = new(NewPooledTransactionHashes66)
case (GetPooledTransactions{}.Code()): case (GetPooledTransactions{}.Code()):
ethMsg := new(eth.GetPooledTransactionsPacket66) ethMsg := new(eth.GetPooledTransactionsPacket66)
if err := rlp.DecodeBytes(rawData, ethMsg); err != nil { if err := rlp.DecodeBytes(rawData, ethMsg); err != nil {

View File

@ -37,9 +37,9 @@ const (
var ( var (
// Remote node under test // Remote node under test
Remote string Remote string
// IP where the first tester is listening, port will be assigned // Listen1 is the IP where the first tester is listening, port will be assigned
Listen1 string = "127.0.0.1" Listen1 string = "127.0.0.1"
// IP where the second tester is listening, port will be assigned // Listen2 is the IP where the second tester is listening, port will be assigned
// Before running the test, you may have to `sudo ifconfig lo0 add 127.0.0.2` (on MacOS at least) // Before running the test, you may have to `sudo ifconfig lo0 add 127.0.0.2` (on MacOS at least)
Listen2 string = "127.0.0.2" Listen2 string = "127.0.0.2"
) )
@ -68,7 +68,7 @@ func futureExpiration() uint64 {
return uint64(time.Now().Add(expiration).Unix()) return uint64(time.Now().Add(expiration).Unix())
} }
// This test just sends a PING packet and expects a response. // BasicPing just sends a PING packet and expects a response.
func BasicPing(t *utesting.T) { func BasicPing(t *utesting.T) {
te := newTestEnv(Remote, Listen1, Listen2) te := newTestEnv(Remote, Listen1, Listen2)
defer te.close() defer te.close()
@ -137,7 +137,7 @@ func (te *testenv) checkPong(reply v4wire.Packet, pingHash []byte) error {
return nil return nil
} }
// This test sends a PING packet with wrong 'to' field and expects a PONG response. // PingWrongTo sends a PING packet with wrong 'to' field and expects a PONG response.
func PingWrongTo(t *utesting.T) { func PingWrongTo(t *utesting.T) {
te := newTestEnv(Remote, Listen1, Listen2) te := newTestEnv(Remote, Listen1, Listen2)
defer te.close() defer te.close()
@ -154,7 +154,7 @@ func PingWrongTo(t *utesting.T) {
} }
} }
// This test sends a PING packet with wrong 'from' field and expects a PONG response. // PingWrongFrom sends a PING packet with wrong 'from' field and expects a PONG response.
func PingWrongFrom(t *utesting.T) { func PingWrongFrom(t *utesting.T) {
te := newTestEnv(Remote, Listen1, Listen2) te := newTestEnv(Remote, Listen1, Listen2)
defer te.close() defer te.close()
@ -172,7 +172,7 @@ func PingWrongFrom(t *utesting.T) {
} }
} }
// This test sends a PING packet with additional data at the end and expects a PONG // PingExtraData This test sends a PING packet with additional data at the end and expects a PONG
// response. The remote node should respond because EIP-8 mandates ignoring additional // response. The remote node should respond because EIP-8 mandates ignoring additional
// trailing data. // trailing data.
func PingExtraData(t *utesting.T) { func PingExtraData(t *utesting.T) {
@ -256,6 +256,7 @@ func WrongPacketType(t *utesting.T) {
func BondThenPingWithWrongFrom(t *utesting.T) { func BondThenPingWithWrongFrom(t *utesting.T) {
te := newTestEnv(Remote, Listen1, Listen2) te := newTestEnv(Remote, Listen1, Listen2)
defer te.close() defer te.close()
bond(t, te) bond(t, te)
wrongEndpoint := v4wire.Endpoint{IP: net.ParseIP("192.0.2.0")} wrongEndpoint := v4wire.Endpoint{IP: net.ParseIP("192.0.2.0")}
@ -265,10 +266,25 @@ func BondThenPingWithWrongFrom(t *utesting.T) {
To: te.remoteEndpoint(), To: te.remoteEndpoint(),
Expiration: futureExpiration(), Expiration: futureExpiration(),
}) })
if reply, _, err := te.read(te.l1); err != nil {
t.Fatal(err) waitForPong:
} else if err := te.checkPong(reply, pingHash); err != nil { for {
t.Fatal(err) reply, _, err := te.read(te.l1)
if err != nil {
t.Fatal(err)
}
switch reply.Kind() {
case v4wire.PongPacket:
if err := te.checkPong(reply, pingHash); err != nil {
t.Fatal(err)
}
break waitForPong
case v4wire.FindnodePacket:
// FINDNODE from the node is acceptable here since the endpoint
// verification was performed earlier.
default:
t.Fatalf("Expected PONG, got %v %v", reply.Name(), reply)
}
} }
} }
@ -379,7 +395,7 @@ func FindnodePastExpiration(t *utesting.T) {
// bond performs the endpoint proof with the remote node. // bond performs the endpoint proof with the remote node.
func bond(t *utesting.T, te *testenv) { func bond(t *utesting.T, te *testenv) {
te.send(te.l1, &v4wire.Ping{ pingHash := te.send(te.l1, &v4wire.Ping{
Version: 4, Version: 4,
From: te.localEndpoint(te.l1), From: te.localEndpoint(te.l1),
To: te.remoteEndpoint(), To: te.remoteEndpoint(),
@ -401,7 +417,9 @@ func bond(t *utesting.T, te *testenv) {
}) })
gotPing = true gotPing = true
case *v4wire.Pong: case *v4wire.Pong:
// TODO: maybe verify pong data here if err := te.checkPong(req, pingHash); err != nil {
t.Fatal(err)
}
gotPong = true gotPong = true
} }
} }

View File

@ -58,7 +58,7 @@ func (s *Suite) AllTests() []utesting.Test {
} }
} }
// This test sends PING and expects a PONG response. // TestPing sends PING and expects a PONG response.
func (s *Suite) TestPing(t *utesting.T) { func (s *Suite) TestPing(t *utesting.T) {
conn, l1 := s.listen1(t) conn, l1 := s.listen1(t)
defer conn.close() defer conn.close()
@ -84,7 +84,7 @@ func checkPong(t *utesting.T, pong *v5wire.Pong, ping *v5wire.Ping, c net.Packet
} }
} }
// This test sends PING with a 9-byte request ID, which isn't allowed by the spec. // TestPingLargeRequestID sends PING with a 9-byte request ID, which isn't allowed by the spec.
// The remote node should not respond. // The remote node should not respond.
func (s *Suite) TestPingLargeRequestID(t *utesting.T) { func (s *Suite) TestPingLargeRequestID(t *utesting.T) {
conn, l1 := s.listen1(t) conn, l1 := s.listen1(t)
@ -103,7 +103,7 @@ func (s *Suite) TestPingLargeRequestID(t *utesting.T) {
} }
} }
// In this test, a session is established from one IP as usual. The session is then reused // TestPingMultiIP establishes a session from one IP as usual. The session is then reused
// on another IP, which shouldn't work. The remote node should respond with WHOAREYOU for // on another IP, which shouldn't work. The remote node should respond with WHOAREYOU for
// the attempt from a different IP. // the attempt from a different IP.
func (s *Suite) TestPingMultiIP(t *utesting.T) { func (s *Suite) TestPingMultiIP(t *utesting.T) {
@ -153,7 +153,7 @@ func (s *Suite) TestPingMultiIP(t *utesting.T) {
} }
} }
// This test starts a handshake, but doesn't finish it and sends a second ordinary message // TestPingHandshakeInterrupted starts a handshake, but doesn't finish it and sends a second ordinary message
// packet instead of a handshake message packet. The remote node should respond with // packet instead of a handshake message packet. The remote node should respond with
// another WHOAREYOU challenge for the second packet. // another WHOAREYOU challenge for the second packet.
func (s *Suite) TestPingHandshakeInterrupted(t *utesting.T) { func (s *Suite) TestPingHandshakeInterrupted(t *utesting.T) {
@ -180,7 +180,7 @@ func (s *Suite) TestPingHandshakeInterrupted(t *utesting.T) {
} }
} }
// This test sends TALKREQ and expects an empty TALKRESP response. // TestTalkRequest sends TALKREQ and expects an empty TALKRESP response.
func (s *Suite) TestTalkRequest(t *utesting.T) { func (s *Suite) TestTalkRequest(t *utesting.T) {
conn, l1 := s.listen1(t) conn, l1 := s.listen1(t)
defer conn.close() defer conn.close()
@ -215,7 +215,7 @@ func (s *Suite) TestTalkRequest(t *utesting.T) {
} }
} }
// This test checks that the remote node returns itself for FINDNODE with distance zero. // TestFindnodeZeroDistance checks that the remote node returns itself for FINDNODE with distance zero.
func (s *Suite) TestFindnodeZeroDistance(t *utesting.T) { func (s *Suite) TestFindnodeZeroDistance(t *utesting.T) {
conn, l1 := s.listen1(t) conn, l1 := s.listen1(t)
defer conn.close() defer conn.close()
@ -232,7 +232,7 @@ func (s *Suite) TestFindnodeZeroDistance(t *utesting.T) {
} }
} }
// In this test, multiple nodes ping the node under test. After waiting for them to be // TestFindnodeResults pings the node under test from multiple nodes. After waiting for them to be
// accepted into the remote table, the test checks that they are returned by FINDNODE. // accepted into the remote table, the test checks that they are returned by FINDNODE.
func (s *Suite) TestFindnodeResults(t *utesting.T) { func (s *Suite) TestFindnodeResults(t *utesting.T) {
// Create bystanders. // Create bystanders.
@ -355,7 +355,7 @@ func (bn *bystander) loop() {
wasAdded = true wasAdded = true
bn.notifyAdded() bn.notifyAdded()
case *v5wire.Findnode: case *v5wire.Findnode:
bn.conn.write(bn.l, &v5wire.Nodes{ReqID: p.ReqID, Total: 1}, nil) bn.conn.write(bn.l, &v5wire.Nodes{ReqID: p.ReqID, RespCount: 1}, nil)
wasAdded = true wasAdded = true
bn.notifyAdded() bn.notifyAdded()
case *v5wire.TalkRequest: case *v5wire.TalkRequest:

View File

@ -44,6 +44,8 @@ func (p *readError) Unwrap() error { return p.err }
func (p *readError) RequestID() []byte { return nil } func (p *readError) RequestID() []byte { return nil }
func (p *readError) SetRequestID([]byte) {} func (p *readError) SetRequestID([]byte) {}
func (p *readError) AppendLogInfo(ctx []interface{}) []interface{} { return ctx }
// readErrorf creates a readError with the given text. // readErrorf creates a readError with the given text.
func readErrorf(format string, args ...interface{}) *readError { func readErrorf(format string, args ...interface{}) *readError {
return &readError{fmt.Errorf(format, args...)} return &readError{fmt.Errorf(format, args...)}
@ -86,7 +88,7 @@ func newConn(dest *enode.Node, log logger) *conn {
localNode: ln, localNode: ln,
remote: dest, remote: dest,
remoteAddr: &net.UDPAddr{IP: dest.IP(), Port: dest.UDP()}, remoteAddr: &net.UDPAddr{IP: dest.IP(), Port: dest.UDP()},
codec: v5wire.NewCodec(ln, key, mclock.System{}), codec: v5wire.NewCodec(ln, key, mclock.System{}, nil),
log: log, log: log,
} }
} }
@ -171,16 +173,16 @@ func (tc *conn) findnode(c net.PacketConn, dists []uint) ([]*enode.Node, error)
// Check total count. It should be greater than one // Check total count. It should be greater than one
// and needs to be the same across all responses. // and needs to be the same across all responses.
if first { if first {
if resp.Total == 0 || resp.Total > 6 { if resp.RespCount == 0 || resp.RespCount > 6 {
return nil, fmt.Errorf("invalid NODES response 'total' %d (not in (0,7))", resp.Total) return nil, fmt.Errorf("invalid NODES response count %d (not in (0,7))", resp.RespCount)
} }
total = resp.Total total = resp.RespCount
n = int(total) - 1 n = int(total) - 1
first = false first = false
} else { } else {
n-- n--
if resp.Total != total { if resp.RespCount != total {
return nil, fmt.Errorf("invalid NODES response 'total' %d (!= %d)", resp.Total, total) return nil, fmt.Errorf("invalid NODES response count %d (!= %d)", resp.RespCount, total)
} }
} }
// Check nodes. // Check nodes.

View File

@ -22,6 +22,7 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/enr"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
) )
@ -31,7 +32,9 @@ var (
Usage: "Operations on node keys", Usage: "Operations on node keys",
Subcommands: []*cli.Command{ Subcommands: []*cli.Command{
keyGenerateCommand, keyGenerateCommand,
keyToIDCommand,
keyToNodeCommand, keyToNodeCommand,
keyToRecordCommand,
}, },
} }
keyGenerateCommand = &cli.Command{ keyGenerateCommand = &cli.Command{
@ -40,6 +43,13 @@ var (
ArgsUsage: "keyfile", ArgsUsage: "keyfile",
Action: genkey, Action: genkey,
} }
keyToIDCommand = &cli.Command{
Name: "to-id",
Usage: "Creates a node ID from a node key file",
ArgsUsage: "keyfile",
Action: keyToID,
Flags: []cli.Flag{},
}
keyToNodeCommand = &cli.Command{ keyToNodeCommand = &cli.Command{
Name: "to-enode", Name: "to-enode",
Usage: "Creates an enode URL from a node key file", Usage: "Creates an enode URL from a node key file",
@ -47,6 +57,13 @@ var (
Action: keyToURL, Action: keyToURL,
Flags: []cli.Flag{hostFlag, tcpPortFlag, udpPortFlag}, Flags: []cli.Flag{hostFlag, tcpPortFlag, udpPortFlag},
} }
keyToRecordCommand = &cli.Command{
Name: "to-enr",
Usage: "Creates an ENR from a node key file",
ArgsUsage: "keyfile",
Action: keyToRecord,
Flags: []cli.Flag{hostFlag, tcpPortFlag, udpPortFlag},
}
) )
var ( var (
@ -80,9 +97,36 @@ func genkey(ctx *cli.Context) error {
return crypto.SaveECDSA(file, key) return crypto.SaveECDSA(file, key)
} }
func keyToID(ctx *cli.Context) error {
n, err := makeRecord(ctx)
if err != nil {
return err
}
fmt.Println(n.ID())
return nil
}
func keyToURL(ctx *cli.Context) error { func keyToURL(ctx *cli.Context) error {
n, err := makeRecord(ctx)
if err != nil {
return err
}
fmt.Println(n.URLv4())
return nil
}
func keyToRecord(ctx *cli.Context) error {
n, err := makeRecord(ctx)
if err != nil {
return err
}
fmt.Println(n.String())
return nil
}
func makeRecord(ctx *cli.Context) (*enode.Node, error) {
if ctx.NArg() != 1 { if ctx.NArg() != 1 {
return fmt.Errorf("need key file as argument") return nil, fmt.Errorf("need key file as argument")
} }
var ( var (
@ -93,13 +137,26 @@ func keyToURL(ctx *cli.Context) error {
) )
key, err := crypto.LoadECDSA(file) key, err := crypto.LoadECDSA(file)
if err != nil { if err != nil {
return err return nil, err
} }
ip := net.ParseIP(host)
if ip == nil { var r enr.Record
return fmt.Errorf("invalid IP address %q", host) if host != "" {
ip := net.ParseIP(host)
if ip == nil {
return nil, fmt.Errorf("invalid IP address %q", host)
}
r.Set(enr.IP(ip))
} }
node := enode.NewV4(&key.PublicKey, ip, tcp, udp) if udp != 0 {
fmt.Println(node.URLv4()) r.Set(enr.UDP(udp))
return nil }
if tcp != 0 {
r.Set(enr.TCP(tcp))
}
if err := enode.SignV4(&r, key); err != nil {
return nil, err
}
return enode.New(enode.ValidSchemes, &r)
} }

View File

@ -19,30 +19,16 @@ package main
import ( import (
"fmt" "fmt"
"os" "os"
"path/filepath"
"github.com/ethereum/go-ethereum/internal/debug" "github.com/ethereum/go-ethereum/internal/debug"
"github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/internal/flags"
"github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/params"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
) )
var ( var app = flags.NewApp("go-ethereum devp2p tool")
// Git information set by linker when building with ci.go.
gitCommit string
gitDate string
app = &cli.App{
Name: filepath.Base(os.Args[0]),
Usage: "go-ethereum devp2p tool",
Version: params.VersionWithCommit(gitCommit, gitDate),
Writer: os.Stdout,
HideVersion: true,
}
)
func init() { func init() {
// Set up the CLI app.
app.Flags = append(app.Flags, debug.Flags...) app.Flags = append(app.Flags, debug.Flags...)
app.Before = func(ctx *cli.Context) error { app.Before = func(ctx *cli.Context) error {
flags.MigrateGlobalFlags(ctx) flags.MigrateGlobalFlags(ctx)
@ -56,6 +42,7 @@ func init() {
fmt.Fprintf(os.Stderr, "No such command: %s\n", cmd) fmt.Fprintf(os.Stderr, "No such command: %s\n", cmd)
os.Exit(1) os.Exit(1)
} }
// Add subcommands. // Add subcommands.
app.Commands = []*cli.Command{ app.Commands = []*cli.Command{
enrdumpCommand, enrdumpCommand,

View File

@ -181,7 +181,7 @@ func parseFilterLimit(args []string) (int, error) {
return limit, nil return limit, nil
} }
// andFilter parses node filters in args and and returns a single filter that requires all // andFilter parses node filters in args and returns a single filter that requires all
// of them to match. // of them to match.
func andFilter(args []string) (nodeFilter, error) { func andFilter(args []string) (nodeFilter, error) {
checks, err := parseFilters(args) checks, err := parseFilters(args)
@ -233,8 +233,6 @@ func ethFilter(args []string) (nodeFilter, error) {
filter = forkid.NewStaticFilter(params.RinkebyChainConfig, params.RinkebyGenesisHash) filter = forkid.NewStaticFilter(params.RinkebyChainConfig, params.RinkebyGenesisHash)
case "goerli": case "goerli":
filter = forkid.NewStaticFilter(params.GoerliChainConfig, params.GoerliGenesisHash) filter = forkid.NewStaticFilter(params.GoerliChainConfig, params.GoerliGenesisHash)
case "ropsten":
filter = forkid.NewStaticFilter(params.RopstenChainConfig, params.RopstenGenesisHash)
case "sepolia": case "sepolia":
filter = forkid.NewStaticFilter(params.SepoliaChainConfig, params.SepoliaGenesisHash) filter = forkid.NewStaticFilter(params.SepoliaChainConfig, params.SepoliaGenesisHash)
default: default:

View File

@ -28,14 +28,10 @@ const (
defaultKeyfileName = "keyfile.json" defaultKeyfileName = "keyfile.json"
) )
// Git SHA1 commit hash of the release (set via linker flags)
var gitCommit = ""
var gitDate = ""
var app *cli.App var app *cli.App
func init() { func init() {
app = flags.NewApp(gitCommit, gitDate, "an Ethereum key manager") app = flags.NewApp("Ethereum key manager")
app.Commands = []*cli.Command{ app.Commands = []*cli.Command{
commandGenerate, commandGenerate,
commandInspect, commandInspect,

View File

@ -1,56 +1,196 @@
## EVM state transition tool # EVM tool
The EVM tool provides a few useful subcommands to facilitate testing at the EVM
layer.
* transition tool (`t8n`) : a stateless state transition utility
* transaction tool (`t9n`) : a transaction validation utility
* block builder tool (`b11r`): a block assembler utility
## State transition tool (`t8n`)
The `evm t8n` tool is a stateless state transition utility. It is a utility The `evm t8n` tool is a stateless state transition utility. It is a utility
which can which can
1. Take a prestate, including 1. Take a prestate, including
- Accounts, - Accounts,
- Block context information, - Block context information,
- Previous blockshashes (*optional) - Previous blockshashes (*optional)
2. Apply a set of transactions, 2. Apply a set of transactions,
3. Apply a mining-reward (*optional), 3. Apply a mining-reward (*optional),
4. And generate a post-state, including 4. And generate a post-state, including
- State root, transaction root, receipt root, - State root, transaction root, receipt root,
- Information about rejected transactions, - Information about rejected transactions,
- Optionally: a full or partial post-state dump - Optionally: a full or partial post-state dump
## Specification ### Specification
The idea is to specify the behaviour of this binary very _strict_, so that other The idea is to specify the behaviour of this binary very _strict_, so that other
node implementors can build replicas based on their own state-machines, and the node implementors can build replicas based on their own state-machines, and the
state generators can swap between a `geth`-based implementation and a `parityvm`-based state generators can swap between a \`geth\`-based implementation and a \`parityvm\`-based
implementation. implementation.
### Command line params #### Command line params
Command line params that has to be supported are Command line params that need to be supported are
```
--trace Output full trace logs to files <txhash>.jsonl
--trace.nomemory Disable full memory dump in traces
--trace.nostack Disable stack output in traces
--trace.noreturndata Disable return data output in traces
--output.basedir value Specifies where output files are placed. Will be created if it does not exist.
--output.alloc alloc Determines where to put the alloc of the post-state.
`stdout` - into the stdout output
`stderr` - into the stderr output
--output.result result Determines where to put the result (stateroot, txroot etc) of the post-state.
`stdout` - into the stdout output
`stderr` - into the stderr output
--output.body value If set, the RLP of the transactions (block body) will be written to this file.
--input.txs stdin stdin or file name of where to find the transactions to apply. If the file prefix is '.rlp', then the data is interpreted as an RLP list of signed transactions.The '.rlp' format is identical to the output.body format. (default: "txs.json")
--state.fork value Name of ruleset to use.
--state.chainid value ChainID to use (default: 1)
--state.reward value Mining reward. Set to -1 to disable (default: 0)
``` ```
--input.alloc value (default: "alloc.json")
--input.env value (default: "env.json")
--input.txs value (default: "txs.json")
--output.alloc value (default: "alloc.json")
--output.basedir value
--output.body value
--output.result value (default: "result.json")
--state.chainid value (default: 1)
--state.fork value (default: "GrayGlacier")
--state.reward value (default: 0)
--trace.memory (default: false)
--trace.nomemory (default: true)
--trace.noreturndata (default: true)
--trace.nostack (default: false)
--trace.returndata (default: false)
```
#### Objects
### Error codes and output The transition tool uses JSON objects to read and write data related to the transition operation. The
following object definitions are required.
##### `alloc`
The `alloc` object defines the prestate that transition will begin with.
```go
// Map of address to account definition.
type Alloc map[common.Address]Account
// Genesis account. Each field is optional.
type Account struct {
Code []byte `json:"code"`
Storage map[common.Hash]common.Hash `json:"storage"`
Balance *big.Int `json:"balance"`
Nonce uint64 `json:"nonce"`
SecretKey []byte `json:"secretKey"`
}
```
##### `env`
The `env` object defines the environmental context in which the transition will
take place.
```go
type Env struct {
// required
CurrentCoinbase common.Address `json:"currentCoinbase"`
CurrentGasLimit uint64 `json:"currentGasLimit"`
CurrentNumber uint64 `json:"currentNumber"`
CurrentTimestamp uint64 `json:"currentTimestamp"`
Withdrawals []*Withdrawal `json:"withdrawals"`
// optional
CurrentDifficulty *big.Int `json:"currentDifficuly"`
CurrentRandom *big.Int `json:"currentRandom"`
CurrentBaseFee *big.Int `json:"currentBaseFee"`
ParentDifficulty *big.Int `json:"parentDifficulty"`
ParentGasUsed uint64 `json:"parentGasUsed"`
ParentGasLimit uint64 `json:"parentGasLimit"`
ParentTimestamp uint64 `json:"parentTimestamp"`
BlockHashes map[uint64]common.Hash `json:"blockHashes"`
ParentUncleHash common.Hash `json:"parentUncleHash"`
Ommers []Ommer `json:"ommers"`
}
type Ommer struct {
Delta uint64 `json:"delta"`
Address common.Address `json:"address"`
}
type Withdrawal struct {
Index uint64 `json:"index"`
ValidatorIndex uint64 `json:"validatorIndex"`
Recipient common.Address `json:"recipient"`
Amount *big.Int `json:"amount"`
}
```
##### `txs`
The `txs` object is an array of any of the transaction types: `LegacyTx`,
`AccessListTx`, or `DynamicFeeTx`.
```go
type LegacyTx struct {
Nonce uint64 `json:"nonce"`
GasPrice *big.Int `json:"gasPrice"`
Gas uint64 `json:"gas"`
To *common.Address `json:"to"`
Value *big.Int `json:"value"`
Data []byte `json:"data"`
V *big.Int `json:"v"`
R *big.Int `json:"r"`
S *big.Int `json:"s"`
SecretKey *common.Hash `json:"secretKey"`
}
type AccessList []AccessTuple
type AccessTuple struct {
Address common.Address `json:"address" gencodec:"required"`
StorageKeys []common.Hash `json:"storageKeys" gencodec:"required"`
}
type AccessListTx struct {
ChainID *big.Int `json:"chainId"`
Nonce uint64 `json:"nonce"`
GasPrice *big.Int `json:"gasPrice"`
Gas uint64 `json:"gas"`
To *common.Address `json:"to"`
Value *big.Int `json:"value"`
Data []byte `json:"data"`
AccessList AccessList `json:"accessList"`
V *big.Int `json:"v"`
R *big.Int `json:"r"`
S *big.Int `json:"s"`
SecretKey *common.Hash `json:"secretKey"`
}
type DynamicFeeTx struct {
ChainID *big.Int `json:"chainId"`
Nonce uint64 `json:"nonce"`
GasTipCap *big.Int `json:"maxPriorityFeePerGas"`
GasFeeCap *big.Int `json:"maxFeePerGas"`
Gas uint64 `json:"gas"`
To *common.Address `json:"to"`
Value *big.Int `json:"value"`
Data []byte `json:"data"`
AccessList AccessList `json:"accessList"`
V *big.Int `json:"v"`
R *big.Int `json:"r"`
S *big.Int `json:"s"`
SecretKey *common.Hash `json:"secretKey"`
}
```
##### `result`
The `result` object is output after a transition is executed. It includes
information about the post-transition environment.
```go
type ExecutionResult struct {
StateRoot common.Hash `json:"stateRoot"`
TxRoot common.Hash `json:"txRoot"`
ReceiptRoot common.Hash `json:"receiptsRoot"`
LogsHash common.Hash `json:"logsHash"`
Bloom types.Bloom `json:"logsBloom"`
Receipts types.Receipts `json:"receipts"`
Rejected []*rejectedTx `json:"rejected,omitempty"`
Difficulty *big.Int `json:"currentDifficulty"`
GasUsed uint64 `json:"gasUsed"`
BaseFee *big.Int `json:"currentBaseFee,omitempty"`
}
```
#### Error codes and output
All logging should happen against the `stderr`. All logging should happen against the `stderr`.
There are a few (not many) errors that can occur, those are defined below. There are a few (not many) errors that can occur, those are defined below.
#### EVM-based errors (`2` to `9`) ##### EVM-based errors (`2` to `9`)
- Other EVM error. Exit code `2` - Other EVM error. Exit code `2`
- Failed configuration: when a non-supported or invalid fork was specified. Exit code `3`. - Failed configuration: when a non-supported or invalid fork was specified. Exit code `3`.
@ -58,18 +198,30 @@ There are a few (not many) errors that can occur, those are defined below.
is invoked targeting a block which history has not been provided for, the program will is invoked targeting a block which history has not been provided for, the program will
exit with code `4`. exit with code `4`.
#### IO errors (`10`-`20`) ##### IO errors (`10`-`20`)
- Invalid input json: the supplied data could not be marshalled. - Invalid input json: the supplied data could not be marshalled.
The program will exit with code `10` The program will exit with code `10`
- IO problems: failure to load or save files, the program will exit with code `11` - IO problems: failure to load or save files, the program will exit with code `11`
## Examples ```
# This should exit with 3
./evm t8n --input.alloc=./testdata/1/alloc.json --input.txs=./testdata/1/txs.json --input.env=./testdata/1/env.json --state.fork=Frontier+1346 2>/dev/null
exitcode:3 OK
```
#### Forks
### Basic usage ### Basic usage
The chain configuration to be used for a transition is specified via the
`--state.fork` CLI flag. A list of possible values and configurations can be
found in [`tests/init.go`](tests/init.go).
#### Examples
##### Basic usage
Invoking it with the provided example files Invoking it with the provided example files
``` ```
./evm t8n --input.alloc=./testdata/1/alloc.json --input.txs=./testdata/1/txs.json --input.env=./testdata/1/env.json ./evm t8n --input.alloc=./testdata/1/alloc.json --input.txs=./testdata/1/txs.json --input.env=./testdata/1/env.json --state.fork=Berlin
``` ```
Two resulting files: Two resulting files:
@ -94,7 +246,7 @@ Two resulting files:
{ {
"stateRoot": "0x84208a19bc2b46ada7445180c1db162be5b39b9abc8c0a54b05d32943eae4e13", "stateRoot": "0x84208a19bc2b46ada7445180c1db162be5b39b9abc8c0a54b05d32943eae4e13",
"txRoot": "0xc4761fd7b87ff2364c7c60b6c5c8d02e522e815328aaea3f20e3b7b7ef52c42d", "txRoot": "0xc4761fd7b87ff2364c7c60b6c5c8d02e522e815328aaea3f20e3b7b7ef52c42d",
"receiptRoot": "0x056b23fbba480696b65fe5a59b8f2148a1299103c4f57df839233af2cf4ca2d2", "receiptsRoot": "0x056b23fbba480696b65fe5a59b8f2148a1299103c4f57df839233af2cf4ca2d2",
"logsHash": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "logsHash": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"receipts": [ "receipts": [
@ -116,78 +268,82 @@ Two resulting files:
"index": 1, "index": 1,
"error": "nonce too low: address 0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192, tx: 0 state: 1" "error": "nonce too low: address 0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192, tx: 0 state: 1"
} }
] ],
"currentDifficulty": "0x20000",
"gasUsed": "0x5208"
} }
``` ```
We can make them spit out the data to e.g. `stdout` like this: We can make them spit out the data to e.g. `stdout` like this:
``` ```
./evm t8n --input.alloc=./testdata/1/alloc.json --input.txs=./testdata/1/txs.json --input.env=./testdata/1/env.json --output.result=stdout --output.alloc=stdout ./evm t8n --input.alloc=./testdata/1/alloc.json --input.txs=./testdata/1/txs.json --input.env=./testdata/1/env.json --output.result=stdout --output.alloc=stdout --state.fork=Berlin
``` ```
Output: Output:
```json ```json
{ {
"alloc": { "alloc": {
"0x8a8eafb1cf62bfbeb1741769dae1a9dd47996192": { "0x8a8eafb1cf62bfbeb1741769dae1a9dd47996192": {
"balance": "0xfeed1a9d", "balance": "0xfeed1a9d",
"nonce": "0x1" "nonce": "0x1"
},
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": {
"balance": "0x5ffd4878be161d74",
"nonce": "0xac"
},
"0xc94f5374fce5edbc8e2a8697c15331677e6ebf0b": {
"balance": "0xa410"
}
}, },
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": { "result": {
"balance": "0x5ffd4878be161d74", "stateRoot": "0x84208a19bc2b46ada7445180c1db162be5b39b9abc8c0a54b05d32943eae4e13",
"nonce": "0xac" "txRoot": "0xc4761fd7b87ff2364c7c60b6c5c8d02e522e815328aaea3f20e3b7b7ef52c42d",
}, "receiptsRoot": "0x056b23fbba480696b65fe5a59b8f2148a1299103c4f57df839233af2cf4ca2d2",
"0xc94f5374fce5edbc8e2a8697c15331677e6ebf0b": { "logsHash": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"balance": "0xa410"
}
},
"result": {
"stateRoot": "0x84208a19bc2b46ada7445180c1db162be5b39b9abc8c0a54b05d32943eae4e13",
"txRoot": "0xc4761fd7b87ff2364c7c60b6c5c8d02e522e815328aaea3f20e3b7b7ef52c42d",
"receiptRoot": "0x056b23fbba480696b65fe5a59b8f2148a1299103c4f57df839233af2cf4ca2d2",
"logsHash": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"receipts": [
{
"root": "0x",
"status": "0x1",
"cumulativeGasUsed": "0x5208",
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"logs": null, "receipts": [
"transactionHash": "0x0557bacce3375c98d806609b8d5043072f0b6a8bae45ae5a67a00d3a1a18d673", {
"contractAddress": "0x0000000000000000000000000000000000000000", "root": "0x",
"gasUsed": "0x5208", "status": "0x1",
"blockHash": "0x0000000000000000000000000000000000000000000000000000000000000000", "cumulativeGasUsed": "0x5208",
"transactionIndex": "0x0" "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
} "logs": null,
], "transactionHash": "0x0557bacce3375c98d806609b8d5043072f0b6a8bae45ae5a67a00d3a1a18d673",
"rejected": [ "contractAddress": "0x0000000000000000000000000000000000000000",
{ "gasUsed": "0x5208",
"index": 1, "blockHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"error": "nonce too low: address 0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192, tx: 0 state: 1" "transactionIndex": "0x0"
} }
] ],
} "rejected": [
{
"index": 1,
"error": "nonce too low: address 0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192, tx: 0 state: 1"
}
],
"currentDifficulty": "0x20000",
"gasUsed": "0x5208"
}
} }
``` ```
## About Ommers #### About Ommers
Mining rewards and ommer rewards might need to be added. This is how those are applied: Mining rewards and ommer rewards might need to be added. This is how those are applied:
- `block_reward` is the block mining reward for the miner (`0xaa`), of a block at height `N`. - `block_reward` is the block mining reward for the miner (`0xaa`), of a block at height `N`.
- For each ommer (mined by `0xbb`), with blocknumber `N-delta` - For each ommer (mined by `0xbb`), with blocknumber `N-delta`
- (where `delta` is the difference between the current block and the ommer) - (where `delta` is the difference between the current block and the ommer)
- The account `0xbb` (ommer miner) is awarded `(8-delta)/ 8 * block_reward` - The account `0xbb` (ommer miner) is awarded `(8-delta)/ 8 * block_reward`
- The account `0xaa` (block miner) is awarded `block_reward / 32` - The account `0xaa` (block miner) is awarded `block_reward / 32`
To make `state_t8n` apply these, the following inputs are required: To make `t8n` apply these, the following inputs are required:
- `state.reward` - `--state.reward`
- For ethash, it is `5000000000000000000` `wei`, - For ethash, it is `5000000000000000000` `wei`,
- If this is not defined, mining rewards are not applied, - If this is not defined, mining rewards are not applied,
- A value of `0` is valid, and causes accounts to be 'touched'. - A value of `0` is valid, and causes accounts to be 'touched'.
- For each ommer, the tool needs to be given an `address` and a `delta`. This - For each ommer, the tool needs to be given an `addres\` and a `delta`. This
is done via the `env`. is done via the `ommers` field in `env`.
Note: the tool does not verify that e.g. the normal uncle rules apply, Note: the tool does not verify that e.g. the normal uncle rules apply,
and allows e.g two uncles at the same height, or the uncle-distance. This means that and allows e.g two uncles at the same height, or the uncle-distance. This means that
@ -208,24 +364,24 @@ Example:
] ]
} }
``` ```
When applying this, using a reward of `0x80` When applying this, using a reward of `0x08`
Output: Output:
```json ```json
{ {
"alloc": { "alloc": {
"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": { "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": {
"balance": "0x88" "balance": "0x88"
}, },
"0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb": { "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb": {
"balance": "0x70" "balance": "0x70"
}, },
"0xcccccccccccccccccccccccccccccccccccccccc": { "0xcccccccccccccccccccccccccccccccccccccccc": {
"balance": "0x60" "balance": "0x60"
}
} }
}
} }
``` ```
### Future EIPS #### Future EIPS
It is also possible to experiment with future eips that are not yet defined in a hard fork. It is also possible to experiment with future eips that are not yet defined in a hard fork.
Example, putting EIP-1344 into Frontier: Example, putting EIP-1344 into Frontier:
@ -233,17 +389,13 @@ Example, putting EIP-1344 into Frontier:
./evm t8n --state.fork=Frontier+1344 --input.pre=./testdata/1/pre.json --input.txs=./testdata/1/txs.json --input.env=/testdata/1/env.json ./evm t8n --state.fork=Frontier+1344 --input.pre=./testdata/1/pre.json --input.txs=./testdata/1/txs.json --input.env=/testdata/1/env.json
``` ```
### Block history #### Block history
The `BLOCKHASH` opcode requires blockhashes to be provided by the caller, inside the `env`. The `BLOCKHASH` opcode requires blockhashes to be provided by the caller, inside the `env`.
If a required blockhash is not provided, the exit code should be `4`: If a required blockhash is not provided, the exit code should be `4`:
Example where blockhashes are provided: Example where blockhashes are provided:
``` ```
./evm --verbosity=1 t8n --input.alloc=./testdata/3/alloc.json --input.txs=./testdata/3/txs.json --input.env=./testdata/3/env.json --trace ./evm t8n --input.alloc=./testdata/3/alloc.json --input.txs=./testdata/3/txs.json --input.env=./testdata/3/env.json --trace --state.fork=Berlin
INFO [07-27|11:53:40.960] Trie dumping started root=b7341d..857ea1
INFO [07-27|11:53:40.960] Trie dumping complete accounts=3 elapsed="103.298µs"
INFO [07-27|11:53:40.960] Wrote file file=alloc.json
INFO [07-27|11:53:40.960] Wrote file file=result.json
``` ```
@ -251,34 +403,24 @@ INFO [07-27|11:53:40.960] Wrote file file=result.j
cat trace-0-0x72fadbef39cd251a437eea619cfeda752271a5faaaa2147df012e112159ffb81.jsonl | grep BLOCKHASH -C2 cat trace-0-0x72fadbef39cd251a437eea619cfeda752271a5faaaa2147df012e112159ffb81.jsonl | grep BLOCKHASH -C2
``` ```
``` ```
{"pc":0,"op":96,"gas":"0x5f58ef8","gasCost":"0x3","memory":"0x","memSize":0,"stack":[],"returnData":"0x","depth":1,"refund":0,"opName":"PUSH1","error":""} {"pc":0,"op":96,"gas":"0x5f58ef8","gasCost":"0x3","memSize":0,"stack":[],"depth":1,"refund":0,"opName":"PUSH1"}
{"pc":2,"op":64,"gas":"0x5f58ef5","gasCost":"0x14","memory":"0x","memSize":0,"stack":["0x1"],"returnData":"0x","depth":1,"refund":0,"opName":"BLOCKHASH","error":""} {"pc":2,"op":64,"gas":"0x5f58ef5","gasCost":"0x14","memSize":0,"stack":["0x1"],"depth":1,"refund":0,"opName":"BLOCKHASH"}
{"pc":3,"op":0,"gas":"0x5f58ee1","gasCost":"0x0","memory":"0x","memSize":0,"stack":["0xdac58aa524e50956d0c0bae7f3f8bb9d35381365d07804dd5b48a5a297c06af4"],"returnData":"0x","depth":1,"refund":0,"opName":"STOP","error":""} {"pc":3,"op":0,"gas":"0x5f58ee1","gasCost":"0x0","memSize":0,"stack":["0xdac58aa524e50956d0c0bae7f3f8bb9d35381365d07804dd5b48a5a297c06af4"],"depth":1,"refund":0,"opName":"STOP"}
{"output":"","gasUsed":"0x17","time":156276} {"output":"","gasUsed":"0x17"}
``` ```
In this example, the caller has not provided the required blockhash: In this example, the caller has not provided the required blockhash:
``` ```
./evm t8n --input.alloc=./testdata/4/alloc.json --input.txs=./testdata/4/txs.json --input.env=./testdata/4/env.json --trace ./evm t8n --input.alloc=./testdata/4/alloc.json --input.txs=./testdata/4/txs.json --input.env=./testdata/4/env.json --trace --state.fork=Berlin
ERROR(4): getHash(3) invoked, blockhash for that block not provided ERROR(4): getHash(3) invoked, blockhash for that block not provided
``` ```
Error code: 4 Error code: 4
### Chaining #### Chaining
Another thing that can be done, is to chain invocations: Another thing that can be done, is to chain invocations:
``` ```
./evm t8n --input.alloc=./testdata/1/alloc.json --input.txs=./testdata/1/txs.json --input.env=./testdata/1/env.json --output.alloc=stdout | ./evm t8n --input.alloc=stdin --input.env=./testdata/1/env.json --input.txs=./testdata/1/txs.json ./evm t8n --input.alloc=./testdata/1/alloc.json --input.txs=./testdata/1/txs.json --input.env=./testdata/1/env.json --state.fork=Berlin --output.alloc=stdout | ./evm t8n --input.alloc=stdin --input.env=./testdata/1/env.json --input.txs=./testdata/1/txs.json --state.fork=Berlin
INFO [07-27|11:53:41.049] rejected tx index=1 hash=0557ba..18d673 from=0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192 error="nonce too low: address 0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192, tx: 0 state: 1"
INFO [07-27|11:53:41.050] Trie dumping started root=84208a..ae4e13
INFO [07-27|11:53:41.050] Trie dumping complete accounts=3 elapsed="59.412µs"
INFO [07-27|11:53:41.050] Wrote file file=result.json
INFO [07-27|11:53:41.051] rejected tx index=0 hash=0557ba..18d673 from=0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192 error="nonce too low: address 0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192, tx: 0 state: 1"
INFO [07-27|11:53:41.051] rejected tx index=1 hash=0557ba..18d673 from=0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192 error="nonce too low: address 0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192, tx: 0 state: 1"
INFO [07-27|11:53:41.052] Trie dumping started root=84208a..ae4e13
INFO [07-27|11:53:41.052] Trie dumping complete accounts=3 elapsed="45.734µs"
INFO [07-27|11:53:41.052] Wrote file file=alloc.json
INFO [07-27|11:53:41.052] Wrote file file=result.json
``` ```
What happened here, is that we first applied two identical transactions, so the second one was rejected. What happened here, is that we first applied two identical transactions, so the second one was rejected.
@ -288,7 +430,7 @@ the same two transactions: this time, both failed due to too low nonce.
In order to meaningfully chain invocations, one would need to provide meaningful new `env`, otherwise the In order to meaningfully chain invocations, one would need to provide meaningful new `env`, otherwise the
actual blocknumber (exposed to the EVM) would not increase. actual blocknumber (exposed to the EVM) would not increase.
### Transactions in RLP form #### Transactions in RLP form
It is possible to provide already-signed transactions as input to, using an `input.txs` which ends with the `rlp` suffix. It is possible to provide already-signed transactions as input to, using an `input.txs` which ends with the `rlp` suffix.
The input format for RLP-form transactions is _identical_ to the _output_ format for block bodies. Therefore, it's fully possible The input format for RLP-form transactions is _identical_ to the _output_ format for block bodies. Therefore, it's fully possible
@ -297,12 +439,11 @@ to use the evm to go from `json` input to `rlp` input.
The following command takes **json** the transactions in `./testdata/13/txs.json` and signs them. After execution, they are output to `signed_txs.rlp`.: The following command takes **json** the transactions in `./testdata/13/txs.json` and signs them. After execution, they are output to `signed_txs.rlp`.:
``` ```
./evm t8n --state.fork=London --input.alloc=./testdata/13/alloc.json --input.txs=./testdata/13/txs.json --input.env=./testdata/13/env.json --output.result=alloc_jsontx.json --output.body=signed_txs.rlp ./evm t8n --state.fork=London --input.alloc=./testdata/13/alloc.json --input.txs=./testdata/13/txs.json --input.env=./testdata/13/env.json --output.result=alloc_jsontx.json --output.body=signed_txs.rlp
INFO [07-27|11:53:41.124] Trie dumping started root=e4b924..6aef61 INFO [12-27|09:25:11.102] Trie dumping started root=e4b924..6aef61
INFO [07-27|11:53:41.124] Trie dumping complete accounts=3 elapsed="94.284µs" INFO [12-27|09:25:11.102] Trie dumping complete accounts=3 elapsed="275.66µs"
INFO [07-27|11:53:41.125] Wrote file file=alloc.json INFO [12-27|09:25:11.102] Wrote file file=alloc.json
INFO [07-27|11:53:41.125] Wrote file file=alloc_jsontx.json INFO [12-27|09:25:11.103] Wrote file file=alloc_jsontx.json
INFO [07-27|11:53:41.125] Wrote file file=signed_txs.rlp INFO [12-27|09:25:11.103] Wrote file file=signed_txs.rlp
``` ```
The `output.body` is the rlp-list of transactions, encoded in hex and placed in a string a'la `json` encoding rules: The `output.body` is the rlp-list of transactions, encoded in hex and placed in a string a'la `json` encoding rules:
@ -322,13 +463,11 @@ rlpdump -hex $(cat signed_txs.rlp | jq -r )
Now, we can now use those (or any other already signed transactions), as input, like so: Now, we can now use those (or any other already signed transactions), as input, like so:
``` ```
./evm t8n --state.fork=London --input.alloc=./testdata/13/alloc.json --input.txs=./signed_txs.rlp --input.env=./testdata/13/env.json --output.result=alloc_rlptx.json ./evm t8n --state.fork=London --input.alloc=./testdata/13/alloc.json --input.txs=./signed_txs.rlp --input.env=./testdata/13/env.json --output.result=alloc_rlptx.json
INFO [07-27|11:53:41.253] Trie dumping started root=e4b924..6aef61 INFO [12-27|09:25:11.187] Trie dumping started root=e4b924..6aef61
INFO [07-27|11:53:41.253] Trie dumping complete accounts=3 elapsed="128.445µs" INFO [12-27|09:25:11.187] Trie dumping complete accounts=3 elapsed="123.676µs"
INFO [07-27|11:53:41.253] Wrote file file=alloc.json INFO [12-27|09:25:11.187] Wrote file file=alloc.json
INFO [07-27|11:53:41.255] Wrote file file=alloc_rlptx.json INFO [12-27|09:25:11.187] Wrote file file=alloc_rlptx.json
``` ```
You might have noticed that the results from these two invocations were stored in two separate files. You might have noticed that the results from these two invocations were stored in two separate files.
And we can now finally check that they match. And we can now finally check that they match.
``` ```
@ -336,3 +475,152 @@ cat alloc_jsontx.json | jq .stateRoot && cat alloc_rlptx.json | jq .stateRoot
"0xe4b924a6adb5959fccf769d5b7bb2f6359e26d1e76a2443c5a91a36d826aef61" "0xe4b924a6adb5959fccf769d5b7bb2f6359e26d1e76a2443c5a91a36d826aef61"
"0xe4b924a6adb5959fccf769d5b7bb2f6359e26d1e76a2443c5a91a36d826aef61" "0xe4b924a6adb5959fccf769d5b7bb2f6359e26d1e76a2443c5a91a36d826aef61"
``` ```
## Transaction tool
The transaction tool is used to perform static validity checks on transactions such as:
* intrinsic gas calculation
* max values on integers
* fee semantics, such as `maxFeePerGas < maxPriorityFeePerGas`
* newer tx types on old forks
### Examples
```
./evm t9n --state.fork Homestead --input.txs testdata/15/signed_txs.rlp
[
{
"error": "transaction type not supported",
"hash": "0xa98a24882ea90916c6a86da650fbc6b14238e46f0af04a131ce92be897507476"
},
{
"error": "transaction type not supported",
"hash": "0x36bad80acce7040c45fd32764b5c2b2d2e6f778669fb41791f73f546d56e739a"
}
]
```
```
./evm t9n --state.fork London --input.txs testdata/15/signed_txs.rlp
[
{
"address": "0xd02d72e067e77158444ef2020ff2d325f929b363",
"hash": "0xa98a24882ea90916c6a86da650fbc6b14238e46f0af04a131ce92be897507476",
"intrinsicGas": "0x5208"
},
{
"address": "0xd02d72e067e77158444ef2020ff2d325f929b363",
"hash": "0x36bad80acce7040c45fd32764b5c2b2d2e6f778669fb41791f73f546d56e739a",
"intrinsicGas": "0x5208"
}
]
```
## Block builder tool (b11r)
The `evm b11r` tool is used to assemble and seal full block rlps.
### Specification
#### Command line params
Command line params that need to be supported are:
```
--input.header value `stdin` or file name of where to find the block header to use. (default: "header.json")
--input.ommers value `stdin` or file name of where to find the list of ommer header RLPs to use.
--input.txs value `stdin` or file name of where to find the transactions list in RLP form. (default: "txs.rlp")
--output.basedir value Specifies where output files are placed. Will be created if it does not exist.
--output.block value Determines where to put the alloc of the post-state. (default: "block.json")
<file> - into the file <file>
`stdout` - into the stdout output
`stderr` - into the stderr output
--seal.clique value Seal block with Clique. `stdin` or file name of where to find the Clique sealing data.
--seal.ethash Seal block with ethash. (default: false)
--seal.ethash.dir value Path to ethash DAG. If none exists, a new DAG will be generated.
--seal.ethash.mode value Defines the type and amount of PoW verification an ethash engine makes. (default: "normal")
--verbosity value Sets the verbosity level. (default: 3)
```
#### Objects
##### `header`
The `header` object is a consensus header.
```go=
type Header struct {
ParentHash common.Hash `json:"parentHash"`
OmmerHash *common.Hash `json:"sha3Uncles"`
Coinbase *common.Address `json:"miner"`
Root common.Hash `json:"stateRoot" gencodec:"required"`
TxHash *common.Hash `json:"transactionsRoot"`
ReceiptHash *common.Hash `json:"receiptsRoot"`
Bloom types.Bloom `json:"logsBloom"`
Difficulty *big.Int `json:"difficulty"`
Number *big.Int `json:"number" gencodec:"required"`
GasLimit uint64 `json:"gasLimit" gencodec:"required"`
GasUsed uint64 `json:"gasUsed"`
Time uint64 `json:"timestamp" gencodec:"required"`
Extra []byte `json:"extraData"`
MixDigest common.Hash `json:"mixHash"`
Nonce *types.BlockNonce `json:"nonce"`
BaseFee *big.Int `json:"baseFeePerGas"`
}
```
#### `ommers`
The `ommers` object is a list of RLP-encoded ommer blocks in hex
representation.
```go=
type Ommers []string
```
#### `txs`
The `txs` object is a list of RLP-encoded transactions in hex representation.
```go=
type Txs []string
```
#### `clique`
The `clique` object provides the necessary information to complete a clique
seal of the block.
```go=
var CliqueInfo struct {
Key *common.Hash `json:"secretKey"`
Voted *common.Address `json:"voted"`
Authorize *bool `json:"authorize"`
Vanity common.Hash `json:"vanity"`
}
```
#### `output`
The `output` object contains two values, the block RLP and the block hash.
```go=
type BlockInfo struct {
Rlp []byte `json:"rlp"`
Hash common.Hash `json:"hash"`
}
```
## A Note on Encoding
The encoding of values for `evm` utility attempts to be relatively flexible. It
generally supports hex-encoded or decimal-encoded numeric values, and
hex-encoded byte values (like `common.Address`, `common.Hash`, etc). When in
doubt, the [`execution-apis`](https://github.com/ethereum/execution-apis) way
of encoding should always be accepted.
## Testing
There are many test cases in the [`cmd/evm/testdata`](./testdata) directory.
These fixtures are used to power the `t8n` tests in
[`t8n_test.go`](./t8n_test.go). The best way to verify correctness of new `evm`
implementations is to execute these and verify the output and error codes match
the expected values.

61
cmd/evm/blockrunner.go Normal file
View File

@ -0,0 +1,61 @@
// Copyright 2023 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/tests"
"github.com/urfave/cli/v2"
)
var blockTestCommand = &cli.Command{
Action: blockTestCmd,
Name: "blocktest",
Usage: "executes the given blockchain tests",
ArgsUsage: "<file>",
}
func blockTestCmd(ctx *cli.Context) error {
if len(ctx.Args().First()) == 0 {
return errors.New("path-to-test argument required")
}
// Configure the go-ethereum logger
glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
glogger.Verbosity(log.Lvl(ctx.Int(VerbosityFlag.Name)))
log.Root().SetHandler(glogger)
// Load the test content from the input file
src, err := os.ReadFile(ctx.Args().First())
if err != nil {
return err
}
var tests map[string]tests.BlockTest
if err = json.Unmarshal(src, &tests); err != nil {
return err
}
for i, test := range tests {
if err := test.Run(false); err != nil {
return fmt.Errorf("test %v: %w", i, err)
}
}
return nil
}

View File

@ -38,22 +38,23 @@ import (
//go:generate go run github.com/fjl/gencodec -type header -field-override headerMarshaling -out gen_header.go //go:generate go run github.com/fjl/gencodec -type header -field-override headerMarshaling -out gen_header.go
type header struct { type header struct {
ParentHash common.Hash `json:"parentHash"` ParentHash common.Hash `json:"parentHash"`
OmmerHash *common.Hash `json:"sha3Uncles"` OmmerHash *common.Hash `json:"sha3Uncles"`
Coinbase *common.Address `json:"miner"` Coinbase *common.Address `json:"miner"`
Root common.Hash `json:"stateRoot" gencodec:"required"` Root common.Hash `json:"stateRoot" gencodec:"required"`
TxHash *common.Hash `json:"transactionsRoot"` TxHash *common.Hash `json:"transactionsRoot"`
ReceiptHash *common.Hash `json:"receiptsRoot"` ReceiptHash *common.Hash `json:"receiptsRoot"`
Bloom types.Bloom `json:"logsBloom"` Bloom types.Bloom `json:"logsBloom"`
Difficulty *big.Int `json:"difficulty"` Difficulty *big.Int `json:"difficulty"`
Number *big.Int `json:"number" gencodec:"required"` Number *big.Int `json:"number" gencodec:"required"`
GasLimit uint64 `json:"gasLimit" gencodec:"required"` GasLimit uint64 `json:"gasLimit" gencodec:"required"`
GasUsed uint64 `json:"gasUsed"` GasUsed uint64 `json:"gasUsed"`
Time uint64 `json:"timestamp" gencodec:"required"` Time uint64 `json:"timestamp" gencodec:"required"`
Extra []byte `json:"extraData"` Extra []byte `json:"extraData"`
MixDigest common.Hash `json:"mixHash"` MixDigest common.Hash `json:"mixHash"`
Nonce *types.BlockNonce `json:"nonce"` Nonce *types.BlockNonce `json:"nonce"`
BaseFee *big.Int `json:"baseFeePerGas" rlp:"optional"` BaseFee *big.Int `json:"baseFeePerGas" rlp:"optional"`
WithdrawalsHash *common.Hash `json:"withdrawalsRoot" rlp:"optional"`
} }
type headerMarshaling struct { type headerMarshaling struct {
@ -67,10 +68,11 @@ type headerMarshaling struct {
} }
type bbInput struct { type bbInput struct {
Header *header `json:"header,omitempty"` Header *header `json:"header,omitempty"`
OmmersRlp []string `json:"ommers,omitempty"` OmmersRlp []string `json:"ommers,omitempty"`
TxRlp string `json:"txs,omitempty"` TxRlp string `json:"txs,omitempty"`
Clique *cliqueInput `json:"clique,omitempty"` Withdrawals []*types.Withdrawal `json:"withdrawals,omitempty"`
Clique *cliqueInput `json:"clique,omitempty"`
Ethash bool `json:"-"` Ethash bool `json:"-"`
EthashDir string `json:"-"` EthashDir string `json:"-"`
@ -114,21 +116,22 @@ func (c *cliqueInput) UnmarshalJSON(input []byte) error {
// ToBlock converts i into a *types.Block // ToBlock converts i into a *types.Block
func (i *bbInput) ToBlock() *types.Block { func (i *bbInput) ToBlock() *types.Block {
header := &types.Header{ header := &types.Header{
ParentHash: i.Header.ParentHash, ParentHash: i.Header.ParentHash,
UncleHash: types.EmptyUncleHash, UncleHash: types.EmptyUncleHash,
Coinbase: common.Address{}, Coinbase: common.Address{},
Root: i.Header.Root, Root: i.Header.Root,
TxHash: types.EmptyRootHash, TxHash: types.EmptyTxsHash,
ReceiptHash: types.EmptyRootHash, ReceiptHash: types.EmptyReceiptsHash,
Bloom: i.Header.Bloom, Bloom: i.Header.Bloom,
Difficulty: common.Big0, Difficulty: common.Big0,
Number: i.Header.Number, Number: i.Header.Number,
GasLimit: i.Header.GasLimit, GasLimit: i.Header.GasLimit,
GasUsed: i.Header.GasUsed, GasUsed: i.Header.GasUsed,
Time: i.Header.Time, Time: i.Header.Time,
Extra: i.Header.Extra, Extra: i.Header.Extra,
MixDigest: i.Header.MixDigest, MixDigest: i.Header.MixDigest,
BaseFee: i.Header.BaseFee, BaseFee: i.Header.BaseFee,
WithdrawalsHash: i.Header.WithdrawalsHash,
} }
// Fill optional values. // Fill optional values.
@ -153,7 +156,7 @@ func (i *bbInput) ToBlock() *types.Block {
if header.Difficulty != nil { if header.Difficulty != nil {
header.Difficulty = i.Header.Difficulty header.Difficulty = i.Header.Difficulty
} }
return types.NewBlockWithHeader(header).WithBody(i.Txs, i.Ommers) return types.NewBlockWithHeader(header).WithBody(i.Txs, i.Ommers).WithWithdrawals(i.Withdrawals)
} }
// SealBlock seals the given block using the configured engine. // SealBlock seals the given block using the configured engine.
@ -259,14 +262,15 @@ func BuildBlock(ctx *cli.Context) error {
func readInput(ctx *cli.Context) (*bbInput, error) { func readInput(ctx *cli.Context) (*bbInput, error) {
var ( var (
headerStr = ctx.String(InputHeaderFlag.Name) headerStr = ctx.String(InputHeaderFlag.Name)
ommersStr = ctx.String(InputOmmersFlag.Name) ommersStr = ctx.String(InputOmmersFlag.Name)
txsStr = ctx.String(InputTxsRlpFlag.Name) withdrawalsStr = ctx.String(InputWithdrawalsFlag.Name)
cliqueStr = ctx.String(SealCliqueFlag.Name) txsStr = ctx.String(InputTxsRlpFlag.Name)
ethashOn = ctx.Bool(SealEthashFlag.Name) cliqueStr = ctx.String(SealCliqueFlag.Name)
ethashDir = ctx.String(SealEthashDirFlag.Name) ethashOn = ctx.Bool(SealEthashFlag.Name)
ethashMode = ctx.String(SealEthashModeFlag.Name) ethashDir = ctx.String(SealEthashDirFlag.Name)
inputData = &bbInput{} ethashMode = ctx.String(SealEthashModeFlag.Name)
inputData = &bbInput{}
) )
if ethashOn && cliqueStr != "" { if ethashOn && cliqueStr != "" {
return nil, NewError(ErrorConfig, fmt.Errorf("both ethash and clique sealing specified, only one may be chosen")) return nil, NewError(ErrorConfig, fmt.Errorf("both ethash and clique sealing specified, only one may be chosen"))
@ -312,6 +316,13 @@ func readInput(ctx *cli.Context) (*bbInput, error) {
} }
inputData.OmmersRlp = ommers inputData.OmmersRlp = ommers
} }
if withdrawalsStr != stdinSelector && withdrawalsStr != "" {
var withdrawals []*types.Withdrawal
if err := readFile(withdrawalsStr, "withdrawals", &withdrawals); err != nil {
return nil, err
}
inputData.Withdrawals = withdrawals
}
if txsStr != stdinSelector { if txsStr != stdinSelector {
var txs string var txs string
if err := readFile(txsStr, "txs", &txs); err != nil { if err := readFile(txsStr, "txs", &txs); err != nil {
@ -351,15 +362,14 @@ func readInput(ctx *cli.Context) (*bbInput, error) {
// files // files
func dispatchBlock(ctx *cli.Context, baseDir string, block *types.Block) error { func dispatchBlock(ctx *cli.Context, baseDir string, block *types.Block) error {
raw, _ := rlp.EncodeToBytes(block) raw, _ := rlp.EncodeToBytes(block)
type blockInfo struct { type blockInfo struct {
Rlp hexutil.Bytes `json:"rlp"` Rlp hexutil.Bytes `json:"rlp"`
Hash common.Hash `json:"hash"` Hash common.Hash `json:"hash"`
} }
var enc blockInfo enc := blockInfo{
enc.Rlp = raw Rlp: raw,
enc.Hash = block.Hash() Hash: block.Hash(),
}
b, err := json.MarshalIndent(enc, "", " ") b, err := json.MarshalIndent(enc, "", " ")
if err != nil { if err != nil {
return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err)) return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err))

Some files were not shown because too many files have changed in this diff Show More