mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-08-05 03:23: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>
992 lines
34 KiB
Go
992 lines
34 KiB
Go
// Copyright 2019 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 fetcher
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
mrand "math/rand"
|
|
"sort"
|
|
"time"
|
|
|
|
mapset "github.com/deckarep/golang-set/v2"
|
|
|
|
"github.com/ethereum/go-ethereum/common"
|
|
"github.com/ethereum/go-ethereum/common/mclock"
|
|
"github.com/ethereum/go-ethereum/core/txpool"
|
|
"github.com/ethereum/go-ethereum/core/types"
|
|
"github.com/ethereum/go-ethereum/log"
|
|
"github.com/ethereum/go-ethereum/metrics"
|
|
)
|
|
|
|
const (
|
|
// maxTxAnnounces is the maximum number of unique transaction a peer
|
|
// can announce in a short time.
|
|
maxTxAnnounces = 4096
|
|
|
|
// maxTxRetrievals is the maximum transaction number can be fetched in one
|
|
// request. The rationale to pick 256 is:
|
|
// - In eth protocol, the softResponseLimit is 2MB. Nowadays according to
|
|
// Etherscan the average transaction size is around 200B, so in theory
|
|
// we can include lots of transaction in a single protocol packet.
|
|
// - However the maximum size of a single transaction is raised to 128KB,
|
|
// so pick a middle value here to ensure we can maximize the efficiency
|
|
// of the retrieval and response size overflow won't happen in most cases.
|
|
maxTxRetrievals = 256
|
|
|
|
// maxTxUnderpricedSetSize is the size of the underpriced transaction set that
|
|
// is used to track recent transactions that have been dropped so we don't
|
|
// re-request them.
|
|
maxTxUnderpricedSetSize = 32768
|
|
|
|
// txGatherSlack is the interval used to collate almost-expired announces
|
|
// with network fetches.
|
|
txGatherSlack = 100 * time.Millisecond
|
|
|
|
// maxTxArrivalWait is the longest acceptable duration for the txArrivalWait
|
|
// configuration value. Longer config values will default to this.
|
|
maxTxArrivalWait = 500 * time.Millisecond
|
|
)
|
|
|
|
var (
|
|
// txFetchTimeout is the maximum allotted time to return an explicitly
|
|
// requested transaction.
|
|
txFetchTimeout = 5 * time.Second
|
|
)
|
|
|
|
var (
|
|
txAnnounceInMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/announces/in", nil)
|
|
txAnnounceKnownMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/announces/known", nil)
|
|
txAnnounceUnderpricedMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/announces/underpriced", nil)
|
|
txAnnounceDOSMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/announces/dos", nil)
|
|
|
|
txBroadcastInMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/broadcasts/in", nil)
|
|
txBroadcastKnownMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/broadcasts/known", nil)
|
|
txBroadcastUnderpricedMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/broadcasts/underpriced", nil)
|
|
txBroadcastOtherRejectMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/broadcasts/otherreject", nil)
|
|
|
|
txRequestOutMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/request/out", nil)
|
|
txRequestFailMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/request/fail", nil)
|
|
txRequestDoneMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/request/done", nil)
|
|
txRequestTimeoutMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/request/timeout", nil)
|
|
|
|
txReplyInMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/replies/in", nil)
|
|
txReplyKnownMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/replies/known", nil)
|
|
txReplyUnderpricedMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/replies/underpriced", nil)
|
|
txReplyOtherRejectMeter = metrics.NewRegisteredMeter("eth/fetcher/transaction/replies/otherreject", nil)
|
|
|
|
txFetcherWaitingPeers = metrics.NewRegisteredGauge("eth/fetcher/transaction/waiting/peers", nil)
|
|
txFetcherWaitingHashes = metrics.NewRegisteredGauge("eth/fetcher/transaction/waiting/hashes", nil)
|
|
txFetcherQueueingPeers = metrics.NewRegisteredGauge("eth/fetcher/transaction/queueing/peers", nil)
|
|
txFetcherQueueingHashes = metrics.NewRegisteredGauge("eth/fetcher/transaction/queueing/hashes", nil)
|
|
txFetcherFetchingPeers = metrics.NewRegisteredGauge("eth/fetcher/transaction/fetching/peers", nil)
|
|
txFetcherFetchingHashes = metrics.NewRegisteredGauge("eth/fetcher/transaction/fetching/hashes", nil)
|
|
)
|
|
|
|
// txAnnounce is the notification of the availability of a batch
|
|
// of new transactions in the network.
|
|
type txAnnounce struct {
|
|
origin string // Identifier of the peer originating the notification
|
|
hashes []common.Hash // Batch of transaction hashes being announced
|
|
}
|
|
|
|
// txRequest represents an in-flight transaction retrieval request destined to
|
|
// a specific peers.
|
|
type txRequest struct {
|
|
hashes []common.Hash // Transactions having been requested
|
|
stolen map[common.Hash]struct{} // Deliveries by someone else (don't re-request)
|
|
time mclock.AbsTime // Timestamp of the request
|
|
}
|
|
|
|
// txDelivery is the notification that a batch of transactions have been added
|
|
// to the pool and should be untracked.
|
|
type txDelivery struct {
|
|
origin string // Identifier of the peer originating the notification
|
|
hashes []common.Hash // Batch of transaction hashes having been delivered
|
|
direct bool // Whether this is a direct reply or a broadcast
|
|
}
|
|
|
|
// txDrop is the notification that a peer has disconnected.
|
|
type txDrop struct {
|
|
peer string
|
|
}
|
|
|
|
// TxFetcher is responsible for retrieving new transaction based on announcements.
|
|
//
|
|
// The fetcher operates in 3 stages:
|
|
// - Transactions that are newly discovered are moved into a wait list.
|
|
// - After ~500ms passes, transactions from the wait list that have not been
|
|
// broadcast to us in whole are moved into a queueing area.
|
|
// - When a connected peer doesn't have in-flight retrieval requests, any
|
|
// transaction queued up (and announced by the peer) are allocated to the
|
|
// peer and moved into a fetching status until it's fulfilled or fails.
|
|
//
|
|
// The invariants of the fetcher are:
|
|
// - Each tracked transaction (hash) must only be present in one of the
|
|
// three stages. This ensures that the fetcher operates akin to a finite
|
|
// state automata and there's do data leak.
|
|
// - Each peer that announced transactions may be scheduled retrievals, but
|
|
// only ever one concurrently. This ensures we can immediately know what is
|
|
// missing from a reply and reschedule it.
|
|
type TxFetcher struct {
|
|
notify chan *txAnnounce
|
|
cleanup chan *txDelivery
|
|
drop chan *txDrop
|
|
quit chan struct{}
|
|
|
|
underpriced mapset.Set[common.Hash] // Transactions discarded as too cheap (don't re-fetch)
|
|
|
|
// Stage 1: Waiting lists for newly discovered transactions that might be
|
|
// broadcast without needing explicit request/reply round trips.
|
|
waitlist map[common.Hash]map[string]struct{} // Transactions waiting for an potential broadcast
|
|
waittime map[common.Hash]mclock.AbsTime // Timestamps when transactions were added to the waitlist
|
|
waitslots map[string]map[common.Hash]struct{} // Waiting announcements grouped by peer (DoS protection)
|
|
|
|
// Stage 2: Queue of transactions that waiting to be allocated to some peer
|
|
// to be retrieved directly.
|
|
announces map[string]map[common.Hash]struct{} // Set of announced transactions, grouped by origin peer
|
|
announced map[common.Hash]map[string]struct{} // Set of download locations, grouped by transaction hash
|
|
|
|
// Stage 3: Set of transactions currently being retrieved, some which may be
|
|
// fulfilled and some rescheduled. Note, this step shares 'announces' from the
|
|
// previous stage to avoid having to duplicate (need it for DoS checks).
|
|
fetching map[common.Hash]string // Transaction set currently being retrieved
|
|
requests map[string]*txRequest // In-flight transaction retrievals
|
|
alternates map[common.Hash]map[string]struct{} // In-flight transaction alternate origins if retrieval fails
|
|
|
|
// Callbacks
|
|
hasTx func(common.Hash) bool // Retrieves a tx from the local txpool
|
|
addTxs func([]*types.Transaction) []error // Insert a batch of transactions into local txpool
|
|
fetchTxs func(string, []common.Hash) error // Retrieves a set of txs from a remote peer
|
|
|
|
step chan struct{} // Notification channel when the fetcher loop iterates
|
|
clock mclock.Clock // Time wrapper to simulate in tests
|
|
rand *mrand.Rand // Randomizer to use in tests instead of map range loops (soft-random)
|
|
|
|
txArrivalWait time.Duration // txArrivalWait is the time allowance before an announced transaction is explicitly requested.
|
|
}
|
|
|
|
// NewTxFetcher creates a transaction fetcher to retrieve transaction
|
|
// based on hash announcements.
|
|
func NewTxFetcher(hasTx func(common.Hash) bool, addTxs func([]*types.Transaction) []error, fetchTxs func(string, []common.Hash) error, txArrivalWait time.Duration) *TxFetcher {
|
|
return NewTxFetcherForTests(hasTx, addTxs, fetchTxs, mclock.System{}, nil, txArrivalWait)
|
|
}
|
|
|
|
// NewTxFetcherForTests is a testing method to mock out the realtime clock with
|
|
// a simulated version and the internal randomness with a deterministic one.
|
|
func NewTxFetcherForTests(
|
|
hasTx func(common.Hash) bool, addTxs func([]*types.Transaction) []error, fetchTxs func(string, []common.Hash) error,
|
|
clock mclock.Clock, rand *mrand.Rand, txArrivalWait time.Duration) *TxFetcher {
|
|
return &TxFetcher{
|
|
notify: make(chan *txAnnounce),
|
|
cleanup: make(chan *txDelivery),
|
|
drop: make(chan *txDrop),
|
|
quit: make(chan struct{}),
|
|
waitlist: make(map[common.Hash]map[string]struct{}),
|
|
waittime: make(map[common.Hash]mclock.AbsTime),
|
|
waitslots: make(map[string]map[common.Hash]struct{}),
|
|
announces: make(map[string]map[common.Hash]struct{}),
|
|
announced: make(map[common.Hash]map[string]struct{}),
|
|
fetching: make(map[common.Hash]string),
|
|
requests: make(map[string]*txRequest),
|
|
alternates: make(map[common.Hash]map[string]struct{}),
|
|
underpriced: mapset.NewSet[common.Hash](),
|
|
hasTx: hasTx,
|
|
addTxs: addTxs,
|
|
fetchTxs: fetchTxs,
|
|
clock: clock,
|
|
rand: rand,
|
|
txArrivalWait: txArrivalWait,
|
|
}
|
|
}
|
|
|
|
// Notify announces the fetcher of the potential availability of a new batch of
|
|
// transactions in the network.
|
|
func (f *TxFetcher) Notify(peer string, hashes []common.Hash) error {
|
|
// Keep track of all the announced transactions
|
|
txAnnounceInMeter.Mark(int64(len(hashes)))
|
|
|
|
// Skip any transaction announcements that we already know of, or that we've
|
|
// previously marked as cheap and discarded. This check is of course racy,
|
|
// because multiple concurrent notifies will still manage to pass it, but it's
|
|
// still valuable to check here because it runs concurrent to the internal
|
|
// loop, so anything caught here is time saved internally.
|
|
var (
|
|
unknowns = make([]common.Hash, 0, len(hashes))
|
|
duplicate, underpriced int64
|
|
)
|
|
|
|
for _, hash := range hashes {
|
|
switch {
|
|
case f.hasTx(hash):
|
|
duplicate++
|
|
|
|
case f.underpriced.Contains(hash):
|
|
underpriced++
|
|
|
|
default:
|
|
unknowns = append(unknowns, hash)
|
|
}
|
|
}
|
|
|
|
txAnnounceKnownMeter.Mark(duplicate)
|
|
txAnnounceUnderpricedMeter.Mark(underpriced)
|
|
|
|
// If anything's left to announce, push it into the internal loop
|
|
if len(unknowns) == 0 {
|
|
return nil
|
|
}
|
|
|
|
announce := &txAnnounce{
|
|
origin: peer,
|
|
hashes: unknowns,
|
|
}
|
|
select {
|
|
case f.notify <- announce:
|
|
return nil
|
|
case <-f.quit:
|
|
return errTerminated
|
|
}
|
|
}
|
|
|
|
// Enqueue imports a batch of received transaction into the transaction pool
|
|
// and the fetcher. This method may be called by both transaction broadcasts and
|
|
// direct request replies. The differentiation is important so the fetcher can
|
|
// re-schedule missing transactions as soon as possible.
|
|
func (f *TxFetcher) Enqueue(peer string, txs []*types.Transaction, direct bool) error {
|
|
var (
|
|
inMeter = txReplyInMeter
|
|
knownMeter = txReplyKnownMeter
|
|
underpricedMeter = txReplyUnderpricedMeter
|
|
otherRejectMeter = txReplyOtherRejectMeter
|
|
)
|
|
|
|
if !direct {
|
|
inMeter = txBroadcastInMeter
|
|
knownMeter = txBroadcastKnownMeter
|
|
underpricedMeter = txBroadcastUnderpricedMeter
|
|
otherRejectMeter = txBroadcastOtherRejectMeter
|
|
}
|
|
// Keep track of all the propagated transactions
|
|
inMeter.Mark(int64(len(txs)))
|
|
|
|
// Push all the transactions into the pool, tracking underpriced ones to avoid
|
|
// re-requesting them and dropping the peer in case of malicious transfers.
|
|
var (
|
|
added = make([]common.Hash, 0, len(txs))
|
|
)
|
|
// proceed in batches
|
|
for i := 0; i < len(txs); i += 128 {
|
|
end := i + 128
|
|
if end > len(txs) {
|
|
end = len(txs)
|
|
}
|
|
|
|
var (
|
|
duplicate int64
|
|
underpriced int64
|
|
otherreject int64
|
|
)
|
|
|
|
batch := txs[i:end]
|
|
for j, err := range f.addTxs(batch) {
|
|
// Track the transaction hash if the price is too low for us.
|
|
// Avoid re-request this transaction when we receive another
|
|
// announcement.
|
|
if errors.Is(err, txpool.ErrUnderpriced) || errors.Is(err, txpool.ErrReplaceUnderpriced) {
|
|
for f.underpriced.Cardinality() >= maxTxUnderpricedSetSize {
|
|
f.underpriced.Pop()
|
|
}
|
|
f.underpriced.Add(batch[j].Hash())
|
|
}
|
|
// Track a few interesting failure types
|
|
switch {
|
|
case err == nil: // Noop, but need to handle to not count these
|
|
|
|
case errors.Is(err, txpool.ErrAlreadyKnown):
|
|
duplicate++
|
|
|
|
case errors.Is(err, txpool.ErrUnderpriced) || errors.Is(err, txpool.ErrReplaceUnderpriced):
|
|
underpriced++
|
|
|
|
default:
|
|
otherreject++
|
|
}
|
|
|
|
added = append(added, batch[j].Hash())
|
|
}
|
|
|
|
knownMeter.Mark(duplicate)
|
|
underpricedMeter.Mark(underpriced)
|
|
otherRejectMeter.Mark(otherreject)
|
|
|
|
// If 'other reject' is >25% of the deliveries in any batch, sleep a bit.
|
|
if otherreject > 128/4 {
|
|
time.Sleep(200 * time.Millisecond)
|
|
log.Warn("Peer delivering stale transactions", "peer", peer, "rejected", otherreject)
|
|
}
|
|
}
|
|
select {
|
|
case f.cleanup <- &txDelivery{origin: peer, hashes: added, direct: direct}:
|
|
return nil
|
|
case <-f.quit:
|
|
return errTerminated
|
|
}
|
|
}
|
|
|
|
// Drop should be called when a peer disconnects. It cleans up all the internal
|
|
// data structures of the given node.
|
|
func (f *TxFetcher) Drop(peer string) error {
|
|
select {
|
|
case f.drop <- &txDrop{peer: peer}:
|
|
return nil
|
|
case <-f.quit:
|
|
return errTerminated
|
|
}
|
|
}
|
|
|
|
// Start boots up the announcement based synchroniser, accepting and processing
|
|
// hash notifications and block fetches until termination requested.
|
|
func (f *TxFetcher) Start() {
|
|
// the txArrivalWait duration should not be less than the txGatherSlack duration
|
|
if f.txArrivalWait < txGatherSlack {
|
|
f.txArrivalWait = txGatherSlack
|
|
}
|
|
|
|
// the txArrivalWait duration should not be greater than the maxTxArrivalWait duration
|
|
if f.txArrivalWait > maxTxArrivalWait {
|
|
f.txArrivalWait = maxTxArrivalWait
|
|
}
|
|
|
|
go f.loop()
|
|
}
|
|
|
|
// Stop terminates the announcement based synchroniser, canceling all pending
|
|
// operations.
|
|
func (f *TxFetcher) Stop() {
|
|
close(f.quit)
|
|
}
|
|
|
|
func (f *TxFetcher) loop() {
|
|
var (
|
|
waitTimer = new(mclock.Timer)
|
|
timeoutTimer = new(mclock.Timer)
|
|
|
|
waitTrigger = make(chan struct{}, 1)
|
|
timeoutTrigger = make(chan struct{}, 1)
|
|
)
|
|
|
|
log.Info("TxFetcher", "txArrivalWait", f.txArrivalWait.String())
|
|
|
|
for {
|
|
select {
|
|
case ann := <-f.notify:
|
|
// Drop part of the new announcements if there are too many accumulated.
|
|
// Note, we could but do not filter already known transactions here as
|
|
// the probability of something arriving between this call and the pre-
|
|
// filter outside is essentially zero.
|
|
used := len(f.waitslots[ann.origin]) + len(f.announces[ann.origin])
|
|
if used >= maxTxAnnounces {
|
|
// This can happen if a set of transactions are requested but not
|
|
// all fulfilled, so the remainder are rescheduled without the cap
|
|
// check. Should be fine as the limit is in the thousands and the
|
|
// request size in the hundreds.
|
|
txAnnounceDOSMeter.Mark(int64(len(ann.hashes)))
|
|
break
|
|
}
|
|
|
|
want := used + len(ann.hashes)
|
|
if want > maxTxAnnounces {
|
|
txAnnounceDOSMeter.Mark(int64(want - maxTxAnnounces))
|
|
ann.hashes = ann.hashes[:want-maxTxAnnounces]
|
|
}
|
|
// All is well, schedule the remainder of the transactions
|
|
idleWait := len(f.waittime) == 0
|
|
_, oldPeer := f.announces[ann.origin]
|
|
|
|
for _, hash := range ann.hashes {
|
|
// If the transaction is already downloading, add it to the list
|
|
// of possible alternates (in case the current retrieval fails) and
|
|
// also account it for the peer.
|
|
if f.alternates[hash] != nil {
|
|
f.alternates[hash][ann.origin] = struct{}{}
|
|
|
|
// Stage 2 and 3 share the set of origins per tx
|
|
if announces := f.announces[ann.origin]; announces != nil {
|
|
announces[hash] = struct{}{}
|
|
} else {
|
|
f.announces[ann.origin] = map[common.Hash]struct{}{hash: {}}
|
|
}
|
|
|
|
continue
|
|
}
|
|
// If the transaction is not downloading, but is already queued
|
|
// from a different peer, track it for the new peer too.
|
|
if f.announced[hash] != nil {
|
|
f.announced[hash][ann.origin] = struct{}{}
|
|
|
|
// Stage 2 and 3 share the set of origins per tx
|
|
if announces := f.announces[ann.origin]; announces != nil {
|
|
announces[hash] = struct{}{}
|
|
} else {
|
|
f.announces[ann.origin] = map[common.Hash]struct{}{hash: {}}
|
|
}
|
|
|
|
continue
|
|
}
|
|
// If the transaction is already known to the fetcher, but not
|
|
// yet downloading, add the peer as an alternate origin in the
|
|
// waiting list.
|
|
if f.waitlist[hash] != nil {
|
|
f.waitlist[hash][ann.origin] = struct{}{}
|
|
|
|
if waitslots := f.waitslots[ann.origin]; waitslots != nil {
|
|
waitslots[hash] = struct{}{}
|
|
} else {
|
|
f.waitslots[ann.origin] = map[common.Hash]struct{}{hash: {}}
|
|
}
|
|
|
|
continue
|
|
}
|
|
// Transaction unknown to the fetcher, insert it into the waiting list
|
|
f.waitlist[hash] = map[string]struct{}{ann.origin: {}}
|
|
f.waittime[hash] = f.clock.Now()
|
|
|
|
if waitslots := f.waitslots[ann.origin]; waitslots != nil {
|
|
waitslots[hash] = struct{}{}
|
|
} else {
|
|
f.waitslots[ann.origin] = map[common.Hash]struct{}{hash: {}}
|
|
}
|
|
}
|
|
// If a new item was added to the waitlist, schedule it into the fetcher
|
|
if idleWait && len(f.waittime) > 0 {
|
|
f.rescheduleWait(waitTimer, waitTrigger)
|
|
}
|
|
// If this peer is new and announced something already queued, maybe
|
|
// request transactions from them
|
|
if !oldPeer && len(f.announces[ann.origin]) > 0 {
|
|
f.scheduleFetches(timeoutTimer, timeoutTrigger, map[string]struct{}{ann.origin: {}})
|
|
}
|
|
|
|
case <-waitTrigger:
|
|
// At least one transaction's waiting time ran out, push all expired
|
|
// ones into the retrieval queues
|
|
actives := make(map[string]struct{})
|
|
|
|
for hash, instance := range f.waittime {
|
|
if time.Duration(f.clock.Now()-instance)+txGatherSlack > f.txArrivalWait {
|
|
// Transaction expired without propagation, schedule for retrieval
|
|
if f.announced[hash] != nil {
|
|
panic("announce tracker already contains waitlist item")
|
|
}
|
|
|
|
f.announced[hash] = f.waitlist[hash]
|
|
for peer := range f.waitlist[hash] {
|
|
if announces := f.announces[peer]; announces != nil {
|
|
announces[hash] = struct{}{}
|
|
} else {
|
|
f.announces[peer] = map[common.Hash]struct{}{hash: {}}
|
|
}
|
|
|
|
delete(f.waitslots[peer], hash)
|
|
|
|
if len(f.waitslots[peer]) == 0 {
|
|
delete(f.waitslots, peer)
|
|
}
|
|
|
|
actives[peer] = struct{}{}
|
|
}
|
|
|
|
delete(f.waittime, hash)
|
|
delete(f.waitlist, hash)
|
|
}
|
|
}
|
|
// If transactions are still waiting for propagation, reschedule the wait timer
|
|
if len(f.waittime) > 0 {
|
|
f.rescheduleWait(waitTimer, waitTrigger)
|
|
}
|
|
// If any peers became active and are idle, request transactions from them
|
|
if len(actives) > 0 {
|
|
f.scheduleFetches(timeoutTimer, timeoutTrigger, actives)
|
|
}
|
|
|
|
case <-timeoutTrigger:
|
|
// Clean up any expired retrievals and avoid re-requesting them from the
|
|
// same peer (either overloaded or malicious, useless in both cases). We
|
|
// could also penalize (Drop), but there's nothing to gain, and if could
|
|
// possibly further increase the load on it.
|
|
for peer, req := range f.requests {
|
|
if time.Duration(f.clock.Now()-req.time)+txGatherSlack > txFetchTimeout {
|
|
txRequestTimeoutMeter.Mark(int64(len(req.hashes)))
|
|
|
|
// Reschedule all the not-yet-delivered fetches to alternate peers
|
|
for _, hash := range req.hashes {
|
|
// Skip rescheduling hashes already delivered by someone else
|
|
if req.stolen != nil {
|
|
if _, ok := req.stolen[hash]; ok {
|
|
continue
|
|
}
|
|
}
|
|
// Move the delivery back from fetching to queued
|
|
if _, ok := f.announced[hash]; ok {
|
|
panic("announced tracker already contains alternate item")
|
|
}
|
|
|
|
if f.alternates[hash] != nil { // nil if tx was broadcast during fetch
|
|
f.announced[hash] = f.alternates[hash]
|
|
}
|
|
|
|
delete(f.announced[hash], peer)
|
|
|
|
if len(f.announced[hash]) == 0 {
|
|
delete(f.announced, hash)
|
|
}
|
|
|
|
delete(f.announces[peer], hash)
|
|
delete(f.alternates, hash)
|
|
delete(f.fetching, hash)
|
|
}
|
|
|
|
if len(f.announces[peer]) == 0 {
|
|
delete(f.announces, peer)
|
|
}
|
|
// Keep track of the request as dangling, but never expire
|
|
f.requests[peer].hashes = nil
|
|
}
|
|
}
|
|
// Schedule a new transaction retrieval
|
|
f.scheduleFetches(timeoutTimer, timeoutTrigger, nil)
|
|
|
|
// No idea if we scheduled something or not, trigger the timer if needed
|
|
// TODO(karalabe): this is kind of lame, can't we dump it into scheduleFetches somehow?
|
|
f.rescheduleTimeout(timeoutTimer, timeoutTrigger)
|
|
|
|
case delivery := <-f.cleanup:
|
|
// Independent if the delivery was direct or broadcast, remove all
|
|
// traces of the hash from internal trackers
|
|
for _, hash := range delivery.hashes {
|
|
if _, ok := f.waitlist[hash]; ok {
|
|
for peer, txset := range f.waitslots {
|
|
delete(txset, hash)
|
|
|
|
if len(txset) == 0 {
|
|
delete(f.waitslots, peer)
|
|
}
|
|
}
|
|
|
|
delete(f.waitlist, hash)
|
|
delete(f.waittime, hash)
|
|
} else {
|
|
for peer, txset := range f.announces {
|
|
delete(txset, hash)
|
|
|
|
if len(txset) == 0 {
|
|
delete(f.announces, peer)
|
|
}
|
|
}
|
|
|
|
delete(f.announced, hash)
|
|
delete(f.alternates, hash)
|
|
|
|
// If a transaction currently being fetched from a different
|
|
// origin was delivered (delivery stolen), mark it so the
|
|
// actual delivery won't double schedule it.
|
|
if origin, ok := f.fetching[hash]; ok && (origin != delivery.origin || !delivery.direct) {
|
|
stolen := f.requests[origin].stolen
|
|
if stolen == nil {
|
|
f.requests[origin].stolen = make(map[common.Hash]struct{})
|
|
stolen = f.requests[origin].stolen
|
|
}
|
|
|
|
stolen[hash] = struct{}{}
|
|
}
|
|
|
|
delete(f.fetching, hash)
|
|
}
|
|
}
|
|
// In case of a direct delivery, also reschedule anything missing
|
|
// from the original query
|
|
if delivery.direct {
|
|
// Mark the requesting successful (independent of individual status)
|
|
txRequestDoneMeter.Mark(int64(len(delivery.hashes)))
|
|
|
|
// Make sure something was pending, nuke it
|
|
req := f.requests[delivery.origin]
|
|
if req == nil {
|
|
log.Warn("Unexpected transaction delivery", "peer", delivery.origin)
|
|
break
|
|
}
|
|
|
|
delete(f.requests, delivery.origin)
|
|
|
|
// Anything not delivered should be re-scheduled (with or without
|
|
// this peer, depending on the response cutoff)
|
|
delivered := make(map[common.Hash]struct{})
|
|
for _, hash := range delivery.hashes {
|
|
delivered[hash] = struct{}{}
|
|
}
|
|
|
|
cutoff := len(req.hashes) // If nothing is delivered, assume everything is missing, don't retry!!!
|
|
|
|
for i, hash := range req.hashes {
|
|
if _, ok := delivered[hash]; ok {
|
|
cutoff = i
|
|
}
|
|
}
|
|
// Reschedule missing hashes from alternates, not-fulfilled from alt+self
|
|
for i, hash := range req.hashes {
|
|
// Skip rescheduling hashes already delivered by someone else
|
|
if req.stolen != nil {
|
|
if _, ok := req.stolen[hash]; ok {
|
|
continue
|
|
}
|
|
}
|
|
|
|
if _, ok := delivered[hash]; !ok {
|
|
if i < cutoff {
|
|
delete(f.alternates[hash], delivery.origin)
|
|
delete(f.announces[delivery.origin], hash)
|
|
|
|
if len(f.announces[delivery.origin]) == 0 {
|
|
delete(f.announces, delivery.origin)
|
|
}
|
|
}
|
|
|
|
if len(f.alternates[hash]) > 0 {
|
|
if _, ok := f.announced[hash]; ok {
|
|
panic(fmt.Sprintf("announced tracker already contains alternate item: %v", f.announced[hash]))
|
|
}
|
|
|
|
f.announced[hash] = f.alternates[hash]
|
|
}
|
|
}
|
|
|
|
delete(f.alternates, hash)
|
|
delete(f.fetching, hash)
|
|
}
|
|
// Something was delivered, try to reschedule requests
|
|
f.scheduleFetches(timeoutTimer, timeoutTrigger, nil) // Partial delivery may enable others to deliver too
|
|
}
|
|
|
|
case drop := <-f.drop:
|
|
// A peer was dropped, remove all traces of it
|
|
if _, ok := f.waitslots[drop.peer]; ok {
|
|
for hash := range f.waitslots[drop.peer] {
|
|
delete(f.waitlist[hash], drop.peer)
|
|
|
|
if len(f.waitlist[hash]) == 0 {
|
|
delete(f.waitlist, hash)
|
|
delete(f.waittime, hash)
|
|
}
|
|
}
|
|
|
|
delete(f.waitslots, drop.peer)
|
|
|
|
if len(f.waitlist) > 0 {
|
|
f.rescheduleWait(waitTimer, waitTrigger)
|
|
}
|
|
}
|
|
// Clean up any active requests
|
|
var request *txRequest
|
|
if request = f.requests[drop.peer]; request != nil {
|
|
for _, hash := range request.hashes {
|
|
// Skip rescheduling hashes already delivered by someone else
|
|
if request.stolen != nil {
|
|
if _, ok := request.stolen[hash]; ok {
|
|
continue
|
|
}
|
|
}
|
|
// Undelivered hash, reschedule if there's an alternative origin available
|
|
delete(f.alternates[hash], drop.peer)
|
|
|
|
if len(f.alternates[hash]) == 0 {
|
|
delete(f.alternates, hash)
|
|
} else {
|
|
f.announced[hash] = f.alternates[hash]
|
|
delete(f.alternates, hash)
|
|
}
|
|
|
|
delete(f.fetching, hash)
|
|
}
|
|
|
|
delete(f.requests, drop.peer)
|
|
}
|
|
// Clean up general announcement tracking
|
|
if _, ok := f.announces[drop.peer]; ok {
|
|
for hash := range f.announces[drop.peer] {
|
|
delete(f.announced[hash], drop.peer)
|
|
|
|
if len(f.announced[hash]) == 0 {
|
|
delete(f.announced, hash)
|
|
}
|
|
}
|
|
|
|
delete(f.announces, drop.peer)
|
|
}
|
|
// If a request was cancelled, check if anything needs to be rescheduled
|
|
if request != nil {
|
|
f.scheduleFetches(timeoutTimer, timeoutTrigger, nil)
|
|
f.rescheduleTimeout(timeoutTimer, timeoutTrigger)
|
|
}
|
|
|
|
case <-f.quit:
|
|
return
|
|
}
|
|
// No idea what happened, but bump some sanity metrics
|
|
txFetcherWaitingPeers.Update(int64(len(f.waitslots)))
|
|
txFetcherWaitingHashes.Update(int64(len(f.waitlist)))
|
|
txFetcherQueueingPeers.Update(int64(len(f.announces) - len(f.requests)))
|
|
txFetcherQueueingHashes.Update(int64(len(f.announced)))
|
|
txFetcherFetchingPeers.Update(int64(len(f.requests)))
|
|
txFetcherFetchingHashes.Update(int64(len(f.fetching)))
|
|
|
|
// Loop did something, ping the step notifier if needed (tests)
|
|
if f.step != nil {
|
|
f.step <- struct{}{}
|
|
}
|
|
}
|
|
}
|
|
|
|
// rescheduleWait iterates over all the transactions currently in the waitlist
|
|
// and schedules the movement into the fetcher for the earliest.
|
|
//
|
|
// The method has a granularity of 'gatherSlack', since there's not much point in
|
|
// spinning over all the transactions just to maybe find one that should trigger
|
|
// a few ms earlier.
|
|
func (f *TxFetcher) rescheduleWait(timer *mclock.Timer, trigger chan struct{}) {
|
|
if *timer != nil {
|
|
(*timer).Stop()
|
|
}
|
|
|
|
now := f.clock.Now()
|
|
|
|
earliest := now
|
|
for _, instance := range f.waittime {
|
|
if earliest > instance {
|
|
earliest = instance
|
|
if f.txArrivalWait-time.Duration(now-earliest) < gatherSlack {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
*timer = f.clock.AfterFunc(
|
|
f.txArrivalWait-time.Duration(now-earliest),
|
|
func() { trigger <- struct{}{} },
|
|
)
|
|
}
|
|
|
|
// rescheduleTimeout iterates over all the transactions currently in flight and
|
|
// schedules a cleanup run when the first would trigger.
|
|
//
|
|
// The method has a granularity of 'gatherSlack', since there's not much point in
|
|
// spinning over all the transactions just to maybe find one that should trigger
|
|
// a few ms earlier.
|
|
//
|
|
// This method is a bit "flaky" "by design". In theory the timeout timer only ever
|
|
// should be rescheduled if some request is pending. In practice, a timeout will
|
|
// cause the timer to be rescheduled every 5 secs (until the peer comes through or
|
|
// disconnects). This is a limitation of the fetcher code because we don't trac
|
|
// pending requests and timed out requests separately. Without double tracking, if
|
|
// we simply didn't reschedule the timer on all-timeout then the timer would never
|
|
// be set again since len(request) > 0 => something's running.
|
|
func (f *TxFetcher) rescheduleTimeout(timer *mclock.Timer, trigger chan struct{}) {
|
|
if *timer != nil {
|
|
(*timer).Stop()
|
|
}
|
|
|
|
now := f.clock.Now()
|
|
|
|
earliest := now
|
|
|
|
for _, req := range f.requests {
|
|
// If this request already timed out, skip it altogether
|
|
if req.hashes == nil {
|
|
continue
|
|
}
|
|
|
|
if earliest > req.time {
|
|
earliest = req.time
|
|
if txFetchTimeout-time.Duration(now-earliest) < gatherSlack {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
*timer = f.clock.AfterFunc(txFetchTimeout-time.Duration(now-earliest), func() {
|
|
trigger <- struct{}{}
|
|
})
|
|
}
|
|
|
|
// scheduleFetches starts a batch of retrievals for all available idle peers.
|
|
func (f *TxFetcher) scheduleFetches(timer *mclock.Timer, timeout chan struct{}, whitelist map[string]struct{}) {
|
|
// Gather the set of peers we want to retrieve from (default to all)
|
|
actives := whitelist
|
|
if actives == nil {
|
|
actives = make(map[string]struct{})
|
|
for peer := range f.announces {
|
|
actives[peer] = struct{}{}
|
|
}
|
|
}
|
|
|
|
if len(actives) == 0 {
|
|
return
|
|
}
|
|
// For each active peer, try to schedule some transaction fetches
|
|
idle := len(f.requests) == 0
|
|
|
|
f.forEachPeer(actives, func(peer string) {
|
|
if f.requests[peer] != nil {
|
|
return // continue in the for-each
|
|
}
|
|
|
|
if len(f.announces[peer]) == 0 {
|
|
return // continue in the for-each
|
|
}
|
|
|
|
hashes := make([]common.Hash, 0, maxTxRetrievals)
|
|
|
|
f.forEachHash(f.announces[peer], func(hash common.Hash) bool {
|
|
if _, ok := f.fetching[hash]; !ok {
|
|
// Mark the hash as fetching and stash away possible alternates
|
|
f.fetching[hash] = peer
|
|
|
|
if _, ok := f.alternates[hash]; ok {
|
|
panic(fmt.Sprintf("alternate tracker already contains fetching item: %v", f.alternates[hash]))
|
|
}
|
|
|
|
f.alternates[hash] = f.announced[hash]
|
|
delete(f.announced, hash)
|
|
|
|
// Accumulate the hash and stop if the limit was reached
|
|
hashes = append(hashes, hash)
|
|
if len(hashes) >= maxTxRetrievals {
|
|
return false // break in the for-each
|
|
}
|
|
}
|
|
|
|
return true // continue in the for-each
|
|
})
|
|
// If any hashes were allocated, request them from the peer
|
|
if len(hashes) > 0 {
|
|
f.requests[peer] = &txRequest{hashes: hashes, time: f.clock.Now()}
|
|
txRequestOutMeter.Mark(int64(len(hashes)))
|
|
|
|
go func(peer string, hashes []common.Hash) {
|
|
// Try to fetch the transactions, but in case of a request
|
|
// failure (e.g. peer disconnected), reschedule the hashes.
|
|
if err := f.fetchTxs(peer, hashes); err != nil {
|
|
txRequestFailMeter.Mark(int64(len(hashes)))
|
|
f.Drop(peer)
|
|
}
|
|
}(peer, hashes)
|
|
}
|
|
})
|
|
// If a new request was fired, schedule a timeout timer
|
|
if idle && len(f.requests) > 0 {
|
|
f.rescheduleTimeout(timer, timeout)
|
|
}
|
|
}
|
|
|
|
// forEachPeer does a range loop over a map of peers in production, but during
|
|
// testing it does a deterministic sorted random to allow reproducing issues.
|
|
func (f *TxFetcher) forEachPeer(peers map[string]struct{}, do func(peer string)) {
|
|
// If we're running production, use whatever Go's map gives us
|
|
if f.rand == nil {
|
|
for peer := range peers {
|
|
do(peer)
|
|
}
|
|
|
|
return
|
|
}
|
|
// We're running the test suite, make iteration deterministic
|
|
list := make([]string, 0, len(peers))
|
|
for peer := range peers {
|
|
list = append(list, peer)
|
|
}
|
|
|
|
sort.Strings(list)
|
|
rotateStrings(list, f.rand.Intn(len(list)))
|
|
|
|
for _, peer := range list {
|
|
do(peer)
|
|
}
|
|
}
|
|
|
|
// forEachHash does a range loop over a map of hashes in production, but during
|
|
// testing it does a deterministic sorted random to allow reproducing issues.
|
|
func (f *TxFetcher) forEachHash(hashes map[common.Hash]struct{}, do func(hash common.Hash) bool) {
|
|
// If we're running production, use whatever Go's map gives us
|
|
if f.rand == nil {
|
|
for hash := range hashes {
|
|
if !do(hash) {
|
|
return
|
|
}
|
|
}
|
|
|
|
return
|
|
}
|
|
// We're running the test suite, make iteration deterministic
|
|
list := make([]common.Hash, 0, len(hashes))
|
|
for hash := range hashes {
|
|
list = append(list, hash)
|
|
}
|
|
|
|
sortHashes(list)
|
|
rotateHashes(list, f.rand.Intn(len(list)))
|
|
|
|
for _, hash := range list {
|
|
if !do(hash) {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// rotateStrings rotates the contents of a slice by n steps. This method is only
|
|
// used in tests to simulate random map iteration but keep it deterministic.
|
|
func rotateStrings(slice []string, n int) {
|
|
orig := make([]string, len(slice))
|
|
copy(orig, slice)
|
|
|
|
for i := 0; i < len(orig); i++ {
|
|
slice[i] = orig[(i+n)%len(orig)]
|
|
}
|
|
}
|
|
|
|
// sortHashes sorts a slice of hashes. This method is only used in tests in order
|
|
// to simulate random map iteration but keep it deterministic.
|
|
func sortHashes(slice []common.Hash) {
|
|
for i := 0; i < len(slice); i++ {
|
|
for j := i + 1; j < len(slice); j++ {
|
|
if bytes.Compare(slice[i][:], slice[j][:]) > 0 {
|
|
slice[i], slice[j] = slice[j], slice[i]
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// rotateHashes rotates the contents of a slice by n steps. This method is only
|
|
// used in tests to simulate random map iteration but keep it deterministic.
|
|
func rotateHashes(slice []common.Hash, n int) {
|
|
orig := make([]common.Hash, len(slice))
|
|
copy(orig, slice)
|
|
|
|
for i := 0; i < len(orig); i++ {
|
|
slice[i] = orig[(i+n)%len(orig)]
|
|
}
|
|
}
|