mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-08-01 09:33:46 +00:00
* ethdb/pebble: fix nil callbacks (#26650) * eth/downloader: fix timeout resurrection panic (#26652) * common/prque, eth/downloader: fix timeout resurrection panic * common/prque: revert -1 hack for les, temporaryly! * core/state, trie: remove unused error-return from trie Commit operation (#26641) * go.mod: update pebble to latest master (#26654) * 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> * ethdb: add benchmark test suite (#26659) * params: schedule shanghai fork on sepolia (#26662) * params: schedule shanghai fork on sepolia * params: u64 -> newUint64 * 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. * 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. * tests/fuzzers: supply gnark multiexp config, fixes #26669 (#26670) This change fixes a fuzzer which broke when we updated the gnark dependency earlier. * 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. * params: update mainnet + rinkeby CHT (#26677) This change updates the CHT entries for mainnet and rinkeby * 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> * p2p/dnsdisc: fix tests with Go 1.20 (#26690) * 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 * 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). * 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. * params: go-ethereum v1.11.0 stable * params: begin v1.11.1 release cycle * travis, build: update Go to 1.20.1 (#26653) travis, build: update Go to 1.20 * core: check genesis state presence by disk read (#26703) * core, eth/downloader: make body validation more strict (#26704) * eth/downloader: fix empty-body case in queue fetchresult (#26707) * eth/downloader: fix typo (#26716) * 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. * params: go-ethereum v1.11.1 stable * params: begin v1.11.2 release cycle * 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 * ci: disable coverage reporting in appveyor and travis * 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> * 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> * 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> * build: ship bootstrapper Go along with builder for PPA (#26731) * build: fix setting env var, temp early exit * build: fix gobootstrap path for the PPA * build: add some PPA debug logs, sigh * internal/build: revert raising the chunk size for PPA * build: yet another weird PPA fix * build: fix (finaly?) the PPA env vars for Go bootstrapping * build: fix Go 1.19.0 bootstrapper issues on 386 PPA * build: enable Lunar Lobster PPA builds * Revert "core/trie: remove trie tracer (#26665)" (#26732) This reverts commit7c749c947a. * cmd/geth: clarify dumpconfig options (#26729) Clarifies the documentation around dumpconfi Signed-off-by: Sungwoo Kim <git@sung-woo.kim> * core, eth: merge snap-sync chain download progress logs (#26676) * core: fix accessor mismatch for genesis state (#26747) * core/rawdb: expose chain freezer constructor without internals (#26748) * 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 * 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> * common/math: allow HexOrDecimal to accept unquoted decimals too (#26758) * params: release Geth v1.11.2 * params: begin v.1.11.3 release cycle * log: improve documentation (#26753) Add usage examples * core/rawdb, node: use standalone flock dependency (#26633) * eth: use the last announced finalized block as the sync ancient limit (#26685) * 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. * 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> * 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> * ethdb/pebble: fix range compaction (#26771) * ethdb/pebble: fix range compaction * ethdb/pebble: add comment * ethdb/pebble: fix max memorytable size (#26776) * ethclient: include withdrawals in ethclient block responses (#26778) * include withdrawals in ethclient responses * omit empty withdrawals array in json serialization * all: change chain head markers from block to header (#26777) * core/rawdb, ethdb/pebble: disable pebble on openbsd (#26801) * core: fix a merge fault (#26802) * README, go.mod, event, internal/version: bump min Go to 1.19 (#26803) * travi: remove strange leftover Go version * core, params: schedule Shanghai on goerli (#26795) * core: params: schedule Shanghai on goerli * core/forkid: fix comment * eth: remove admin.peers[i].eth.head and difficulty (#26804) * 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> * 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. * 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> * ethclient: fix panic when requesting missing blocks (#26817) This fixes a regression introduced by #26723. Fixes #26816. * 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 * 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> * cmd/evm: correct `alloc` for `t8n` testdata (#26822) Fixes a minor error in the testdata * eth/tracers/native: set created address to nil in case of failure (#26779) Fixes #26073 * 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. * 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> * build: update to go 1.20.2 (#26824) * params: go-ethereum v1.11.3 stable * params: begin v1.11.4 release cycle * 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> * 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> * params: remove EF azure bootnodes (#26828) * core/vm: use golang native big.Int (#26834) reverts #26021, to use the upstream bigint instead. * core/vm: fix typo in comment (#26838) fixes eip 220 -> 2200 * 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. * cmd/evm: update readmes for the tests (#26841) * 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 commitdb494170dc, 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> * travis: only build PPAs nightly, not on every push, too heavy (#26846) * p2p: small comment typo (#26850) Update server.go * 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. * 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> * params: go-ethereum v1.11.4 stable * params: begin v1.11.5 release cycle * tests: define `MuirGlacier` fork (#26856) add muir glacier to t8n * code/vm: fix comment typo (#26865) it should be constantinople rather than contantinople * core: minor code refactor (#26852) * core: refactor code * core: drop it from this anonymous goroutine func * core/txpool: use priceList.Put instead of heap.Push (#26863) Minor refactor to use the 'intended' accessor * 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> * .travis.yml: reenable PPA build on tag push (#26873) * core/state, trie: port changes from PBSS (#26763) * 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. * all: update links in documentation (#26882) Co-authored-by: Stephen Flynn <stephen.flynn@gapac.com> * 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 * 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. * 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. * 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. * eth/catalyst: increase update consensus timeout (#26840) Increases the time between consensus updates that we give the CL before we start warning the user. * internal/ethapi: avoid int overflow in GetTransactionReceipt (#26911) * trie, accounts/abi: add error-checks (#26914) * 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> * 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> * trie: reduce unit test time (#26918) * core/txpool: use atomic int added in go1.19 (#26913) Makes use of atomic.Uint64 instead of atomic by pointer * 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 * core/txpool: allow future local transactions (#26930) Local transactions should not be subject to the "future shouldn't churn pending txs" rule * params: go-ethereum v1.11.5 stable * params: begin v1.11.6 release cycle * build: allow building nightly archives via cron jobs (#26938) * log: add special casing of uint256 into the logger (#26936) * core/rawdb: use atomic int added in go1.19 (#26935) * 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. * eth/catalyst: fix races (#26950) * 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> * 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. * 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. * 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. * 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. * eth/gasprice: change feehistory input type from int to uint64 (#26922) Change input param type from int to uint64 * go.mod: update golang.org/x/tools (#26960) * rlp/rlpgen: print want/expect output string if mismatch (#26932) Co-authored-by: Marius van der Wijden <m.vanderwijden@live.de> * ethclient: ensure returned subscription is nil on error (#26976) * 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> * 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) * 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> * core/bloombits: use atomic type (#26993) * core/state: use atomic.Bool (#26992) * 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. * 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> * internal/debug: add log.logfmt flag to set logging to use logfmt (#26970) * docs: update outdated DeriveSha docs comment (#26968) * remove @gballet as a GraphQL codeowner (#27012) * core: use atomic type (#27011) * graphql: revert storage access regression (#27007) * 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> * ethdb/pebble: use atomic type (#27014) * common: fix json marshaller MixedcaseAddress (#26998) Fix the json marshaller of MixedcaseAddress * 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”> * miner: use atomic type (#27013) Use the new typed atomics in the miner package * 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> * 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 * go.mod : update snappy (#27027) * common: delete MakeName (#27023) common,p2p: remove unused function MakeName * 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> * 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 * test/fuzzers: fuzz rlp handling of big.Int and uint256.Int (#26917) test/fuzzers: fuzz rlp handling of big.Lnt and uint256.Int * 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. * 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> * core/vm: clarify comment (#27045) * consensus, core/typer: add 4844 excessDataGas to header, tie it to Cancun (#27046) * 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> * 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> * 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> * 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> * 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> * build: upgrade -dlgo version to Go 1.20.3 * 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. * 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. * params: new sepolia bootnodes (#27099) New sepolia bootnodes managed by EF devops * cmd/devp2p: fix erroneous log output in crawler (#27089) cmd/devp2p: fix log of ignored recent nodes counter * signer/core: rename testdata files (#27063) Sets a meaningful name on test-files * core: fix comment to reflect function name (#27070) * 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> * p2p: access embedded fields of Server directly (#27078) * consensus/ethash: use atomic type (#27068) * 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. * cmd/geth: rename --vmodule to --log.vmodule (#27071) renames `--vmodule` to `--log.vmodule`, and prints a warning if the old form is used. * core/vm: order opcodes properly (#27113) * metrics: use atomic type (#27121) * 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. * params: go-ethereum v1.11.6 stable * dev: chg: regression changes for bor after merge * dev: chg: more regression changes for bor after merge * dev: chg: txpool_test regression changes after merge * dev: chg: gomock re-generate mocks for backend interface * dev: chg: regression changes after develop is merged into upstream-merge * dev: chg: further fixes merging develop into upstream-merge * dev: chg: apply changes to NewParallelBlockChain * dev: chg: solve some TODOs * dev: fix: CreateConsensusEngine for new ethereum objects * dev: fix: NewParallelBlockChain using Genesis * dev: fix: build ci.go * dev: fix: thelper and tparallel lint * dev: fix: http related and nilnil lint errors * dev: fix: ineffassign lint errors * dev: chg: comment position fix * dev: fix: govet lint errors * dev: fix: error related lint issues * dev: fix: bodyclose lint issues * dev: fix: some wsl lint issues * dev: fix: more wsl lint issues * dev: fix: errorcheck lint issues * dev: fix: solve more lint issues * dev: fix: more wsl lint issues * dev: fix: more errcheck lint issues * dev: fix: most of wsl lint issues * dev: fix: all remaining lint issues * dev: fix: t.Parallel called multiple times * dev: fix: tests failing due to t.Parallel * fix : runtime testcases * fix : testcase : config, addTxWithChain, burnAmount * fix : ethhash bor burn contract * fix : genspec config * fix : freezer, TestStateProcessorErrors * core,eth,miner: fix initial test cases (#922) * fix : TestTransactionIndices, testBeaconSync * fix : TestBeaconSync66 * core,eth: fix TestDeduplication, TestSyncAccountPerformance, TestTraceTransaction * fix : TestTxIndexer * rm : multiple coinbase balance * fix : testCommitInterruptExperimentBor * adding balance send to burntcontract back * Fix header encoding test * core,eth/tracers: fix TestPrestateWithDiffModeTracer * consensus/bor,eth/filters,miner,params,tests: fix mocks * fix : TestGraphQLConcurrentResolvers * fix : TestBuildPayload * common,core,miner: fix goleaks,duplicate init and inconsistent mutex (un)locks * fix : lint * fix : lint * fix : test-integration * fix : test-integration * core: restore AddFeeTransferLog post miner tipping * fix : TestGraphQLConcurrentResolvers * fix : deadlocks * rm: t.parallel from testQueueTimeLimiting tests * Merge branch 'develop' into mardizzone/upstream-merge * fix : lint * fix : test-integration * fix : TxDependency * add rpc.enabledeprecatedpersonal flag --------- Signed-off-by: Sungwoo Kim <git@sung-woo.kim> Signed-off-by: jsvisa <delweng@gmail.com> Co-authored-by: Péter Szilágyi <peterke@gmail.com> Co-authored-by: Martin Holst Swende <martin@swende.se> Co-authored-by: Chris Ziogas <ziogaschr@gmail.com> Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com> Co-authored-by: rjl493456442 <garyrong0905@gmail.com> Co-authored-by: Marius van der Wijden <m.vanderwijden@live.de> Co-authored-by: Sina Mahmoodi <1591639+s1na@users.noreply.github.com> Co-authored-by: Darioush Jalali <darioush.jalali@avalabs.org> Co-authored-by: Felix Lange <fjl@twurst.com> Co-authored-by: Patrick O'Grady <prohb125@gmail.com> Co-authored-by: ucwong <ucwong@126.com> Co-authored-by: Roman Krasiuk <rokrassyuk@gmail.com> Co-authored-by: Jason Yuan <jason.yuan@curvegrid.com> Co-authored-by: Jason Yuan <jason.yuan869@gmail.com> Co-authored-by: Sungwoo Kim <git@sung-woo.kim> Co-authored-by: Yier <90763233+yierx@users.noreply.github.com> Co-authored-by: Catror <me@catror.com> Co-authored-by: Nate Armstrong <naterarmstrong@gmail.com> Co-authored-by: Dan Cline <6798349+Rjected@users.noreply.github.com> Co-authored-by: Peter (bitfly) <1674920+peterbitfly@users.noreply.github.com> Co-authored-by: PulsarAI <dev@pulsar-systems.fi> Co-authored-by: turboboost55 <7891737+turboboost55@users.noreply.github.com> Co-authored-by: Adrian Sutton <adrian@symphonious.net> Co-authored-by: Guruprasad Kamath <48196632+gurukamath@users.noreply.github.com> Co-authored-by: James Prestwich <10149425+prestwich@users.noreply.github.com> Co-authored-by: Daniel Fernandes <711733+daferna@users.noreply.github.com> Co-authored-by: Rafael Matias <rafael@skyle.net> Co-authored-by: xiyang <90125263+JBossBC@users.noreply.github.com> Co-authored-by: Roberto Bayardo <bayardo@alum.mit.edu> Co-authored-by: panicalways <113693386+panicalways@users.noreply.github.com> Co-authored-by: dwn1998 <42262393+dwn1998@users.noreply.github.com> Co-authored-by: s7v7nislands <s7v7nislands@gmail.com> Co-authored-by: lightclient <14004106+lightclient@users.noreply.github.com> Co-authored-by: Stephen Flynn <ssflynn@gmail.com> Co-authored-by: Stephen Flynn <stephen.flynn@gapac.com> Co-authored-by: Jonathan Otto <jonathan.otto@gmail.com> Co-authored-by: Delweng <delweng@gmail.com> Co-authored-by: Guillaume Ballet <3272758+gballet@users.noreply.github.com> Co-authored-by: aaronbuchwald <aaron.buchwald56@gmail.com> Co-authored-by: ucwong <ethereum2k@gmail.com> Co-authored-by: norwnd <112318969+norwnd@users.noreply.github.com> Co-authored-by: jwasinger <j-wasinger@hotmail.com> Co-authored-by: Adrian Sutton <adrian@oplabs.co> Co-authored-by: David Murdoch <187813+davidmurdoch@users.noreply.github.com> Co-authored-by: openex <openexkevin@gmail.com> Co-authored-by: “openex27” <“openexkevin@gmail.com”> Co-authored-by: sudeep <sudeepdino008@gmail.com> Co-authored-by: joohhnnn <68833933+joohhnnn@users.noreply.github.com> Co-authored-by: 0xTylerHolmes <tyler@ethereum.org> Co-authored-by: Exca-DK <85954505+Exca-DK@users.noreply.github.com> Co-authored-by: Exca-DK <dev@DESKTOP-RI45P4J.localdomain> Co-authored-by: Marius Kjærstad <mkjaerstad@protonmail.com> Co-authored-by: Parithosh Jayanthi <parithosh@indenwolken.xyz> Co-authored-by: noel <72006780+0x00Duke@users.noreply.github.com> Co-authored-by: Taeguk Kwon <xornrbboy@gmail.com> Co-authored-by: Anusha <63559942+anusha-ctrl@users.noreply.github.com> Co-authored-by: Alex Beregszaszi <alex@rtfs.hu> Co-authored-by: Shivam Sharma <shivam691999@gmail.com> Co-authored-by: Raneet Debnath <35629432+Raneet10@users.noreply.github.com> Co-authored-by: Raneet Debnath <raneetdebnath10@gmail.com> Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Manav Darji <manavdarji.india@gmail.com>
1990 lines
54 KiB
Go
1990 lines
54 KiB
Go
// Copyright 2021 The go-ethereum Authors
|
|
// This file is part of the go-ethereum library.
|
|
//
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
|
// it under the terms of the GNU Lesser General Public License as published by
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
// (at your option) any later version.
|
|
//
|
|
// The go-ethereum library 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 Lesser General Public License for more details.
|
|
//
|
|
// 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/>.
|
|
|
|
package snap
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/rand"
|
|
"encoding/binary"
|
|
"fmt"
|
|
"math/big"
|
|
"sort"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/ethereum/go-ethereum/common"
|
|
"github.com/ethereum/go-ethereum/core/rawdb"
|
|
"github.com/ethereum/go-ethereum/core/types"
|
|
"github.com/ethereum/go-ethereum/crypto"
|
|
"github.com/ethereum/go-ethereum/ethdb"
|
|
"github.com/ethereum/go-ethereum/light"
|
|
"github.com/ethereum/go-ethereum/log"
|
|
"github.com/ethereum/go-ethereum/rlp"
|
|
"github.com/ethereum/go-ethereum/trie"
|
|
"golang.org/x/crypto/sha3"
|
|
)
|
|
|
|
func TestHashing(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var bytecodes = make([][]byte, 10)
|
|
for i := 0; i < len(bytecodes); i++ {
|
|
buf := make([]byte, 100)
|
|
rand.Read(buf)
|
|
bytecodes[i] = buf
|
|
}
|
|
|
|
var want, got string
|
|
|
|
var old = func() {
|
|
hasher := sha3.NewLegacyKeccak256()
|
|
for i := 0; i < len(bytecodes); i++ {
|
|
hasher.Reset()
|
|
hasher.Write(bytecodes[i])
|
|
hash := hasher.Sum(nil)
|
|
got = fmt.Sprintf("%v\n%v", got, hash)
|
|
}
|
|
}
|
|
|
|
var new = func() {
|
|
hasher := sha3.NewLegacyKeccak256().(crypto.KeccakState)
|
|
var hash = make([]byte, 32)
|
|
for i := 0; i < len(bytecodes); i++ {
|
|
hasher.Reset()
|
|
hasher.Write(bytecodes[i])
|
|
hasher.Read(hash)
|
|
want = fmt.Sprintf("%v\n%v", want, hash)
|
|
}
|
|
}
|
|
|
|
old()
|
|
new()
|
|
|
|
if want != got {
|
|
t.Errorf("want\n%v\ngot\n%v\n", want, got)
|
|
}
|
|
}
|
|
|
|
func BenchmarkHashing(b *testing.B) {
|
|
var bytecodes = make([][]byte, 10000)
|
|
for i := 0; i < len(bytecodes); i++ {
|
|
buf := make([]byte, 100)
|
|
rand.Read(buf)
|
|
bytecodes[i] = buf
|
|
}
|
|
|
|
var old = func() {
|
|
hasher := sha3.NewLegacyKeccak256()
|
|
for i := 0; i < len(bytecodes); i++ {
|
|
hasher.Reset()
|
|
hasher.Write(bytecodes[i])
|
|
hasher.Sum(nil)
|
|
}
|
|
}
|
|
|
|
var new = func() {
|
|
hasher := sha3.NewLegacyKeccak256().(crypto.KeccakState)
|
|
var hash = make([]byte, 32)
|
|
for i := 0; i < len(bytecodes); i++ {
|
|
hasher.Reset()
|
|
hasher.Write(bytecodes[i])
|
|
hasher.Read(hash)
|
|
}
|
|
}
|
|
|
|
b.Run("old", func(b *testing.B) {
|
|
b.ReportAllocs()
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
old()
|
|
}
|
|
})
|
|
b.Run("new", func(b *testing.B) {
|
|
b.ReportAllocs()
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
new()
|
|
}
|
|
})
|
|
}
|
|
|
|
type (
|
|
accountHandlerFunc func(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error
|
|
storageHandlerFunc func(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error
|
|
trieHandlerFunc func(t *testPeer, requestId uint64, root common.Hash, paths []TrieNodePathSet, cap uint64) error
|
|
codeHandlerFunc func(t *testPeer, id uint64, hashes []common.Hash, max uint64) error
|
|
)
|
|
|
|
type testPeer struct {
|
|
id string
|
|
test *testing.T
|
|
remote *Syncer
|
|
logger log.Logger
|
|
accountTrie *trie.Trie
|
|
accountValues entrySlice
|
|
storageTries map[common.Hash]*trie.Trie
|
|
storageValues map[common.Hash]entrySlice
|
|
|
|
accountRequestHandler accountHandlerFunc
|
|
storageRequestHandler storageHandlerFunc
|
|
trieRequestHandler trieHandlerFunc
|
|
codeRequestHandler codeHandlerFunc
|
|
term func()
|
|
|
|
// counters
|
|
nAccountRequests int
|
|
nStorageRequests int
|
|
nBytecodeRequests int
|
|
nTrienodeRequests int
|
|
}
|
|
|
|
func newTestPeer(id string, t *testing.T, term func()) *testPeer {
|
|
peer := &testPeer{
|
|
id: id,
|
|
test: t,
|
|
logger: log.New("id", id),
|
|
accountRequestHandler: defaultAccountRequestHandler,
|
|
trieRequestHandler: defaultTrieRequestHandler,
|
|
storageRequestHandler: defaultStorageRequestHandler,
|
|
codeRequestHandler: defaultCodeRequestHandler,
|
|
term: term,
|
|
}
|
|
//stderrHandler := log.StreamHandler(os.Stderr, log.TerminalFormat(true))
|
|
//peer.logger.SetHandler(stderrHandler)
|
|
return peer
|
|
}
|
|
|
|
func (t *testPeer) setStorageTries(tries map[common.Hash]*trie.Trie) {
|
|
t.storageTries = make(map[common.Hash]*trie.Trie)
|
|
for root, trie := range tries {
|
|
t.storageTries[root] = trie.Copy()
|
|
}
|
|
}
|
|
|
|
func (t *testPeer) ID() string { return t.id }
|
|
func (t *testPeer) Log() log.Logger { return t.logger }
|
|
|
|
func (t *testPeer) Stats() string {
|
|
return fmt.Sprintf(`Account requests: %d
|
|
Storage requests: %d
|
|
Bytecode requests: %d
|
|
Trienode requests: %d
|
|
`, t.nAccountRequests, t.nStorageRequests, t.nBytecodeRequests, t.nTrienodeRequests)
|
|
}
|
|
|
|
func (t *testPeer) RequestAccountRange(id uint64, root, origin, limit common.Hash, bytes uint64) error {
|
|
t.logger.Trace("Fetching range of accounts", "reqid", id, "root", root, "origin", origin, "limit", limit, "bytes", common.StorageSize(bytes))
|
|
|
|
t.nAccountRequests++
|
|
go t.accountRequestHandler(t, id, root, origin, limit, bytes)
|
|
|
|
return nil
|
|
}
|
|
|
|
func (t *testPeer) RequestTrieNodes(id uint64, root common.Hash, paths []TrieNodePathSet, bytes uint64) error {
|
|
t.logger.Trace("Fetching set of trie nodes", "reqid", id, "root", root, "pathsets", len(paths), "bytes", common.StorageSize(bytes))
|
|
|
|
t.nTrienodeRequests++
|
|
go t.trieRequestHandler(t, id, root, paths, bytes)
|
|
|
|
return nil
|
|
}
|
|
|
|
func (t *testPeer) RequestStorageRanges(id uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, bytes uint64) error {
|
|
t.nStorageRequests++
|
|
if len(accounts) == 1 && origin != nil {
|
|
t.logger.Trace("Fetching range of large storage slots", "reqid", id, "root", root, "account", accounts[0], "origin", common.BytesToHash(origin), "limit", common.BytesToHash(limit), "bytes", common.StorageSize(bytes))
|
|
} else {
|
|
t.logger.Trace("Fetching ranges of small storage slots", "reqid", id, "root", root, "accounts", len(accounts), "first", accounts[0], "bytes", common.StorageSize(bytes))
|
|
}
|
|
|
|
go t.storageRequestHandler(t, id, root, accounts, origin, limit, bytes)
|
|
|
|
return nil
|
|
}
|
|
|
|
func (t *testPeer) RequestByteCodes(id uint64, hashes []common.Hash, bytes uint64) error {
|
|
t.nBytecodeRequests++
|
|
t.logger.Trace("Fetching set of byte codes", "reqid", id, "hashes", len(hashes), "bytes", common.StorageSize(bytes))
|
|
|
|
go t.codeRequestHandler(t, id, hashes, bytes)
|
|
|
|
return nil
|
|
}
|
|
|
|
// defaultTrieRequestHandler is a well-behaving handler for trie healing requests
|
|
func defaultTrieRequestHandler(t *testPeer, requestId uint64, root common.Hash, paths []TrieNodePathSet, cap uint64) error {
|
|
// Pass the response
|
|
var nodes [][]byte
|
|
|
|
for _, pathset := range paths {
|
|
switch len(pathset) {
|
|
case 1:
|
|
blob, _, err := t.accountTrie.GetNode(pathset[0])
|
|
if err != nil {
|
|
t.logger.Info("Error handling req", "error", err)
|
|
break
|
|
}
|
|
|
|
nodes = append(nodes, blob)
|
|
default:
|
|
account := t.storageTries[(common.BytesToHash(pathset[0]))]
|
|
for _, path := range pathset[1:] {
|
|
blob, _, err := account.GetNode(path)
|
|
if err != nil {
|
|
t.logger.Info("Error handling req", "error", err)
|
|
break
|
|
}
|
|
|
|
nodes = append(nodes, blob)
|
|
}
|
|
}
|
|
}
|
|
|
|
t.remote.OnTrieNodes(t, requestId, nodes)
|
|
|
|
return nil
|
|
}
|
|
|
|
// defaultAccountRequestHandler is a well-behaving handler for AccountRangeRequests
|
|
func defaultAccountRequestHandler(t *testPeer, id uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error {
|
|
keys, vals, proofs := createAccountRequestResponse(t, root, origin, limit, cap)
|
|
if err := t.remote.OnAccounts(t, id, keys, vals, proofs); err != nil {
|
|
t.test.Errorf("Remote side rejected our delivery: %v", err)
|
|
t.term()
|
|
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func createAccountRequestResponse(t *testPeer, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) (keys []common.Hash, vals [][]byte, proofs [][]byte) {
|
|
var size uint64
|
|
|
|
if limit == (common.Hash{}) {
|
|
limit = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
|
|
}
|
|
|
|
for _, entry := range t.accountValues {
|
|
if size > cap {
|
|
break
|
|
}
|
|
|
|
if bytes.Compare(origin[:], entry.k) <= 0 {
|
|
keys = append(keys, common.BytesToHash(entry.k))
|
|
vals = append(vals, entry.v)
|
|
size += uint64(32 + len(entry.v))
|
|
}
|
|
// If we've exceeded the request threshold, abort
|
|
if bytes.Compare(entry.k, limit[:]) >= 0 {
|
|
break
|
|
}
|
|
}
|
|
// Unless we send the entire trie, we need to supply proofs
|
|
// Actually, we need to supply proofs either way! This seems to be an implementation
|
|
// quirk in go-ethereum
|
|
proof := light.NewNodeSet()
|
|
if err := t.accountTrie.Prove(origin[:], 0, proof); err != nil {
|
|
t.logger.Error("Could not prove inexistence of origin", "origin", origin, "error", err)
|
|
}
|
|
|
|
if len(keys) > 0 {
|
|
lastK := (keys[len(keys)-1])[:]
|
|
if err := t.accountTrie.Prove(lastK, 0, proof); err != nil {
|
|
t.logger.Error("Could not prove last item", "error", err)
|
|
}
|
|
}
|
|
|
|
for _, blob := range proof.NodeList() {
|
|
proofs = append(proofs, blob)
|
|
}
|
|
|
|
return keys, vals, proofs
|
|
}
|
|
|
|
// defaultStorageRequestHandler is a well-behaving storage request handler
|
|
func defaultStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, bOrigin, bLimit []byte, max uint64) error {
|
|
hashes, slots, proofs := createStorageRequestResponse(t, root, accounts, bOrigin, bLimit, max)
|
|
if err := t.remote.OnStorage(t, requestId, hashes, slots, proofs); err != nil {
|
|
t.test.Errorf("Remote side rejected our delivery: %v", err)
|
|
t.term()
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func defaultCodeRequestHandler(t *testPeer, id uint64, hashes []common.Hash, max uint64) error {
|
|
var bytecodes [][]byte
|
|
for _, h := range hashes {
|
|
bytecodes = append(bytecodes, getCodeByHash(h))
|
|
}
|
|
|
|
if err := t.remote.OnByteCodes(t, id, bytecodes); err != nil {
|
|
t.test.Errorf("Remote side rejected our delivery: %v", err)
|
|
t.term()
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func createStorageRequestResponse(t *testPeer, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) (hashes [][]common.Hash, slots [][][]byte, proofs [][]byte) {
|
|
var size uint64
|
|
|
|
for _, account := range accounts {
|
|
// The first account might start from a different origin and end sooner
|
|
var originHash common.Hash
|
|
if len(origin) > 0 {
|
|
originHash = common.BytesToHash(origin)
|
|
}
|
|
|
|
var limitHash = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
|
|
if len(limit) > 0 {
|
|
limitHash = common.BytesToHash(limit)
|
|
}
|
|
|
|
var (
|
|
keys []common.Hash
|
|
vals [][]byte
|
|
abort bool
|
|
)
|
|
|
|
for _, entry := range t.storageValues[account] {
|
|
if size >= max {
|
|
abort = true
|
|
break
|
|
}
|
|
|
|
if bytes.Compare(entry.k, originHash[:]) < 0 {
|
|
continue
|
|
}
|
|
|
|
keys = append(keys, common.BytesToHash(entry.k))
|
|
vals = append(vals, entry.v)
|
|
size += uint64(32 + len(entry.v))
|
|
|
|
if bytes.Compare(entry.k, limitHash[:]) >= 0 {
|
|
break
|
|
}
|
|
}
|
|
|
|
if len(keys) > 0 {
|
|
hashes = append(hashes, keys)
|
|
slots = append(slots, vals)
|
|
}
|
|
// Generate the Merkle proofs for the first and last storage slot, but
|
|
// only if the response was capped. If the entire storage trie included
|
|
// in the response, no need for any proofs.
|
|
if originHash != (common.Hash{}) || (abort && len(keys) > 0) {
|
|
// If we're aborting, we need to prove the first and last item
|
|
// This terminates the response (and thus the loop)
|
|
proof := light.NewNodeSet()
|
|
stTrie := t.storageTries[account]
|
|
|
|
// Here's a potential gotcha: when constructing the proof, we cannot
|
|
// use the 'origin' slice directly, but must use the full 32-byte
|
|
// hash form.
|
|
if err := stTrie.Prove(originHash[:], 0, proof); err != nil {
|
|
t.logger.Error("Could not prove inexistence of origin", "origin", originHash, "error", err)
|
|
}
|
|
|
|
if len(keys) > 0 {
|
|
lastK := (keys[len(keys)-1])[:]
|
|
if err := stTrie.Prove(lastK, 0, proof); err != nil {
|
|
t.logger.Error("Could not prove last item", "error", err)
|
|
}
|
|
}
|
|
|
|
for _, blob := range proof.NodeList() {
|
|
proofs = append(proofs, blob)
|
|
}
|
|
|
|
break
|
|
}
|
|
}
|
|
|
|
return hashes, slots, proofs
|
|
}
|
|
|
|
// createStorageRequestResponseAlwaysProve tests a cornercase, where the peer always
|
|
// supplies the proof for the last account, even if it is 'complete'.
|
|
func createStorageRequestResponseAlwaysProve(t *testPeer, root common.Hash, accounts []common.Hash, bOrigin, bLimit []byte, max uint64) (hashes [][]common.Hash, slots [][][]byte, proofs [][]byte) {
|
|
var size uint64
|
|
|
|
max = max * 3 / 4
|
|
|
|
var origin common.Hash
|
|
if len(bOrigin) > 0 {
|
|
origin = common.BytesToHash(bOrigin)
|
|
}
|
|
|
|
var exit bool
|
|
|
|
for i, account := range accounts {
|
|
var keys []common.Hash
|
|
|
|
var vals [][]byte
|
|
|
|
for _, entry := range t.storageValues[account] {
|
|
if bytes.Compare(entry.k, origin[:]) < 0 {
|
|
exit = true
|
|
}
|
|
|
|
keys = append(keys, common.BytesToHash(entry.k))
|
|
vals = append(vals, entry.v)
|
|
|
|
size += uint64(32 + len(entry.v))
|
|
if size > max {
|
|
exit = true
|
|
}
|
|
}
|
|
|
|
if i == len(accounts)-1 {
|
|
exit = true
|
|
}
|
|
|
|
hashes = append(hashes, keys)
|
|
slots = append(slots, vals)
|
|
|
|
if exit {
|
|
// If we're aborting, we need to prove the first and last item
|
|
// This terminates the response (and thus the loop)
|
|
proof := light.NewNodeSet()
|
|
stTrie := t.storageTries[account]
|
|
|
|
// Here's a potential gotcha: when constructing the proof, we cannot
|
|
// use the 'origin' slice directly, but must use the full 32-byte
|
|
// hash form.
|
|
if err := stTrie.Prove(origin[:], 0, proof); err != nil {
|
|
t.logger.Error("Could not prove inexistence of origin", "origin", origin,
|
|
"error", err)
|
|
}
|
|
|
|
if len(keys) > 0 {
|
|
lastK := (keys[len(keys)-1])[:]
|
|
if err := stTrie.Prove(lastK, 0, proof); err != nil {
|
|
t.logger.Error("Could not prove last item", "error", err)
|
|
}
|
|
}
|
|
|
|
for _, blob := range proof.NodeList() {
|
|
proofs = append(proofs, blob)
|
|
}
|
|
|
|
break
|
|
}
|
|
}
|
|
|
|
return hashes, slots, proofs
|
|
}
|
|
|
|
// emptyRequestAccountRangeFn is a rejects AccountRangeRequests
|
|
func emptyRequestAccountRangeFn(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error {
|
|
t.remote.OnAccounts(t, requestId, nil, nil, nil)
|
|
return nil
|
|
}
|
|
|
|
func nonResponsiveRequestAccountRangeFn(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error {
|
|
return nil
|
|
}
|
|
|
|
func emptyTrieRequestHandler(t *testPeer, requestId uint64, root common.Hash, paths []TrieNodePathSet, cap uint64) error {
|
|
t.remote.OnTrieNodes(t, requestId, nil)
|
|
return nil
|
|
}
|
|
|
|
func nonResponsiveTrieRequestHandler(t *testPeer, requestId uint64, root common.Hash, paths []TrieNodePathSet, cap uint64) error {
|
|
return nil
|
|
}
|
|
|
|
func emptyStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error {
|
|
t.remote.OnStorage(t, requestId, nil, nil, nil)
|
|
return nil
|
|
}
|
|
|
|
func nonResponsiveStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error {
|
|
return nil
|
|
}
|
|
|
|
func proofHappyStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error {
|
|
hashes, slots, proofs := createStorageRequestResponseAlwaysProve(t, root, accounts, origin, limit, max)
|
|
if err := t.remote.OnStorage(t, requestId, hashes, slots, proofs); err != nil {
|
|
t.test.Errorf("Remote side rejected our delivery: %v", err)
|
|
t.term()
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
//func emptyCodeRequestHandler(t *testPeer, id uint64, hashes []common.Hash, max uint64) error {
|
|
// var bytecodes [][]byte
|
|
// t.remote.OnByteCodes(t, id, bytecodes)
|
|
// return nil
|
|
//}
|
|
|
|
func corruptCodeRequestHandler(t *testPeer, id uint64, hashes []common.Hash, max uint64) error {
|
|
var bytecodes [][]byte
|
|
for _, h := range hashes {
|
|
// Send back the hashes
|
|
bytecodes = append(bytecodes, h[:])
|
|
}
|
|
|
|
if err := t.remote.OnByteCodes(t, id, bytecodes); err != nil {
|
|
t.logger.Info("remote error on delivery (as expected)", "error", err)
|
|
// Mimic the real-life handler, which drops a peer on errors
|
|
t.remote.Unregister(t.id)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func cappedCodeRequestHandler(t *testPeer, id uint64, hashes []common.Hash, max uint64) error {
|
|
var bytecodes [][]byte
|
|
for _, h := range hashes[:1] {
|
|
bytecodes = append(bytecodes, getCodeByHash(h))
|
|
}
|
|
// Missing bytecode can be retrieved again, no error expected
|
|
if err := t.remote.OnByteCodes(t, id, bytecodes); err != nil {
|
|
t.test.Errorf("Remote side rejected our delivery: %v", err)
|
|
t.term()
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// starvingStorageRequestHandler is somewhat well-behaving storage handler, but it caps the returned results to be very small
|
|
func starvingStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error {
|
|
return defaultStorageRequestHandler(t, requestId, root, accounts, origin, limit, 500)
|
|
}
|
|
|
|
func starvingAccountRequestHandler(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error {
|
|
return defaultAccountRequestHandler(t, requestId, root, origin, limit, 500)
|
|
}
|
|
|
|
//func misdeliveringAccountRequestHandler(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, cap uint64) error {
|
|
// return defaultAccountRequestHandler(t, requestId-1, root, origin, 500)
|
|
//}
|
|
|
|
func corruptAccountRequestHandler(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error {
|
|
hashes, accounts, proofs := createAccountRequestResponse(t, root, origin, limit, cap)
|
|
if len(proofs) > 0 {
|
|
proofs = proofs[1:]
|
|
}
|
|
|
|
if err := t.remote.OnAccounts(t, requestId, hashes, accounts, proofs); err != nil {
|
|
t.logger.Info("remote error on delivery (as expected)", "error", err)
|
|
// Mimic the real-life handler, which drops a peer on errors
|
|
t.remote.Unregister(t.id)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// corruptStorageRequestHandler doesn't provide good proofs
|
|
func corruptStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error {
|
|
hashes, slots, proofs := createStorageRequestResponse(t, root, accounts, origin, limit, max)
|
|
if len(proofs) > 0 {
|
|
proofs = proofs[1:]
|
|
}
|
|
|
|
if err := t.remote.OnStorage(t, requestId, hashes, slots, proofs); err != nil {
|
|
t.logger.Info("remote error on delivery (as expected)", "error", err)
|
|
// Mimic the real-life handler, which drops a peer on errors
|
|
t.remote.Unregister(t.id)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func noProofStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error {
|
|
hashes, slots, _ := createStorageRequestResponse(t, root, accounts, origin, limit, max)
|
|
if err := t.remote.OnStorage(t, requestId, hashes, slots, nil); err != nil {
|
|
t.logger.Info("remote error on delivery (as expected)", "error", err)
|
|
// Mimic the real-life handler, which drops a peer on errors
|
|
t.remote.Unregister(t.id)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// TestSyncBloatedProof tests a scenario where we provide only _one_ value, but
|
|
// also ship the entire trie inside the proof. If the attack is successful,
|
|
// the remote side does not do any follow-up requests
|
|
func TestSyncBloatedProof(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems := makeAccountTrieNoStorage(100)
|
|
source := newTestPeer("source", t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
|
|
source.accountRequestHandler = func(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error {
|
|
var (
|
|
proofs [][]byte
|
|
keys []common.Hash
|
|
vals [][]byte
|
|
)
|
|
// The values
|
|
for _, entry := range t.accountValues {
|
|
if bytes.Compare(entry.k, origin[:]) < 0 {
|
|
continue
|
|
}
|
|
|
|
if bytes.Compare(entry.k, limit[:]) > 0 {
|
|
continue
|
|
}
|
|
|
|
keys = append(keys, common.BytesToHash(entry.k))
|
|
vals = append(vals, entry.v)
|
|
}
|
|
// The proofs
|
|
proof := light.NewNodeSet()
|
|
if err := t.accountTrie.Prove(origin[:], 0, proof); err != nil {
|
|
t.logger.Error("Could not prove origin", "origin", origin, "error", err)
|
|
}
|
|
// The bloat: add proof of every single element
|
|
for _, entry := range t.accountValues {
|
|
if err := t.accountTrie.Prove(entry.k, 0, proof); err != nil {
|
|
t.logger.Error("Could not prove item", "error", err)
|
|
}
|
|
}
|
|
// And remove one item from the elements
|
|
if len(keys) > 2 {
|
|
keys = append(keys[:1], keys[2:]...)
|
|
vals = append(vals[:1], vals[2:]...)
|
|
}
|
|
|
|
for _, blob := range proof.NodeList() {
|
|
proofs = append(proofs, blob)
|
|
}
|
|
|
|
if err := t.remote.OnAccounts(t, requestId, keys, vals, proofs); err != nil {
|
|
t.logger.Info("remote error on delivery (as expected)", "error", err)
|
|
t.term()
|
|
// This is actually correct, signal to exit the test successfully
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
syncer := setupSyncer(nodeScheme, source)
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err == nil {
|
|
t.Fatal("No error returned from incomplete/cancelled sync")
|
|
}
|
|
}
|
|
|
|
func setupSyncer(scheme string, peers ...*testPeer) *Syncer {
|
|
stateDb := rawdb.NewMemoryDatabase()
|
|
|
|
syncer := NewSyncer(stateDb, scheme)
|
|
for _, peer := range peers {
|
|
syncer.Register(peer)
|
|
peer.remote = syncer
|
|
}
|
|
|
|
return syncer
|
|
}
|
|
|
|
// TestSync tests a basic sync with one peer
|
|
func TestSync(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems := makeAccountTrieNoStorage(100)
|
|
|
|
mkSource := func(name string) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
|
|
return source
|
|
}
|
|
|
|
syncer := setupSyncer(nodeScheme, mkSource("source"))
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
// TestSyncTinyTriePanic tests a basic sync with one peer, and a tiny trie. This caused a
|
|
// panic within the prover
|
|
func TestSyncTinyTriePanic(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems := makeAccountTrieNoStorage(1)
|
|
|
|
mkSource := func(name string) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
|
|
return source
|
|
}
|
|
syncer := setupSyncer(nodeScheme, mkSource("source"))
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
// TestMultiSync tests a basic sync with multiple peers
|
|
func TestMultiSync(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems := makeAccountTrieNoStorage(100)
|
|
|
|
mkSource := func(name string) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
|
|
return source
|
|
}
|
|
syncer := setupSyncer(nodeScheme, mkSource("sourceA"), mkSource("sourceB"))
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
// TestSyncWithStorage tests basic sync using accounts + storage + code
|
|
func TestSyncWithStorage(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(3, 3000, true, false)
|
|
|
|
mkSource := func(name string) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
source.setStorageTries(storageTries)
|
|
source.storageValues = storageElems
|
|
|
|
return source
|
|
}
|
|
syncer := setupSyncer(nodeScheme, mkSource("sourceA"))
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
// TestMultiSyncManyUseless contains one good peer, and many which doesn't return anything valuable at all
|
|
func TestMultiSyncManyUseless(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true, false)
|
|
|
|
mkSource := func(name string, noAccount, noStorage, noTrieNode bool) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
source.setStorageTries(storageTries)
|
|
source.storageValues = storageElems
|
|
|
|
if !noAccount {
|
|
source.accountRequestHandler = emptyRequestAccountRangeFn
|
|
}
|
|
|
|
if !noStorage {
|
|
source.storageRequestHandler = emptyStorageRequestHandler
|
|
}
|
|
|
|
if !noTrieNode {
|
|
source.trieRequestHandler = emptyTrieRequestHandler
|
|
}
|
|
|
|
return source
|
|
}
|
|
|
|
syncer := setupSyncer(
|
|
nodeScheme,
|
|
mkSource("full", true, true, true),
|
|
mkSource("noAccounts", false, true, true),
|
|
mkSource("noStorage", true, false, true),
|
|
mkSource("noTrie", true, true, false),
|
|
)
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
// TestMultiSyncManyUseless contains one good peer, and many which doesn't return anything valuable at all
|
|
func TestMultiSyncManyUselessWithLowTimeout(t *testing.T) {
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true, false)
|
|
|
|
mkSource := func(name string, noAccount, noStorage, noTrieNode bool) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
source.setStorageTries(storageTries)
|
|
source.storageValues = storageElems
|
|
|
|
if !noAccount {
|
|
source.accountRequestHandler = emptyRequestAccountRangeFn
|
|
}
|
|
|
|
if !noStorage {
|
|
source.storageRequestHandler = emptyStorageRequestHandler
|
|
}
|
|
|
|
if !noTrieNode {
|
|
source.trieRequestHandler = emptyTrieRequestHandler
|
|
}
|
|
|
|
return source
|
|
}
|
|
|
|
syncer := setupSyncer(
|
|
nodeScheme,
|
|
mkSource("full", true, true, true),
|
|
mkSource("noAccounts", false, true, true),
|
|
mkSource("noStorage", true, false, true),
|
|
mkSource("noTrie", true, true, false),
|
|
)
|
|
// We're setting the timeout to very low, to increase the chance of the timeout
|
|
// being triggered. This was previously a cause of panic, when a response
|
|
// arrived simultaneously as a timeout was triggered.
|
|
syncer.rates.OverrideTTLLimit = time.Millisecond
|
|
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
// TestMultiSyncManyUnresponsive contains one good peer, and many which doesn't respond at all
|
|
func TestMultiSyncManyUnresponsive(t *testing.T) {
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true, false)
|
|
|
|
mkSource := func(name string, noAccount, noStorage, noTrieNode bool) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
source.setStorageTries(storageTries)
|
|
source.storageValues = storageElems
|
|
|
|
if !noAccount {
|
|
source.accountRequestHandler = nonResponsiveRequestAccountRangeFn
|
|
}
|
|
|
|
if !noStorage {
|
|
source.storageRequestHandler = nonResponsiveStorageRequestHandler
|
|
}
|
|
|
|
if !noTrieNode {
|
|
source.trieRequestHandler = nonResponsiveTrieRequestHandler
|
|
}
|
|
|
|
return source
|
|
}
|
|
|
|
syncer := setupSyncer(
|
|
nodeScheme,
|
|
mkSource("full", true, true, true),
|
|
mkSource("noAccounts", false, true, true),
|
|
mkSource("noStorage", true, false, true),
|
|
mkSource("noTrie", true, true, false),
|
|
)
|
|
// We're setting the timeout to very low, to make the test run a bit faster
|
|
syncer.rates.OverrideTTLLimit = time.Millisecond
|
|
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
func checkStall(t *testing.T, term func()) chan struct{} {
|
|
testDone := make(chan struct{})
|
|
|
|
go func() {
|
|
select {
|
|
case <-time.After(time.Minute): // TODO(karalabe): Make tests smaller, this is too much
|
|
t.Log("Sync stalled")
|
|
term()
|
|
case <-testDone:
|
|
return
|
|
}
|
|
}()
|
|
|
|
return testDone
|
|
}
|
|
|
|
// TestSyncBoundaryAccountTrie tests sync against a few normal peers, but the
|
|
// account trie has a few boundary elements.
|
|
func TestSyncBoundaryAccountTrie(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems := makeBoundaryAccountTrie(3000)
|
|
|
|
mkSource := func(name string) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
|
|
return source
|
|
}
|
|
syncer := setupSyncer(
|
|
nodeScheme,
|
|
mkSource("peer-a"),
|
|
mkSource("peer-b"),
|
|
)
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
// TestSyncNoStorageAndOneCappedPeer tests sync using accounts and no storage, where one peer is
|
|
// consistently returning very small results
|
|
func TestSyncNoStorageAndOneCappedPeer(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems := makeAccountTrieNoStorage(3000)
|
|
|
|
mkSource := func(name string, slow bool) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
|
|
if slow {
|
|
source.accountRequestHandler = starvingAccountRequestHandler
|
|
}
|
|
|
|
return source
|
|
}
|
|
|
|
syncer := setupSyncer(
|
|
nodeScheme,
|
|
mkSource("nice-a", false),
|
|
mkSource("nice-b", false),
|
|
mkSource("nice-c", false),
|
|
mkSource("capped", true),
|
|
)
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
// TestSyncNoStorageAndOneCodeCorruptPeer has one peer which doesn't deliver
|
|
// code requests properly.
|
|
func TestSyncNoStorageAndOneCodeCorruptPeer(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems := makeAccountTrieNoStorage(3000)
|
|
|
|
mkSource := func(name string, codeFn codeHandlerFunc) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
source.codeRequestHandler = codeFn
|
|
|
|
return source
|
|
}
|
|
// One is capped, one is corrupt. If we don't use a capped one, there's a 50%
|
|
// chance that the full set of codes requested are sent only to the
|
|
// non-corrupt peer, which delivers everything in one go, and makes the
|
|
// test moot
|
|
syncer := setupSyncer(
|
|
nodeScheme,
|
|
mkSource("capped", cappedCodeRequestHandler),
|
|
mkSource("corrupt", corruptCodeRequestHandler),
|
|
)
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
func TestSyncNoStorageAndOneAccountCorruptPeer(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems := makeAccountTrieNoStorage(3000)
|
|
|
|
mkSource := func(name string, accFn accountHandlerFunc) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
source.accountRequestHandler = accFn
|
|
|
|
return source
|
|
}
|
|
// One is capped, one is corrupt. If we don't use a capped one, there's a 50%
|
|
// chance that the full set of codes requested are sent only to the
|
|
// non-corrupt peer, which delivers everything in one go, and makes the
|
|
// test moot
|
|
syncer := setupSyncer(
|
|
nodeScheme,
|
|
mkSource("capped", defaultAccountRequestHandler),
|
|
mkSource("corrupt", corruptAccountRequestHandler),
|
|
)
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
// TestSyncNoStorageAndOneCodeCappedPeer has one peer which delivers code hashes
|
|
// one by one
|
|
func TestSyncNoStorageAndOneCodeCappedPeer(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems := makeAccountTrieNoStorage(3000)
|
|
|
|
mkSource := func(name string, codeFn codeHandlerFunc) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
source.codeRequestHandler = codeFn
|
|
|
|
return source
|
|
}
|
|
// Count how many times it's invoked. Remember, there are only 8 unique hashes,
|
|
// so it shouldn't be more than that
|
|
var counter int
|
|
|
|
syncer := setupSyncer(
|
|
nodeScheme,
|
|
mkSource("capped", func(t *testPeer, id uint64, hashes []common.Hash, max uint64) error {
|
|
counter++
|
|
return cappedCodeRequestHandler(t, id, hashes, max)
|
|
}),
|
|
)
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
|
|
// There are only 8 unique hashes, and 3K accounts. However, the code
|
|
// deduplication is per request batch. If it were a perfect global dedup,
|
|
// we would expect only 8 requests. If there were no dedup, there would be
|
|
// 3k requests.
|
|
// We expect somewhere below 100 requests for these 8 unique hashes. But
|
|
// the number can be flaky, so don't limit it so strictly.
|
|
if threshold := 100; counter > threshold {
|
|
t.Logf("Error, expected < %d invocations, got %d", threshold, counter)
|
|
}
|
|
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
// TestSyncBoundaryStorageTrie tests sync against a few normal peers, but the
|
|
// storage trie has a few boundary elements.
|
|
func TestSyncBoundaryStorageTrie(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(10, 1000, false, true)
|
|
|
|
mkSource := func(name string) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
source.setStorageTries(storageTries)
|
|
source.storageValues = storageElems
|
|
|
|
return source
|
|
}
|
|
syncer := setupSyncer(
|
|
nodeScheme,
|
|
mkSource("peer-a"),
|
|
mkSource("peer-b"),
|
|
)
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
// TestSyncWithStorageAndOneCappedPeer tests sync using accounts + storage, where one peer is
|
|
// consistently returning very small results
|
|
func TestSyncWithStorageAndOneCappedPeer(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(300, 1000, false, false)
|
|
|
|
mkSource := func(name string, slow bool) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
source.setStorageTries(storageTries)
|
|
source.storageValues = storageElems
|
|
|
|
if slow {
|
|
source.storageRequestHandler = starvingStorageRequestHandler
|
|
}
|
|
|
|
return source
|
|
}
|
|
|
|
syncer := setupSyncer(
|
|
nodeScheme,
|
|
mkSource("nice-a", false),
|
|
mkSource("slow", true),
|
|
)
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
// TestSyncWithStorageAndCorruptPeer tests sync using accounts + storage, where one peer is
|
|
// sometimes sending bad proofs
|
|
func TestSyncWithStorageAndCorruptPeer(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true, false)
|
|
|
|
mkSource := func(name string, handler storageHandlerFunc) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
source.setStorageTries(storageTries)
|
|
source.storageValues = storageElems
|
|
source.storageRequestHandler = handler
|
|
|
|
return source
|
|
}
|
|
|
|
syncer := setupSyncer(
|
|
nodeScheme,
|
|
mkSource("nice-a", defaultStorageRequestHandler),
|
|
mkSource("nice-b", defaultStorageRequestHandler),
|
|
mkSource("nice-c", defaultStorageRequestHandler),
|
|
mkSource("corrupt", corruptStorageRequestHandler),
|
|
)
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
func TestSyncWithStorageAndNonProvingPeer(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true, false)
|
|
|
|
mkSource := func(name string, handler storageHandlerFunc) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
source.setStorageTries(storageTries)
|
|
source.storageValues = storageElems
|
|
source.storageRequestHandler = handler
|
|
|
|
return source
|
|
}
|
|
syncer := setupSyncer(
|
|
nodeScheme,
|
|
mkSource("nice-a", defaultStorageRequestHandler),
|
|
mkSource("nice-b", defaultStorageRequestHandler),
|
|
mkSource("nice-c", defaultStorageRequestHandler),
|
|
mkSource("corrupt", noProofStorageRequestHandler),
|
|
)
|
|
done := checkStall(t, term)
|
|
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
close(done)
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
// TestSyncWithStorage tests basic sync using accounts + storage + code, against
|
|
// a peer who insists on delivering full storage sets _and_ proofs. This triggered
|
|
// an error, where the recipient erroneously clipped the boundary nodes, but
|
|
// did not mark the account for healing.
|
|
func TestSyncWithStorageMisbehavingProve(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorageWithUniqueStorage(10, 30, false)
|
|
|
|
mkSource := func(name string) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
source.setStorageTries(storageTries)
|
|
source.storageValues = storageElems
|
|
source.storageRequestHandler = proofHappyStorageRequestHandler
|
|
|
|
return source
|
|
}
|
|
|
|
syncer := setupSyncer(nodeScheme, mkSource("sourceA"))
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
}
|
|
|
|
type kv struct {
|
|
k, v []byte
|
|
}
|
|
|
|
// Some helpers for sorting
|
|
type entrySlice []*kv
|
|
|
|
func (p entrySlice) Len() int { return len(p) }
|
|
func (p entrySlice) Less(i, j int) bool { return bytes.Compare(p[i].k, p[j].k) < 0 }
|
|
func (p entrySlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
|
|
|
|
func key32(i uint64) []byte {
|
|
key := make([]byte, 32)
|
|
binary.LittleEndian.PutUint64(key, i)
|
|
|
|
return key
|
|
}
|
|
|
|
var (
|
|
codehashes = []common.Hash{
|
|
crypto.Keccak256Hash([]byte{0}),
|
|
crypto.Keccak256Hash([]byte{1}),
|
|
crypto.Keccak256Hash([]byte{2}),
|
|
crypto.Keccak256Hash([]byte{3}),
|
|
crypto.Keccak256Hash([]byte{4}),
|
|
crypto.Keccak256Hash([]byte{5}),
|
|
crypto.Keccak256Hash([]byte{6}),
|
|
crypto.Keccak256Hash([]byte{7}),
|
|
}
|
|
)
|
|
|
|
// getCodeHash returns a pseudo-random code hash
|
|
func getCodeHash(i uint64) []byte {
|
|
h := codehashes[int(i)%len(codehashes)]
|
|
return common.CopyBytes(h[:])
|
|
}
|
|
|
|
// getCodeByHash convenience function to lookup the code from the code hash
|
|
func getCodeByHash(hash common.Hash) []byte {
|
|
if hash == types.EmptyCodeHash {
|
|
return nil
|
|
}
|
|
|
|
for i, h := range codehashes {
|
|
if h == hash {
|
|
return []byte{byte(i)}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// makeAccountTrieNoStorage spits out a trie, along with the leafs
|
|
func makeAccountTrieNoStorage(n int) (string, *trie.Trie, entrySlice) {
|
|
// nolint:prealloc
|
|
var (
|
|
db = trie.NewDatabase(rawdb.NewMemoryDatabase())
|
|
accTrie = trie.NewEmpty(db)
|
|
entries entrySlice
|
|
)
|
|
|
|
for i := uint64(1); i <= uint64(n); i++ {
|
|
value, _ := rlp.EncodeToBytes(&types.StateAccount{
|
|
Nonce: i,
|
|
Balance: big.NewInt(int64(i)),
|
|
Root: types.EmptyRootHash,
|
|
CodeHash: getCodeHash(i),
|
|
})
|
|
key := key32(i)
|
|
elem := &kv{key, value}
|
|
accTrie.MustUpdate(elem.k, elem.v)
|
|
entries = append(entries, elem)
|
|
}
|
|
sort.Sort(entries)
|
|
|
|
// Commit the state changes into db and re-create the trie
|
|
// for accessing later.
|
|
root, nodes := accTrie.Commit(false)
|
|
_ = db.Update(trie.NewWithNodeSet(nodes))
|
|
|
|
accTrie, _ = trie.New(trie.StateTrieID(root), db)
|
|
|
|
return db.Scheme(), accTrie, entries
|
|
}
|
|
|
|
// makeBoundaryAccountTrie constructs an account trie. Instead of filling
|
|
// accounts normally, this function will fill a few accounts which have
|
|
// boundary hash.
|
|
func makeBoundaryAccountTrie(n int) (string, *trie.Trie, entrySlice) {
|
|
var (
|
|
entries entrySlice
|
|
boundaries []common.Hash
|
|
|
|
db = trie.NewDatabase(rawdb.NewMemoryDatabase())
|
|
accTrie = trie.NewEmpty(db)
|
|
)
|
|
// Initialize boundaries
|
|
var next common.Hash
|
|
|
|
step := new(big.Int).Sub(
|
|
new(big.Int).Div(
|
|
new(big.Int).Exp(common.Big2, common.Big256, nil),
|
|
big.NewInt(int64(accountConcurrency)),
|
|
), common.Big1,
|
|
)
|
|
for i := 0; i < accountConcurrency; i++ {
|
|
last := common.BigToHash(new(big.Int).Add(next.Big(), step))
|
|
if i == accountConcurrency-1 {
|
|
last = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
|
|
}
|
|
|
|
boundaries = append(boundaries, last)
|
|
next = common.BigToHash(new(big.Int).Add(last.Big(), common.Big1))
|
|
}
|
|
// Fill boundary accounts
|
|
for i := 0; i < len(boundaries); i++ {
|
|
value, _ := rlp.EncodeToBytes(&types.StateAccount{
|
|
Nonce: uint64(0),
|
|
Balance: big.NewInt(int64(i)),
|
|
Root: types.EmptyRootHash,
|
|
CodeHash: getCodeHash(uint64(i)),
|
|
})
|
|
elem := &kv{boundaries[i].Bytes(), value}
|
|
accTrie.MustUpdate(elem.k, elem.v)
|
|
entries = append(entries, elem)
|
|
}
|
|
// Fill other accounts if required
|
|
for i := uint64(1); i <= uint64(n); i++ {
|
|
value, _ := rlp.EncodeToBytes(&types.StateAccount{
|
|
Nonce: i,
|
|
Balance: big.NewInt(int64(i)),
|
|
Root: types.EmptyRootHash,
|
|
CodeHash: getCodeHash(i),
|
|
})
|
|
elem := &kv{key32(i), value}
|
|
accTrie.MustUpdate(elem.k, elem.v)
|
|
entries = append(entries, elem)
|
|
}
|
|
sort.Sort(entries)
|
|
|
|
// Commit the state changes into db and re-create the trie
|
|
// for accessing later.
|
|
root, nodes := accTrie.Commit(false)
|
|
_ = db.Update(trie.NewWithNodeSet(nodes))
|
|
|
|
accTrie, _ = trie.New(trie.StateTrieID(root), db)
|
|
|
|
return db.Scheme(), accTrie, entries
|
|
}
|
|
|
|
// makeAccountTrieWithStorageWithUniqueStorage creates an account trie where each accounts
|
|
// has a unique storage set.
|
|
func makeAccountTrieWithStorageWithUniqueStorage(accounts, slots int, code bool) (string, *trie.Trie, entrySlice, map[common.Hash]*trie.Trie, map[common.Hash]entrySlice) {
|
|
var (
|
|
db = trie.NewDatabase(rawdb.NewMemoryDatabase())
|
|
accTrie = trie.NewEmpty(db)
|
|
entries entrySlice
|
|
storageRoots = make(map[common.Hash]common.Hash)
|
|
storageTries = make(map[common.Hash]*trie.Trie)
|
|
storageEntries = make(map[common.Hash]entrySlice)
|
|
nodes = trie.NewMergedNodeSet()
|
|
)
|
|
// Create n accounts in the trie
|
|
for i := uint64(1); i <= uint64(accounts); i++ {
|
|
key := key32(i)
|
|
|
|
codehash := types.EmptyCodeHash.Bytes()
|
|
if code {
|
|
codehash = getCodeHash(i)
|
|
}
|
|
// Create a storage trie
|
|
stRoot, stNodes, stEntries := makeStorageTrieWithSeed(common.BytesToHash(key), uint64(slots), i, db)
|
|
_ = nodes.Merge(stNodes)
|
|
|
|
value, _ := rlp.EncodeToBytes(&types.StateAccount{
|
|
Nonce: i,
|
|
Balance: big.NewInt(int64(i)),
|
|
Root: stRoot,
|
|
CodeHash: codehash,
|
|
})
|
|
elem := &kv{key, value}
|
|
accTrie.MustUpdate(elem.k, elem.v)
|
|
entries = append(entries, elem)
|
|
|
|
storageRoots[common.BytesToHash(key)] = stRoot
|
|
storageEntries[common.BytesToHash(key)] = stEntries
|
|
}
|
|
sort.Sort(entries)
|
|
|
|
// Commit account trie
|
|
root, set := accTrie.Commit(true)
|
|
_ = nodes.Merge(set)
|
|
|
|
// Commit gathered dirty nodes into database
|
|
_ = db.Update(nodes)
|
|
|
|
// Re-create tries with new root
|
|
accTrie, _ = trie.New(trie.StateTrieID(root), db)
|
|
|
|
for i := uint64(1); i <= uint64(accounts); i++ {
|
|
key := key32(i)
|
|
id := trie.StorageTrieID(root, common.BytesToHash(key), storageRoots[common.BytesToHash(key)])
|
|
trie, _ := trie.New(id, db)
|
|
storageTries[common.BytesToHash(key)] = trie
|
|
}
|
|
|
|
return db.Scheme(), accTrie, entries, storageTries, storageEntries
|
|
}
|
|
|
|
// makeAccountTrieWithStorage spits out a trie, along with the leafs
|
|
func makeAccountTrieWithStorage(accounts, slots int, code, boundary bool) (string, *trie.Trie, entrySlice, map[common.Hash]*trie.Trie, map[common.Hash]entrySlice) {
|
|
var (
|
|
db = trie.NewDatabase(rawdb.NewMemoryDatabase())
|
|
accTrie = trie.NewEmpty(db)
|
|
entries entrySlice
|
|
storageRoots = make(map[common.Hash]common.Hash)
|
|
storageTries = make(map[common.Hash]*trie.Trie)
|
|
storageEntries = make(map[common.Hash]entrySlice)
|
|
nodes = trie.NewMergedNodeSet()
|
|
)
|
|
// Create n accounts in the trie
|
|
for i := uint64(1); i <= uint64(accounts); i++ {
|
|
key := key32(i)
|
|
|
|
codehash := types.EmptyCodeHash.Bytes()
|
|
if code {
|
|
codehash = getCodeHash(i)
|
|
}
|
|
// Make a storage trie
|
|
var (
|
|
stRoot common.Hash
|
|
stNodes *trie.NodeSet
|
|
stEntries entrySlice
|
|
)
|
|
|
|
if boundary {
|
|
stRoot, stNodes, stEntries = makeBoundaryStorageTrie(common.BytesToHash(key), slots, db)
|
|
} else {
|
|
stRoot, stNodes, stEntries = makeStorageTrieWithSeed(common.BytesToHash(key), uint64(slots), 0, db)
|
|
}
|
|
|
|
_ = nodes.Merge(stNodes)
|
|
|
|
value, _ := rlp.EncodeToBytes(&types.StateAccount{
|
|
Nonce: i,
|
|
Balance: big.NewInt(int64(i)),
|
|
Root: stRoot,
|
|
CodeHash: codehash,
|
|
})
|
|
elem := &kv{key, value}
|
|
accTrie.MustUpdate(elem.k, elem.v)
|
|
entries = append(entries, elem)
|
|
|
|
// we reuse the same one for all accounts
|
|
storageRoots[common.BytesToHash(key)] = stRoot
|
|
storageEntries[common.BytesToHash(key)] = stEntries
|
|
}
|
|
sort.Sort(entries)
|
|
|
|
// Commit account trie
|
|
root, set := accTrie.Commit(true)
|
|
_ = nodes.Merge(set)
|
|
|
|
// Commit gathered dirty nodes into database
|
|
_ = db.Update(nodes)
|
|
|
|
// Re-create tries with new root
|
|
accTrie, err := trie.New(trie.StateTrieID(root), db)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
for i := uint64(1); i <= uint64(accounts); i++ {
|
|
key := key32(i)
|
|
id := trie.StorageTrieID(root, common.BytesToHash(key), storageRoots[common.BytesToHash(key)])
|
|
|
|
trie, err := trie.New(id, db)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
storageTries[common.BytesToHash(key)] = trie
|
|
}
|
|
|
|
return db.Scheme(), accTrie, entries, storageTries, storageEntries
|
|
}
|
|
|
|
// makeStorageTrieWithSeed fills a storage trie with n items, returning the
|
|
// not-yet-committed trie and the sorted entries. The seeds can be used to ensure
|
|
// that tries are unique.
|
|
func makeStorageTrieWithSeed(owner common.Hash, n, seed uint64, db *trie.Database) (common.Hash, *trie.NodeSet, entrySlice) {
|
|
trie, _ := trie.New(trie.StorageTrieID(common.Hash{}, owner, common.Hash{}), db)
|
|
|
|
var entries entrySlice
|
|
|
|
for i := uint64(1); i <= n; i++ {
|
|
// store 'x' at slot 'x'
|
|
slotValue := key32(i + seed)
|
|
rlpSlotValue, _ := rlp.EncodeToBytes(common.TrimLeftZeroes(slotValue[:]))
|
|
|
|
slotKey := key32(i)
|
|
key := crypto.Keccak256Hash(slotKey[:])
|
|
|
|
elem := &kv{key[:], rlpSlotValue}
|
|
trie.MustUpdate(elem.k, elem.v)
|
|
entries = append(entries, elem)
|
|
}
|
|
sort.Sort(entries)
|
|
|
|
root, nodes := trie.Commit(false)
|
|
|
|
return root, nodes, entries
|
|
}
|
|
|
|
// makeBoundaryStorageTrie constructs a storage trie. Instead of filling
|
|
// storage slots normally, this function will fill a few slots which have
|
|
// boundary hash.
|
|
func makeBoundaryStorageTrie(owner common.Hash, n int, db *trie.Database) (common.Hash, *trie.NodeSet, entrySlice) {
|
|
var (
|
|
entries entrySlice
|
|
boundaries []common.Hash
|
|
trie, _ = trie.New(trie.StorageTrieID(common.Hash{}, owner, common.Hash{}), db)
|
|
)
|
|
// Initialize boundaries
|
|
var next common.Hash
|
|
|
|
step := new(big.Int).Sub(
|
|
new(big.Int).Div(
|
|
new(big.Int).Exp(common.Big2, common.Big256, nil),
|
|
big.NewInt(int64(accountConcurrency)),
|
|
), common.Big1,
|
|
)
|
|
for i := 0; i < accountConcurrency; i++ {
|
|
last := common.BigToHash(new(big.Int).Add(next.Big(), step))
|
|
if i == accountConcurrency-1 {
|
|
last = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
|
|
}
|
|
|
|
boundaries = append(boundaries, last)
|
|
next = common.BigToHash(new(big.Int).Add(last.Big(), common.Big1))
|
|
}
|
|
// Fill boundary slots
|
|
for i := 0; i < len(boundaries); i++ {
|
|
key := boundaries[i]
|
|
val := []byte{0xde, 0xad, 0xbe, 0xef}
|
|
|
|
elem := &kv{key[:], val}
|
|
trie.MustUpdate(elem.k, elem.v)
|
|
entries = append(entries, elem)
|
|
}
|
|
// Fill other slots if required
|
|
for i := uint64(1); i <= uint64(n); i++ {
|
|
slotKey := key32(i)
|
|
key := crypto.Keccak256Hash(slotKey[:])
|
|
|
|
slotValue := key32(i)
|
|
rlpSlotValue, _ := rlp.EncodeToBytes(common.TrimLeftZeroes(slotValue[:]))
|
|
|
|
elem := &kv{key[:], rlpSlotValue}
|
|
trie.MustUpdate(elem.k, elem.v)
|
|
entries = append(entries, elem)
|
|
}
|
|
sort.Sort(entries)
|
|
|
|
root, nodes := trie.Commit(false)
|
|
|
|
return root, nodes, entries
|
|
}
|
|
|
|
func verifyTrie(db ethdb.KeyValueStore, root common.Hash, t *testing.T) {
|
|
t.Helper()
|
|
|
|
triedb := trie.NewDatabase(rawdb.NewDatabase(db))
|
|
|
|
accTrie, err := trie.New(trie.StateTrieID(root), triedb)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
accounts, slots := 0, 0
|
|
|
|
accIt := trie.NewIterator(accTrie.NodeIterator(nil))
|
|
for accIt.Next() {
|
|
var acc struct {
|
|
Nonce uint64
|
|
Balance *big.Int
|
|
Root common.Hash
|
|
CodeHash []byte
|
|
}
|
|
|
|
if err := rlp.DecodeBytes(accIt.Value, &acc); err != nil {
|
|
log.Crit("Invalid account encountered during snapshot creation", "err", err)
|
|
}
|
|
|
|
accounts++
|
|
|
|
if acc.Root != types.EmptyRootHash {
|
|
id := trie.StorageTrieID(root, common.BytesToHash(accIt.Key), acc.Root)
|
|
|
|
storeTrie, err := trie.NewStateTrie(id, triedb)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
storeIt := trie.NewIterator(storeTrie.NodeIterator(nil))
|
|
for storeIt.Next() {
|
|
slots++
|
|
}
|
|
|
|
if err := storeIt.Err; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
if err := accIt.Err; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
t.Logf("accounts: %d, slots: %d", accounts, slots)
|
|
}
|
|
|
|
// TestSyncAccountPerformance tests how efficient the snap algo is at minimizing
|
|
// state healing
|
|
func TestSyncAccountPerformance(t *testing.T) {
|
|
// Set the account concurrency to 1. This _should_ result in the
|
|
// range root to become correct, and there should be no healing needed
|
|
defer func(old int) { accountConcurrency = old }(accountConcurrency)
|
|
accountConcurrency = 1
|
|
|
|
var (
|
|
once sync.Once
|
|
cancel = make(chan struct{})
|
|
term = func() {
|
|
once.Do(func() {
|
|
close(cancel)
|
|
})
|
|
}
|
|
)
|
|
|
|
nodeScheme, sourceAccountTrie, elems := makeAccountTrieNoStorage(100)
|
|
|
|
mkSource := func(name string) *testPeer {
|
|
source := newTestPeer(name, t, term)
|
|
source.accountTrie = sourceAccountTrie.Copy()
|
|
source.accountValues = elems
|
|
|
|
return source
|
|
}
|
|
src := mkSource("source")
|
|
|
|
syncer := setupSyncer(nodeScheme, src)
|
|
if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
|
|
t.Fatalf("sync failed: %v", err)
|
|
}
|
|
|
|
verifyTrie(syncer.db, sourceAccountTrie.Hash(), t)
|
|
// The trie root will always be requested, since it is added when the snap
|
|
// sync cycle starts. When popping the queue, we do not look it up again.
|
|
// Doing so would bring this number down to zero in this artificial testcase,
|
|
// but only add extra IO for no reason in practice.
|
|
if have, want := src.nTrienodeRequests, 1; have != want {
|
|
fmt.Print(src.Stats())
|
|
t.Errorf("trie node heal requests wrong, want %d, have %d", want, have)
|
|
}
|
|
}
|
|
|
|
func TestSlotEstimation(t *testing.T) {
|
|
for i, tc := range []struct {
|
|
last common.Hash
|
|
count int
|
|
want uint64
|
|
}{
|
|
{
|
|
// Half the space
|
|
common.HexToHash("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
|
|
100,
|
|
100,
|
|
},
|
|
{
|
|
// 1 / 16th
|
|
common.HexToHash("0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
|
|
100,
|
|
1500,
|
|
},
|
|
{
|
|
// Bit more than 1 / 16th
|
|
common.HexToHash("0x1000000000000000000000000000000000000000000000000000000000000000"),
|
|
100,
|
|
1499,
|
|
},
|
|
{
|
|
// Almost everything
|
|
common.HexToHash("0xF000000000000000000000000000000000000000000000000000000000000000"),
|
|
100,
|
|
6,
|
|
},
|
|
{
|
|
// Almost nothing -- should lead to error
|
|
common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000001"),
|
|
1,
|
|
0,
|
|
},
|
|
{
|
|
// Nothing -- should lead to error
|
|
common.Hash{},
|
|
100,
|
|
0,
|
|
},
|
|
} {
|
|
have, _ := estimateRemainingSlots(tc.count, tc.last)
|
|
if want := tc.want; have != want {
|
|
t.Errorf("test %d: have %d want %d", i, have, want)
|
|
}
|
|
}
|
|
}
|