mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-07-27 07:06:42 +00:00
Merge tag 'v1.15.8' into release/geth-1.x-fh3.0
This commit is contained in:
commit
d610166694
95 changed files with 2479 additions and 1314 deletions
|
|
@ -1,31 +1,25 @@
|
||||||
# This file configures github.com/golangci/golangci-lint.
|
# This file configures github.com/golangci/golangci-lint.
|
||||||
|
version: '2'
|
||||||
run:
|
run:
|
||||||
timeout: 20m
|
|
||||||
tests: true
|
tests: true
|
||||||
|
|
||||||
linters:
|
linters:
|
||||||
disable-all: true
|
default: none
|
||||||
enable:
|
enable:
|
||||||
- goimports
|
|
||||||
- gosimple
|
|
||||||
- govet
|
|
||||||
- ineffassign
|
|
||||||
- misspell
|
|
||||||
- unconvert
|
|
||||||
- typecheck
|
|
||||||
- unused
|
|
||||||
- staticcheck
|
|
||||||
- bidichk
|
- bidichk
|
||||||
- durationcheck
|
|
||||||
- copyloopvar
|
- copyloopvar
|
||||||
- whitespace
|
|
||||||
- revive # only certain checks enabled
|
|
||||||
- durationcheck
|
- durationcheck
|
||||||
- gocheckcompilerdirectives
|
- gocheckcompilerdirectives
|
||||||
- reassign
|
- govet
|
||||||
|
- ineffassign
|
||||||
- mirror
|
- mirror
|
||||||
|
- misspell
|
||||||
|
- reassign
|
||||||
|
- revive # only certain checks enabled
|
||||||
|
- staticcheck
|
||||||
|
- unconvert
|
||||||
|
- unused
|
||||||
- usetesting
|
- usetesting
|
||||||
|
- whitespace
|
||||||
### linters we tried and will not be using:
|
### linters we tried and will not be using:
|
||||||
###
|
###
|
||||||
# - structcheck # lots of false positives
|
# - structcheck # lots of false positives
|
||||||
|
|
@ -36,10 +30,11 @@ linters:
|
||||||
# - exhaustive # silly check
|
# - exhaustive # silly check
|
||||||
# - makezero # false positives
|
# - makezero # false positives
|
||||||
# - nilerr # several intentional
|
# - nilerr # several intentional
|
||||||
|
settings:
|
||||||
linters-settings:
|
staticcheck:
|
||||||
gofmt:
|
checks:
|
||||||
simplify: true
|
# disable Quickfixes
|
||||||
|
- -QF1*
|
||||||
revive:
|
revive:
|
||||||
enable-all-rules: false
|
enable-all-rules: false
|
||||||
# here we enable specific useful rules
|
# here we enable specific useful rules
|
||||||
|
|
@ -48,22 +43,23 @@ linters-settings:
|
||||||
- name: receiver-naming
|
- name: receiver-naming
|
||||||
severity: warning
|
severity: warning
|
||||||
disabled: false
|
disabled: false
|
||||||
exclude: [""]
|
exclude:
|
||||||
|
- ''
|
||||||
issues:
|
exclusions:
|
||||||
# default is true. Enables skipping of directories:
|
generated: lax
|
||||||
# vendor$, third_party$, testdata$, examples$, Godeps$, builtin$
|
presets:
|
||||||
exclude-dirs-use-default: true
|
- comments
|
||||||
exclude-files:
|
- common-false-positives
|
||||||
- core/genesis_alloc.go
|
- legacy
|
||||||
exclude-rules:
|
- std-error-handling
|
||||||
- path: crypto/bn256/cloudflare/optate.go
|
rules:
|
||||||
linters:
|
- linters:
|
||||||
- deadcode
|
- deadcode
|
||||||
- staticcheck
|
- staticcheck
|
||||||
- path: crypto/bn256/
|
path: crypto/bn256/cloudflare/optate.go
|
||||||
linters:
|
- linters:
|
||||||
- revive
|
- revive
|
||||||
|
path: crypto/bn256/
|
||||||
- path: cmd/utils/flags.go
|
- path: cmd/utils/flags.go
|
||||||
text: "SA1019: cfg.TxLookupLimit is deprecated: use 'TransactionHistory' instead."
|
text: "SA1019: cfg.TxLookupLimit is deprecated: use 'TransactionHistory' instead."
|
||||||
- path: cmd/utils/flags.go
|
- path: cmd/utils/flags.go
|
||||||
|
|
@ -72,8 +68,29 @@ issues:
|
||||||
text: 'SA1019: "golang.org/x/crypto/openpgp" is deprecated: this package is unmaintained except for security fixes.'
|
text: 'SA1019: "golang.org/x/crypto/openpgp" is deprecated: this package is unmaintained except for security fixes.'
|
||||||
- path: core/vm/contracts.go
|
- path: core/vm/contracts.go
|
||||||
text: 'SA1019: "golang.org/x/crypto/ripemd160" is deprecated: RIPEMD-160 is a legacy hash and should not be used for new applications.'
|
text: 'SA1019: "golang.org/x/crypto/ripemd160" is deprecated: RIPEMD-160 is a legacy hash and should not be used for new applications.'
|
||||||
exclude:
|
- path: (.+)\.go$
|
||||||
- 'SA1019: event.TypeMux is deprecated: use Feed'
|
text: 'SA1019: event.TypeMux is deprecated: use Feed'
|
||||||
- 'SA1019: strings.Title is deprecated'
|
- path: (.+)\.go$
|
||||||
- 'SA1019: strings.Title has been deprecated since Go 1.18 and an alternative has been available since Go 1.0: The rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.'
|
text: 'SA1019: strings.Title is deprecated'
|
||||||
- 'SA1029: should not use built-in type string as key for value'
|
- path: (.+)\.go$
|
||||||
|
text: 'SA1019: strings.Title has been deprecated since Go 1.18 and an alternative has been available since Go 1.0: The rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.'
|
||||||
|
- path: (.+)\.go$
|
||||||
|
text: 'SA1029: should not use built-in type string as key for value'
|
||||||
|
paths:
|
||||||
|
- core/genesis_alloc.go
|
||||||
|
- third_party$
|
||||||
|
- builtin$
|
||||||
|
- examples$
|
||||||
|
formatters:
|
||||||
|
enable:
|
||||||
|
- goimports
|
||||||
|
settings:
|
||||||
|
gofmt:
|
||||||
|
simplify: true
|
||||||
|
exclusions:
|
||||||
|
generated: lax
|
||||||
|
paths:
|
||||||
|
- core/genesis_alloc.go
|
||||||
|
- third_party$
|
||||||
|
- builtin$
|
||||||
|
- examples$
|
||||||
|
|
|
||||||
|
|
@ -1806,7 +1806,9 @@ var bindTests = []struct {
|
||||||
[]string{"608060405234801561001057600080fd5b50610113806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c806324ec1d3f14602d575b600080fd5b60336035565b005b7fb4b2ff75e30cb4317eaae16dd8a187dd89978df17565104caa6c2797caae27d460405180604001604052806001815260200160028152506040516078919060ba565b60405180910390a1565b6040820160008201516096600085018260ad565b50602082015160a7602085018260ad565b50505050565b60b48160d3565b82525050565b600060408201905060cd60008301846082565b92915050565b600081905091905056fea26469706673582212208823628796125bf9941ce4eda18da1be3cf2931b231708ab848e1bd7151c0c9a64736f6c63430008070033"},
|
[]string{"608060405234801561001057600080fd5b50610113806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c806324ec1d3f14602d575b600080fd5b60336035565b005b7fb4b2ff75e30cb4317eaae16dd8a187dd89978df17565104caa6c2797caae27d460405180604001604052806001815260200160028152506040516078919060ba565b60405180910390a1565b6040820160008201516096600085018260ad565b50602082015160a7602085018260ad565b50505050565b60b48160d3565b82525050565b600060408201905060cd60008301846082565b92915050565b600081905091905056fea26469706673582212208823628796125bf9941ce4eda18da1be3cf2931b231708ab848e1bd7151c0c9a64736f6c63430008070033"},
|
||||||
[]string{`[{"anonymous":false,"inputs":[{"components":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"uint256","name":"b","type":"uint256"}],"indexed":false,"internalType":"struct Test.MyStruct","name":"s","type":"tuple"}],"name":"StructEvent","type":"event"},{"inputs":[],"name":"TestEvent","outputs":[],"stateMutability":"nonpayable","type":"function"}]`},
|
[]string{`[{"anonymous":false,"inputs":[{"components":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"uint256","name":"b","type":"uint256"}],"indexed":false,"internalType":"struct Test.MyStruct","name":"s","type":"tuple"}],"name":"StructEvent","type":"event"},{"inputs":[],"name":"TestEvent","outputs":[],"stateMutability":"nonpayable","type":"function"}]`},
|
||||||
`
|
`
|
||||||
|
"context"
|
||||||
"math/big"
|
"math/big"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/ethereum/go-ethereum/accounts/abi/bind"
|
"github.com/ethereum/go-ethereum/accounts/abi/bind"
|
||||||
"github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
|
"github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
|
||||||
|
|
@ -1828,12 +1830,23 @@ var bindTests = []struct {
|
||||||
}
|
}
|
||||||
sim.Commit()
|
sim.Commit()
|
||||||
|
|
||||||
_, err = d.TestEvent(user)
|
tx, err := d.TestEvent(user)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to call contract %v", err)
|
t.Fatalf("Failed to call contract %v", err)
|
||||||
}
|
}
|
||||||
sim.Commit()
|
sim.Commit()
|
||||||
|
|
||||||
|
// Wait for the transaction to be mined
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
receipt, err := bind.WaitMined(ctx, sim, tx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to wait for tx to be mined: %v", err)
|
||||||
|
}
|
||||||
|
if receipt.Status != types.ReceiptStatusSuccessful {
|
||||||
|
t.Fatal("Transaction failed")
|
||||||
|
}
|
||||||
|
|
||||||
it, err := d.FilterStructEvent(nil)
|
it, err := d.FilterStructEvent(nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to filter contract event %v", err)
|
t.Fatalf("Failed to filter contract event %v", err)
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,7 @@ import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"math"
|
||||||
"math/big"
|
"math/big"
|
||||||
|
|
||||||
"github.com/ethereum/go-ethereum/accounts"
|
"github.com/ethereum/go-ethereum/accounts"
|
||||||
|
|
@ -249,7 +250,11 @@ func (w *trezorDriver) trezorSign(derivationPath []uint32, tx *types.Transaction
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Extract the Ethereum signature and do a sanity validation
|
// Extract the Ethereum signature and do a sanity validation
|
||||||
if len(response.GetSignatureR()) == 0 || len(response.GetSignatureS()) == 0 || response.GetSignatureV() == 0 {
|
if len(response.GetSignatureR()) == 0 || len(response.GetSignatureS()) == 0 {
|
||||||
|
return common.Address{}, nil, errors.New("reply lacks signature")
|
||||||
|
} else if response.GetSignatureV() == 0 && int(chainID.Int64()) <= (math.MaxUint32-36)/2 {
|
||||||
|
// for chainId >= (MaxUint32-36)/2, Trezor returns signature bit only
|
||||||
|
// https://github.com/trezor/trezor-mcu/pull/399
|
||||||
return common.Address{}, nil, errors.New("reply lacks signature")
|
return common.Address{}, nil, errors.New("reply lacks signature")
|
||||||
}
|
}
|
||||||
signature := append(append(response.GetSignatureR(), response.GetSignatureS()...), byte(response.GetSignatureV()))
|
signature := append(append(response.GetSignatureR(), response.GetSignatureS()...), byte(response.GetSignatureV()))
|
||||||
|
|
@ -261,8 +266,12 @@ func (w *trezorDriver) trezorSign(derivationPath []uint32, tx *types.Transaction
|
||||||
} else {
|
} else {
|
||||||
// Trezor backend does not support typed transactions yet.
|
// Trezor backend does not support typed transactions yet.
|
||||||
signer = types.NewEIP155Signer(chainID)
|
signer = types.NewEIP155Signer(chainID)
|
||||||
|
// if chainId is above (MaxUint32 - 36) / 2 then the final v values is returned
|
||||||
|
// directly. Otherwise, the returned value is 35 + chainid * 2.
|
||||||
|
if signature[64] > 1 && int(chainID.Int64()) <= (math.MaxUint32-36)/2 {
|
||||||
signature[64] -= byte(chainID.Uint64()*2 + 35)
|
signature[64] -= byte(chainID.Uint64()*2 + 35)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Inject the final signature into the transaction and sanity check the sender
|
// Inject the final signature into the transaction and sanity check the sender
|
||||||
signed, err := tx.WithSignature(signer, signature)
|
signed, err := tx.WithSignature(signer, signature)
|
||||||
|
|
|
||||||
|
|
@ -23,9 +23,11 @@ import (
|
||||||
"github.com/ethereum/go-ethereum/beacon/light/sync"
|
"github.com/ethereum/go-ethereum/beacon/light/sync"
|
||||||
"github.com/ethereum/go-ethereum/beacon/params"
|
"github.com/ethereum/go-ethereum/beacon/params"
|
||||||
"github.com/ethereum/go-ethereum/beacon/types"
|
"github.com/ethereum/go-ethereum/beacon/types"
|
||||||
|
"github.com/ethereum/go-ethereum/common"
|
||||||
"github.com/ethereum/go-ethereum/common/mclock"
|
"github.com/ethereum/go-ethereum/common/mclock"
|
||||||
"github.com/ethereum/go-ethereum/ethdb/memorydb"
|
"github.com/ethereum/go-ethereum/ethdb/memorydb"
|
||||||
"github.com/ethereum/go-ethereum/event"
|
"github.com/ethereum/go-ethereum/event"
|
||||||
|
"github.com/ethereum/go-ethereum/log"
|
||||||
"github.com/ethereum/go-ethereum/rpc"
|
"github.com/ethereum/go-ethereum/rpc"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -46,7 +48,13 @@ func NewClient(config params.ClientConfig) *Client {
|
||||||
var (
|
var (
|
||||||
db = memorydb.New()
|
db = memorydb.New()
|
||||||
committeeChain = light.NewCommitteeChain(db, &config.ChainConfig, config.Threshold, !config.NoFilter)
|
committeeChain = light.NewCommitteeChain(db, &config.ChainConfig, config.Threshold, !config.NoFilter)
|
||||||
headTracker = light.NewHeadTracker(committeeChain, config.Threshold)
|
headTracker = light.NewHeadTracker(committeeChain, config.Threshold, func(checkpoint common.Hash) {
|
||||||
|
if saved, err := config.SaveCheckpointToFile(checkpoint); saved {
|
||||||
|
log.Debug("Saved beacon checkpoint", "file", config.CheckpointFile, "checkpoint", checkpoint)
|
||||||
|
} else if err != nil {
|
||||||
|
log.Error("Failed to save beacon checkpoint", "file", config.CheckpointFile, "checkpoint", checkpoint, "error", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
)
|
)
|
||||||
headSync := sync.NewHeadSync(headTracker, committeeChain)
|
headSync := sync.NewHeadSync(headTracker, committeeChain)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,9 @@ import (
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/ethereum/go-ethereum/beacon/params"
|
||||||
"github.com/ethereum/go-ethereum/beacon/types"
|
"github.com/ethereum/go-ethereum/beacon/types"
|
||||||
|
"github.com/ethereum/go-ethereum/common"
|
||||||
"github.com/ethereum/go-ethereum/log"
|
"github.com/ethereum/go-ethereum/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -38,13 +40,15 @@ type HeadTracker struct {
|
||||||
hasFinalityUpdate bool
|
hasFinalityUpdate bool
|
||||||
prefetchHead types.HeadInfo
|
prefetchHead types.HeadInfo
|
||||||
changeCounter uint64
|
changeCounter uint64
|
||||||
|
saveCheckpoint func(common.Hash)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewHeadTracker creates a new HeadTracker.
|
// NewHeadTracker creates a new HeadTracker.
|
||||||
func NewHeadTracker(committeeChain *CommitteeChain, minSignerCount int) *HeadTracker {
|
func NewHeadTracker(committeeChain *CommitteeChain, minSignerCount int, saveCheckpoint func(common.Hash)) *HeadTracker {
|
||||||
return &HeadTracker{
|
return &HeadTracker{
|
||||||
committeeChain: committeeChain,
|
committeeChain: committeeChain,
|
||||||
minSignerCount: minSignerCount,
|
minSignerCount: minSignerCount,
|
||||||
|
saveCheckpoint: saveCheckpoint,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -100,6 +104,9 @@ func (h *HeadTracker) ValidateFinality(update types.FinalityUpdate) (bool, error
|
||||||
if replace {
|
if replace {
|
||||||
h.finalityUpdate, h.hasFinalityUpdate = update, true
|
h.finalityUpdate, h.hasFinalityUpdate = update, true
|
||||||
h.changeCounter++
|
h.changeCounter++
|
||||||
|
if h.saveCheckpoint != nil && update.Finalized.Slot%params.EpochLength == 0 {
|
||||||
|
h.saveCheckpoint(update.Finalized.Hash())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return replace, err
|
return replace, err
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -54,6 +54,7 @@ type ChainConfig struct {
|
||||||
GenesisValidatorsRoot common.Hash // Root hash of the genesis validator set, used for signature domain calculation
|
GenesisValidatorsRoot common.Hash // Root hash of the genesis validator set, used for signature domain calculation
|
||||||
Forks Forks
|
Forks Forks
|
||||||
Checkpoint common.Hash
|
Checkpoint common.Hash
|
||||||
|
CheckpointFile string
|
||||||
}
|
}
|
||||||
|
|
||||||
// ForkAtEpoch returns the latest active fork at the given epoch.
|
// ForkAtEpoch returns the latest active fork at the given epoch.
|
||||||
|
|
@ -211,3 +212,36 @@ func (f Forks) Less(i, j int) bool {
|
||||||
}
|
}
|
||||||
return f[i].knownIndex < f[j].knownIndex
|
return f[i].knownIndex < f[j].knownIndex
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetCheckpointFile sets the checkpoint import/export file name and attempts to
|
||||||
|
// read the checkpoint from the file if it already exists. It returns true if
|
||||||
|
// a checkpoint has been loaded.
|
||||||
|
func (c *ChainConfig) SetCheckpointFile(checkpointFile string) (bool, error) {
|
||||||
|
c.CheckpointFile = checkpointFile
|
||||||
|
file, err := os.ReadFile(checkpointFile)
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return false, nil // did not load checkpoint
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("failed to read beacon checkpoint file: %v", err)
|
||||||
|
}
|
||||||
|
cp, err := hexutil.Decode(string(file))
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("failed to decode hex string in beacon checkpoint file: %v", err)
|
||||||
|
}
|
||||||
|
if len(cp) != 32 {
|
||||||
|
return false, fmt.Errorf("invalid hex string length in beacon checkpoint file: %d", len(cp))
|
||||||
|
}
|
||||||
|
copy(c.Checkpoint[:len(cp)], cp)
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveCheckpointToFile saves the given checkpoint to file if a checkpoint
|
||||||
|
// import/export file has been specified.
|
||||||
|
func (c *ChainConfig) SaveCheckpointToFile(checkpoint common.Hash) (bool, error) {
|
||||||
|
if c.CheckpointFile == "" {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
err := os.WriteFile(c.CheckpointFile, []byte(checkpoint.Hex()), 0600)
|
||||||
|
return err == nil, err
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,109 +5,109 @@
|
||||||
# https://github.com/ethereum/execution-spec-tests/releases/download/pectra-devnet-6%40v1.0.0/
|
# https://github.com/ethereum/execution-spec-tests/releases/download/pectra-devnet-6%40v1.0.0/
|
||||||
b69211752a3029083c020dc635fe12156ca1a6725a08559da540a0337586a77e fixtures_pectra-devnet-6.tar.gz
|
b69211752a3029083c020dc635fe12156ca1a6725a08559da540a0337586a77e fixtures_pectra-devnet-6.tar.gz
|
||||||
|
|
||||||
# version:golang 1.24.1
|
# version:golang 1.24.2
|
||||||
# https://go.dev/dl/
|
# https://go.dev/dl/
|
||||||
8244ebf46c65607db10222b5806aeb31c1fcf8979c1b6b12f60c677e9a3c0656 go1.24.1.src.tar.gz
|
9dc77ffadc16d837a1bf32d99c624cb4df0647cee7b119edd9e7b1bcc05f2e00 go1.24.2.src.tar.gz
|
||||||
8d627dc163a4bffa2b1887112ad6194af175dce108d606ed1714a089fb806033 go1.24.1.aix-ppc64.tar.gz
|
427b373540d8fd51dbcc46bdecd340af109cd41514443c000d3dcde72b2c65a3 go1.24.2.aix-ppc64.tar.gz
|
||||||
addbfce2056744962e2d7436313ab93486660cf7a2e066d171b9d6f2da7c7abe go1.24.1.darwin-amd64.tar.gz
|
238d9c065d09ff6af229d2e3b8b5e85e688318d69f4006fb85a96e41c216ea83 go1.24.2.darwin-amd64.tar.gz
|
||||||
58d529334561cff11087cd4ab18fe0b46d8d5aad88f45c02b9645f847e014512 go1.24.1.darwin-amd64.pkg
|
535ed9ff283fee39575a7fb9b6d8b1901b6dc640d06dc71fd7d3faeefdaf8030 go1.24.2.darwin-amd64.pkg
|
||||||
295581b5619acc92f5106e5bcb05c51869337eb19742fdfa6c8346c18e78ff88 go1.24.1.darwin-arm64.tar.gz
|
b70f8b3c5b4ccb0ad4ffa5ee91cd38075df20fdbd953a1daedd47f50fbcff47a go1.24.2.darwin-arm64.tar.gz
|
||||||
78b0fc8ddc344eb499f1a952c687cb84cbd28ba2b739cfa0d4eb042f07e44e82 go1.24.1.darwin-arm64.pkg
|
4732f607a47ce4d898c0af01ff68f07e0820a6b50603aef5d5c777d1102505e2 go1.24.2.darwin-arm64.pkg
|
||||||
e70053f56f7eb93806d80cbd5726f78509a0a467602f7bea0e2c4ee8ed7c3968 go1.24.1.dragonfly-amd64.tar.gz
|
c17686b5fd61a663fbfafccfa177961be59386cf294e935ce35866b9dcb8e78a go1.24.2.dragonfly-amd64.tar.gz
|
||||||
3595e2674ed8fe72e604ca59c964d3e5277aafb08475c2b1aaca2d2fd69c24fc go1.24.1.freebsd-386.tar.gz
|
026f1dd906189acff714c7625686bbc4ed91042618ba010d45b671461acc9e63 go1.24.2.freebsd-386.tar.gz
|
||||||
47d7de8bb64d5c3ee7b6723aa62d5ecb11e3568ef2249bbe1d4bbd432d37c00c go1.24.1.freebsd-amd64.tar.gz
|
49399ba759b570a8f87d12179133403da6c2dd296d63a8830dee309161b9c40c go1.24.2.freebsd-amd64.tar.gz
|
||||||
04eec3bcfaa14c1370cdf98e8307fac7e4853496c3045afb9c3124a29cbca205 go1.24.1.freebsd-arm.tar.gz
|
1f48f47183794d97c29736004247ab541177cf984ac6322c78bc43828daa1172 go1.24.2.freebsd-arm.tar.gz
|
||||||
51aa70146e40cfdc20927424083dc86e6223f85dc08089913a1651973b55665b go1.24.1.freebsd-arm64.tar.gz
|
ef856428b60a8c0bd9a2cba596e83024be6f1c2d5574e89cb1ff2262b08df8b9 go1.24.2.freebsd-arm64.tar.gz
|
||||||
3c131d8e3fc285a1340f87813153e24226d3ddbd6e54f3facbd6e4c46a84655e go1.24.1.freebsd-riscv64.tar.gz
|
ec2088823e16df00600a6d0f72e9a7dc6d2f80c9c140c2043c0cf20e1404d1a9 go1.24.2.freebsd-riscv64.tar.gz
|
||||||
201d09da737ba39d5367f87d4e8b31edaeeb3dc9b9c407cb8cfb40f90c5a727a go1.24.1.illumos-amd64.tar.gz
|
e030e7cedbb8688f1d75cb80f3de6ee2e6617a67d34051e794e5992b53462147 go1.24.2.illumos-amd64.tar.gz
|
||||||
8c530ecedbc17e42ce10177bea07ccc96a3e77c792ea1ea72173a9675d16ffa5 go1.24.1.linux-386.tar.gz
|
4c382776d52313266f3026236297a224a6688751256a2dffa3f524d8d6f6c0ba go1.24.2.linux-386.tar.gz
|
||||||
cb2396bae64183cdccf81a9a6df0aea3bce9511fc21469fb89a0c00470088073 go1.24.1.linux-amd64.tar.gz
|
68097bd680839cbc9d464a0edce4f7c333975e27a90246890e9f1078c7e702ad go1.24.2.linux-amd64.tar.gz
|
||||||
8df5750ffc0281017fb6070fba450f5d22b600a02081dceef47966ffaf36a3af go1.24.1.linux-arm64.tar.gz
|
756274ea4b68fa5535eb9fe2559889287d725a8da63c6aae4d5f23778c229f4b go1.24.2.linux-arm64.tar.gz
|
||||||
6d95f8d7884bfe2364644c837f080f2b585903d0b771eb5b06044e226a4f120a go1.24.1.linux-armv6l.tar.gz
|
438d5d3d7dcb239b58d893a715672eabe670b9730b1fd1c8fc858a46722a598a go1.24.2.linux-armv6l.tar.gz
|
||||||
19304a4a56e46d04604547d2d83235dc4f9b192c79832560ce337d26cc7b835a go1.24.1.linux-loong64.tar.gz
|
6aefd3bf59c3c5592eda4fb287322207f119c2210f3795afa9be48d3ccb73e1b go1.24.2.linux-loong64.tar.gz
|
||||||
6347be77fa5359c12a5308c8ab87147c1fc4717b0c216493d1706c3b9fcde22d go1.24.1.linux-mips.tar.gz
|
93e49bb4692783b0e9a2deab9558c6e8d2867f35592aeff285adda60924167f3 go1.24.2.linux-mips.tar.gz
|
||||||
1647df415f7030b82d4105670192aa7e8910e18563bb0d505192d72800cc2d21 go1.24.1.linux-mips64.tar.gz
|
6e86e703675016f3faf6604b8f68f20dc1bba75849136e6dd4f43f69c8a4a9d9 go1.24.2.linux-mips64.tar.gz
|
||||||
762da594e4ec0f9cf6defae6ef971f5f7901203ee6a2d979e317adec96657317 go1.24.1.linux-mips64le.tar.gz
|
f233d237538ca1559a7d7cf519a29f0147923a951377bc4e467af4c059e68851 go1.24.2.linux-mips64le.tar.gz
|
||||||
9d8133c7b23a557399fab870b5cf464079c2b623a43b214a7567cf11c254a444 go1.24.1.linux-mipsle.tar.gz
|
545e1b9a7939f923fd53bde98334b987ef42eb353ee3e0bfede8aa06079d6b24 go1.24.2.linux-mipsle.tar.gz
|
||||||
132f10999abbaccbada47fa85462db30c423955913b14d6c692de25f4636c766 go1.24.1.linux-ppc64.tar.gz
|
6eab31481f2f46187bc1b6c887662eef06fc9d7271a8390854072cdb387c8d74 go1.24.2.linux-ppc64.tar.gz
|
||||||
0fb522efcefabae6e37e69bdc444094e75bfe824ea6d4cc3cbc70c7ae1b16858 go1.24.1.linux-ppc64le.tar.gz
|
5fff857791d541c71d8ea0171c73f6f99770d15ff7e2ad979104856d01f36563 go1.24.2.linux-ppc64le.tar.gz
|
||||||
eaef4323d5467ff97fb1979c8491764060dade19f02f3275a9313f9a0da3b9c0 go1.24.1.linux-riscv64.tar.gz
|
91bda1558fcbd1c92769ad86c8f5cf796f8c67b0d9d9c19f76eecfc75ce71527 go1.24.2.linux-riscv64.tar.gz
|
||||||
6c05e14d8f11094cb56a1c50f390b6b658bed8a7cbd8d1a57e926581b7eabfce go1.24.1.linux-s390x.tar.gz
|
1cb3448166d6abb515a85a3ee5afbdf932081fb58ad7143a8fb666fbc06146d9 go1.24.2.linux-s390x.tar.gz
|
||||||
5dbb287d343ea00d58a70b11629f32ee716dc50a6875c459ea2018df0f294cd8 go1.24.1.netbsd-386.tar.gz
|
a9a2c0db2e826f20f00b02bee01dfdaeb49591c2f6ffacb78dc64a950894f7ff go1.24.2.netbsd-386.tar.gz
|
||||||
617aa3faee50ce84c343db0888e9a210c310a7203666b4ed620f31030c9fb32f go1.24.1.netbsd-amd64.tar.gz
|
cd1a35b76ed9c7b6c0c1616741bd319699a77867ade0be9924f32496c0a87a3f go1.24.2.netbsd-amd64.tar.gz
|
||||||
59a928b7080c4a6ac985946274b7c65ce1cecc0b468ecd992d17b7c12fab9296 go1.24.1.netbsd-arm.tar.gz
|
8c666388d066e479155cc5116950eeb435df28087ef277c18f1dc7479f836e60 go1.24.2.netbsd-arm.tar.gz
|
||||||
28daa8d0feb4aef2af60cefa3305bb9314de7e8a05cbca41ac548964cdfe89b7 go1.24.1.netbsd-arm64.tar.gz
|
5d42f0be04f58da5be788a1e260f8747c316b8ce182bf0b273c2e4c691feaa1a go1.24.2.netbsd-arm64.tar.gz
|
||||||
b7382b2f5d99813aeac14db482faa3bfbd47a68880b607fa2a7e669e26bab9cd go1.24.1.openbsd-386.tar.gz
|
688effa23ea3973cc8b0fdf4246712cbeef55ff20c45f3a9e28b0c2db04246cf go1.24.2.openbsd-386.tar.gz
|
||||||
2513b6537c45deead5e641c7ce7502913e7d5e6f0b21c52542fb11f81578690f go1.24.1.openbsd-amd64.tar.gz
|
e5daf95f1048d8026b1366450a3f8044d668b0639db6422ad9a83755c6745cf7 go1.24.2.openbsd-amd64.tar.gz
|
||||||
853c1917d4fc7b144c55a02842aa48542d5cc798dde8db96dc0fdbc263200e04 go1.24.1.openbsd-arm.tar.gz
|
aeadaf74bd544d1a12ba9b14c0e7cdb1964de3ba9a52acb4619e91dbae7def7b go1.24.2.openbsd-arm.tar.gz
|
||||||
6bc207b91e6f6ae3347fb54616a8fb2f5c11983713846a4cef111ff3f4f94d14 go1.24.1.openbsd-arm64.tar.gz
|
9e222d9adb0ce836a5b3c8d5aadbd167c8869c030b113f4a81aa88e9a200f279 go1.24.2.openbsd-arm64.tar.gz
|
||||||
4279260e2f2b94ee94e81470d13db7367f4393b061fee60985528fa0fa430df4 go1.24.1.openbsd-ppc64.tar.gz
|
192fffa34536adc3cd1bb7c1ee785b8bc156ae7afd10bbf5db99ec8f2e93066e go1.24.2.openbsd-ppc64.tar.gz
|
||||||
6fc4023a0a339ee0778522364a127d94c78e62122288d47d820dba703f81dc07 go1.24.1.openbsd-riscv64.tar.gz
|
a23e90b451a390549042c2a7efbec6f29ed98b2d5618c8d2a35704e21be96e09 go1.24.2.openbsd-riscv64.tar.gz
|
||||||
b5eb9fafd77146e7e1f748acfd95559580ecc8d2f15abf432a20f58c929c7cd2 go1.24.1.plan9-386.tar.gz
|
5cdcafe455d859b02779611a5a1e1d63e498b922e05818fb3debe410a5959e9e go1.24.2.plan9-386.tar.gz
|
||||||
24dcad6361b141fc8cced15b092351e12a99d2e58d7013204a3013c50daf9fdd go1.24.1.plan9-amd64.tar.gz
|
81351659804fa505c1b3ec6fdf9599f7f88df08614307eeb96071bf5e2e74beb go1.24.2.plan9-amd64.tar.gz
|
||||||
a026ac3b55aa1e6fdc2aaab30207a117eafbe965ed81d3aa0676409f280ddc37 go1.24.1.plan9-arm.tar.gz
|
6e337d5def14ed0123423c1c32e2e6d8b19161e5d5ffaa7356dad48ee0fd80b4 go1.24.2.plan9-arm.tar.gz
|
||||||
8e4f6a77388dc6e5aa481efd5abdb3b9f5c9463bb82f4db074494e04e5c84992 go1.24.1.solaris-amd64.tar.gz
|
07e6926ebc476c044d7d5b17706abfc52be52bccc2073d1734174efe63c6b35e go1.24.2.solaris-amd64.tar.gz
|
||||||
b799f4ab264eef12a014c759383ed934056608c483e0f73e34ea6caf9f1df5f9 go1.24.1.windows-386.zip
|
13d86cb818bba331da75fcd18246ab31a1067b44fb4a243b6dfd93097eda7f37 go1.24.2.windows-386.zip
|
||||||
db128981033ac82a64688a123f631e61297b6b8f52ca913145e57caa8ce94cc3 go1.24.1.windows-386.msi
|
8a702d9f7104a15bd935f4191c58c24c0b6389e066b9d5661b93915114a2bef0 go1.24.2.windows-386.msi
|
||||||
95666b551453209a2b8869d29d177285ff9573af10f085d961d7ae5440f645ce go1.24.1.windows-amd64.zip
|
29c553aabee0743e2ffa3e9fa0cda00ef3b3cc4ff0bc92007f31f80fd69892e1 go1.24.2.windows-amd64.zip
|
||||||
5968e7adcf26e68a54f1cd41ad561275a670a8e2ca5263bc375b524638557dfb go1.24.1.windows-amd64.msi
|
acefb191e72fea0bdb1a3f5f8f6f5ab18b42b3bbce0c7183f189f25953aff275 go1.24.2.windows-amd64.msi
|
||||||
e28c4e6d0b913955765b46157ab88ae59bb636acaa12d7bec959aa6900f1cebd go1.24.1.windows-arm64.zip
|
ab267f7f9a3366d48d7664be9e627ce3e63273231430cce5f7783fb910f14148 go1.24.2.windows-arm64.zip
|
||||||
6d352c1f154a102a5b90c480cc64bab205ccf2681e34e78a3a4d3f1ddfbc81e4 go1.24.1.windows-arm64.msi
|
d187bfe539356c39573d2f46766d1d08122b4f33da00fd14d12485fa9e241ff5 go1.24.2.windows-arm64.msi
|
||||||
|
|
||||||
# version:golangci 1.64.6
|
# version:golangci 2.0.2
|
||||||
# https://github.com/golangci/golangci-lint/releases/
|
# https://github.com/golangci/golangci-lint/releases/
|
||||||
# https://github.com/golangci/golangci-lint/releases/download/v1.64.6/
|
# https://github.com/golangci/golangci-lint/releases/download/v2.0.2/
|
||||||
08f9459e7125fed2612abd71596e04d172695921aff82120d1c1e5e9b6fff2a3 golangci-lint-1.64.6-darwin-amd64.tar.gz
|
a88cbdc86b483fe44e90bf2dcc3fec2af8c754116e6edf0aa6592cac5baa7a0e golangci-lint-2.0.2-darwin-amd64.tar.gz
|
||||||
8c10d0c7c3935b8c2269d628b6a06a8f48d8fb4cc31af02fe4ce0cd18b0704c1 golangci-lint-1.64.6-darwin-arm64.tar.gz
|
664550e7954f5f4451aae99b4f7382c1a47039c66f39ca605f5d9af1a0d32b49 golangci-lint-2.0.2-darwin-arm64.tar.gz
|
||||||
c07fcabb55deb8d2c4d390025568e76162d7f91b1d14bd2311be45d8d440a624 golangci-lint-1.64.6-freebsd-386.tar.gz
|
bda0f0f27d300502faceda8428834a76ca25986f6d9fc2bd41d201c3ed73f08e golangci-lint-2.0.2-freebsd-386.tar.gz
|
||||||
8ed1ef1102e1a42983ffcaae8e06de6a540334c3a69e205c610b8a7c92d469cd golangci-lint-1.64.6-freebsd-amd64.tar.gz
|
1cbd0c7ade3fb027d61d38a646ec1b51be5846952b4b04a5330e7f4687f2270c golangci-lint-2.0.2-freebsd-amd64.tar.gz
|
||||||
8f8dda66d1b4a85cc8a1daf1b69af6559c3eb0a41dd8033148a9ad85cfc0e1d9 golangci-lint-1.64.6-freebsd-armv6.tar.gz
|
1e828a597726198b2e35acdbcc5f3aad85244d79846d2d2bdb05241c5a535f9e golangci-lint-2.0.2-freebsd-armv6.tar.gz
|
||||||
59e8ca1fa254661b2a55e96515b14a10cd02221d443054deac5b28c3c3e12d6b golangci-lint-1.64.6-freebsd-armv7.tar.gz
|
848b49315dc5cddd0c9ce35e96ab33d584db0ea8fb57bcbf9784f1622bec0269 golangci-lint-2.0.2-freebsd-armv7.tar.gz
|
||||||
e3d323d5f132e9b7593141bfe1d19c8460e65a55cea1008ec96945fed563f981 golangci-lint-1.64.6-illumos-amd64.tar.gz
|
cabf9a6beab574c7f98581eb237919e580024759e3cdc05c4d516b044dce6770 golangci-lint-2.0.2-illumos-amd64.tar.gz
|
||||||
5ce910f2a864c5fbeb32a30cbd506e1b2ef215f7a0f422cd5be6370b13db6f03 golangci-lint-1.64.6-linux-386.deb
|
2fde80d15ed6527791f106d606120620e913c3a663c90a8596861d0a4461169e golangci-lint-2.0.2-linux-386.deb
|
||||||
2caab682a26b9a5fb94ba24e3a7e1404fa9eab2c12e36ae1c5548d80a1be190c golangci-lint-1.64.6-linux-386.rpm
|
804bc6e350a8c613aaa0a33d8d45414a80157b0ba1b2c2335ac859f85ad98ebd golangci-lint-2.0.2-linux-386.rpm
|
||||||
2d82d0a4716e6d9b70c95103054855cb4b5f20f7bbdee42297f0189955bd14b6 golangci-lint-1.64.6-linux-386.tar.gz
|
e64beb72fecf581e57d88ae3adb1c9d4bf022694b6bd92e3c8e460910bbdc37d golangci-lint-2.0.2-linux-386.tar.gz
|
||||||
9cd82503e9841abcaa57663fc899587fe90363c26d86a793a98d3080fd25e907 golangci-lint-1.64.6-linux-amd64.deb
|
9c55aed174d7a52bb1d4006b36e7edee9023631f6b814a80cb39c9860d6f75c3 golangci-lint-2.0.2-linux-amd64.deb
|
||||||
981aaca5e5202d4fbb162ec7080490eb67ef5d32add5fb62fb02210597acc9da golangci-lint-1.64.6-linux-amd64.rpm
|
c55a2ef741a687b4c679696931f7fd4a467babd64c9457cf17bb9632fd1cecd1 golangci-lint-2.0.2-linux-amd64.rpm
|
||||||
71e290acbacb7b3ba4f68f0540fb74dc180c4336ac8a6f3bdcd7fcc48b15148d golangci-lint-1.64.6-linux-amd64.tar.gz
|
89cc8a7810dc63b9a37900da03e37c3601caf46d42265d774e0f1a5d883d53e2 golangci-lint-2.0.2-linux-amd64.tar.gz
|
||||||
718016bb06c1f598a8d23c7964e2643de621dbe5808688cb38857eb0bb773c84 golangci-lint-1.64.6-linux-arm64.deb
|
a3e78583c4e7ea1b63e82559f126bb3a5b12788676f158526752d53e67824b99 golangci-lint-2.0.2-linux-arm64.deb
|
||||||
ddc0e7b4b10b47cf894aea157e89e3674bbb60f8f5c480110c21c49cc2c1634d golangci-lint-1.64.6-linux-arm64.rpm
|
bd5dd52b5c9f18aa7a2904eda9a9f91c628e98623fe70b7afcbb847e2de84422 golangci-lint-2.0.2-linux-arm64.rpm
|
||||||
99a7ff13dec7a8781a68408b6ecb8a1c5e82786cba3189eaa91d5cdcc24362ce golangci-lint-1.64.6-linux-arm64.tar.gz
|
789d5b91219ac68c2336f77d41cd7e33a910420594780f455893f8453d09595b golangci-lint-2.0.2-linux-arm64.tar.gz
|
||||||
90e360f89c244394912b8709fb83a900b6d56cf19141df2afaf9e902ef3057b1 golangci-lint-1.64.6-linux-armv6.deb
|
534cd4c464a66178714ed68152c1ed7aa73e5700bf409e4ed1a8363adf96afca golangci-lint-2.0.2-linux-armv6.deb
|
||||||
46546ff7c98d873ffcdbee06b39dc1024fc08db4fbf1f6309360a44cf976b5c2 golangci-lint-1.64.6-linux-armv6.rpm
|
cf7d02905a5fc80b96c9a64621693b4cc7337b1ce29986c19fd72608dafe66c5 golangci-lint-2.0.2-linux-armv6.rpm
|
||||||
e45c1a42868aca0b0ee54d14fb89da216f3b4409367cd7bce3b5f36788b4fc92 golangci-lint-1.64.6-linux-armv6.tar.gz
|
a0d81cb527d8fe878377f2356b5773e219b0b91832a6b59e7b9bcf9a90fe0b0e golangci-lint-2.0.2-linux-armv6.tar.gz
|
||||||
3cf6ddbbbf358db3de4b64a24f9683bbe2da3f003cfdee86cb610124b57abafb golangci-lint-1.64.6-linux-armv7.deb
|
dedd5be7fff8cba8fe15b658a59347ea90d7d02a9fff87f09c7687e6da05a8b6 golangci-lint-2.0.2-linux-armv7.deb
|
||||||
508b6712710da10f11aab9ea5e63af415c932dfe7fff718e649d3100b838f797 golangci-lint-1.64.6-linux-armv7.rpm
|
85521b6f3ad2f5a2bc9bfe14b9b08623f764964048f75ed6dfcfaf8eb7d57cc1 golangci-lint-2.0.2-linux-armv7.rpm
|
||||||
da9a8bbee86b4dfee73fbc17e0856ec84c5b04919eb09bf3dd5904c39ce41753 golangci-lint-1.64.6-linux-armv7.tar.gz
|
96471046c7780dda4ea680f65e92c2ef56ff58d40bcffaf6cfe9d6d48e3c27aa golangci-lint-2.0.2-linux-armv7.tar.gz
|
||||||
ad496a58284e1e9c8ac6f993fec429dcd96c85a8c4715dbb6530a5af0dae7fbd golangci-lint-1.64.6-linux-loong64.deb
|
815d914a7738e4362466b2d11004e8618b696b49e8ace13df2c2b25f28fb1e17 golangci-lint-2.0.2-linux-loong64.deb
|
||||||
3bd70fa737b224750254dce616d9a188570e49b894b0cdb2fd04155e2c061350 golangci-lint-1.64.6-linux-loong64.rpm
|
f16381e3d8a0f011b95e086d83d620248432b915d01f4beab4d29cfe4dc388b0 golangci-lint-2.0.2-linux-loong64.rpm
|
||||||
a535af973499729f2215a84303eb0de61399057aad6901ddea1b4f73f68d5f2c golangci-lint-1.64.6-linux-loong64.tar.gz
|
1bd8d7714f9c92db6a0f23bae89f39c85ba047bec8eeb42b8748d30ae3228d18 golangci-lint-2.0.2-linux-loong64.tar.gz
|
||||||
6ad2a1cd37ca30303a488abfca2de52aff57519901c6d8d2608656fe9fb05292 golangci-lint-1.64.6-linux-mips64.deb
|
ea6e9d4aabb526aa298e47e8b026d8893d918c5eb919ba0ab403e315def74cc5 golangci-lint-2.0.2-linux-mips64.deb
|
||||||
5f18369f0ca010a02c267352ebe6e3e0514c6debff49899c9e5520906c0da287 golangci-lint-1.64.6-linux-mips64.rpm
|
519d8d53af83fdc9c25cc3fba8b663331ac22ef68131d4b0084cb6f425b6f79a golangci-lint-2.0.2-linux-mips64.rpm
|
||||||
3449d6c13307b91b0e8817f8911c07c3412cdb6931b8d101e42db3e9762e91ad golangci-lint-1.64.6-linux-mips64.tar.gz
|
80d655a0a1ac1b19dcef4b58fa2a7dadb646cc50ad08d460b5c53cdb421165e4 golangci-lint-2.0.2-linux-mips64.tar.gz
|
||||||
d4712a348f65dcaf9f6c58f1cfd6d0984d54a902873dca5e76f0d686f5c59499 golangci-lint-1.64.6-linux-mips64le.deb
|
aa0e75384bb482c865d4dfc95d23ceb25666bf20461b67a832f0eea6670312ec golangci-lint-2.0.2-linux-mips64le.deb
|
||||||
57cea4538894558cb8c956d6b69c5509e4304546abe4a467478fc9ada0c736d6 golangci-lint-1.64.6-linux-mips64le.rpm
|
f2a8b500fb69bdea1b01df6267aaa5218fa4a58aeb781c1a20d0d802fe465a52 golangci-lint-2.0.2-linux-mips64le.rpm
|
||||||
bc030977d44535b2152fddb2732f056d193c043992fe638ddecea21a40ef09fe golangci-lint-1.64.6-linux-mips64le.tar.gz
|
e66a0c0c9a275f02d27a7caa9576112622306f001d73dfc082cf1ae446fc1242 golangci-lint-2.0.2-linux-mips64le.tar.gz
|
||||||
1ceb4e492efa527d246c61798c581f49113756fab8c39bb3eefdb1fa97041f92 golangci-lint-1.64.6-linux-ppc64le.deb
|
e85ad51aac6428be2d8a37000d053697371a538a5bcbc1644caa7c5e77f6d0af golangci-lint-2.0.2-linux-ppc64le.deb
|
||||||
454e1c2b3583a8644e0c33a970fb4ce35b8f11848e1a770d9095d99d159ad0ab golangci-lint-1.64.6-linux-ppc64le.rpm
|
906798365eac1944af2a9b9a303e6fd49ec9043307bc681b7a96277f7f8beea5 golangci-lint-2.0.2-linux-ppc64le.rpm
|
||||||
fddf30d35923eb6c7bb57520d8645768f802bf86c4cbf5a3a13049efb9e71b82 golangci-lint-1.64.6-linux-ppc64le.tar.gz
|
f7f1a271b0af274d6c9ce000f5dc6e1fb194350c67bcc62494f96f791882ba92 golangci-lint-2.0.2-linux-ppc64le.tar.gz
|
||||||
bd75f0dd6f65bee5821c433803b28f3c427ef3582764c3d0e7f7fae1c9d468b6 golangci-lint-1.64.6-linux-riscv64.deb
|
eea8bf643a42bf05de9780530db22923e5ab0d588f0e173594dc6518f2a25d2a golangci-lint-2.0.2-linux-riscv64.deb
|
||||||
58457207c225cbd5340c8dcb75d9a44aa890d604e28464115a3a9762febaed04 golangci-lint-1.64.6-linux-riscv64.rpm
|
4ff40f9fe2954400836e2a011ba4744d00ffab5068a51368552dfce6aba3b81b golangci-lint-2.0.2-linux-riscv64.rpm
|
||||||
82639518a613a6705b7e2de5b28c278e875d782a5c97e9c1b2ac10b4ecd7852f golangci-lint-1.64.6-linux-riscv64.tar.gz
|
531d8f225866674977d630afbf0533eb02f9bec607fb13895f7a2cd7b2e0a648 golangci-lint-2.0.2-linux-riscv64.tar.gz
|
||||||
131d69204f8ced200b1437731e987cc886edac30dc87e6e1dcbd4f833d351713 golangci-lint-1.64.6-linux-s390x.deb
|
6f827647046c603f40d97ea5aadc6f48cd0bb5d19f7a3d56500c3b833d2a0342 golangci-lint-2.0.2-linux-s390x.deb
|
||||||
ca6caf28ca7a1df7cff720f8fd6ac4b8f2eac10c8cbfe7d2eade70876aded570 golangci-lint-1.64.6-linux-s390x.rpm
|
387a090e9576d19ca86aac738172e58e07c19f2784a13bb387f4f0d75fb9c8d3 golangci-lint-2.0.2-linux-s390x.rpm
|
||||||
ed966d28a6512bc2b1120029a9f78ed77f2015e330b589a731d67d59be30b0b1 golangci-lint-1.64.6-linux-s390x.tar.gz
|
57de1fb7722a9feb2d11ed0a007a93959d05b9db5929a392abc222e30012467e golangci-lint-2.0.2-linux-s390x.tar.gz
|
||||||
b181132b41943fc77ace7f9f5523085d12d3613f27774a0e35e17dd5e65ba589 golangci-lint-1.64.6-netbsd-386.tar.gz
|
ed95e0492ea86bf79eb661f0334474b2a4255093685ff587eccd797c5a54db7e golangci-lint-2.0.2-netbsd-386.tar.gz
|
||||||
f7b81c426006e3c699dc8665797a462aecba8c2cd23ac4971472e55184d95bc9 golangci-lint-1.64.6-netbsd-amd64.tar.gz
|
eab81d729778166415d349a80e568b2f2b3a781745a9be3212a92abb1e732daf golangci-lint-2.0.2-netbsd-amd64.tar.gz
|
||||||
663d6fb4c3bef57b8aacdb1b1a4634075e55d294ed170724b443374860897ca6 golangci-lint-1.64.6-netbsd-arm64.tar.gz
|
d20add73f7c2de2c3b01ed4fd7b63ffcf0a6597d5ea228d1699e92339a3cd047 golangci-lint-2.0.2-netbsd-arm64.tar.gz
|
||||||
8c7a76ee822568cc19352bbb9b2b0863dc5e185eb07782adbbaf648afd02ebcd golangci-lint-1.64.6-netbsd-armv6.tar.gz
|
4e4f44e6057879cd62424ff1800a767d25a595c0e91d6d48809eea9186b4c739 golangci-lint-2.0.2-netbsd-armv6.tar.gz
|
||||||
0ce26d56ce78e516529e087118ba3f1bcd71d311b4c5b2bde6ec24a6e8966d85 golangci-lint-1.64.6-netbsd-armv7.tar.gz
|
51ec17b16d8743ae4098a0171f04f0ed4d64561e3051b982778b0e6c306a1b03 golangci-lint-2.0.2-netbsd-armv7.tar.gz
|
||||||
135d5d998168683f46e4fab308cef5aa3c282025b7de6b258f976aadfb820db7 golangci-lint-1.64.6-source.tar.gz
|
5482cf27b93fae1765c70ee2a95d4074d038e9dee61bdd61d017ce8893d3a4a8 golangci-lint-2.0.2-source.tar.gz
|
||||||
ccdb0cc249531a205304a76308cfa7cda830083d083d557884416a2461148263 golangci-lint-1.64.6-windows-386.zip
|
a35d8fdf3e14079a10880dbbb7586b46faec89be96f086b244b3e565aac80313 golangci-lint-2.0.2-windows-386.zip
|
||||||
2d88f282e08e1853c70bc7c914b5f58beaa6509903d56098aeb9bc3df30ea9d5 golangci-lint-1.64.6-windows-amd64.zip
|
fe4b946cc01366b989001215687003a9c4a7098589921f75e6228d6d8cffc15c golangci-lint-2.0.2-windows-amd64.zip
|
||||||
6a3c6e7afc6916392679d7d6b95ac239827644e3e50ec4e8ca6ab1e4e6db65fe golangci-lint-1.64.6-windows-arm64.zip
|
646bd9250ef8c771d85cd22fe8e6f2397ae39599179755e3bbfa9ef97ad44090 golangci-lint-2.0.2-windows-arm64.zip
|
||||||
9c9c1ef9687651566987f93e76252f7526c386901d7d8aeee044ca88115da4b1 golangci-lint-1.64.6-windows-armv6.zip
|
ce1dc0bad6f8a61d64e6b3779eeb773479c175125d6f686b0e67ef9c8432d16e golangci-lint-2.0.2-windows-armv6.zip
|
||||||
4f0df114155791799dfde8cd8cb6307fecfb17fed70b44205486ec925e2f39cf golangci-lint-1.64.6-windows-armv7.zip
|
92684a48faabe792b11ac27ca8b25551eff940b0a1e84ad7244e98b4994962db golangci-lint-2.0.2-windows-armv7.zip
|
||||||
|
|
||||||
# This is the builder on PPA that will build Go itself (inception-y), don't modify!
|
# This is the builder on PPA that will build Go itself (inception-y), don't modify!
|
||||||
#
|
#
|
||||||
|
|
|
||||||
|
|
@ -43,6 +43,7 @@ func main() {
|
||||||
utils.BeaconGenesisRootFlag,
|
utils.BeaconGenesisRootFlag,
|
||||||
utils.BeaconGenesisTimeFlag,
|
utils.BeaconGenesisTimeFlag,
|
||||||
utils.BeaconCheckpointFlag,
|
utils.BeaconCheckpointFlag,
|
||||||
|
utils.BeaconCheckpointFileFlag,
|
||||||
//TODO datadir for optional permanent database
|
//TODO datadir for optional permanent database
|
||||||
utils.MainnetFlag,
|
utils.MainnetFlag,
|
||||||
utils.SepoliaFlag,
|
utils.SepoliaFlag,
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# Clef
|
# Clef
|
||||||
|
|
||||||
Clef can be used to sign transactions and data and is meant as a(n eventual) replacement for Geth's account management. This allows DApps to not depend on Geth's account management. When a DApp wants to sign data (or a transaction), it can send the content to Clef, which will then provide the user with context and asks for permission to sign the content. If the users grants the signing request, Clef will send the signature back to the DApp.
|
Clef can be used to sign transactions and data and is meant as a(n eventual) replacement for Geth's account management. This allows DApps to not depend on Geth's account management. When a DApp wants to sign data (or a transaction), it can send the content to Clef, which will then provide the user with context and ask for permission to sign the content. If the user grants the signing request, Clef will send the signature back to the DApp.
|
||||||
|
|
||||||
This setup allows a DApp to connect to a remote Ethereum node and send transactions that are locally signed. This can help in situations when a DApp is connected to an untrusted remote Ethereum node, because a local one is not available, not synchronized with the chain, or is a node that has no built-in (or limited) account management.
|
This setup allows a DApp to connect to a remote Ethereum node and send transactions that are locally signed. This can help in situations when a DApp is connected to an untrusted remote Ethereum node, because a local one is not available, not synchronized with the chain, or is a node that has no built-in (or limited) account management.
|
||||||
|
|
||||||
|
|
@ -123,7 +123,7 @@ The External API is **untrusted**: it does not accept credentials, nor does it e
|
||||||
|
|
||||||
Clef has one native console-based UI, for operation without any standalone tools. However, there is also an API to communicate with an external UI. To enable that UI, the signer needs to be executed with the `--stdio-ui` option, which allocates `stdin` / `stdout` for the UI API.
|
Clef has one native console-based UI, for operation without any standalone tools. However, there is also an API to communicate with an external UI. To enable that UI, the signer needs to be executed with the `--stdio-ui` option, which allocates `stdin` / `stdout` for the UI API.
|
||||||
|
|
||||||
An example (insecure) proof-of-concept of has been implemented in `pythonsigner.py`.
|
An example (insecure) proof-of-concept has been implemented in `pythonsigner.py`.
|
||||||
|
|
||||||
The model is as follows:
|
The model is as follows:
|
||||||
|
|
||||||
|
|
@ -335,7 +335,7 @@ Bash example:
|
||||||
|
|
||||||
#### Arguments
|
#### Arguments
|
||||||
- content type [string]: type of signed data
|
- content type [string]: type of signed data
|
||||||
- `text/validator`: hex data with custom validator defined in a contract
|
- `text/validator`: hex data with a custom validator defined in a contract
|
||||||
- `application/clique`: [clique](https://github.com/ethereum/EIPs/issues/225) headers
|
- `application/clique`: [clique](https://github.com/ethereum/EIPs/issues/225) headers
|
||||||
- `text/plain`: simple hex data validated by `account_ecRecover`
|
- `text/plain`: simple hex data validated by `account_ecRecover`
|
||||||
- account [address]: account to sign with
|
- account [address]: account to sign with
|
||||||
|
|
|
||||||
|
|
@ -59,8 +59,9 @@ func (s *Suite) AllTests() []utesting.Test {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestPing sends PING and expects a PONG response.
|
|
||||||
func (s *Suite) TestPing(t *utesting.T) {
|
func (s *Suite) TestPing(t *utesting.T) {
|
||||||
|
t.Log(`This test is just a sanity check. It sends PING and expects a PONG response.`)
|
||||||
|
|
||||||
conn, l1 := s.listen1(t)
|
conn, l1 := s.listen1(t)
|
||||||
defer conn.close()
|
defer conn.close()
|
||||||
|
|
||||||
|
|
@ -85,9 +86,10 @@ func checkPong(t *utesting.T, pong *v5wire.Pong, ping *v5wire.Ping, c net.Packet
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestPingLargeRequestID sends PING with a 9-byte request ID, which isn't allowed by the spec.
|
|
||||||
// The remote node should not respond.
|
|
||||||
func (s *Suite) TestPingLargeRequestID(t *utesting.T) {
|
func (s *Suite) TestPingLargeRequestID(t *utesting.T) {
|
||||||
|
t.Log(`This test sends PING with a 9-byte request ID, which isn't allowed by the spec.
|
||||||
|
The remote node should not respond.`)
|
||||||
|
|
||||||
conn, l1 := s.listen1(t)
|
conn, l1 := s.listen1(t)
|
||||||
defer conn.close()
|
defer conn.close()
|
||||||
|
|
||||||
|
|
@ -104,10 +106,11 @@ func (s *Suite) TestPingLargeRequestID(t *utesting.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestPingMultiIP establishes a session from one IP as usual. The session is then reused
|
|
||||||
// on another IP, which shouldn't work. The remote node should respond with WHOAREYOU for
|
|
||||||
// the attempt from a different IP.
|
|
||||||
func (s *Suite) TestPingMultiIP(t *utesting.T) {
|
func (s *Suite) TestPingMultiIP(t *utesting.T) {
|
||||||
|
t.Log(`This test establishes a session from one IP as usual. The session is then reused
|
||||||
|
on another IP, which shouldn't work. The remote node should respond with WHOAREYOU for
|
||||||
|
the attempt from a different IP.`)
|
||||||
|
|
||||||
conn, l1, l2 := s.listen2(t)
|
conn, l1, l2 := s.listen2(t)
|
||||||
defer conn.close()
|
defer conn.close()
|
||||||
|
|
||||||
|
|
@ -120,6 +123,7 @@ func (s *Suite) TestPingMultiIP(t *utesting.T) {
|
||||||
checkPong(t, resp.(*v5wire.Pong), ping, l1)
|
checkPong(t, resp.(*v5wire.Pong), ping, l1)
|
||||||
|
|
||||||
// Send on l2. This reuses the session because there is only one codec.
|
// Send on l2. This reuses the session because there is only one codec.
|
||||||
|
t.Log("sending ping from alternate IP", l2.LocalAddr())
|
||||||
ping2 := &v5wire.Ping{ReqID: conn.nextReqID()}
|
ping2 := &v5wire.Ping{ReqID: conn.nextReqID()}
|
||||||
conn.write(l2, ping2, nil)
|
conn.write(l2, ping2, nil)
|
||||||
switch resp := conn.read(l2).(type) {
|
switch resp := conn.read(l2).(type) {
|
||||||
|
|
@ -158,6 +162,10 @@ func (s *Suite) TestPingMultiIP(t *utesting.T) {
|
||||||
// packet instead of a handshake message packet. The remote node should respond with
|
// packet instead of a handshake message packet. The remote node should respond with
|
||||||
// another WHOAREYOU challenge for the second packet.
|
// another WHOAREYOU challenge for the second packet.
|
||||||
func (s *Suite) TestPingHandshakeInterrupted(t *utesting.T) {
|
func (s *Suite) TestPingHandshakeInterrupted(t *utesting.T) {
|
||||||
|
t.Log(`TestPingHandshakeInterrupted starts a handshake, but doesn't finish it and sends a second ordinary message
|
||||||
|
packet instead of a handshake message packet. The remote node should respond with
|
||||||
|
another WHOAREYOU challenge for the second packet.`)
|
||||||
|
|
||||||
conn, l1 := s.listen1(t)
|
conn, l1 := s.listen1(t)
|
||||||
defer conn.close()
|
defer conn.close()
|
||||||
|
|
||||||
|
|
@ -181,8 +189,10 @@ func (s *Suite) TestPingHandshakeInterrupted(t *utesting.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestTalkRequest sends TALKREQ and expects an empty TALKRESP response.
|
|
||||||
func (s *Suite) TestTalkRequest(t *utesting.T) {
|
func (s *Suite) TestTalkRequest(t *utesting.T) {
|
||||||
|
t.Log(`This test sends some examples of TALKREQ with a protocol-id of "test-protocol"
|
||||||
|
and expects an empty TALKRESP response.`)
|
||||||
|
|
||||||
conn, l1 := s.listen1(t)
|
conn, l1 := s.listen1(t)
|
||||||
defer conn.close()
|
defer conn.close()
|
||||||
|
|
||||||
|
|
@ -202,6 +212,7 @@ func (s *Suite) TestTalkRequest(t *utesting.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Empty request ID.
|
// Empty request ID.
|
||||||
|
t.Log("sending TALKREQ with empty request-id")
|
||||||
resp = conn.reqresp(l1, &v5wire.TalkRequest{Protocol: "test-protocol"})
|
resp = conn.reqresp(l1, &v5wire.TalkRequest{Protocol: "test-protocol"})
|
||||||
switch resp := resp.(type) {
|
switch resp := resp.(type) {
|
||||||
case *v5wire.TalkResponse:
|
case *v5wire.TalkResponse:
|
||||||
|
|
@ -216,8 +227,9 @@ func (s *Suite) TestTalkRequest(t *utesting.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestFindnodeZeroDistance checks that the remote node returns itself for FINDNODE with distance zero.
|
|
||||||
func (s *Suite) TestFindnodeZeroDistance(t *utesting.T) {
|
func (s *Suite) TestFindnodeZeroDistance(t *utesting.T) {
|
||||||
|
t.Log(`This test checks that the remote node returns itself for FINDNODE with distance zero.`)
|
||||||
|
|
||||||
conn, l1 := s.listen1(t)
|
conn, l1 := s.listen1(t)
|
||||||
defer conn.close()
|
defer conn.close()
|
||||||
|
|
||||||
|
|
@ -233,9 +245,11 @@ func (s *Suite) TestFindnodeZeroDistance(t *utesting.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestFindnodeResults pings the node under test from multiple nodes. After waiting for them to be
|
|
||||||
// accepted into the remote table, the test checks that they are returned by FINDNODE.
|
|
||||||
func (s *Suite) TestFindnodeResults(t *utesting.T) {
|
func (s *Suite) TestFindnodeResults(t *utesting.T) {
|
||||||
|
t.Log(`This test pings the node under test from multiple other endpoints and node identities
|
||||||
|
(the 'bystanders'). After waiting for them to be accepted into the remote table, the test checks
|
||||||
|
that they are returned by FINDNODE.`)
|
||||||
|
|
||||||
// Create bystanders.
|
// Create bystanders.
|
||||||
nodes := make([]*bystander, 5)
|
nodes := make([]*bystander, 5)
|
||||||
added := make(chan enode.ID, len(nodes))
|
added := make(chan enode.ID, len(nodes))
|
||||||
|
|
@ -273,6 +287,7 @@ func (s *Suite) TestFindnodeResults(t *utesting.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send FINDNODE for all distances.
|
// Send FINDNODE for all distances.
|
||||||
|
t.Log("requesting nodes")
|
||||||
conn, l1 := s.listen1(t)
|
conn, l1 := s.listen1(t)
|
||||||
defer conn.close()
|
defer conn.close()
|
||||||
foundNodes, err := conn.findnode(l1, dists)
|
foundNodes, err := conn.findnode(l1, dists)
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,7 @@ which can
|
||||||
1. Take a prestate, including
|
1. Take a prestate, including
|
||||||
- Accounts,
|
- Accounts,
|
||||||
- Block context information,
|
- Block context information,
|
||||||
- Previous blockshashes (*optional)
|
- Previous block hashes (*optional)
|
||||||
2. Apply a set of transactions,
|
2. Apply a set of transactions,
|
||||||
3. Apply a mining-reward (*optional),
|
3. Apply a mining-reward (*optional),
|
||||||
4. And generate a post-state, including
|
4. And generate a post-state, including
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,7 @@ import "regexp"
|
||||||
// within its filename by the execution spec test (EEST).
|
// within its filename by the execution spec test (EEST).
|
||||||
type testMetadata struct {
|
type testMetadata struct {
|
||||||
fork string
|
fork string
|
||||||
module string // which python module gnerated the test, e.g. eip7702
|
module string // which python module generated the test, e.g. eip7702
|
||||||
file string // exact file the test came from, e.g. test_gas.py
|
file string // exact file the test came from, e.g. test_gas.py
|
||||||
function string // func that created the test, e.g. test_valid_mcopy_operations
|
function string // func that created the test, e.g. test_valid_mcopy_operations
|
||||||
parameters string // the name of the parameters which were used to fill the test, e.g. zero_inputs
|
parameters string // the name of the parameters which were used to fill the test, e.g. zero_inputs
|
||||||
|
|
|
||||||
|
|
@ -79,11 +79,15 @@ if one is set. Otherwise it prints the genesis from the datadir.`,
|
||||||
Usage: "Import a blockchain file",
|
Usage: "Import a blockchain file",
|
||||||
ArgsUsage: "<filename> (<filename 2> ... <filename N>) ",
|
ArgsUsage: "<filename> (<filename 2> ... <filename N>) ",
|
||||||
Flags: slices.Concat([]cli.Flag{
|
Flags: slices.Concat([]cli.Flag{
|
||||||
utils.CacheFlag,
|
|
||||||
utils.GCModeFlag,
|
utils.GCModeFlag,
|
||||||
utils.SnapshotFlag,
|
utils.SnapshotFlag,
|
||||||
|
utils.CacheFlag,
|
||||||
utils.CacheDatabaseFlag,
|
utils.CacheDatabaseFlag,
|
||||||
|
utils.CacheTrieFlag,
|
||||||
utils.CacheGCFlag,
|
utils.CacheGCFlag,
|
||||||
|
utils.CacheSnapshotFlag,
|
||||||
|
utils.CacheNoPrefetchFlag,
|
||||||
|
utils.CachePreimagesFlag,
|
||||||
utils.NoCompactionFlag,
|
utils.NoCompactionFlag,
|
||||||
utils.MetricsEnabledFlag,
|
utils.MetricsEnabledFlag,
|
||||||
utils.MetricsEnabledExpensiveFlag,
|
utils.MetricsEnabledExpensiveFlag,
|
||||||
|
|
@ -457,7 +461,7 @@ func importHistory(ctx *cli.Context) error {
|
||||||
network = networks[0]
|
network = networks[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := utils.ImportHistory(chain, db, dir, network); err != nil {
|
if err := utils.ImportHistory(chain, dir, network); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
fmt.Printf("Import done in %v\n", time.Since(start))
|
fmt.Printf("Import done in %v\n", time.Since(start))
|
||||||
|
|
|
||||||
|
|
@ -157,6 +157,7 @@ var (
|
||||||
utils.BeaconGenesisRootFlag,
|
utils.BeaconGenesisRootFlag,
|
||||||
utils.BeaconGenesisTimeFlag,
|
utils.BeaconGenesisTimeFlag,
|
||||||
utils.BeaconCheckpointFlag,
|
utils.BeaconCheckpointFlag,
|
||||||
|
utils.BeaconCheckpointFileFlag,
|
||||||
}, utils.NetworkFlags, utils.DatabaseFlags)
|
}, utils.NetworkFlags, utils.DatabaseFlags)
|
||||||
|
|
||||||
rpcFlags = []cli.Flag{
|
rpcFlags = []cli.Flag{
|
||||||
|
|
|
||||||
|
|
@ -246,8 +246,9 @@ func readList(filename string) ([]string, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ImportHistory imports Era1 files containing historical block information,
|
// ImportHistory imports Era1 files containing historical block information,
|
||||||
// starting from genesis.
|
// starting from genesis. The assumption is held that the provided chain
|
||||||
func ImportHistory(chain *core.BlockChain, db ethdb.Database, dir string, network string) error {
|
// segment in Era1 file should all be canonical and verified.
|
||||||
|
func ImportHistory(chain *core.BlockChain, dir string, network string) error {
|
||||||
if chain.CurrentSnapBlock().Number.BitLen() != 0 {
|
if chain.CurrentSnapBlock().Number.BitLen() != 0 {
|
||||||
return errors.New("history import only supported when starting from genesis")
|
return errors.New("history import only supported when starting from genesis")
|
||||||
}
|
}
|
||||||
|
|
@ -308,11 +309,6 @@ func ImportHistory(chain *core.BlockChain, db ethdb.Database, dir string, networ
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("error reading receipts %d: %w", it.Number(), err)
|
return fmt.Errorf("error reading receipts %d: %w", it.Number(), err)
|
||||||
}
|
}
|
||||||
if status, err := chain.HeaderChain().InsertHeaderChain([]*types.Header{block.Header()}, start); err != nil {
|
|
||||||
return fmt.Errorf("error inserting header %d: %w", it.Number(), err)
|
|
||||||
} else if status != core.CanonStatTy {
|
|
||||||
return fmt.Errorf("error inserting header %d, not canon: %v", it.Number(), status)
|
|
||||||
}
|
|
||||||
if _, err := chain.InsertReceiptChain([]*types.Block{block}, []types.Receipts{receipts}, 2^64-1); err != nil {
|
if _, err := chain.InsertReceiptChain([]*types.Block{block}, []types.Receipts{receipts}, 2^64-1); err != nil {
|
||||||
return fmt.Errorf("error inserting body %d: %w", it.Number(), err)
|
return fmt.Errorf("error inserting body %d: %w", it.Number(), err)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -342,6 +342,11 @@ var (
|
||||||
Usage: "Beacon chain weak subjectivity checkpoint block hash",
|
Usage: "Beacon chain weak subjectivity checkpoint block hash",
|
||||||
Category: flags.BeaconCategory,
|
Category: flags.BeaconCategory,
|
||||||
}
|
}
|
||||||
|
BeaconCheckpointFileFlag = &cli.StringFlag{
|
||||||
|
Name: "beacon.checkpoint.file",
|
||||||
|
Usage: "Beacon chain weak subjectivity checkpoint import/export file",
|
||||||
|
Category: flags.BeaconCategory,
|
||||||
|
}
|
||||||
BlsyncApiFlag = &cli.StringFlag{
|
BlsyncApiFlag = &cli.StringFlag{
|
||||||
Name: "blsync.engine.api",
|
Name: "blsync.engine.api",
|
||||||
Usage: "Target EL engine API URL",
|
Usage: "Target EL engine API URL",
|
||||||
|
|
@ -1889,7 +1894,7 @@ func MakeBeaconLightConfig(ctx *cli.Context) bparams.ClientConfig {
|
||||||
if !ctx.IsSet(BeaconGenesisTimeFlag.Name) {
|
if !ctx.IsSet(BeaconGenesisTimeFlag.Name) {
|
||||||
Fatalf("Custom beacon chain config is specified but genesis time is missing")
|
Fatalf("Custom beacon chain config is specified but genesis time is missing")
|
||||||
}
|
}
|
||||||
if !ctx.IsSet(BeaconCheckpointFlag.Name) {
|
if !ctx.IsSet(BeaconCheckpointFlag.Name) && !ctx.IsSet(BeaconCheckpointFileFlag.Name) {
|
||||||
Fatalf("Custom beacon chain config is specified but checkpoint is missing")
|
Fatalf("Custom beacon chain config is specified but checkpoint is missing")
|
||||||
}
|
}
|
||||||
config.ChainConfig = bparams.ChainConfig{
|
config.ChainConfig = bparams.ChainConfig{
|
||||||
|
|
@ -1914,13 +1919,28 @@ func MakeBeaconLightConfig(ctx *cli.Context) bparams.ClientConfig {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Checkpoint is required with custom chain config and is optional with pre-defined config
|
// Checkpoint is required with custom chain config and is optional with pre-defined config
|
||||||
if ctx.IsSet(BeaconCheckpointFlag.Name) {
|
// If both checkpoint block hash and checkpoint file are specified then the
|
||||||
if c, err := hexutil.Decode(ctx.String(BeaconCheckpointFlag.Name)); err == nil && len(c) <= 32 {
|
// client is initialized with the specified block hash and new checkpoints
|
||||||
copy(config.Checkpoint[:len(c)], c)
|
// are saved to the specified file.
|
||||||
} else {
|
if ctx.IsSet(BeaconCheckpointFileFlag.Name) {
|
||||||
Fatalf("Invalid hex string", "beacon.checkpoint", ctx.String(BeaconCheckpointFlag.Name), "error", err)
|
if _, err := config.SetCheckpointFile(ctx.String(BeaconCheckpointFileFlag.Name)); err != nil {
|
||||||
|
Fatalf("Could not load beacon checkpoint file", "beacon.checkpoint.file", ctx.String(BeaconCheckpointFileFlag.Name), "error", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if ctx.IsSet(BeaconCheckpointFlag.Name) {
|
||||||
|
hex := ctx.String(BeaconCheckpointFlag.Name)
|
||||||
|
c, err := hexutil.Decode(hex)
|
||||||
|
if err != nil {
|
||||||
|
Fatalf("Invalid hex string", "beacon.checkpoint", hex, "error", err)
|
||||||
|
}
|
||||||
|
if len(c) != 32 {
|
||||||
|
Fatalf("Invalid hex string length", "beacon.checkpoint", hex, "length", len(c))
|
||||||
|
}
|
||||||
|
copy(config.Checkpoint[:len(c)], c)
|
||||||
|
}
|
||||||
|
if config.Checkpoint == (common.Hash{}) {
|
||||||
|
Fatalf("Beacon checkpoint not specified")
|
||||||
|
}
|
||||||
config.Apis = ctx.StringSlice(BeaconApiFlag.Name)
|
config.Apis = ctx.StringSlice(BeaconApiFlag.Name)
|
||||||
if config.Apis == nil {
|
if config.Apis == nil {
|
||||||
Fatalf("Beacon node light client API URL not specified")
|
Fatalf("Beacon node light client API URL not specified")
|
||||||
|
|
@ -2188,6 +2208,8 @@ func MakeChain(ctx *cli.Context, stack *node.Node, readonly bool) (*core.BlockCh
|
||||||
}
|
}
|
||||||
if !ctx.Bool(SnapshotFlag.Name) {
|
if !ctx.Bool(SnapshotFlag.Name) {
|
||||||
cache.SnapshotLimit = 0 // Disabled
|
cache.SnapshotLimit = 0 // Disabled
|
||||||
|
} else if ctx.IsSet(CacheFlag.Name) || ctx.IsSet(CacheSnapshotFlag.Name) {
|
||||||
|
cache.SnapshotLimit = ctx.Int(CacheFlag.Name) * ctx.Int(CacheSnapshotFlag.Name) / 100
|
||||||
}
|
}
|
||||||
// If we're in readonly, do not bother generating snapshot data.
|
// If we're in readonly, do not bother generating snapshot data.
|
||||||
if readonly {
|
if readonly {
|
||||||
|
|
|
||||||
|
|
@ -171,7 +171,7 @@ func TestHistoryImportAndExport(t *testing.T) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("unable to initialize chain: %v", err)
|
t.Fatalf("unable to initialize chain: %v", err)
|
||||||
}
|
}
|
||||||
if err := ImportHistory(imported, db2, dir, "mainnet"); err != nil {
|
if err := ImportHistory(imported, dir, "mainnet"); err != nil {
|
||||||
t.Fatalf("failed to import chain: %v", err)
|
t.Fatalf("failed to import chain: %v", err)
|
||||||
}
|
}
|
||||||
if have, want := imported.CurrentHeader(), chain.CurrentHeader(); have.Hash() != want.Hash() {
|
if have, want := imported.CurrentHeader(), chain.CurrentHeader(); have.Hash() != want.Hash() {
|
||||||
|
|
|
||||||
|
|
@ -183,7 +183,7 @@ func benchInsertChain(b *testing.B, disk bool, gen func(int, *BlockGen)) {
|
||||||
if !disk {
|
if !disk {
|
||||||
db = rawdb.NewMemoryDatabase()
|
db = rawdb.NewMemoryDatabase()
|
||||||
} else {
|
} else {
|
||||||
pdb, err := pebble.New(b.TempDir(), 128, 128, "", false)
|
pdb, err := pebble.New(b.TempDir(), 128, 128, "", false, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatalf("cannot create temporary database: %v", err)
|
b.Fatalf("cannot create temporary database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -303,7 +303,7 @@ func makeChainForBench(db ethdb.Database, genesis *Genesis, full bool, count uin
|
||||||
func benchWriteChain(b *testing.B, full bool, count uint64) {
|
func benchWriteChain(b *testing.B, full bool, count uint64) {
|
||||||
genesis := &Genesis{Config: params.AllEthashProtocolChanges}
|
genesis := &Genesis{Config: params.AllEthashProtocolChanges}
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
pdb, err := pebble.New(b.TempDir(), 1024, 128, "", false)
|
pdb, err := pebble.New(b.TempDir(), 1024, 128, "", false, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatalf("error opening database: %v", err)
|
b.Fatalf("error opening database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -316,7 +316,7 @@ func benchWriteChain(b *testing.B, full bool, count uint64) {
|
||||||
func benchReadChain(b *testing.B, full bool, count uint64) {
|
func benchReadChain(b *testing.B, full bool, count uint64) {
|
||||||
dir := b.TempDir()
|
dir := b.TempDir()
|
||||||
|
|
||||||
pdb, err := pebble.New(dir, 1024, 128, "", false)
|
pdb, err := pebble.New(dir, 1024, 128, "", false, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatalf("error opening database: %v", err)
|
b.Fatalf("error opening database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -332,7 +332,7 @@ func benchReadChain(b *testing.B, full bool, count uint64) {
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
pdb, err = pebble.New(dir, 1024, 128, "", false)
|
pdb, err = pebble.New(dir, 1024, 128, "", false, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatalf("error opening database: %v", err)
|
b.Fatalf("error opening database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ import (
|
||||||
"math/big"
|
"math/big"
|
||||||
"runtime"
|
"runtime"
|
||||||
"slices"
|
"slices"
|
||||||
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
|
|
@ -157,7 +158,8 @@ type CacheConfig struct {
|
||||||
|
|
||||||
// This defines the cutoff block for history expiry.
|
// This defines the cutoff block for history expiry.
|
||||||
// Blocks before this number may be unavailable in the chain database.
|
// Blocks before this number may be unavailable in the chain database.
|
||||||
HistoryPruningCutoff uint64
|
HistoryPruningCutoffNumber uint64
|
||||||
|
HistoryPruningCutoffHash common.Hash
|
||||||
}
|
}
|
||||||
|
|
||||||
// triedbConfig derives the configures for trie database.
|
// triedbConfig derives the configures for trie database.
|
||||||
|
|
@ -262,7 +264,6 @@ type BlockChain struct {
|
||||||
txLookupLock sync.RWMutex
|
txLookupLock sync.RWMutex
|
||||||
txLookupCache *lru.Cache[common.Hash, txLookup]
|
txLookupCache *lru.Cache[common.Hash, txLookup]
|
||||||
|
|
||||||
wg sync.WaitGroup
|
|
||||||
quit chan struct{} // shutdown signal, closed in Stop.
|
quit chan struct{} // shutdown signal, closed in Stop.
|
||||||
stopping atomic.Bool // false if chain is running, true when stopped
|
stopping atomic.Bool // false if chain is running, true when stopped
|
||||||
procInterrupt atomic.Bool // interrupt signaler for block processing
|
procInterrupt atomic.Bool // interrupt signaler for block processing
|
||||||
|
|
@ -333,10 +334,10 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis
|
||||||
bc.processor = NewStateProcessor(chainConfig, bc.hc)
|
bc.processor = NewStateProcessor(chainConfig, bc.hc)
|
||||||
|
|
||||||
genesisHeader := bc.GetHeaderByNumber(0)
|
genesisHeader := bc.GetHeaderByNumber(0)
|
||||||
bc.genesisBlock = types.NewBlockWithHeader(genesisHeader)
|
if genesisHeader == nil {
|
||||||
if bc.genesisBlock == nil {
|
|
||||||
return nil, ErrNoGenesis
|
return nil, ErrNoGenesis
|
||||||
}
|
}
|
||||||
|
bc.genesisBlock = types.NewBlockWithHeader(genesisHeader)
|
||||||
|
|
||||||
bc.currentBlock.Store(nil)
|
bc.currentBlock.Store(nil)
|
||||||
bc.currentSnapBlock.Store(nil)
|
bc.currentSnapBlock.Store(nil)
|
||||||
|
|
@ -1110,7 +1111,6 @@ func (bc *BlockChain) stopWithoutSaving() {
|
||||||
// the mutex should become available quickly. It cannot be taken again after Close has
|
// the mutex should become available quickly. It cannot be taken again after Close has
|
||||||
// returned.
|
// returned.
|
||||||
bc.chainmu.Close()
|
bc.chainmu.Close()
|
||||||
bc.wg.Wait()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stop stops the blockchain service. If any imports are currently in progress
|
// Stop stops the blockchain service. If any imports are currently in progress
|
||||||
|
|
@ -1197,79 +1197,64 @@ const (
|
||||||
SideStatTy
|
SideStatTy
|
||||||
)
|
)
|
||||||
|
|
||||||
// InsertReceiptChain attempts to complete an already existing header chain with
|
// InsertReceiptChain inserts a batch of blocks along with their receipts into
|
||||||
// transaction and receipt data.
|
// the database. Unlike InsertChain, this function does not verify the state root
|
||||||
|
// in the blocks. It is used exclusively for snap sync. All the inserted blocks
|
||||||
|
// will be regarded as canonical, chain reorg is not supported.
|
||||||
|
//
|
||||||
|
// The optional ancientLimit can also be specified and chain segment before that
|
||||||
|
// will be directly stored in the ancient, getting rid of the chain migration.
|
||||||
func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts, ancientLimit uint64) (int, error) {
|
func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts, ancientLimit uint64) (int, error) {
|
||||||
// We don't require the chainMu here since we want to maximize the
|
// Verify the supplied headers before insertion without lock
|
||||||
// concurrency of header insertion and receipt insertion.
|
var headers []*types.Header
|
||||||
bc.wg.Add(1)
|
for _, block := range blockChain {
|
||||||
defer bc.wg.Done()
|
headers = append(headers, block.Header())
|
||||||
|
|
||||||
var (
|
// Here we also validate that blob transactions in the block do not
|
||||||
ancientBlocks, liveBlocks types.Blocks
|
// contain a sidecar. While the sidecar does not affect the block hash
|
||||||
ancientReceipts, liveReceipts []types.Receipts
|
// or tx hash, sending blobs within a block is not allowed.
|
||||||
)
|
|
||||||
// Do a sanity check that the provided chain is actually ordered and linked
|
|
||||||
for i, block := range blockChain {
|
|
||||||
if i != 0 {
|
|
||||||
prev := blockChain[i-1]
|
|
||||||
if block.NumberU64() != prev.NumberU64()+1 || block.ParentHash() != prev.Hash() {
|
|
||||||
log.Error("Non contiguous receipt insert",
|
|
||||||
"number", block.Number(), "hash", block.Hash(), "parent", block.ParentHash(),
|
|
||||||
"prevnumber", prev.Number(), "prevhash", prev.Hash())
|
|
||||||
return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x..], item %d is #%d [%x..] (parent [%x..])",
|
|
||||||
i-1, prev.NumberU64(), prev.Hash().Bytes()[:4],
|
|
||||||
i, block.NumberU64(), block.Hash().Bytes()[:4], block.ParentHash().Bytes()[:4])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if block.NumberU64() <= ancientLimit {
|
|
||||||
ancientBlocks, ancientReceipts = append(ancientBlocks, block), append(ancientReceipts, receiptChain[i])
|
|
||||||
} else {
|
|
||||||
liveBlocks, liveReceipts = append(liveBlocks, block), append(liveReceipts, receiptChain[i])
|
|
||||||
}
|
|
||||||
|
|
||||||
// Here we also validate that blob transactions in the block do not contain a sidecar.
|
|
||||||
// While the sidecar does not affect the block hash / tx hash, sending blobs within a block is not allowed.
|
|
||||||
for txIndex, tx := range block.Transactions() {
|
for txIndex, tx := range block.Transactions() {
|
||||||
if tx.Type() == types.BlobTxType && tx.BlobTxSidecar() != nil {
|
if tx.Type() == types.BlobTxType && tx.BlobTxSidecar() != nil {
|
||||||
return 0, fmt.Errorf("block #%d contains unexpected blob sidecar in tx at index %d", block.NumberU64(), txIndex)
|
return 0, fmt.Errorf("block #%d contains unexpected blob sidecar in tx at index %d", block.NumberU64(), txIndex)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if n, err := bc.hc.ValidateHeaderChain(headers); err != nil {
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
// Hold the mutation lock
|
||||||
|
if !bc.chainmu.TryLock() {
|
||||||
|
return 0, errChainStopped
|
||||||
|
}
|
||||||
|
defer bc.chainmu.Unlock()
|
||||||
|
|
||||||
var (
|
var (
|
||||||
stats = struct{ processed, ignored int32 }{}
|
stats = struct{ processed, ignored int32 }{}
|
||||||
start = time.Now()
|
start = time.Now()
|
||||||
size = int64(0)
|
size = int64(0)
|
||||||
)
|
)
|
||||||
|
// updateHead updates the head header and head snap block flags.
|
||||||
// updateHead updates the head snap sync block if the inserted blocks are better
|
updateHead := func(header *types.Header) error {
|
||||||
// and returns an indicator whether the inserted blocks are canonical.
|
batch := bc.db.NewBatch()
|
||||||
updateHead := func(head *types.Block) bool {
|
hash := header.Hash()
|
||||||
if !bc.chainmu.TryLock() {
|
rawdb.WriteHeadHeaderHash(batch, hash)
|
||||||
return false
|
rawdb.WriteHeadFastBlockHash(batch, hash)
|
||||||
|
if err := batch.Write(); err != nil {
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
defer bc.chainmu.Unlock()
|
bc.hc.currentHeader.Store(header)
|
||||||
|
bc.currentSnapBlock.Store(header)
|
||||||
// Rewind may have occurred, skip in that case.
|
headHeaderGauge.Update(header.Number.Int64())
|
||||||
if bc.CurrentHeader().Number.Cmp(head.Number()) >= 0 {
|
headFastBlockGauge.Update(header.Number.Int64())
|
||||||
rawdb.WriteHeadFastBlockHash(bc.db, head.Hash())
|
return nil
|
||||||
bc.currentSnapBlock.Store(head.Header())
|
|
||||||
headFastBlockGauge.Update(int64(head.NumberU64()))
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
// writeAncient writes blockchain and corresponding receipt chain into ancient store.
|
// writeAncient writes blockchain and corresponding receipt chain into ancient store.
|
||||||
//
|
//
|
||||||
// this function only accepts canonical chain data. All side chain will be reverted
|
// this function only accepts canonical chain data. All side chain will be reverted
|
||||||
// eventually.
|
// eventually.
|
||||||
writeAncient := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
|
writeAncient := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
|
||||||
first := blockChain[0]
|
// Ensure genesis is in the ancient store
|
||||||
last := blockChain[len(blockChain)-1]
|
if blockChain[0].NumberU64() == 1 {
|
||||||
|
|
||||||
// Ensure genesis is in ancients.
|
|
||||||
if first.NumberU64() == 1 {
|
|
||||||
if frozen, _ := bc.db.Ancients(); frozen == 0 {
|
if frozen, _ := bc.db.Ancients(); frozen == 0 {
|
||||||
writeSize, err := rawdb.WriteAncientBlocks(bc.db, []*types.Block{bc.genesisBlock}, []types.Receipts{nil})
|
writeSize, err := rawdb.WriteAncientBlocks(bc.db, []*types.Block{bc.genesisBlock}, []types.Receipts{nil})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -1280,12 +1265,6 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [
|
||||||
log.Info("Wrote genesis to ancients")
|
log.Info("Wrote genesis to ancients")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Before writing the blocks to the ancients, we need to ensure that
|
|
||||||
// they correspond to the what the headerchain 'expects'.
|
|
||||||
// We only check the last block/header, since it's a contiguous chain.
|
|
||||||
if !bc.HasHeader(last.Hash(), last.NumberU64()) {
|
|
||||||
return 0, fmt.Errorf("containing header #%d [%x..] unknown", last.Number(), last.Hash().Bytes()[:4])
|
|
||||||
}
|
|
||||||
// Write all chain data to ancients.
|
// Write all chain data to ancients.
|
||||||
writeSize, err := rawdb.WriteAncientBlocks(bc.db, blockChain, receiptChain)
|
writeSize, err := rawdb.WriteAncientBlocks(bc.db, blockChain, receiptChain)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -1298,44 +1277,28 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [
|
||||||
if err := bc.db.Sync(); err != nil {
|
if err := bc.db.Sync(); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
// Update the current snap block because all block data is now present in DB.
|
// Write hash to number mappings
|
||||||
previousSnapBlock := bc.CurrentSnapBlock().Number.Uint64()
|
batch := bc.db.NewBatch()
|
||||||
if !updateHead(blockChain[len(blockChain)-1]) {
|
|
||||||
// We end up here if the header chain has reorg'ed, and the blocks/receipts
|
|
||||||
// don't match the canonical chain.
|
|
||||||
if _, err := bc.db.TruncateHead(previousSnapBlock + 1); err != nil {
|
|
||||||
log.Error("Can't truncate ancient store after failed insert", "err", err)
|
|
||||||
}
|
|
||||||
return 0, errSideChainReceipts
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete block data from the main database.
|
|
||||||
var (
|
|
||||||
batch = bc.db.NewBatch()
|
|
||||||
canonHashes = make(map[common.Hash]struct{}, len(blockChain))
|
|
||||||
)
|
|
||||||
for _, block := range blockChain {
|
for _, block := range blockChain {
|
||||||
canonHashes[block.Hash()] = struct{}{}
|
rawdb.WriteHeaderNumber(batch, block.Hash(), block.NumberU64())
|
||||||
if block.NumberU64() == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
rawdb.DeleteCanonicalHash(batch, block.NumberU64())
|
|
||||||
rawdb.DeleteBlockWithoutNumber(batch, block.Hash(), block.NumberU64())
|
|
||||||
}
|
|
||||||
// Delete side chain hash-to-number mappings.
|
|
||||||
for _, nh := range rawdb.ReadAllHashesInRange(bc.db, first.NumberU64(), last.NumberU64()) {
|
|
||||||
if _, canon := canonHashes[nh.Hash]; !canon {
|
|
||||||
rawdb.DeleteHeader(batch, nh.Hash, nh.Number)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if err := batch.Write(); err != nil {
|
if err := batch.Write(); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
// Update the current snap block because all block data is now present in DB.
|
||||||
|
if err := updateHead(blockChain[len(blockChain)-1].Header()); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
stats.processed += int32(len(blockChain))
|
stats.processed += int32(len(blockChain))
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeLive writes blockchain and corresponding receipt chain into active store.
|
// writeLive writes the blockchain and corresponding receipt chain to the active store.
|
||||||
|
//
|
||||||
|
// Notably, in different snap sync cycles, the supplied chain may partially reorganize
|
||||||
|
// existing local chain segments (reorg around the chain tip). The reorganized part
|
||||||
|
// will be included in the provided chain segment, and stale canonical markers will be
|
||||||
|
// silently rewritten. Therefore, no explicit reorg logic is needed.
|
||||||
writeLive := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
|
writeLive := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
|
||||||
var (
|
var (
|
||||||
skipPresenceCheck = false
|
skipPresenceCheck = false
|
||||||
|
|
@ -1346,10 +1309,6 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [
|
||||||
if bc.insertStopped() {
|
if bc.insertStopped() {
|
||||||
return 0, errInsertionInterrupted
|
return 0, errInsertionInterrupted
|
||||||
}
|
}
|
||||||
// Short circuit if the owner header is unknown
|
|
||||||
if !bc.HasHeader(block.Hash(), block.NumberU64()) {
|
|
||||||
return i, fmt.Errorf("containing header #%d [%x..] unknown", block.Number(), block.Hash().Bytes()[:4])
|
|
||||||
}
|
|
||||||
if !skipPresenceCheck {
|
if !skipPresenceCheck {
|
||||||
// Ignore if the entire data is already known
|
// Ignore if the entire data is already known
|
||||||
if bc.HasBlock(block.Hash(), block.NumberU64()) {
|
if bc.HasBlock(block.Hash(), block.NumberU64()) {
|
||||||
|
|
@ -1363,7 +1322,8 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Write all the data out into the database
|
// Write all the data out into the database
|
||||||
rawdb.WriteBody(batch, block.Hash(), block.NumberU64(), block.Body())
|
rawdb.WriteCanonicalHash(batch, block.Hash(), block.NumberU64())
|
||||||
|
rawdb.WriteBlock(batch, block)
|
||||||
rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receiptChain[i])
|
rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receiptChain[i])
|
||||||
|
|
||||||
// Write everything belongs to the blocks into the database. So that
|
// Write everything belongs to the blocks into the database. So that
|
||||||
|
|
@ -1387,21 +1347,27 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
updateHead(blockChain[len(blockChain)-1])
|
if err := updateHead(blockChain[len(blockChain)-1].Header()); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write downloaded chain data and corresponding receipt chain data
|
// Split the supplied blocks into two groups, according to the
|
||||||
if len(ancientBlocks) > 0 {
|
// given ancient limit.
|
||||||
if n, err := writeAncient(ancientBlocks, ancientReceipts); err != nil {
|
index := sort.Search(len(blockChain), func(i int) bool {
|
||||||
|
return blockChain[i].NumberU64() >= ancientLimit
|
||||||
|
})
|
||||||
|
if index > 0 {
|
||||||
|
if n, err := writeAncient(blockChain[:index], receiptChain[:index]); err != nil {
|
||||||
if err == errInsertionInterrupted {
|
if err == errInsertionInterrupted {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
return n, err
|
return n, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(liveBlocks) > 0 {
|
if index != len(blockChain) {
|
||||||
if n, err := writeLive(liveBlocks, liveReceipts); err != nil {
|
if n, err := writeLive(blockChain[index:], receiptChain[index:]); err != nil {
|
||||||
if err == errInsertionInterrupted {
|
if err == errInsertionInterrupted {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
@ -1420,7 +1386,6 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [
|
||||||
context = append(context, []interface{}{"ignored", stats.ignored}...)
|
context = append(context, []interface{}{"ignored", stats.ignored}...)
|
||||||
}
|
}
|
||||||
log.Debug("Imported new block receipts", context...)
|
log.Debug("Imported new block receipts", context...)
|
||||||
|
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2505,15 +2470,83 @@ func (bc *BlockChain) InsertHeaderChain(chain []*types.Header) (int, error) {
|
||||||
if i, err := bc.hc.ValidateHeaderChain(chain); err != nil {
|
if i, err := bc.hc.ValidateHeaderChain(chain); err != nil {
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if !bc.chainmu.TryLock() {
|
if !bc.chainmu.TryLock() {
|
||||||
return 0, errChainStopped
|
return 0, errChainStopped
|
||||||
}
|
}
|
||||||
defer bc.chainmu.Unlock()
|
defer bc.chainmu.Unlock()
|
||||||
|
|
||||||
_, err := bc.hc.InsertHeaderChain(chain, start)
|
_, err := bc.hc.InsertHeaderChain(chain, start)
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// InsertHeadersBeforeCutoff inserts the given headers into the ancient store
|
||||||
|
// as they are claimed older than the configured chain cutoff point. All the
|
||||||
|
// inserted headers are regarded as canonical and chain reorg is not supported.
|
||||||
|
func (bc *BlockChain) InsertHeadersBeforeCutoff(headers []*types.Header) (int, error) {
|
||||||
|
if len(headers) == 0 {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
// TODO(rjl493456442): Headers before the configured cutoff have already
|
||||||
|
// been verified by the hash of cutoff header. Theoretically, header validation
|
||||||
|
// could be skipped here.
|
||||||
|
if n, err := bc.hc.ValidateHeaderChain(headers); err != nil {
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
if !bc.chainmu.TryLock() {
|
||||||
|
return 0, errChainStopped
|
||||||
|
}
|
||||||
|
defer bc.chainmu.Unlock()
|
||||||
|
|
||||||
|
// Initialize the ancient store with genesis block if it's empty.
|
||||||
|
var (
|
||||||
|
frozen, _ = bc.db.Ancients()
|
||||||
|
first = headers[0].Number.Uint64()
|
||||||
|
)
|
||||||
|
if first == 1 && frozen == 0 {
|
||||||
|
_, err := rawdb.WriteAncientBlocks(bc.db, []*types.Block{bc.genesisBlock}, []types.Receipts{nil})
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error writing genesis to ancients", "err", err)
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
log.Info("Wrote genesis to ancient store")
|
||||||
|
} else if frozen != first {
|
||||||
|
return 0, fmt.Errorf("headers are gapped with the ancient store, first: %d, ancient: %d", first, frozen)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write headers to the ancient store, with block bodies and receipts set to nil
|
||||||
|
// to ensure consistency across tables in the freezer.
|
||||||
|
_, err := rawdb.WriteAncientHeaderChain(bc.db, headers)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if err := bc.db.Sync(); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
// Write hash to number mappings
|
||||||
|
batch := bc.db.NewBatch()
|
||||||
|
for _, header := range headers {
|
||||||
|
rawdb.WriteHeaderNumber(batch, header.Hash(), header.Number.Uint64())
|
||||||
|
}
|
||||||
|
// Write head header and head snap block flags
|
||||||
|
last := headers[len(headers)-1]
|
||||||
|
rawdb.WriteHeadHeaderHash(batch, last.Hash())
|
||||||
|
rawdb.WriteHeadFastBlockHash(batch, last.Hash())
|
||||||
|
if err := batch.Write(); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
// Truncate the useless chain segment (zero bodies and receipts) in the
|
||||||
|
// ancient store.
|
||||||
|
if _, err := bc.db.TruncateTail(last.Number.Uint64() + 1); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
// Last step update all in-memory markers
|
||||||
|
bc.hc.currentHeader.Store(last)
|
||||||
|
bc.currentSnapBlock.Store(last)
|
||||||
|
headHeaderGauge.Update(last.Number.Int64())
|
||||||
|
headFastBlockGauge.Update(last.Number.Int64())
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
// SetBlockValidatorAndProcessorForTesting sets the current validator and processor.
|
// SetBlockValidatorAndProcessorForTesting sets the current validator and processor.
|
||||||
// This method can be used to force an invalid blockchain to be verified for tests.
|
// This method can be used to force an invalid blockchain to be verified for tests.
|
||||||
// This method is unsafe and should only be used before block import starts.
|
// This method is unsafe and should only be used before block import starts.
|
||||||
|
|
@ -2533,9 +2566,3 @@ func (bc *BlockChain) SetTrieFlushInterval(interval time.Duration) {
|
||||||
func (bc *BlockChain) GetTrieFlushInterval() time.Duration {
|
func (bc *BlockChain) GetTrieFlushInterval() time.Duration {
|
||||||
return time.Duration(bc.flushInterval.Load())
|
return time.Duration(bc.flushInterval.Load())
|
||||||
}
|
}
|
||||||
|
|
||||||
// HistoryPruningCutoff returns the configured history pruning point.
|
|
||||||
// Blocks before this might not be available in the database.
|
|
||||||
func (bc *BlockChain) HistoryPruningCutoff() uint64 {
|
|
||||||
return bc.cacheConfig.HistoryPruningCutoff
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -86,6 +86,11 @@ func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
|
||||||
return bc.hc.GetHeaderByNumber(number)
|
return bc.hc.GetHeaderByNumber(number)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetBlockNumber retrieves the block number associated with a block hash.
|
||||||
|
func (bc *BlockChain) GetBlockNumber(hash common.Hash) *uint64 {
|
||||||
|
return bc.hc.GetBlockNumber(hash)
|
||||||
|
}
|
||||||
|
|
||||||
// GetHeadersFrom returns a contiguous segment of headers, in rlp-form, going
|
// GetHeadersFrom returns a contiguous segment of headers, in rlp-form, going
|
||||||
// backwards from the given number.
|
// backwards from the given number.
|
||||||
func (bc *BlockChain) GetHeadersFrom(number, count uint64) []rlp.RawValue {
|
func (bc *BlockChain) GetHeadersFrom(number, count uint64) []rlp.RawValue {
|
||||||
|
|
@ -402,6 +407,12 @@ func (bc *BlockChain) TxIndexProgress() (TxIndexProgress, error) {
|
||||||
return bc.txIndexer.txIndexProgress()
|
return bc.txIndexer.txIndexProgress()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// HistoryPruningCutoff returns the configured history pruning point.
|
||||||
|
// Blocks before this might not be available in the database.
|
||||||
|
func (bc *BlockChain) HistoryPruningCutoff() (uint64, common.Hash) {
|
||||||
|
return bc.cacheConfig.HistoryPruningCutoffNumber, bc.cacheConfig.HistoryPruningCutoffHash
|
||||||
|
}
|
||||||
|
|
||||||
// TrieDB retrieves the low level trie database used for data storage.
|
// TrieDB retrieves the low level trie database used for data storage.
|
||||||
func (bc *BlockChain) TrieDB() *triedb.Database {
|
func (bc *BlockChain) TrieDB() *triedb.Database {
|
||||||
return bc.triedb
|
return bc.triedb
|
||||||
|
|
|
||||||
|
|
@ -1765,7 +1765,7 @@ func testRepairWithScheme(t *testing.T, tt *rewindTest, snapshots bool, scheme s
|
||||||
datadir := t.TempDir()
|
datadir := t.TempDir()
|
||||||
ancient := filepath.Join(datadir, "ancient")
|
ancient := filepath.Join(datadir, "ancient")
|
||||||
|
|
||||||
pdb, err := pebble.New(datadir, 0, 0, "", false)
|
pdb, err := pebble.New(datadir, 0, 0, "", false, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to create persistent key-value database: %v", err)
|
t.Fatalf("Failed to create persistent key-value database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -1850,7 +1850,7 @@ func testRepairWithScheme(t *testing.T, tt *rewindTest, snapshots bool, scheme s
|
||||||
chain.stopWithoutSaving()
|
chain.stopWithoutSaving()
|
||||||
|
|
||||||
// Start a new blockchain back up and see where the repair leads us
|
// Start a new blockchain back up and see where the repair leads us
|
||||||
pdb, err = pebble.New(datadir, 0, 0, "", false)
|
pdb, err = pebble.New(datadir, 0, 0, "", false, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to reopen persistent key-value database: %v", err)
|
t.Fatalf("Failed to reopen persistent key-value database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -1915,7 +1915,7 @@ func testIssue23496(t *testing.T, scheme string) {
|
||||||
datadir := t.TempDir()
|
datadir := t.TempDir()
|
||||||
ancient := filepath.Join(datadir, "ancient")
|
ancient := filepath.Join(datadir, "ancient")
|
||||||
|
|
||||||
pdb, err := pebble.New(datadir, 0, 0, "", false)
|
pdb, err := pebble.New(datadir, 0, 0, "", false, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to create persistent key-value database: %v", err)
|
t.Fatalf("Failed to create persistent key-value database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -1973,7 +1973,7 @@ func testIssue23496(t *testing.T, scheme string) {
|
||||||
chain.stopWithoutSaving()
|
chain.stopWithoutSaving()
|
||||||
|
|
||||||
// Start a new blockchain back up and see where the repair leads us
|
// Start a new blockchain back up and see where the repair leads us
|
||||||
pdb, err = pebble.New(datadir, 0, 0, "", false)
|
pdb, err = pebble.New(datadir, 0, 0, "", false, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to reopen persistent key-value database: %v", err)
|
t.Fatalf("Failed to reopen persistent key-value database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1969,7 +1969,7 @@ func testSetHeadWithScheme(t *testing.T, tt *rewindTest, snapshots bool, scheme
|
||||||
datadir := t.TempDir()
|
datadir := t.TempDir()
|
||||||
ancient := filepath.Join(datadir, "ancient")
|
ancient := filepath.Join(datadir, "ancient")
|
||||||
|
|
||||||
pdb, err := pebble.New(datadir, 0, 0, "", false)
|
pdb, err := pebble.New(datadir, 0, 0, "", false, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to create persistent key-value database: %v", err)
|
t.Fatalf("Failed to create persistent key-value database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -66,7 +66,7 @@ func (basic *snapshotTestBasic) prepare(t *testing.T) (*BlockChain, []*types.Blo
|
||||||
datadir := t.TempDir()
|
datadir := t.TempDir()
|
||||||
ancient := filepath.Join(datadir, "ancient")
|
ancient := filepath.Join(datadir, "ancient")
|
||||||
|
|
||||||
pdb, err := pebble.New(datadir, 0, 0, "", false)
|
pdb, err := pebble.New(datadir, 0, 0, "", false, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to create persistent key-value database: %v", err)
|
t.Fatalf("Failed to create persistent key-value database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -257,7 +257,7 @@ func (snaptest *crashSnapshotTest) test(t *testing.T) {
|
||||||
chain.triedb.Close()
|
chain.triedb.Close()
|
||||||
|
|
||||||
// Start a new blockchain back up and see where the repair leads us
|
// Start a new blockchain back up and see where the repair leads us
|
||||||
pdb, err := pebble.New(snaptest.datadir, 0, 0, "", false)
|
pdb, err := pebble.New(snaptest.datadir, 0, 0, "", false, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to create persistent key-value database: %v", err)
|
t.Fatalf("Failed to create persistent key-value database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -733,13 +733,6 @@ func testFastVsFullChains(t *testing.T, scheme string) {
|
||||||
fast, _ := NewBlockChain(fastDb, DefaultCacheConfigWithScheme(scheme), gspec, nil, ethash.NewFaker(), vm.Config{}, nil)
|
fast, _ := NewBlockChain(fastDb, DefaultCacheConfigWithScheme(scheme), gspec, nil, ethash.NewFaker(), vm.Config{}, nil)
|
||||||
defer fast.Stop()
|
defer fast.Stop()
|
||||||
|
|
||||||
headers := make([]*types.Header, len(blocks))
|
|
||||||
for i, block := range blocks {
|
|
||||||
headers[i] = block.Header()
|
|
||||||
}
|
|
||||||
if n, err := fast.InsertHeaderChain(headers); err != nil {
|
|
||||||
t.Fatalf("failed to insert header %d: %v", n, err)
|
|
||||||
}
|
|
||||||
if n, err := fast.InsertReceiptChain(blocks, receipts, 0); err != nil {
|
if n, err := fast.InsertReceiptChain(blocks, receipts, 0); err != nil {
|
||||||
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
||||||
}
|
}
|
||||||
|
|
@ -753,9 +746,6 @@ func testFastVsFullChains(t *testing.T, scheme string) {
|
||||||
ancient, _ := NewBlockChain(ancientDb, DefaultCacheConfigWithScheme(scheme), gspec, nil, ethash.NewFaker(), vm.Config{}, nil)
|
ancient, _ := NewBlockChain(ancientDb, DefaultCacheConfigWithScheme(scheme), gspec, nil, ethash.NewFaker(), vm.Config{}, nil)
|
||||||
defer ancient.Stop()
|
defer ancient.Stop()
|
||||||
|
|
||||||
if n, err := ancient.InsertHeaderChain(headers); err != nil {
|
|
||||||
t.Fatalf("failed to insert header %d: %v", n, err)
|
|
||||||
}
|
|
||||||
if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(len(blocks)/2)); err != nil {
|
if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(len(blocks)/2)); err != nil {
|
||||||
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
||||||
}
|
}
|
||||||
|
|
@ -880,13 +870,6 @@ func testLightVsFastVsFullChainHeads(t *testing.T, scheme string) {
|
||||||
fast, _ := NewBlockChain(fastDb, DefaultCacheConfigWithScheme(scheme), gspec, nil, ethash.NewFaker(), vm.Config{}, nil)
|
fast, _ := NewBlockChain(fastDb, DefaultCacheConfigWithScheme(scheme), gspec, nil, ethash.NewFaker(), vm.Config{}, nil)
|
||||||
defer fast.Stop()
|
defer fast.Stop()
|
||||||
|
|
||||||
headers := make([]*types.Header, len(blocks))
|
|
||||||
for i, block := range blocks {
|
|
||||||
headers[i] = block.Header()
|
|
||||||
}
|
|
||||||
if n, err := fast.InsertHeaderChain(headers); err != nil {
|
|
||||||
t.Fatalf("failed to insert header %d: %v", n, err)
|
|
||||||
}
|
|
||||||
if n, err := fast.InsertReceiptChain(blocks, receipts, 0); err != nil {
|
if n, err := fast.InsertReceiptChain(blocks, receipts, 0); err != nil {
|
||||||
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
||||||
}
|
}
|
||||||
|
|
@ -900,9 +883,6 @@ func testLightVsFastVsFullChainHeads(t *testing.T, scheme string) {
|
||||||
ancient, _ := NewBlockChain(ancientDb, DefaultCacheConfigWithScheme(scheme), gspec, nil, ethash.NewFaker(), vm.Config{}, nil)
|
ancient, _ := NewBlockChain(ancientDb, DefaultCacheConfigWithScheme(scheme), gspec, nil, ethash.NewFaker(), vm.Config{}, nil)
|
||||||
defer ancient.Stop()
|
defer ancient.Stop()
|
||||||
|
|
||||||
if n, err := ancient.InsertHeaderChain(headers); err != nil {
|
|
||||||
t.Fatalf("failed to insert header %d: %v", n, err)
|
|
||||||
}
|
|
||||||
if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(3*len(blocks)/4)); err != nil {
|
if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(3*len(blocks)/4)); err != nil {
|
||||||
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
||||||
}
|
}
|
||||||
|
|
@ -916,6 +896,11 @@ func testLightVsFastVsFullChainHeads(t *testing.T, scheme string) {
|
||||||
// Import the chain as a light node and ensure all pointers are updated
|
// Import the chain as a light node and ensure all pointers are updated
|
||||||
lightDb := makeDb()
|
lightDb := makeDb()
|
||||||
defer lightDb.Close()
|
defer lightDb.Close()
|
||||||
|
|
||||||
|
headers := make([]*types.Header, len(blocks))
|
||||||
|
for i, block := range blocks {
|
||||||
|
headers[i] = block.Header()
|
||||||
|
}
|
||||||
light, _ := NewBlockChain(lightDb, DefaultCacheConfigWithScheme(scheme), gspec, nil, ethash.NewFaker(), vm.Config{}, nil)
|
light, _ := NewBlockChain(lightDb, DefaultCacheConfigWithScheme(scheme), gspec, nil, ethash.NewFaker(), vm.Config{}, nil)
|
||||||
if n, err := light.InsertHeaderChain(headers); err != nil {
|
if n, err := light.InsertHeaderChain(headers); err != nil {
|
||||||
t.Fatalf("failed to insert header %d: %v", n, err)
|
t.Fatalf("failed to insert header %d: %v", n, err)
|
||||||
|
|
@ -1710,13 +1695,6 @@ func testBlockchainRecovery(t *testing.T, scheme string) {
|
||||||
defer ancientDb.Close()
|
defer ancientDb.Close()
|
||||||
ancient, _ := NewBlockChain(ancientDb, DefaultCacheConfigWithScheme(scheme), gspec, nil, ethash.NewFaker(), vm.Config{}, nil)
|
ancient, _ := NewBlockChain(ancientDb, DefaultCacheConfigWithScheme(scheme), gspec, nil, ethash.NewFaker(), vm.Config{}, nil)
|
||||||
|
|
||||||
headers := make([]*types.Header, len(blocks))
|
|
||||||
for i, block := range blocks {
|
|
||||||
headers[i] = block.Header()
|
|
||||||
}
|
|
||||||
if n, err := ancient.InsertHeaderChain(headers); err != nil {
|
|
||||||
t.Fatalf("failed to insert header %d: %v", n, err)
|
|
||||||
}
|
|
||||||
if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(3*len(blocks)/4)); err != nil {
|
if n, err := ancient.InsertReceiptChain(blocks, receipts, uint64(3*len(blocks)/4)); err != nil {
|
||||||
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
||||||
}
|
}
|
||||||
|
|
@ -1741,82 +1719,6 @@ func testBlockchainRecovery(t *testing.T, scheme string) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// This test checks that InsertReceiptChain will roll back correctly when attempting to insert a side chain.
|
|
||||||
func TestInsertReceiptChainRollback(t *testing.T) {
|
|
||||||
testInsertReceiptChainRollback(t, rawdb.HashScheme)
|
|
||||||
testInsertReceiptChainRollback(t, rawdb.PathScheme)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testInsertReceiptChainRollback(t *testing.T, scheme string) {
|
|
||||||
// Generate forked chain. The returned BlockChain object is used to process the side chain blocks.
|
|
||||||
tmpChain, sideblocks, canonblocks, gspec, err := getLongAndShortChains(scheme)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer tmpChain.Stop()
|
|
||||||
// Get the side chain receipts.
|
|
||||||
if _, err := tmpChain.InsertChain(sideblocks); err != nil {
|
|
||||||
t.Fatal("processing side chain failed:", err)
|
|
||||||
}
|
|
||||||
t.Log("sidechain head:", tmpChain.CurrentBlock().Number, tmpChain.CurrentBlock().Hash())
|
|
||||||
sidechainReceipts := make([]types.Receipts, len(sideblocks))
|
|
||||||
for i, block := range sideblocks {
|
|
||||||
sidechainReceipts[i] = tmpChain.GetReceiptsByHash(block.Hash())
|
|
||||||
}
|
|
||||||
// Get the canon chain receipts.
|
|
||||||
if _, err := tmpChain.InsertChain(canonblocks); err != nil {
|
|
||||||
t.Fatal("processing canon chain failed:", err)
|
|
||||||
}
|
|
||||||
t.Log("canon head:", tmpChain.CurrentBlock().Number, tmpChain.CurrentBlock().Hash())
|
|
||||||
canonReceipts := make([]types.Receipts, len(canonblocks))
|
|
||||||
for i, block := range canonblocks {
|
|
||||||
canonReceipts[i] = tmpChain.GetReceiptsByHash(block.Hash())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set up a BlockChain that uses the ancient store.
|
|
||||||
ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), "", "", false)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to create temp freezer db: %v", err)
|
|
||||||
}
|
|
||||||
defer ancientDb.Close()
|
|
||||||
|
|
||||||
ancientChain, _ := NewBlockChain(ancientDb, DefaultCacheConfigWithScheme(scheme), gspec, nil, ethash.NewFaker(), vm.Config{}, nil)
|
|
||||||
defer ancientChain.Stop()
|
|
||||||
|
|
||||||
// Import the canonical header chain.
|
|
||||||
canonHeaders := make([]*types.Header, len(canonblocks))
|
|
||||||
for i, block := range canonblocks {
|
|
||||||
canonHeaders[i] = block.Header()
|
|
||||||
}
|
|
||||||
if _, err = ancientChain.InsertHeaderChain(canonHeaders); err != nil {
|
|
||||||
t.Fatal("can't import canon headers:", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to insert blocks/receipts of the side chain.
|
|
||||||
_, err = ancientChain.InsertReceiptChain(sideblocks, sidechainReceipts, uint64(len(sideblocks)))
|
|
||||||
if err == nil {
|
|
||||||
t.Fatal("expected error from InsertReceiptChain.")
|
|
||||||
}
|
|
||||||
if ancientChain.CurrentSnapBlock().Number.Uint64() != 0 {
|
|
||||||
t.Fatalf("failed to rollback ancient data, want %d, have %d", 0, ancientChain.CurrentSnapBlock().Number)
|
|
||||||
}
|
|
||||||
if frozen, err := ancientChain.db.Ancients(); err != nil || frozen != 1 {
|
|
||||||
t.Fatalf("failed to truncate ancient data, frozen index is %d", frozen)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Insert blocks/receipts of the canonical chain.
|
|
||||||
_, err = ancientChain.InsertReceiptChain(canonblocks, canonReceipts, uint64(len(canonblocks)))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("can't import canon chain receipts: %v", err)
|
|
||||||
}
|
|
||||||
if ancientChain.CurrentSnapBlock().Number.Uint64() != canonblocks[len(canonblocks)-1].NumberU64() {
|
|
||||||
t.Fatalf("failed to insert ancient recept chain after rollback")
|
|
||||||
}
|
|
||||||
if frozen, _ := ancientChain.db.Ancients(); frozen != uint64(len(canonblocks))+1 {
|
|
||||||
t.Fatalf("wrong ancients count %d", frozen)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tests that importing a very large side fork, which is larger than the canon chain,
|
// Tests that importing a very large side fork, which is larger than the canon chain,
|
||||||
// but where the difficulty per block is kept low: this means that it will not
|
// but where the difficulty per block is kept low: this means that it will not
|
||||||
// overtake the 'canon' chain until after it's passed canon by about 200 blocks.
|
// overtake the 'canon' chain until after it's passed canon by about 200 blocks.
|
||||||
|
|
@ -2088,14 +1990,6 @@ func testInsertKnownChainData(t *testing.T, typ string, scheme string) {
|
||||||
}
|
}
|
||||||
} else if typ == "receipts" {
|
} else if typ == "receipts" {
|
||||||
inserter = func(blocks []*types.Block, receipts []types.Receipts) error {
|
inserter = func(blocks []*types.Block, receipts []types.Receipts) error {
|
||||||
headers := make([]*types.Header, 0, len(blocks))
|
|
||||||
for _, block := range blocks {
|
|
||||||
headers = append(headers, block.Header())
|
|
||||||
}
|
|
||||||
_, err := chain.InsertHeaderChain(headers)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, err = chain.InsertReceiptChain(blocks, receipts, 0)
|
_, err = chain.InsertReceiptChain(blocks, receipts, 0)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -2262,14 +2156,6 @@ func testInsertKnownChainDataWithMerging(t *testing.T, typ string, mergeHeight i
|
||||||
}
|
}
|
||||||
} else if typ == "receipts" {
|
} else if typ == "receipts" {
|
||||||
inserter = func(blocks []*types.Block, receipts []types.Receipts) error {
|
inserter = func(blocks []*types.Block, receipts []types.Receipts) error {
|
||||||
headers := make([]*types.Header, 0, len(blocks))
|
|
||||||
for _, block := range blocks {
|
|
||||||
headers = append(headers, block.Header())
|
|
||||||
}
|
|
||||||
i, err := chain.InsertHeaderChain(headers)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("index %d: %w", i, err)
|
|
||||||
}
|
|
||||||
_, err = chain.InsertReceiptChain(blocks, receipts, 0)
|
_, err = chain.InsertReceiptChain(blocks, receipts, 0)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -2605,7 +2491,7 @@ func testSideImportPrunedBlocks(t *testing.T, scheme string) {
|
||||||
datadir := t.TempDir()
|
datadir := t.TempDir()
|
||||||
ancient := path.Join(datadir, "ancient")
|
ancient := path.Join(datadir, "ancient")
|
||||||
|
|
||||||
pdb, err := pebble.New(datadir, 0, 0, "", false)
|
pdb, err := pebble.New(datadir, 0, 0, "", false, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to create persistent key-value database: %v", err)
|
t.Fatalf("Failed to create persistent key-value database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -4265,3 +4151,220 @@ func TestEIP7702(t *testing.T) {
|
||||||
t.Fatalf("addr2 storage wrong: expected %d, got %d", fortyTwo, actual)
|
t.Fatalf("addr2 storage wrong: expected %d, got %d", fortyTwo, actual)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Tests the scenario that the synchronization target in snap sync has been changed
|
||||||
|
// with a chain reorg at the tip. In this case the reorg'd segment should be unmarked
|
||||||
|
// with canonical flags.
|
||||||
|
func TestChainReorgSnapSync(t *testing.T) {
|
||||||
|
testChainReorgSnapSync(t, 0)
|
||||||
|
testChainReorgSnapSync(t, 32)
|
||||||
|
testChainReorgSnapSync(t, gomath.MaxUint64)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testChainReorgSnapSync(t *testing.T, ancientLimit uint64) {
|
||||||
|
// log.SetDefault(log.NewLogger(log.NewTerminalHandlerWithLevel(os.Stderr, log.LevelDebug, true)))
|
||||||
|
|
||||||
|
// Configure and generate a sample block chain
|
||||||
|
var (
|
||||||
|
key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
|
||||||
|
address = crypto.PubkeyToAddress(key.PublicKey)
|
||||||
|
funds = big.NewInt(1000000000000000)
|
||||||
|
gspec = &Genesis{
|
||||||
|
Config: params.TestChainConfig,
|
||||||
|
Alloc: types.GenesisAlloc{address: {Balance: funds}},
|
||||||
|
BaseFee: big.NewInt(params.InitialBaseFee),
|
||||||
|
}
|
||||||
|
signer = types.LatestSigner(gspec.Config)
|
||||||
|
engine = beacon.New(ethash.NewFaker())
|
||||||
|
)
|
||||||
|
genDb, blocks, receipts := GenerateChainWithGenesis(gspec, engine, 32, func(i int, block *BlockGen) {
|
||||||
|
block.SetCoinbase(common.Address{0x00})
|
||||||
|
|
||||||
|
// If the block number is multiple of 3, send a few bonus transactions to the miner
|
||||||
|
if i%3 == 2 {
|
||||||
|
for j := 0; j < i%4+1; j++ {
|
||||||
|
tx, err := types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, block.header.BaseFee, nil), signer, key)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
block.AddTx(tx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
chainA, receiptsA := GenerateChain(gspec.Config, blocks[len(blocks)-1], engine, genDb, 16, func(i int, gen *BlockGen) {
|
||||||
|
gen.SetCoinbase(common.Address{0: byte(0xa), 19: byte(i)})
|
||||||
|
})
|
||||||
|
chainB, receiptsB := GenerateChain(gspec.Config, blocks[len(blocks)-1], engine, genDb, 20, func(i int, gen *BlockGen) {
|
||||||
|
gen.SetCoinbase(common.Address{0: byte(0xb), 19: byte(i)})
|
||||||
|
})
|
||||||
|
|
||||||
|
db, _ := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), "", "", false)
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
chain, _ := NewBlockChain(db, DefaultCacheConfigWithScheme(rawdb.PathScheme), gspec, nil, beacon.New(ethash.NewFaker()), vm.Config{}, nil)
|
||||||
|
defer chain.Stop()
|
||||||
|
|
||||||
|
if n, err := chain.InsertReceiptChain(blocks, receipts, ancientLimit); err != nil {
|
||||||
|
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
||||||
|
}
|
||||||
|
if n, err := chain.InsertReceiptChain(chainA, receiptsA, ancientLimit); err != nil {
|
||||||
|
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
||||||
|
}
|
||||||
|
// If the common ancestor is below the ancient limit, rewind the chain head.
|
||||||
|
// It's aligned with the behavior in the snap sync
|
||||||
|
ancestor := blocks[len(blocks)-1].NumberU64()
|
||||||
|
if ancestor < ancientLimit {
|
||||||
|
rawdb.WriteLastPivotNumber(db, ancestor)
|
||||||
|
chain.SetHead(ancestor)
|
||||||
|
}
|
||||||
|
if n, err := chain.InsertReceiptChain(chainB, receiptsB, ancientLimit); err != nil {
|
||||||
|
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
||||||
|
}
|
||||||
|
head := chain.CurrentSnapBlock()
|
||||||
|
if head.Hash() != chainB[len(chainB)-1].Hash() {
|
||||||
|
t.Errorf("head snap block #%d: header mismatch: want: %v, got: %v", head.Number, chainB[len(chainB)-1].Hash(), head.Hash())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Iterate over all chain data components, and cross reference
|
||||||
|
for i := 0; i < len(blocks); i++ {
|
||||||
|
num, hash := blocks[i].NumberU64(), blocks[i].Hash()
|
||||||
|
header := chain.GetHeaderByNumber(num)
|
||||||
|
if header.Hash() != hash {
|
||||||
|
t.Errorf("block #%d: header mismatch: want: %v, got: %v", num, hash, header.Hash())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := 0; i < len(chainA); i++ {
|
||||||
|
num, hash := chainA[i].NumberU64(), chainA[i].Hash()
|
||||||
|
header := chain.GetHeaderByNumber(num)
|
||||||
|
if header == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if header.Hash() == hash {
|
||||||
|
t.Errorf("block #%d: unexpected canonical header: %v", num, hash)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := 0; i < len(chainB); i++ {
|
||||||
|
num, hash := chainB[i].NumberU64(), chainB[i].Hash()
|
||||||
|
header := chain.GetHeaderByNumber(num)
|
||||||
|
if header.Hash() != hash {
|
||||||
|
t.Errorf("block #%d: header mismatch: want: %v, got: %v", num, hash, header.Hash())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tests the scenario that all the inserted chain segment are with the configured
|
||||||
|
// chain cutoff point. In this case the chain segment before the cutoff should
|
||||||
|
// be persisted without the receipts and bodies; chain after should be persisted
|
||||||
|
// normally.
|
||||||
|
func TestInsertChainWithCutoff(t *testing.T) {
|
||||||
|
testInsertChainWithCutoff(t, 32, 32) // cutoff = 32, ancientLimit = 32
|
||||||
|
testInsertChainWithCutoff(t, 32, 64) // cutoff = 32, ancientLimit = 64 (entire chain in ancient)
|
||||||
|
testInsertChainWithCutoff(t, 32, 65) // cutoff = 32, ancientLimit = 65 (64 blocks in ancient, 1 block in live)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testInsertChainWithCutoff(t *testing.T, cutoff uint64, ancientLimit uint64) {
|
||||||
|
// log.SetDefault(log.NewLogger(log.NewTerminalHandlerWithLevel(os.Stderr, log.LevelDebug, true)))
|
||||||
|
|
||||||
|
// Configure and generate a sample block chain
|
||||||
|
var (
|
||||||
|
key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
|
||||||
|
address = crypto.PubkeyToAddress(key.PublicKey)
|
||||||
|
funds = big.NewInt(1000000000000000)
|
||||||
|
gspec = &Genesis{
|
||||||
|
Config: params.TestChainConfig,
|
||||||
|
Alloc: types.GenesisAlloc{address: {Balance: funds}},
|
||||||
|
BaseFee: big.NewInt(params.InitialBaseFee),
|
||||||
|
}
|
||||||
|
signer = types.LatestSigner(gspec.Config)
|
||||||
|
engine = beacon.New(ethash.NewFaker())
|
||||||
|
)
|
||||||
|
_, blocks, receipts := GenerateChainWithGenesis(gspec, engine, int(2*cutoff), func(i int, block *BlockGen) {
|
||||||
|
block.SetCoinbase(common.Address{0x00})
|
||||||
|
|
||||||
|
tx, err := types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, block.header.BaseFee, nil), signer, key)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
block.AddTx(tx)
|
||||||
|
})
|
||||||
|
db, _ := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), "", "", false)
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
cutoffBlock := blocks[cutoff-1]
|
||||||
|
config := DefaultCacheConfigWithScheme(rawdb.PathScheme)
|
||||||
|
config.HistoryPruningCutoffNumber = cutoffBlock.NumberU64()
|
||||||
|
config.HistoryPruningCutoffHash = cutoffBlock.Hash()
|
||||||
|
|
||||||
|
chain, _ := NewBlockChain(db, DefaultCacheConfigWithScheme(rawdb.PathScheme), gspec, nil, beacon.New(ethash.NewFaker()), vm.Config{}, nil)
|
||||||
|
defer chain.Stop()
|
||||||
|
|
||||||
|
var (
|
||||||
|
headersBefore []*types.Header
|
||||||
|
blocksAfter []*types.Block
|
||||||
|
receiptsAfter []types.Receipts
|
||||||
|
)
|
||||||
|
for i, b := range blocks {
|
||||||
|
if b.NumberU64() < cutoffBlock.NumberU64() {
|
||||||
|
headersBefore = append(headersBefore, b.Header())
|
||||||
|
} else {
|
||||||
|
blocksAfter = append(blocksAfter, b)
|
||||||
|
receiptsAfter = append(receiptsAfter, receipts[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n, err := chain.InsertHeadersBeforeCutoff(headersBefore); err != nil {
|
||||||
|
t.Fatalf("failed to insert headers before cutoff %d: %v", n, err)
|
||||||
|
}
|
||||||
|
if n, err := chain.InsertReceiptChain(blocksAfter, receiptsAfter, ancientLimit); err != nil {
|
||||||
|
t.Fatalf("failed to insert receipt %d: %v", n, err)
|
||||||
|
}
|
||||||
|
headSnap := chain.CurrentSnapBlock()
|
||||||
|
if headSnap.Hash() != blocks[len(blocks)-1].Hash() {
|
||||||
|
t.Errorf("head snap block #%d: header mismatch: want: %v, got: %v", headSnap.Number, blocks[len(blocks)-1].Hash(), headSnap.Hash())
|
||||||
|
}
|
||||||
|
headHeader := chain.CurrentHeader()
|
||||||
|
if headHeader.Hash() != blocks[len(blocks)-1].Hash() {
|
||||||
|
t.Errorf("head header #%d: header mismatch: want: %v, got: %v", headHeader.Number, blocks[len(blocks)-1].Hash(), headHeader.Hash())
|
||||||
|
}
|
||||||
|
headBlock := chain.CurrentBlock()
|
||||||
|
if headBlock.Hash() != gspec.ToBlock().Hash() {
|
||||||
|
t.Errorf("head block #%d: header mismatch: want: %v, got: %v", headBlock.Number, gspec.ToBlock().Hash(), headBlock.Hash())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Iterate over all chain data components, and cross reference
|
||||||
|
for i := 0; i < len(blocks); i++ {
|
||||||
|
num, hash := blocks[i].NumberU64(), blocks[i].Hash()
|
||||||
|
|
||||||
|
// Canonical headers should be visible regardless of cutoff
|
||||||
|
header := chain.GetHeaderByNumber(num)
|
||||||
|
if header.Hash() != hash {
|
||||||
|
t.Errorf("block #%d: header mismatch: want: %v, got: %v", num, hash, header.Hash())
|
||||||
|
}
|
||||||
|
tail, err := db.Tail()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to get chain tail, %v", err)
|
||||||
|
}
|
||||||
|
if tail != cutoffBlock.NumberU64() {
|
||||||
|
t.Fatalf("Unexpected chain tail, want: %d, got: %d", cutoffBlock.NumberU64(), tail)
|
||||||
|
}
|
||||||
|
// Block bodies and receipts before the cutoff should be non-existent
|
||||||
|
if num < cutoffBlock.NumberU64() {
|
||||||
|
body := chain.GetBody(hash)
|
||||||
|
if body != nil {
|
||||||
|
t.Fatalf("Unexpected block body: %d, cutoff: %d", num, cutoffBlock.NumberU64())
|
||||||
|
}
|
||||||
|
receipts := chain.GetReceiptsByHash(hash)
|
||||||
|
if receipts != nil {
|
||||||
|
t.Fatalf("Unexpected block receipts: %d, cutoff: %d", num, cutoffBlock.NumberU64())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
body := chain.GetBody(hash)
|
||||||
|
if body == nil || len(body.Transactions) != 1 {
|
||||||
|
t.Fatalf("Missed block body: %d, cutoff: %d", num, cutoffBlock.NumberU64())
|
||||||
|
}
|
||||||
|
receipts := chain.GetReceiptsByHash(hash)
|
||||||
|
if receipts == nil || len(receipts) != 1 {
|
||||||
|
t.Fatalf("Missed block receipts: %d, cutoff: %d", num, cutoffBlock.NumberU64())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -28,8 +28,6 @@ var (
|
||||||
|
|
||||||
// ErrNoGenesis is returned when there is no Genesis Block.
|
// ErrNoGenesis is returned when there is no Genesis Block.
|
||||||
ErrNoGenesis = errors.New("genesis not found in chain")
|
ErrNoGenesis = errors.New("genesis not found in chain")
|
||||||
|
|
||||||
errSideChainReceipts = errors.New("side blocks can't be accepted as ancient chain data")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// List of evm-call-message pre-checking errors. All state transition messages will
|
// List of evm-call-message pre-checking errors. All state transition messages will
|
||||||
|
|
|
||||||
|
|
@ -30,6 +30,23 @@ import (
|
||||||
"github.com/ethereum/go-ethereum/core/types"
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
"github.com/ethereum/go-ethereum/ethdb"
|
"github.com/ethereum/go-ethereum/ethdb"
|
||||||
"github.com/ethereum/go-ethereum/log"
|
"github.com/ethereum/go-ethereum/log"
|
||||||
|
"github.com/ethereum/go-ethereum/metrics"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
mapCountGauge = metrics.NewRegisteredGauge("filtermaps/maps/count", nil) // actual number of rendered maps
|
||||||
|
mapLogValueMeter = metrics.NewRegisteredMeter("filtermaps/maps/logvalues", nil) // number of log values processed
|
||||||
|
mapBlockMeter = metrics.NewRegisteredMeter("filtermaps/maps/blocks", nil) // number of block delimiters processed
|
||||||
|
mapRenderTimer = metrics.NewRegisteredTimer("filtermaps/maps/rendertime", nil) // time elapsed while rendering a single map
|
||||||
|
mapWriteTimer = metrics.NewRegisteredTimer("filtermaps/maps/writetime", nil) // time elapsed while writing a batch of finished maps to db
|
||||||
|
matchRequestTimer = metrics.NewRegisteredTimer("filtermaps/match/requesttime", nil) // processing time a matching request in a single epoch
|
||||||
|
matchEpochTimer = metrics.NewRegisteredTimer("filtermaps/match/epochtime", nil) // total processing time a matching request
|
||||||
|
matchBaseRowAccessMeter = metrics.NewRegisteredMeter("filtermaps/match/baserowaccess", nil) // number of accessed rows on layer 0
|
||||||
|
matchBaseRowSizeMeter = metrics.NewRegisteredMeter("filtermaps/match/baserowsize", nil) // size of accessed rows on layer 0
|
||||||
|
matchExtRowAccessMeter = metrics.NewRegisteredMeter("filtermaps/match/extrowaccess", nil) // number of accessed rows on higher layers
|
||||||
|
matchExtRowSizeMeter = metrics.NewRegisteredMeter("filtermaps/match/extrowsize", nil) // size of accessed rows on higher layers
|
||||||
|
matchLogLookup = metrics.NewRegisteredMeter("filtermaps/match/loglookup", nil) // number of log lookups based on potential matches
|
||||||
|
matchAllMeter = metrics.NewRegisteredMeter("filtermaps/match/matchall", nil) // number of requests returned with ErrMatchAll
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|
@ -429,8 +446,12 @@ func (f *FilterMaps) setRange(batch ethdb.KeyValueWriter, newView *ChainView, ne
|
||||||
TailPartialEpoch: newRange.tailPartialEpoch,
|
TailPartialEpoch: newRange.tailPartialEpoch,
|
||||||
}
|
}
|
||||||
rawdb.WriteFilterMapsRange(batch, rs)
|
rawdb.WriteFilterMapsRange(batch, rs)
|
||||||
|
if !isTempRange {
|
||||||
|
mapCountGauge.Update(int64(newRange.maps.Count() + newRange.tailPartialEpoch))
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
rawdb.DeleteFilterMapsRange(batch)
|
rawdb.DeleteFilterMapsRange(batch)
|
||||||
|
mapCountGauge.Update(0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
"sort"
|
"sort"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/ethereum/go-ethereum/common"
|
"github.com/ethereum/go-ethereum/common"
|
||||||
"github.com/ethereum/go-ethereum/common/lru"
|
"github.com/ethereum/go-ethereum/common/lru"
|
||||||
|
|
@ -301,6 +302,11 @@ func (r *mapRenderer) run(stopCb func() bool, writeCb func()) (bool, error) {
|
||||||
|
|
||||||
// renderCurrentMap renders a single map.
|
// renderCurrentMap renders a single map.
|
||||||
func (r *mapRenderer) renderCurrentMap(stopCb func() bool) (bool, error) {
|
func (r *mapRenderer) renderCurrentMap(stopCb func() bool) (bool, error) {
|
||||||
|
var (
|
||||||
|
totalTime time.Duration
|
||||||
|
logValuesProcessed, blocksProcessed int64
|
||||||
|
)
|
||||||
|
start := time.Now()
|
||||||
if !r.iterator.updateChainView(r.f.targetView) {
|
if !r.iterator.updateChainView(r.f.targetView) {
|
||||||
return false, errChainUpdate
|
return false, errChainUpdate
|
||||||
}
|
}
|
||||||
|
|
@ -316,9 +322,11 @@ func (r *mapRenderer) renderCurrentMap(stopCb func() bool) (bool, error) {
|
||||||
for r.iterator.lvIndex < uint64(r.currentMap.mapIndex+1)<<r.f.logValuesPerMap && !r.iterator.finished {
|
for r.iterator.lvIndex < uint64(r.currentMap.mapIndex+1)<<r.f.logValuesPerMap && !r.iterator.finished {
|
||||||
waitCnt++
|
waitCnt++
|
||||||
if waitCnt >= valuesPerCallback {
|
if waitCnt >= valuesPerCallback {
|
||||||
|
totalTime += time.Since(start)
|
||||||
if stopCb() {
|
if stopCb() {
|
||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
|
start = time.Now()
|
||||||
if !r.iterator.updateChainView(r.f.targetView) {
|
if !r.iterator.updateChainView(r.f.targetView) {
|
||||||
return false, errChainUpdate
|
return false, errChainUpdate
|
||||||
}
|
}
|
||||||
|
|
@ -343,8 +351,10 @@ func (r *mapRenderer) renderCurrentMap(stopCb func() bool) (bool, error) {
|
||||||
return false, fmt.Errorf("failed to advance log iterator at %d while rendering map %d: %v", r.iterator.lvIndex, r.currentMap.mapIndex, err)
|
return false, fmt.Errorf("failed to advance log iterator at %d while rendering map %d: %v", r.iterator.lvIndex, r.currentMap.mapIndex, err)
|
||||||
}
|
}
|
||||||
if !r.iterator.skipToBoundary {
|
if !r.iterator.skipToBoundary {
|
||||||
|
logValuesProcessed++
|
||||||
r.currentMap.lastBlock = r.iterator.blockNumber
|
r.currentMap.lastBlock = r.iterator.blockNumber
|
||||||
if r.iterator.blockStart {
|
if r.iterator.blockStart {
|
||||||
|
blocksProcessed++
|
||||||
r.currentMap.blockLvPtrs = append(r.currentMap.blockLvPtrs, r.iterator.lvIndex)
|
r.currentMap.blockLvPtrs = append(r.currentMap.blockLvPtrs, r.iterator.lvIndex)
|
||||||
}
|
}
|
||||||
if !r.f.testDisableSnapshots && r.renderBefore >= r.f.indexedRange.maps.AfterLast() &&
|
if !r.f.testDisableSnapshots && r.renderBefore >= r.f.indexedRange.maps.AfterLast() &&
|
||||||
|
|
@ -358,12 +368,18 @@ func (r *mapRenderer) renderCurrentMap(stopCb func() bool) (bool, error) {
|
||||||
r.currentMap.headDelimiter = r.iterator.lvIndex
|
r.currentMap.headDelimiter = r.iterator.lvIndex
|
||||||
}
|
}
|
||||||
r.currentMap.lastBlockId = r.f.targetView.getBlockId(r.currentMap.lastBlock)
|
r.currentMap.lastBlockId = r.f.targetView.getBlockId(r.currentMap.lastBlock)
|
||||||
|
totalTime += time.Since(start)
|
||||||
|
mapRenderTimer.Update(totalTime)
|
||||||
|
mapLogValueMeter.Mark(logValuesProcessed)
|
||||||
|
mapBlockMeter.Mark(blocksProcessed)
|
||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeFinishedMaps writes rendered maps to the database and updates
|
// writeFinishedMaps writes rendered maps to the database and updates
|
||||||
// filterMapsRange and indexedView accordingly.
|
// filterMapsRange and indexedView accordingly.
|
||||||
func (r *mapRenderer) writeFinishedMaps(pauseCb func() bool) error {
|
func (r *mapRenderer) writeFinishedMaps(pauseCb func() bool) error {
|
||||||
|
var totalTime time.Duration
|
||||||
|
start := time.Now()
|
||||||
if len(r.finishedMaps) == 0 {
|
if len(r.finishedMaps) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -379,7 +395,7 @@ func (r *mapRenderer) writeFinishedMaps(pauseCb func() bool) error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to get updated rendered range: %v", err)
|
return fmt.Errorf("failed to get updated rendered range: %v", err)
|
||||||
}
|
}
|
||||||
renderedView := r.f.targetView // stopCb callback might still change targetView while writing finished maps
|
renderedView := r.f.targetView // pauseCb callback might still change targetView while writing finished maps
|
||||||
|
|
||||||
batch := r.f.db.NewBatch()
|
batch := r.f.db.NewBatch()
|
||||||
var writeCnt int
|
var writeCnt int
|
||||||
|
|
@ -393,7 +409,9 @@ func (r *mapRenderer) writeFinishedMaps(pauseCb func() bool) error {
|
||||||
// do not exit while in partially written state but do allow processing
|
// do not exit while in partially written state but do allow processing
|
||||||
// events and pausing while block processing is in progress
|
// events and pausing while block processing is in progress
|
||||||
r.f.indexLock.Unlock()
|
r.f.indexLock.Unlock()
|
||||||
|
totalTime += time.Since(start)
|
||||||
pauseCb()
|
pauseCb()
|
||||||
|
start = time.Now()
|
||||||
r.f.indexLock.Lock()
|
r.f.indexLock.Lock()
|
||||||
batch = r.f.db.NewBatch()
|
batch = r.f.db.NewBatch()
|
||||||
}
|
}
|
||||||
|
|
@ -477,6 +495,8 @@ func (r *mapRenderer) writeFinishedMaps(pauseCb func() bool) error {
|
||||||
if err := batch.Write(); err != nil {
|
if err := batch.Write(); err != nil {
|
||||||
log.Crit("Error writing log index update batch", "error", err)
|
log.Crit("Error writing log index update batch", "error", err)
|
||||||
}
|
}
|
||||||
|
totalTime += time.Since(start)
|
||||||
|
mapWriteTimer.Update(totalTime)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -125,6 +125,7 @@ func GetPotentialMatches(ctx context.Context, backend MatcherBackend, firstBlock
|
||||||
|
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
res, err := m.process()
|
res, err := m.process()
|
||||||
|
matchRequestTimer.Update(time.Since(start))
|
||||||
|
|
||||||
if doRuntimeStats {
|
if doRuntimeStats {
|
||||||
log.Info("Log search finished", "elapsed", time.Since(start))
|
log.Info("Log search finished", "elapsed", time.Since(start))
|
||||||
|
|
@ -202,6 +203,7 @@ func (m *matcherEnv) process() ([]*types.Log, error) {
|
||||||
logs = append(logs, tasks[waitEpoch].logs...)
|
logs = append(logs, tasks[waitEpoch].logs...)
|
||||||
if err := tasks[waitEpoch].err; err != nil {
|
if err := tasks[waitEpoch].err; err != nil {
|
||||||
if err == ErrMatchAll {
|
if err == ErrMatchAll {
|
||||||
|
matchAllMeter.Mark(1)
|
||||||
return logs, err
|
return logs, err
|
||||||
}
|
}
|
||||||
return logs, fmt.Errorf("failed to process log index epoch %d: %v", waitEpoch, err)
|
return logs, fmt.Errorf("failed to process log index epoch %d: %v", waitEpoch, err)
|
||||||
|
|
@ -220,6 +222,7 @@ func (m *matcherEnv) process() ([]*types.Log, error) {
|
||||||
|
|
||||||
// processEpoch returns the potentially matching logs from the given epoch.
|
// processEpoch returns the potentially matching logs from the given epoch.
|
||||||
func (m *matcherEnv) processEpoch(epochIndex uint32) ([]*types.Log, error) {
|
func (m *matcherEnv) processEpoch(epochIndex uint32) ([]*types.Log, error) {
|
||||||
|
start := time.Now()
|
||||||
var logs []*types.Log
|
var logs []*types.Log
|
||||||
// create a list of map indices to process
|
// create a list of map indices to process
|
||||||
fm, lm := epochIndex<<m.params.logMapsPerEpoch, (epochIndex+1)<<m.params.logMapsPerEpoch-1
|
fm, lm := epochIndex<<m.params.logMapsPerEpoch, (epochIndex+1)<<m.params.logMapsPerEpoch-1
|
||||||
|
|
@ -254,6 +257,7 @@ func (m *matcherEnv) processEpoch(epochIndex uint32) ([]*types.Log, error) {
|
||||||
logs = append(logs, mlogs...)
|
logs = append(logs, mlogs...)
|
||||||
}
|
}
|
||||||
m.getLogStats.addAmount(st, int64(len(logs)))
|
m.getLogStats.addAmount(st, int64(len(logs)))
|
||||||
|
matchEpochTimer.Update(time.Since(start))
|
||||||
return logs, nil
|
return logs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -273,6 +277,7 @@ func (m *matcherEnv) getLogsFromMatches(matches potentialMatches) ([]*types.Log,
|
||||||
if log != nil {
|
if log != nil {
|
||||||
logs = append(logs, log)
|
logs = append(logs, log)
|
||||||
}
|
}
|
||||||
|
matchLogLookup.Mark(1)
|
||||||
}
|
}
|
||||||
return logs, nil
|
return logs, nil
|
||||||
}
|
}
|
||||||
|
|
@ -381,6 +386,13 @@ func (m *singleMatcherInstance) getMatchesForLayer(ctx context.Context, layerInd
|
||||||
m.stats.setState(&st, stNone)
|
m.stats.setState(&st, stNone)
|
||||||
return nil, fmt.Errorf("failed to retrieve filter map %d row %d: %v", mapIndex, rowIndex, err)
|
return nil, fmt.Errorf("failed to retrieve filter map %d row %d: %v", mapIndex, rowIndex, err)
|
||||||
}
|
}
|
||||||
|
if layerIndex == 0 {
|
||||||
|
matchBaseRowAccessMeter.Mark(1)
|
||||||
|
matchBaseRowSizeMeter.Mark(int64(len(filterRow)))
|
||||||
|
} else {
|
||||||
|
matchExtRowAccessMeter.Mark(1)
|
||||||
|
matchExtRowSizeMeter.Mark(int64(len(filterRow)))
|
||||||
|
}
|
||||||
m.stats.addAmount(st, int64(len(filterRow)))
|
m.stats.addAmount(st, int64(len(filterRow)))
|
||||||
m.stats.setState(&st, stOther)
|
m.stats.setState(&st, stOther)
|
||||||
filterRows = append(filterRows, filterRow)
|
filterRows = append(filterRows, filterRow)
|
||||||
|
|
|
||||||
|
|
@ -237,7 +237,8 @@ func (hc *HeaderChain) WriteHeaders(headers []*types.Header) (int, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeHeadersAndSetHead writes a batch of block headers and applies the last
|
// writeHeadersAndSetHead writes a batch of block headers and applies the last
|
||||||
// header as the chain head if the fork choicer says it's ok to update the chain.
|
// header as the chain head.
|
||||||
|
//
|
||||||
// Note: This method is not concurrent-safe with inserting blocks simultaneously
|
// Note: This method is not concurrent-safe with inserting blocks simultaneously
|
||||||
// into the chain, as side effects caused by reorganisations cannot be emulated
|
// into the chain, as side effects caused by reorganisations cannot be emulated
|
||||||
// without the real blocks. Hence, writing headers directly should only be done
|
// without the real blocks. Hence, writing headers directly should only be done
|
||||||
|
|
@ -272,12 +273,14 @@ func (hc *HeaderChain) writeHeadersAndSetHead(headers []*types.Header) (*headerW
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ValidateHeaderChain verifies that the supplied header chain is contiguous
|
||||||
|
// and conforms to consensus rules.
|
||||||
func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header) (int, error) {
|
func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header) (int, error) {
|
||||||
// Do a sanity check that the provided chain is actually ordered and linked
|
// Do a sanity check that the provided chain is actually ordered and linked
|
||||||
for i := 1; i < len(chain); i++ {
|
for i := 1; i < len(chain); i++ {
|
||||||
if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 {
|
if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 {
|
||||||
hash := chain[i].Hash()
|
hash, parentHash := chain[i].Hash(), chain[i-1].Hash()
|
||||||
parentHash := chain[i-1].Hash()
|
|
||||||
// Chain broke ancestry, log a message (programming error) and skip insertion
|
// Chain broke ancestry, log a message (programming error) and skip insertion
|
||||||
log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", hash,
|
log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", hash,
|
||||||
"parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", parentHash)
|
"parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", parentHash)
|
||||||
|
|
@ -302,7 +305,6 @@ func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header) (int, error) {
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -737,6 +737,30 @@ func writeAncientBlock(op ethdb.AncientWriteOp, block *types.Block, header *type
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteAncientHeaderChain writes the supplied headers along with nil block
|
||||||
|
// bodies and receipts into the ancient store. It's supposed to be used for
|
||||||
|
// storing chain segment before the chain cutoff.
|
||||||
|
func WriteAncientHeaderChain(db ethdb.AncientWriter, headers []*types.Header) (int64, error) {
|
||||||
|
return db.ModifyAncients(func(op ethdb.AncientWriteOp) error {
|
||||||
|
for _, header := range headers {
|
||||||
|
num := header.Number.Uint64()
|
||||||
|
if err := op.AppendRaw(ChainFreezerHashTable, num, header.Hash().Bytes()); err != nil {
|
||||||
|
return fmt.Errorf("can't add block %d hash: %v", num, err)
|
||||||
|
}
|
||||||
|
if err := op.Append(ChainFreezerHeaderTable, num, header); err != nil {
|
||||||
|
return fmt.Errorf("can't append block header %d: %v", num, err)
|
||||||
|
}
|
||||||
|
if err := op.AppendRaw(ChainFreezerBodiesTable, num, nil); err != nil {
|
||||||
|
return fmt.Errorf("can't append block body %d: %v", num, err)
|
||||||
|
}
|
||||||
|
if err := op.AppendRaw(ChainFreezerReceiptTable, num, nil); err != nil {
|
||||||
|
return fmt.Errorf("can't append block %d receipts: %v", num, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// DeleteBlock removes all block data associated with a hash.
|
// DeleteBlock removes all block data associated with a hash.
|
||||||
func DeleteBlock(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
|
func DeleteBlock(db ethdb.KeyValueWriter, hash common.Hash, number uint64) {
|
||||||
DeleteReceipts(db, hash, number)
|
DeleteReceipts(db, hash, number)
|
||||||
|
|
|
||||||
|
|
@ -464,6 +464,48 @@ func TestAncientStorage(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestWriteAncientHeaderChain(t *testing.T) {
|
||||||
|
db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), t.TempDir(), "", false)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create database with ancient backend")
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
// Create a test block
|
||||||
|
var headers []*types.Header
|
||||||
|
headers = append(headers, &types.Header{
|
||||||
|
Number: big.NewInt(0),
|
||||||
|
Extra: []byte("test block"),
|
||||||
|
UncleHash: types.EmptyUncleHash,
|
||||||
|
TxHash: types.EmptyTxsHash,
|
||||||
|
ReceiptHash: types.EmptyReceiptsHash,
|
||||||
|
})
|
||||||
|
headers = append(headers, &types.Header{
|
||||||
|
Number: big.NewInt(1),
|
||||||
|
Extra: []byte("test block"),
|
||||||
|
UncleHash: types.EmptyUncleHash,
|
||||||
|
TxHash: types.EmptyTxsHash,
|
||||||
|
ReceiptHash: types.EmptyReceiptsHash,
|
||||||
|
})
|
||||||
|
// Write and verify the header in the database
|
||||||
|
WriteAncientHeaderChain(db, headers)
|
||||||
|
|
||||||
|
for _, header := range headers {
|
||||||
|
if blob := ReadHeaderRLP(db, header.Hash(), header.Number.Uint64()); len(blob) == 0 {
|
||||||
|
t.Fatalf("no header returned")
|
||||||
|
}
|
||||||
|
if h := ReadCanonicalHash(db, header.Number.Uint64()); h != header.Hash() {
|
||||||
|
t.Fatalf("no canonical hash returned")
|
||||||
|
}
|
||||||
|
if blob := ReadBodyRLP(db, header.Hash(), header.Number.Uint64()); len(blob) != 0 {
|
||||||
|
t.Fatalf("unexpected body returned")
|
||||||
|
}
|
||||||
|
if blob := ReadReceiptsRLP(db, header.Hash(), header.Number.Uint64()); len(blob) != 0 {
|
||||||
|
t.Fatalf("unexpected body returned")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCanonicalHashIteration(t *testing.T) {
|
func TestCanonicalHashIteration(t *testing.T) {
|
||||||
var cases = []struct {
|
var cases = []struct {
|
||||||
from, to uint64
|
from, to uint64
|
||||||
|
|
|
||||||
|
|
@ -58,9 +58,10 @@ type txIndexer struct {
|
||||||
|
|
||||||
// newTxIndexer initializes the transaction indexer.
|
// newTxIndexer initializes the transaction indexer.
|
||||||
func newTxIndexer(limit uint64, chain *BlockChain) *txIndexer {
|
func newTxIndexer(limit uint64, chain *BlockChain) *txIndexer {
|
||||||
|
cutoff, _ := chain.HistoryPruningCutoff()
|
||||||
indexer := &txIndexer{
|
indexer := &txIndexer{
|
||||||
limit: limit,
|
limit: limit,
|
||||||
cutoff: chain.HistoryPruningCutoff(),
|
cutoff: cutoff,
|
||||||
db: chain.db,
|
db: chain.db,
|
||||||
progress: make(chan chan TxIndexProgress),
|
progress: make(chan chan TxIndexProgress),
|
||||||
term: make(chan chan struct{}),
|
term: make(chan chan struct{}),
|
||||||
|
|
|
||||||
|
|
@ -88,7 +88,8 @@ type blobTxMeta struct {
|
||||||
vhashes []common.Hash // Blob versioned hashes to maintain the lookup table
|
vhashes []common.Hash // Blob versioned hashes to maintain the lookup table
|
||||||
|
|
||||||
id uint64 // Storage ID in the pool's persistent store
|
id uint64 // Storage ID in the pool's persistent store
|
||||||
size uint32 // Byte size in the pool's persistent store
|
storageSize uint32 // Byte size in the pool's persistent store
|
||||||
|
size uint64 // RLP-encoded size of transaction including the attached blob
|
||||||
|
|
||||||
nonce uint64 // Needed to prioritize inclusion order within an account
|
nonce uint64 // Needed to prioritize inclusion order within an account
|
||||||
costCap *uint256.Int // Needed to validate cumulative balance sufficiency
|
costCap *uint256.Int // Needed to validate cumulative balance sufficiency
|
||||||
|
|
@ -108,11 +109,12 @@ type blobTxMeta struct {
|
||||||
|
|
||||||
// newBlobTxMeta retrieves the indexed metadata fields from a blob transaction
|
// newBlobTxMeta retrieves the indexed metadata fields from a blob transaction
|
||||||
// and assembles a helper struct to track in memory.
|
// and assembles a helper struct to track in memory.
|
||||||
func newBlobTxMeta(id uint64, size uint32, tx *types.Transaction) *blobTxMeta {
|
func newBlobTxMeta(id uint64, size uint64, storageSize uint32, tx *types.Transaction) *blobTxMeta {
|
||||||
meta := &blobTxMeta{
|
meta := &blobTxMeta{
|
||||||
hash: tx.Hash(),
|
hash: tx.Hash(),
|
||||||
vhashes: tx.BlobHashes(),
|
vhashes: tx.BlobHashes(),
|
||||||
id: id,
|
id: id,
|
||||||
|
storageSize: storageSize,
|
||||||
size: size,
|
size: size,
|
||||||
nonce: tx.Nonce(),
|
nonce: tx.Nonce(),
|
||||||
costCap: uint256.MustFromBig(tx.Cost()),
|
costCap: uint256.MustFromBig(tx.Cost()),
|
||||||
|
|
@ -297,7 +299,8 @@ func newBlobTxMeta(id uint64, size uint32, tx *types.Transaction) *blobTxMeta {
|
||||||
// and leading up to the first no-change.
|
// and leading up to the first no-change.
|
||||||
type BlobPool struct {
|
type BlobPool struct {
|
||||||
config Config // Pool configuration
|
config Config // Pool configuration
|
||||||
reserve txpool.AddressReserver // Address reserver to ensure exclusivity across subpools
|
reserver txpool.Reserver // Address reserver to ensure exclusivity across subpools
|
||||||
|
hasPendingAuth func(common.Address) bool // Determine whether the specified address has a pending 7702-auth
|
||||||
|
|
||||||
store billy.Database // Persistent data store for the tx metadata and blobs
|
store billy.Database // Persistent data store for the tx metadata and blobs
|
||||||
stored uint64 // Useful data size of all transactions on disk
|
stored uint64 // Useful data size of all transactions on disk
|
||||||
|
|
@ -327,13 +330,14 @@ type BlobPool struct {
|
||||||
|
|
||||||
// New creates a new blob transaction pool to gather, sort and filter inbound
|
// New creates a new blob transaction pool to gather, sort and filter inbound
|
||||||
// blob transactions from the network.
|
// blob transactions from the network.
|
||||||
func New(config Config, chain BlockChain) *BlobPool {
|
func New(config Config, chain BlockChain, hasPendingAuth func(common.Address) bool) *BlobPool {
|
||||||
// Sanitize the input to ensure no vulnerable gas prices are set
|
// Sanitize the input to ensure no vulnerable gas prices are set
|
||||||
config = (&config).sanitize()
|
config = (&config).sanitize()
|
||||||
|
|
||||||
// Create the transaction pool with its initial settings
|
// Create the transaction pool with its initial settings
|
||||||
return &BlobPool{
|
return &BlobPool{
|
||||||
config: config,
|
config: config,
|
||||||
|
hasPendingAuth: hasPendingAuth,
|
||||||
signer: types.LatestSigner(chain.Config()),
|
signer: types.LatestSigner(chain.Config()),
|
||||||
chain: chain,
|
chain: chain,
|
||||||
lookup: newLookup(),
|
lookup: newLookup(),
|
||||||
|
|
@ -351,8 +355,8 @@ func (p *BlobPool) Filter(tx *types.Transaction) bool {
|
||||||
// Init sets the gas price needed to keep a transaction in the pool and the chain
|
// Init sets the gas price needed to keep a transaction in the pool and the chain
|
||||||
// head to allow balance / nonce checks. The transaction journal will be loaded
|
// head to allow balance / nonce checks. The transaction journal will be loaded
|
||||||
// from disk and filtered based on the provided starting settings.
|
// from disk and filtered based on the provided starting settings.
|
||||||
func (p *BlobPool) Init(gasTip uint64, head *types.Header, reserve txpool.AddressReserver) error {
|
func (p *BlobPool) Init(gasTip uint64, head *types.Header, reserver txpool.Reserver) error {
|
||||||
p.reserve = reserve
|
p.reserver = reserver
|
||||||
|
|
||||||
var (
|
var (
|
||||||
queuedir string
|
queuedir string
|
||||||
|
|
@ -480,7 +484,7 @@ func (p *BlobPool) parseTransaction(id uint64, size uint32, blob []byte) error {
|
||||||
return errors.New("missing blob sidecar")
|
return errors.New("missing blob sidecar")
|
||||||
}
|
}
|
||||||
|
|
||||||
meta := newBlobTxMeta(id, size, tx)
|
meta := newBlobTxMeta(id, tx.Size(), size, tx)
|
||||||
if p.lookup.exists(meta.hash) {
|
if p.lookup.exists(meta.hash) {
|
||||||
// This path is only possible after a crash, where deleted items are not
|
// This path is only possible after a crash, where deleted items are not
|
||||||
// removed via the normal shutdown-startup procedure and thus may get
|
// removed via the normal shutdown-startup procedure and thus may get
|
||||||
|
|
@ -497,7 +501,7 @@ func (p *BlobPool) parseTransaction(id uint64, size uint32, blob []byte) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, ok := p.index[sender]; !ok {
|
if _, ok := p.index[sender]; !ok {
|
||||||
if err := p.reserve(sender, true); err != nil {
|
if err := p.reserver.Hold(sender); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
p.index[sender] = []*blobTxMeta{}
|
p.index[sender] = []*blobTxMeta{}
|
||||||
|
|
@ -507,7 +511,7 @@ func (p *BlobPool) parseTransaction(id uint64, size uint32, blob []byte) error {
|
||||||
p.spent[sender] = new(uint256.Int).Add(p.spent[sender], meta.costCap)
|
p.spent[sender] = new(uint256.Int).Add(p.spent[sender], meta.costCap)
|
||||||
|
|
||||||
p.lookup.track(meta)
|
p.lookup.track(meta)
|
||||||
p.stored += uint64(meta.size)
|
p.stored += uint64(meta.storageSize)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -539,7 +543,7 @@ func (p *BlobPool) recheck(addr common.Address, inclusions map[common.Hash]uint6
|
||||||
ids = append(ids, txs[i].id)
|
ids = append(ids, txs[i].id)
|
||||||
nonces = append(nonces, txs[i].nonce)
|
nonces = append(nonces, txs[i].nonce)
|
||||||
|
|
||||||
p.stored -= uint64(txs[i].size)
|
p.stored -= uint64(txs[i].storageSize)
|
||||||
p.lookup.untrack(txs[i])
|
p.lookup.untrack(txs[i])
|
||||||
|
|
||||||
// Included transactions blobs need to be moved to the limbo
|
// Included transactions blobs need to be moved to the limbo
|
||||||
|
|
@ -552,7 +556,7 @@ func (p *BlobPool) recheck(addr common.Address, inclusions map[common.Hash]uint6
|
||||||
if inclusions != nil { // only during reorgs will the heap be initialized
|
if inclusions != nil { // only during reorgs will the heap be initialized
|
||||||
heap.Remove(p.evict, p.evict.index[addr])
|
heap.Remove(p.evict, p.evict.index[addr])
|
||||||
}
|
}
|
||||||
p.reserve(addr, false)
|
p.reserver.Release(addr)
|
||||||
|
|
||||||
if gapped {
|
if gapped {
|
||||||
log.Warn("Dropping dangling blob transactions", "from", addr, "missing", next, "drop", nonces, "ids", ids)
|
log.Warn("Dropping dangling blob transactions", "from", addr, "missing", next, "drop", nonces, "ids", ids)
|
||||||
|
|
@ -580,7 +584,7 @@ func (p *BlobPool) recheck(addr common.Address, inclusions map[common.Hash]uint6
|
||||||
nonces = append(nonces, txs[0].nonce)
|
nonces = append(nonces, txs[0].nonce)
|
||||||
|
|
||||||
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], txs[0].costCap)
|
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], txs[0].costCap)
|
||||||
p.stored -= uint64(txs[0].size)
|
p.stored -= uint64(txs[0].storageSize)
|
||||||
p.lookup.untrack(txs[0])
|
p.lookup.untrack(txs[0])
|
||||||
|
|
||||||
// Included transactions blobs need to be moved to the limbo
|
// Included transactions blobs need to be moved to the limbo
|
||||||
|
|
@ -636,7 +640,7 @@ func (p *BlobPool) recheck(addr common.Address, inclusions map[common.Hash]uint6
|
||||||
dropRepeatedMeter.Mark(1)
|
dropRepeatedMeter.Mark(1)
|
||||||
|
|
||||||
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], txs[i].costCap)
|
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], txs[i].costCap)
|
||||||
p.stored -= uint64(txs[i].size)
|
p.stored -= uint64(txs[i].storageSize)
|
||||||
p.lookup.untrack(txs[i])
|
p.lookup.untrack(txs[i])
|
||||||
|
|
||||||
if err := p.store.Delete(id); err != nil {
|
if err := p.store.Delete(id); err != nil {
|
||||||
|
|
@ -658,7 +662,7 @@ func (p *BlobPool) recheck(addr common.Address, inclusions map[common.Hash]uint6
|
||||||
nonces = append(nonces, txs[j].nonce)
|
nonces = append(nonces, txs[j].nonce)
|
||||||
|
|
||||||
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], txs[j].costCap)
|
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], txs[j].costCap)
|
||||||
p.stored -= uint64(txs[j].size)
|
p.stored -= uint64(txs[j].storageSize)
|
||||||
p.lookup.untrack(txs[j])
|
p.lookup.untrack(txs[j])
|
||||||
}
|
}
|
||||||
txs = txs[:i]
|
txs = txs[:i]
|
||||||
|
|
@ -696,7 +700,7 @@ func (p *BlobPool) recheck(addr common.Address, inclusions map[common.Hash]uint6
|
||||||
nonces = append(nonces, last.nonce)
|
nonces = append(nonces, last.nonce)
|
||||||
|
|
||||||
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], last.costCap)
|
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], last.costCap)
|
||||||
p.stored -= uint64(last.size)
|
p.stored -= uint64(last.storageSize)
|
||||||
p.lookup.untrack(last)
|
p.lookup.untrack(last)
|
||||||
}
|
}
|
||||||
if len(txs) == 0 {
|
if len(txs) == 0 {
|
||||||
|
|
@ -705,7 +709,7 @@ func (p *BlobPool) recheck(addr common.Address, inclusions map[common.Hash]uint6
|
||||||
if inclusions != nil { // only during reorgs will the heap be initialized
|
if inclusions != nil { // only during reorgs will the heap be initialized
|
||||||
heap.Remove(p.evict, p.evict.index[addr])
|
heap.Remove(p.evict, p.evict.index[addr])
|
||||||
}
|
}
|
||||||
p.reserve(addr, false)
|
p.reserver.Release(addr)
|
||||||
} else {
|
} else {
|
||||||
p.index[addr] = txs
|
p.index[addr] = txs
|
||||||
}
|
}
|
||||||
|
|
@ -736,7 +740,7 @@ func (p *BlobPool) recheck(addr common.Address, inclusions map[common.Hash]uint6
|
||||||
nonces = append(nonces, last.nonce)
|
nonces = append(nonces, last.nonce)
|
||||||
|
|
||||||
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], last.costCap)
|
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], last.costCap)
|
||||||
p.stored -= uint64(last.size)
|
p.stored -= uint64(last.storageSize)
|
||||||
p.lookup.untrack(last)
|
p.lookup.untrack(last)
|
||||||
}
|
}
|
||||||
p.index[addr] = txs
|
p.index[addr] = txs
|
||||||
|
|
@ -1002,9 +1006,9 @@ func (p *BlobPool) reinject(addr common.Address, txhash common.Hash) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update the indices and metrics
|
// Update the indices and metrics
|
||||||
meta := newBlobTxMeta(id, p.store.Size(id), tx)
|
meta := newBlobTxMeta(id, tx.Size(), p.store.Size(id), tx)
|
||||||
if _, ok := p.index[addr]; !ok {
|
if _, ok := p.index[addr]; !ok {
|
||||||
if err := p.reserve(addr, true); err != nil {
|
if err := p.reserver.Hold(addr); err != nil {
|
||||||
log.Warn("Failed to reserve account for blob pool", "tx", tx.Hash(), "from", addr, "err", err)
|
log.Warn("Failed to reserve account for blob pool", "tx", tx.Hash(), "from", addr, "err", err)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -1016,7 +1020,7 @@ func (p *BlobPool) reinject(addr common.Address, txhash common.Hash) error {
|
||||||
p.spent[addr] = new(uint256.Int).Add(p.spent[addr], meta.costCap)
|
p.spent[addr] = new(uint256.Int).Add(p.spent[addr], meta.costCap)
|
||||||
}
|
}
|
||||||
p.lookup.track(meta)
|
p.lookup.track(meta)
|
||||||
p.stored += uint64(meta.size)
|
p.stored += uint64(meta.storageSize)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1041,7 +1045,7 @@ func (p *BlobPool) SetGasTip(tip *big.Int) {
|
||||||
nonces = []uint64{tx.nonce}
|
nonces = []uint64{tx.nonce}
|
||||||
)
|
)
|
||||||
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], txs[i].costCap)
|
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], txs[i].costCap)
|
||||||
p.stored -= uint64(tx.size)
|
p.stored -= uint64(tx.storageSize)
|
||||||
p.lookup.untrack(tx)
|
p.lookup.untrack(tx)
|
||||||
txs[i] = nil
|
txs[i] = nil
|
||||||
|
|
||||||
|
|
@ -1051,7 +1055,7 @@ func (p *BlobPool) SetGasTip(tip *big.Int) {
|
||||||
nonces = append(nonces, tx.nonce)
|
nonces = append(nonces, tx.nonce)
|
||||||
|
|
||||||
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], tx.costCap)
|
p.spent[addr] = new(uint256.Int).Sub(p.spent[addr], tx.costCap)
|
||||||
p.stored -= uint64(tx.size)
|
p.stored -= uint64(tx.storageSize)
|
||||||
p.lookup.untrack(tx)
|
p.lookup.untrack(tx)
|
||||||
txs[i+1+j] = nil
|
txs[i+1+j] = nil
|
||||||
}
|
}
|
||||||
|
|
@ -1064,7 +1068,7 @@ func (p *BlobPool) SetGasTip(tip *big.Int) {
|
||||||
delete(p.spent, addr)
|
delete(p.spent, addr)
|
||||||
|
|
||||||
heap.Remove(p.evict, p.evict.index[addr])
|
heap.Remove(p.evict, p.evict.index[addr])
|
||||||
p.reserve(addr, false)
|
p.reserver.Release(addr)
|
||||||
}
|
}
|
||||||
// Clear out the transactions from the data store
|
// Clear out the transactions from the data store
|
||||||
log.Warn("Dropping underpriced blob transaction", "from", addr, "rejected", tx.nonce, "tip", tx.execTipCap, "want", tip, "drop", nonces, "ids", ids)
|
log.Warn("Dropping underpriced blob transaction", "from", addr, "rejected", tx.nonce, "tip", tx.execTipCap, "want", tip, "drop", nonces, "ids", ids)
|
||||||
|
|
@ -1099,6 +1103,39 @@ func (p *BlobPool) ValidateTxBasics(tx *types.Transaction) error {
|
||||||
return txpool.ValidateTransaction(tx, p.head, p.signer, opts)
|
return txpool.ValidateTransaction(tx, p.head, p.signer, opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// checkDelegationLimit determines if the tx sender is delegated or has a
|
||||||
|
// pending delegation, and if so, ensures they have at most one in-flight
|
||||||
|
// **executable** transaction, e.g. disallow stacked and gapped transactions
|
||||||
|
// from the account.
|
||||||
|
func (p *BlobPool) checkDelegationLimit(tx *types.Transaction) error {
|
||||||
|
from, _ := types.Sender(p.signer, tx) // validated
|
||||||
|
|
||||||
|
// Short circuit if the sender has neither delegation nor pending delegation.
|
||||||
|
if p.state.GetCodeHash(from) == types.EmptyCodeHash {
|
||||||
|
// Because there is no exclusive lock held between different subpools
|
||||||
|
// when processing transactions, a blob transaction may be accepted
|
||||||
|
// while other SetCode transactions with pending authorities from the
|
||||||
|
// same address are also accepted simultaneously.
|
||||||
|
//
|
||||||
|
// This scenario is considered acceptable, as the rule primarily ensures
|
||||||
|
// that attackers cannot easily and endlessly stack blob transactions
|
||||||
|
// with a delegated or pending delegated sender.
|
||||||
|
if p.hasPendingAuth == nil || !p.hasPendingAuth(from) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Allow a single in-flight pending transaction.
|
||||||
|
pending := p.index[from]
|
||||||
|
if len(pending) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// If account already has a pending transaction, allow replacement only.
|
||||||
|
if len(pending) == 1 && pending[0].nonce == tx.Nonce() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return txpool.ErrInflightTxLimitReached
|
||||||
|
}
|
||||||
|
|
||||||
// validateTx checks whether a transaction is valid according to the consensus
|
// validateTx checks whether a transaction is valid according to the consensus
|
||||||
// rules and adheres to some heuristic limits of the local node (price and size).
|
// rules and adheres to some heuristic limits of the local node (price and size).
|
||||||
func (p *BlobPool) validateTx(tx *types.Transaction) error {
|
func (p *BlobPool) validateTx(tx *types.Transaction) error {
|
||||||
|
|
@ -1139,6 +1176,9 @@ func (p *BlobPool) validateTx(tx *types.Transaction) error {
|
||||||
if err := txpool.ValidateTransactionWithState(tx, p.signer, stateOpts); err != nil {
|
if err := txpool.ValidateTransactionWithState(tx, p.signer, stateOpts); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if err := p.checkDelegationLimit(tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
// If the transaction replaces an existing one, ensure that price bumps are
|
// If the transaction replaces an existing one, ensure that price bumps are
|
||||||
// adhered to.
|
// adhered to.
|
||||||
var (
|
var (
|
||||||
|
|
@ -1236,6 +1276,25 @@ func (p *BlobPool) GetRLP(hash common.Hash) []byte {
|
||||||
return p.getRLP(hash)
|
return p.getRLP(hash)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetMetadata returns the transaction type and transaction size with the
|
||||||
|
// given transaction hash.
|
||||||
|
//
|
||||||
|
// The size refers the length of the 'rlp encoding' of a blob transaction
|
||||||
|
// including the attached blobs.
|
||||||
|
func (p *BlobPool) GetMetadata(hash common.Hash) *txpool.TxMetadata {
|
||||||
|
p.lock.RLock()
|
||||||
|
defer p.lock.RUnlock()
|
||||||
|
|
||||||
|
size, ok := p.lookup.sizeOfTx(hash)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &txpool.TxMetadata{
|
||||||
|
Type: types.BlobTxType,
|
||||||
|
Size: size,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// GetBlobs returns a number of blobs are proofs for the given versioned hashes.
|
// GetBlobs returns a number of blobs are proofs for the given versioned hashes.
|
||||||
// This is a utility method for the engine API, enabling consensus clients to
|
// This is a utility method for the engine API, enabling consensus clients to
|
||||||
// retrieve blobs from the pools directly instead of the network.
|
// retrieve blobs from the pools directly instead of the network.
|
||||||
|
|
@ -1290,6 +1349,9 @@ func (p *BlobPool) GetBlobs(vhashes []common.Hash) ([]*kzg4844.Blob, []*kzg4844.
|
||||||
|
|
||||||
// Add inserts a set of blob transactions into the pool if they pass validation (both
|
// Add inserts a set of blob transactions into the pool if they pass validation (both
|
||||||
// consensus validity and pool restrictions).
|
// consensus validity and pool restrictions).
|
||||||
|
//
|
||||||
|
// Note, if sync is set the method will block until all internal maintenance
|
||||||
|
// related to the add is finished. Only use this during tests for determinism.
|
||||||
func (p *BlobPool) Add(txs []*types.Transaction, sync bool) []error {
|
func (p *BlobPool) Add(txs []*types.Transaction, sync bool) []error {
|
||||||
var (
|
var (
|
||||||
adds = make([]*types.Transaction, 0, len(txs))
|
adds = make([]*types.Transaction, 0, len(txs))
|
||||||
|
|
@ -1348,7 +1410,7 @@ func (p *BlobPool) add(tx *types.Transaction) (err error) {
|
||||||
// only by this subpool until all transactions are evicted
|
// only by this subpool until all transactions are evicted
|
||||||
from, _ := types.Sender(p.signer, tx) // already validated above
|
from, _ := types.Sender(p.signer, tx) // already validated above
|
||||||
if _, ok := p.index[from]; !ok {
|
if _, ok := p.index[from]; !ok {
|
||||||
if err := p.reserve(from, true); err != nil {
|
if err := p.reserver.Hold(from); err != nil {
|
||||||
addNonExclusiveMeter.Mark(1)
|
addNonExclusiveMeter.Mark(1)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -1360,7 +1422,7 @@ func (p *BlobPool) add(tx *types.Transaction) (err error) {
|
||||||
// by a return statement before running deferred methods. Take care with
|
// by a return statement before running deferred methods. Take care with
|
||||||
// removing or subscoping err as it will break this clause.
|
// removing or subscoping err as it will break this clause.
|
||||||
if err != nil {
|
if err != nil {
|
||||||
p.reserve(from, false)
|
p.reserver.Release(from)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
@ -1375,7 +1437,7 @@ func (p *BlobPool) add(tx *types.Transaction) (err error) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
meta := newBlobTxMeta(id, p.store.Size(id), tx)
|
meta := newBlobTxMeta(id, tx.Size(), p.store.Size(id), tx)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
next = p.state.GetNonce(from)
|
next = p.state.GetNonce(from)
|
||||||
|
|
@ -1403,7 +1465,7 @@ func (p *BlobPool) add(tx *types.Transaction) (err error) {
|
||||||
|
|
||||||
p.lookup.untrack(prev)
|
p.lookup.untrack(prev)
|
||||||
p.lookup.track(meta)
|
p.lookup.track(meta)
|
||||||
p.stored += uint64(meta.size) - uint64(prev.size)
|
p.stored += uint64(meta.storageSize) - uint64(prev.storageSize)
|
||||||
} else {
|
} else {
|
||||||
// Transaction extends previously scheduled ones
|
// Transaction extends previously scheduled ones
|
||||||
p.index[from] = append(p.index[from], meta)
|
p.index[from] = append(p.index[from], meta)
|
||||||
|
|
@ -1413,7 +1475,7 @@ func (p *BlobPool) add(tx *types.Transaction) (err error) {
|
||||||
}
|
}
|
||||||
p.spent[from] = new(uint256.Int).Add(p.spent[from], meta.costCap)
|
p.spent[from] = new(uint256.Int).Add(p.spent[from], meta.costCap)
|
||||||
p.lookup.track(meta)
|
p.lookup.track(meta)
|
||||||
p.stored += uint64(meta.size)
|
p.stored += uint64(meta.storageSize)
|
||||||
}
|
}
|
||||||
// Recompute the rolling eviction fields. In case of a replacement, this will
|
// Recompute the rolling eviction fields. In case of a replacement, this will
|
||||||
// recompute all subsequent fields. In case of an append, this will only do
|
// recompute all subsequent fields. In case of an append, this will only do
|
||||||
|
|
@ -1492,7 +1554,7 @@ func (p *BlobPool) drop() {
|
||||||
if last {
|
if last {
|
||||||
delete(p.index, from)
|
delete(p.index, from)
|
||||||
delete(p.spent, from)
|
delete(p.spent, from)
|
||||||
p.reserve(from, false)
|
p.reserver.Release(from)
|
||||||
} else {
|
} else {
|
||||||
txs[len(txs)-1] = nil
|
txs[len(txs)-1] = nil
|
||||||
txs = txs[:len(txs)-1]
|
txs = txs[:len(txs)-1]
|
||||||
|
|
@ -1500,7 +1562,7 @@ func (p *BlobPool) drop() {
|
||||||
p.index[from] = txs
|
p.index[from] = txs
|
||||||
p.spent[from] = new(uint256.Int).Sub(p.spent[from], drop.costCap)
|
p.spent[from] = new(uint256.Int).Sub(p.spent[from], drop.costCap)
|
||||||
}
|
}
|
||||||
p.stored -= uint64(drop.size)
|
p.stored -= uint64(drop.storageSize)
|
||||||
p.lookup.untrack(drop)
|
p.lookup.untrack(drop)
|
||||||
|
|
||||||
// Remove the transaction from the pool's eviction heap:
|
// Remove the transaction from the pool's eviction heap:
|
||||||
|
|
@ -1733,6 +1795,9 @@ func (p *BlobPool) Status(hash common.Hash) txpool.TxStatus {
|
||||||
|
|
||||||
// Clear implements txpool.SubPool, removing all tracked transactions
|
// Clear implements txpool.SubPool, removing all tracked transactions
|
||||||
// from the blob pool and persistent store.
|
// from the blob pool and persistent store.
|
||||||
|
//
|
||||||
|
// Note, do not use this in production / live code. In live code, the pool is
|
||||||
|
// meant to reset on a separate thread to avoid DoS vectors.
|
||||||
func (p *BlobPool) Clear() {
|
func (p *BlobPool) Clear() {
|
||||||
p.lock.Lock()
|
p.lock.Lock()
|
||||||
defer p.lock.Unlock()
|
defer p.lock.Unlock()
|
||||||
|
|
@ -1768,7 +1833,7 @@ func (p *BlobPool) Clear() {
|
||||||
// can't happen until Clear releases the reservation lock. Clear cannot
|
// can't happen until Clear releases the reservation lock. Clear cannot
|
||||||
// acquire the subpool lock until the transaction addition is completed.
|
// acquire the subpool lock until the transaction addition is completed.
|
||||||
for acct := range p.index {
|
for acct := range p.index {
|
||||||
p.reserve(acct, false)
|
p.reserver.Release(acct)
|
||||||
}
|
}
|
||||||
p.lookup = newLookup()
|
p.lookup = newLookup()
|
||||||
p.index = make(map[common.Address][]*blobTxMeta)
|
p.index = make(map[common.Address][]*blobTxMeta)
|
||||||
|
|
|
||||||
|
|
@ -168,31 +168,42 @@ func (bc *testBlockChain) StateAt(common.Hash) (*state.StateDB, error) {
|
||||||
return bc.statedb, nil
|
return bc.statedb, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// makeAddressReserver is a utility method to sanity check that accounts are
|
// reserver is a utility struct to sanity check that accounts are
|
||||||
// properly reserved by the blobpool (no duplicate reserves or unreserves).
|
// properly reserved by the blobpool (no duplicate reserves or unreserves).
|
||||||
func makeAddressReserver() txpool.AddressReserver {
|
type reserver struct {
|
||||||
var (
|
accounts map[common.Address]struct{}
|
||||||
reserved = make(map[common.Address]struct{})
|
lock sync.RWMutex
|
||||||
lock sync.Mutex
|
}
|
||||||
)
|
|
||||||
return func(addr common.Address, reserve bool) error {
|
|
||||||
lock.Lock()
|
|
||||||
defer lock.Unlock()
|
|
||||||
|
|
||||||
_, exists := reserved[addr]
|
func newReserver() txpool.Reserver {
|
||||||
if reserve {
|
return &reserver{accounts: make(map[common.Address]struct{})}
|
||||||
if exists {
|
}
|
||||||
|
|
||||||
|
func (r *reserver) Hold(addr common.Address) error {
|
||||||
|
r.lock.Lock()
|
||||||
|
defer r.lock.Unlock()
|
||||||
|
if _, exists := r.accounts[addr]; exists {
|
||||||
panic("already reserved")
|
panic("already reserved")
|
||||||
}
|
}
|
||||||
reserved[addr] = struct{}{}
|
r.accounts[addr] = struct{}{}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if !exists {
|
|
||||||
|
func (r *reserver) Release(addr common.Address) error {
|
||||||
|
r.lock.Lock()
|
||||||
|
defer r.lock.Unlock()
|
||||||
|
if _, exists := r.accounts[addr]; !exists {
|
||||||
panic("not reserved")
|
panic("not reserved")
|
||||||
}
|
}
|
||||||
delete(reserved, addr)
|
delete(r.accounts, addr)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *reserver) Has(address common.Address) bool {
|
||||||
|
r.lock.RLock()
|
||||||
|
defer r.lock.RUnlock()
|
||||||
|
_, exists := r.accounts[address]
|
||||||
|
return exists
|
||||||
}
|
}
|
||||||
|
|
||||||
// makeTx is a utility method to construct a random blob transaction and sign it
|
// makeTx is a utility method to construct a random blob transaction and sign it
|
||||||
|
|
@ -376,7 +387,7 @@ func verifyPoolInternals(t *testing.T, pool *BlobPool) {
|
||||||
var stored uint64
|
var stored uint64
|
||||||
for _, txs := range pool.index {
|
for _, txs := range pool.index {
|
||||||
for _, tx := range txs {
|
for _, tx := range txs {
|
||||||
stored += uint64(tx.size)
|
stored += uint64(tx.storageSize)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if pool.stored != stored {
|
if pool.stored != stored {
|
||||||
|
|
@ -699,8 +710,8 @@ func TestOpenDrops(t *testing.T) {
|
||||||
blobfee: uint256.NewInt(params.BlobTxMinBlobGasprice),
|
blobfee: uint256.NewInt(params.BlobTxMinBlobGasprice),
|
||||||
statedb: statedb,
|
statedb: statedb,
|
||||||
}
|
}
|
||||||
pool := New(Config{Datadir: storage}, chain)
|
pool := New(Config{Datadir: storage}, chain, nil)
|
||||||
if err := pool.Init(1, chain.CurrentBlock(), makeAddressReserver()); err != nil {
|
if err := pool.Init(1, chain.CurrentBlock(), newReserver()); err != nil {
|
||||||
t.Fatalf("failed to create blob pool: %v", err)
|
t.Fatalf("failed to create blob pool: %v", err)
|
||||||
}
|
}
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
@ -817,8 +828,8 @@ func TestOpenIndex(t *testing.T) {
|
||||||
blobfee: uint256.NewInt(params.BlobTxMinBlobGasprice),
|
blobfee: uint256.NewInt(params.BlobTxMinBlobGasprice),
|
||||||
statedb: statedb,
|
statedb: statedb,
|
||||||
}
|
}
|
||||||
pool := New(Config{Datadir: storage}, chain)
|
pool := New(Config{Datadir: storage}, chain, nil)
|
||||||
if err := pool.Init(1, chain.CurrentBlock(), makeAddressReserver()); err != nil {
|
if err := pool.Init(1, chain.CurrentBlock(), newReserver()); err != nil {
|
||||||
t.Fatalf("failed to create blob pool: %v", err)
|
t.Fatalf("failed to create blob pool: %v", err)
|
||||||
}
|
}
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
@ -918,8 +929,8 @@ func TestOpenHeap(t *testing.T) {
|
||||||
blobfee: uint256.NewInt(105),
|
blobfee: uint256.NewInt(105),
|
||||||
statedb: statedb,
|
statedb: statedb,
|
||||||
}
|
}
|
||||||
pool := New(Config{Datadir: storage}, chain)
|
pool := New(Config{Datadir: storage}, chain, nil)
|
||||||
if err := pool.Init(1, chain.CurrentBlock(), makeAddressReserver()); err != nil {
|
if err := pool.Init(1, chain.CurrentBlock(), newReserver()); err != nil {
|
||||||
t.Fatalf("failed to create blob pool: %v", err)
|
t.Fatalf("failed to create blob pool: %v", err)
|
||||||
}
|
}
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
@ -997,8 +1008,8 @@ func TestOpenCap(t *testing.T) {
|
||||||
blobfee: uint256.NewInt(105),
|
blobfee: uint256.NewInt(105),
|
||||||
statedb: statedb,
|
statedb: statedb,
|
||||||
}
|
}
|
||||||
pool := New(Config{Datadir: storage, Datacap: datacap}, chain)
|
pool := New(Config{Datadir: storage, Datacap: datacap}, chain, nil)
|
||||||
if err := pool.Init(1, chain.CurrentBlock(), makeAddressReserver()); err != nil {
|
if err := pool.Init(1, chain.CurrentBlock(), newReserver()); err != nil {
|
||||||
t.Fatalf("failed to create blob pool: %v", err)
|
t.Fatalf("failed to create blob pool: %v", err)
|
||||||
}
|
}
|
||||||
// Verify that enough transactions have been dropped to get the pool's size
|
// Verify that enough transactions have been dropped to get the pool's size
|
||||||
|
|
@ -1098,8 +1109,8 @@ func TestChangingSlotterSize(t *testing.T) {
|
||||||
blobfee: uint256.NewInt(105),
|
blobfee: uint256.NewInt(105),
|
||||||
statedb: statedb,
|
statedb: statedb,
|
||||||
}
|
}
|
||||||
pool := New(Config{Datadir: storage}, chain)
|
pool := New(Config{Datadir: storage}, chain, nil)
|
||||||
if err := pool.Init(1, chain.CurrentBlock(), makeAddressReserver()); err != nil {
|
if err := pool.Init(1, chain.CurrentBlock(), newReserver()); err != nil {
|
||||||
t.Fatalf("failed to create blob pool: %v", err)
|
t.Fatalf("failed to create blob pool: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1541,8 +1552,8 @@ func TestAdd(t *testing.T) {
|
||||||
blobfee: uint256.NewInt(105),
|
blobfee: uint256.NewInt(105),
|
||||||
statedb: statedb,
|
statedb: statedb,
|
||||||
}
|
}
|
||||||
pool := New(Config{Datadir: storage}, chain)
|
pool := New(Config{Datadir: storage}, chain, nil)
|
||||||
if err := pool.Init(1, chain.CurrentBlock(), makeAddressReserver()); err != nil {
|
if err := pool.Init(1, chain.CurrentBlock(), newReserver()); err != nil {
|
||||||
t.Fatalf("test %d: failed to create blob pool: %v", i, err)
|
t.Fatalf("test %d: failed to create blob pool: %v", i, err)
|
||||||
}
|
}
|
||||||
verifyPoolInternals(t, pool)
|
verifyPoolInternals(t, pool)
|
||||||
|
|
@ -1553,6 +1564,16 @@ func TestAdd(t *testing.T) {
|
||||||
if err := pool.add(signed); !errors.Is(err, add.err) {
|
if err := pool.add(signed); !errors.Is(err, add.err) {
|
||||||
t.Errorf("test %d, tx %d: adding transaction error mismatch: have %v, want %v", i, j, err, add.err)
|
t.Errorf("test %d, tx %d: adding transaction error mismatch: have %v, want %v", i, j, err, add.err)
|
||||||
}
|
}
|
||||||
|
if add.err == nil {
|
||||||
|
size, exist := pool.lookup.sizeOfTx(signed.Hash())
|
||||||
|
if !exist {
|
||||||
|
t.Errorf("test %d, tx %d: failed to lookup transaction's size", i, j)
|
||||||
|
}
|
||||||
|
if size != signed.Size() {
|
||||||
|
t.Errorf("test %d, tx %d: transaction's size mismatches: have %v, want %v",
|
||||||
|
i, j, size, signed.Size())
|
||||||
|
}
|
||||||
|
}
|
||||||
verifyPoolInternals(t, pool)
|
verifyPoolInternals(t, pool)
|
||||||
}
|
}
|
||||||
verifyPoolInternals(t, pool)
|
verifyPoolInternals(t, pool)
|
||||||
|
|
@ -1628,10 +1649,10 @@ func benchmarkPoolPending(b *testing.B, datacap uint64) {
|
||||||
blobfee: uint256.NewInt(blobfee),
|
blobfee: uint256.NewInt(blobfee),
|
||||||
statedb: statedb,
|
statedb: statedb,
|
||||||
}
|
}
|
||||||
pool = New(Config{Datadir: ""}, chain)
|
pool = New(Config{Datadir: ""}, chain, nil)
|
||||||
)
|
)
|
||||||
|
|
||||||
if err := pool.Init(1, chain.CurrentBlock(), makeAddressReserver()); err != nil {
|
if err := pool.Init(1, chain.CurrentBlock(), newReserver()); err != nil {
|
||||||
b.Fatalf("failed to create blob pool: %v", err)
|
b.Fatalf("failed to create blob pool: %v", err)
|
||||||
}
|
}
|
||||||
// Make the pool not use disk (just drop everything). This test never reads
|
// Make the pool not use disk (just drop everything). This test never reads
|
||||||
|
|
|
||||||
|
|
@ -146,7 +146,7 @@ func TestPriceHeapSorting(t *testing.T) {
|
||||||
)
|
)
|
||||||
index[addr] = []*blobTxMeta{{
|
index[addr] = []*blobTxMeta{{
|
||||||
id: uint64(j),
|
id: uint64(j),
|
||||||
size: 128 * 1024,
|
storageSize: 128 * 1024,
|
||||||
nonce: 0,
|
nonce: 0,
|
||||||
execTipCap: execTip,
|
execTipCap: execTip,
|
||||||
execFeeCap: execFee,
|
execFeeCap: execFee,
|
||||||
|
|
@ -205,7 +205,7 @@ func benchmarkPriceHeapReinit(b *testing.B, datacap uint64) {
|
||||||
)
|
)
|
||||||
index[addr] = []*blobTxMeta{{
|
index[addr] = []*blobTxMeta{{
|
||||||
id: uint64(i),
|
id: uint64(i),
|
||||||
size: 128 * 1024,
|
storageSize: 128 * 1024,
|
||||||
nonce: 0,
|
nonce: 0,
|
||||||
execTipCap: execTip,
|
execTipCap: execTip,
|
||||||
execFeeCap: execFee,
|
execFeeCap: execFee,
|
||||||
|
|
@ -281,7 +281,7 @@ func benchmarkPriceHeapOverflow(b *testing.B, datacap uint64) {
|
||||||
)
|
)
|
||||||
index[addr] = []*blobTxMeta{{
|
index[addr] = []*blobTxMeta{{
|
||||||
id: uint64(i),
|
id: uint64(i),
|
||||||
size: 128 * 1024,
|
storageSize: 128 * 1024,
|
||||||
nonce: 0,
|
nonce: 0,
|
||||||
execTipCap: execTip,
|
execTipCap: execTip,
|
||||||
execFeeCap: execFee,
|
execFeeCap: execFee,
|
||||||
|
|
@ -312,7 +312,7 @@ func benchmarkPriceHeapOverflow(b *testing.B, datacap uint64) {
|
||||||
)
|
)
|
||||||
metas[i] = &blobTxMeta{
|
metas[i] = &blobTxMeta{
|
||||||
id: uint64(int(blobs) + i),
|
id: uint64(int(blobs) + i),
|
||||||
size: 128 * 1024,
|
storageSize: 128 * 1024,
|
||||||
nonce: 0,
|
nonce: 0,
|
||||||
execTipCap: execTip,
|
execTipCap: execTip,
|
||||||
execFeeCap: execFee,
|
execFeeCap: execFee,
|
||||||
|
|
|
||||||
|
|
@ -20,18 +20,24 @@ import (
|
||||||
"github.com/ethereum/go-ethereum/common"
|
"github.com/ethereum/go-ethereum/common"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type txMetadata struct {
|
||||||
|
id uint64 // the billy id of transction
|
||||||
|
size uint64 // the RLP encoded size of transaction (blobs are included)
|
||||||
|
}
|
||||||
|
|
||||||
// lookup maps blob versioned hashes to transaction hashes that include them,
|
// lookup maps blob versioned hashes to transaction hashes that include them,
|
||||||
// and transaction hashes to billy entries that include them.
|
// transaction hashes to billy entries that include them, transaction hashes
|
||||||
|
// to the transaction size
|
||||||
type lookup struct {
|
type lookup struct {
|
||||||
blobIndex map[common.Hash]map[common.Hash]struct{}
|
blobIndex map[common.Hash]map[common.Hash]struct{}
|
||||||
txIndex map[common.Hash]uint64
|
txIndex map[common.Hash]*txMetadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// newLookup creates a new index for tracking blob to tx; and tx to billy mappings.
|
// newLookup creates a new index for tracking blob to tx; and tx to billy mappings.
|
||||||
func newLookup() *lookup {
|
func newLookup() *lookup {
|
||||||
return &lookup{
|
return &lookup{
|
||||||
blobIndex: make(map[common.Hash]map[common.Hash]struct{}),
|
blobIndex: make(map[common.Hash]map[common.Hash]struct{}),
|
||||||
txIndex: make(map[common.Hash]uint64),
|
txIndex: make(map[common.Hash]*txMetadata),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -43,8 +49,11 @@ func (l *lookup) exists(txhash common.Hash) bool {
|
||||||
|
|
||||||
// storeidOfTx returns the datastore storage item id of a transaction.
|
// storeidOfTx returns the datastore storage item id of a transaction.
|
||||||
func (l *lookup) storeidOfTx(txhash common.Hash) (uint64, bool) {
|
func (l *lookup) storeidOfTx(txhash common.Hash) (uint64, bool) {
|
||||||
id, ok := l.txIndex[txhash]
|
meta, ok := l.txIndex[txhash]
|
||||||
return id, ok
|
if !ok {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return meta.id, true
|
||||||
}
|
}
|
||||||
|
|
||||||
// storeidOfBlob returns the datastore storage item id of a blob.
|
// storeidOfBlob returns the datastore storage item id of a blob.
|
||||||
|
|
@ -61,6 +70,15 @@ func (l *lookup) storeidOfBlob(vhash common.Hash) (uint64, bool) {
|
||||||
return 0, false // Weird, don't choke
|
return 0, false // Weird, don't choke
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// sizeOfTx returns the RLP-encoded size of transaction
|
||||||
|
func (l *lookup) sizeOfTx(txhash common.Hash) (uint64, bool) {
|
||||||
|
meta, ok := l.txIndex[txhash]
|
||||||
|
if !ok {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return meta.size, true
|
||||||
|
}
|
||||||
|
|
||||||
// track inserts a new set of mappings from blob versioned hashes to transaction
|
// track inserts a new set of mappings from blob versioned hashes to transaction
|
||||||
// hashes; and from transaction hashes to datastore storage item ids.
|
// hashes; and from transaction hashes to datastore storage item ids.
|
||||||
func (l *lookup) track(tx *blobTxMeta) {
|
func (l *lookup) track(tx *blobTxMeta) {
|
||||||
|
|
@ -71,8 +89,11 @@ func (l *lookup) track(tx *blobTxMeta) {
|
||||||
}
|
}
|
||||||
l.blobIndex[vhash][tx.hash] = struct{}{} // may be double mapped if a tx contains the same blob twice
|
l.blobIndex[vhash][tx.hash] = struct{}{} // may be double mapped if a tx contains the same blob twice
|
||||||
}
|
}
|
||||||
// Map the transaction hash to the datastore id
|
// Map the transaction hash to the datastore id and RLP-encoded transaction size
|
||||||
l.txIndex[tx.hash] = tx.id
|
l.txIndex[tx.hash] = &txMetadata{
|
||||||
|
id: tx.id,
|
||||||
|
size: tx.size,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// untrack removes a set of mappings from blob versioned hashes to transaction
|
// untrack removes a set of mappings from blob versioned hashes to transaction
|
||||||
|
|
|
||||||
|
|
@ -56,4 +56,8 @@ var (
|
||||||
// input transaction of non-blob type when a blob transaction from this sender
|
// input transaction of non-blob type when a blob transaction from this sender
|
||||||
// remains pending (and vice-versa).
|
// remains pending (and vice-versa).
|
||||||
ErrAlreadyReserved = errors.New("address already reserved")
|
ErrAlreadyReserved = errors.New("address already reserved")
|
||||||
|
|
||||||
|
// ErrInflightTxLimitReached is returned when the maximum number of in-flight
|
||||||
|
// transactions is reached for specific accounts.
|
||||||
|
ErrInflightTxLimitReached = errors.New("in-flight transaction limit reached for delegated accounts")
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -63,10 +63,6 @@ var (
|
||||||
// another remote transaction.
|
// another remote transaction.
|
||||||
ErrTxPoolOverflow = errors.New("txpool is full")
|
ErrTxPoolOverflow = errors.New("txpool is full")
|
||||||
|
|
||||||
// ErrInflightTxLimitReached is returned when the maximum number of in-flight
|
|
||||||
// transactions is reached for specific accounts.
|
|
||||||
ErrInflightTxLimitReached = errors.New("in-flight transaction limit reached for delegated accounts")
|
|
||||||
|
|
||||||
// ErrOutOfOrderTxFromDelegated is returned when the transaction with gapped
|
// ErrOutOfOrderTxFromDelegated is returned when the transaction with gapped
|
||||||
// nonce received from the accounts with delegation or pending delegation.
|
// nonce received from the accounts with delegation or pending delegation.
|
||||||
ErrOutOfOrderTxFromDelegated = errors.New("gapped-nonce tx from delegated accounts")
|
ErrOutOfOrderTxFromDelegated = errors.New("gapped-nonce tx from delegated accounts")
|
||||||
|
|
@ -241,8 +237,8 @@ type LegacyPool struct {
|
||||||
currentHead atomic.Pointer[types.Header] // Current head of the blockchain
|
currentHead atomic.Pointer[types.Header] // Current head of the blockchain
|
||||||
currentState *state.StateDB // Current state in the blockchain head
|
currentState *state.StateDB // Current state in the blockchain head
|
||||||
pendingNonces *noncer // Pending state tracking virtual nonces
|
pendingNonces *noncer // Pending state tracking virtual nonces
|
||||||
|
reserver txpool.Reserver // Address reserver to ensure exclusivity across subpools
|
||||||
|
|
||||||
reserve txpool.AddressReserver // Address reserver to ensure exclusivity across subpools
|
|
||||||
pending map[common.Address]*list // All currently processable transactions
|
pending map[common.Address]*list // All currently processable transactions
|
||||||
queue map[common.Address]*list // Queued but non-processable transactions
|
queue map[common.Address]*list // Queued but non-processable transactions
|
||||||
beats map[common.Address]time.Time // Last heartbeat from each known account
|
beats map[common.Address]time.Time // Last heartbeat from each known account
|
||||||
|
|
@ -306,9 +302,9 @@ func (pool *LegacyPool) Filter(tx *types.Transaction) bool {
|
||||||
// Init sets the gas price needed to keep a transaction in the pool and the chain
|
// Init sets the gas price needed to keep a transaction in the pool and the chain
|
||||||
// head to allow balance / nonce checks. The internal
|
// head to allow balance / nonce checks. The internal
|
||||||
// goroutines will be spun up and the pool deemed operational afterwards.
|
// goroutines will be spun up and the pool deemed operational afterwards.
|
||||||
func (pool *LegacyPool) Init(gasTip uint64, head *types.Header, reserve txpool.AddressReserver) error {
|
func (pool *LegacyPool) Init(gasTip uint64, head *types.Header, reserver txpool.Reserver) error {
|
||||||
// Set the address reserver to request exclusive access to pooled accounts
|
// Set the address reserver to request exclusive access to pooled accounts
|
||||||
pool.reserve = reserve
|
pool.reserver = reserver
|
||||||
|
|
||||||
// Set the basic pool parameters
|
// Set the basic pool parameters
|
||||||
pool.gasTip.Store(uint256.NewInt(gasTip))
|
pool.gasTip.Store(uint256.NewInt(gasTip))
|
||||||
|
|
@ -618,7 +614,7 @@ func (pool *LegacyPool) checkDelegationLimit(tx *types.Transaction) error {
|
||||||
from, _ := types.Sender(pool.signer, tx) // validated
|
from, _ := types.Sender(pool.signer, tx) // validated
|
||||||
|
|
||||||
// Short circuit if the sender has neither delegation nor pending delegation.
|
// Short circuit if the sender has neither delegation nor pending delegation.
|
||||||
if pool.currentState.GetCodeHash(from) == types.EmptyCodeHash && pool.all.delegationTxsCount(from) == 0 {
|
if pool.currentState.GetCodeHash(from) == types.EmptyCodeHash && !pool.all.hasAuth(from) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
pending := pool.pending[from]
|
pending := pool.pending[from]
|
||||||
|
|
@ -633,7 +629,7 @@ func (pool *LegacyPool) checkDelegationLimit(tx *types.Transaction) error {
|
||||||
if pending.Contains(tx.Nonce()) {
|
if pending.Contains(tx.Nonce()) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return ErrInflightTxLimitReached
|
return txpool.ErrInflightTxLimitReached
|
||||||
}
|
}
|
||||||
|
|
||||||
// validateAuth verifies that the transaction complies with code authorization
|
// validateAuth verifies that the transaction complies with code authorization
|
||||||
|
|
@ -644,10 +640,29 @@ func (pool *LegacyPool) validateAuth(tx *types.Transaction) error {
|
||||||
if err := pool.checkDelegationLimit(tx); err != nil {
|
if err := pool.checkDelegationLimit(tx); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// Authorities cannot conflict with any pending or queued transactions.
|
// For symmetry, allow at most one in-flight tx for any authority with a
|
||||||
|
// pending transaction.
|
||||||
if auths := tx.SetCodeAuthorities(); len(auths) > 0 {
|
if auths := tx.SetCodeAuthorities(); len(auths) > 0 {
|
||||||
for _, auth := range auths {
|
for _, auth := range auths {
|
||||||
if pool.pending[auth] != nil || pool.queue[auth] != nil {
|
var count int
|
||||||
|
if pending := pool.pending[auth]; pending != nil {
|
||||||
|
count += pending.Len()
|
||||||
|
}
|
||||||
|
if queue := pool.queue[auth]; queue != nil {
|
||||||
|
count += queue.Len()
|
||||||
|
}
|
||||||
|
if count > 1 {
|
||||||
|
return ErrAuthorityReserved
|
||||||
|
}
|
||||||
|
// Because there is no exclusive lock held between different subpools
|
||||||
|
// when processing transactions, the SetCode transaction may be accepted
|
||||||
|
// while other transactions with the same sender address are also
|
||||||
|
// accepted simultaneously in the other pools.
|
||||||
|
//
|
||||||
|
// This scenario is considered acceptable, as the rule primarily ensures
|
||||||
|
// that attackers cannot easily stack a SetCode transaction when the sender
|
||||||
|
// is reserved by other pools.
|
||||||
|
if pool.reserver.Has(auth) {
|
||||||
return ErrAuthorityReserved
|
return ErrAuthorityReserved
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -683,7 +698,7 @@ func (pool *LegacyPool) add(tx *types.Transaction) (replaced bool, err error) {
|
||||||
_, hasQueued = pool.queue[from]
|
_, hasQueued = pool.queue[from]
|
||||||
)
|
)
|
||||||
if !hasPending && !hasQueued {
|
if !hasPending && !hasQueued {
|
||||||
if err := pool.reserve(from, true); err != nil {
|
if err := pool.reserver.Hold(from); err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
defer func() {
|
defer func() {
|
||||||
|
|
@ -694,7 +709,7 @@ func (pool *LegacyPool) add(tx *types.Transaction) (replaced bool, err error) {
|
||||||
// by a return statement before running deferred methods. Take care with
|
// by a return statement before running deferred methods. Take care with
|
||||||
// removing or subscoping err as it will break this clause.
|
// removing or subscoping err as it will break this clause.
|
||||||
if err != nil {
|
if err != nil {
|
||||||
pool.reserve(from, false)
|
pool.reserver.Release(from)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
@ -919,8 +934,8 @@ func (pool *LegacyPool) addRemoteSync(tx *types.Transaction) error {
|
||||||
|
|
||||||
// Add enqueues a batch of transactions into the pool if they are valid.
|
// Add enqueues a batch of transactions into the pool if they are valid.
|
||||||
//
|
//
|
||||||
// If sync is set, the method will block until all internal maintenance related
|
// Note, if sync is set the method will block until all internal maintenance
|
||||||
// to the add is finished. Only use this during tests for determinism!
|
// related to the add is finished. Only use this during tests for determinism.
|
||||||
func (pool *LegacyPool) Add(txs []*types.Transaction, sync bool) []error {
|
func (pool *LegacyPool) Add(txs []*types.Transaction, sync bool) []error {
|
||||||
// Filter out known ones without obtaining the pool lock or recovering signatures
|
// Filter out known ones without obtaining the pool lock or recovering signatures
|
||||||
var (
|
var (
|
||||||
|
|
@ -1035,6 +1050,19 @@ func (pool *LegacyPool) GetRLP(hash common.Hash) []byte {
|
||||||
return encoded
|
return encoded
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetMetadata returns the transaction type and transaction size with the
|
||||||
|
// given transaction hash.
|
||||||
|
func (pool *LegacyPool) GetMetadata(hash common.Hash) *txpool.TxMetadata {
|
||||||
|
tx := pool.all.Get(hash)
|
||||||
|
if tx == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &txpool.TxMetadata{
|
||||||
|
Type: tx.Type(),
|
||||||
|
Size: tx.Size(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// GetBlobs is not supported by the legacy transaction pool, it is just here to
|
// GetBlobs is not supported by the legacy transaction pool, it is just here to
|
||||||
// implement the txpool.SubPool interface.
|
// implement the txpool.SubPool interface.
|
||||||
func (pool *LegacyPool) GetBlobs(vhashes []common.Hash) ([]*kzg4844.Blob, []*kzg4844.Proof) {
|
func (pool *LegacyPool) GetBlobs(vhashes []common.Hash) ([]*kzg4844.Blob, []*kzg4844.Proof) {
|
||||||
|
|
@ -1074,7 +1102,7 @@ func (pool *LegacyPool) removeTx(hash common.Hash, outofbound bool, unreserve bo
|
||||||
_, hasQueued = pool.queue[addr]
|
_, hasQueued = pool.queue[addr]
|
||||||
)
|
)
|
||||||
if !hasPending && !hasQueued {
|
if !hasPending && !hasQueued {
|
||||||
pool.reserve(addr, false)
|
pool.reserver.Release(addr)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
@ -1454,7 +1482,7 @@ func (pool *LegacyPool) promoteExecutables(accounts []common.Address) []*types.T
|
||||||
delete(pool.queue, addr)
|
delete(pool.queue, addr)
|
||||||
delete(pool.beats, addr)
|
delete(pool.beats, addr)
|
||||||
if _, ok := pool.pending[addr]; !ok {
|
if _, ok := pool.pending[addr]; !ok {
|
||||||
pool.reserve(addr, false)
|
pool.reserver.Release(addr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1640,7 +1668,7 @@ func (pool *LegacyPool) demoteUnexecutables() {
|
||||||
if list.Empty() {
|
if list.Empty() {
|
||||||
delete(pool.pending, addr)
|
delete(pool.pending, addr)
|
||||||
if _, ok := pool.queue[addr]; !ok {
|
if _, ok := pool.queue[addr]; !ok {
|
||||||
pool.reserve(addr, false)
|
pool.reserver.Release(addr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1849,11 +1877,13 @@ func (t *lookup) removeAuthorities(tx *types.Transaction) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// delegationTxsCount returns the number of pending authorizations for the specified address.
|
// hasAuth returns a flag indicating whether there are pending authorizations
|
||||||
func (t *lookup) delegationTxsCount(addr common.Address) int {
|
// from the specified address.
|
||||||
|
func (t *lookup) hasAuth(addr common.Address) bool {
|
||||||
t.lock.RLock()
|
t.lock.RLock()
|
||||||
defer t.lock.RUnlock()
|
defer t.lock.RUnlock()
|
||||||
return len(t.auths[addr])
|
|
||||||
|
return len(t.auths[addr]) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// numSlots calculates the number of slots needed for a single transaction.
|
// numSlots calculates the number of slots needed for a single transaction.
|
||||||
|
|
@ -1863,6 +1893,9 @@ func numSlots(tx *types.Transaction) int {
|
||||||
|
|
||||||
// Clear implements txpool.SubPool, removing all tracked txs from the pool
|
// Clear implements txpool.SubPool, removing all tracked txs from the pool
|
||||||
// and rotating the journal.
|
// and rotating the journal.
|
||||||
|
//
|
||||||
|
// Note, do not use this in production / live code. In live code, the pool is
|
||||||
|
// meant to reset on a separate thread to avoid DoS vectors.
|
||||||
func (pool *LegacyPool) Clear() {
|
func (pool *LegacyPool) Clear() {
|
||||||
pool.mu.Lock()
|
pool.mu.Lock()
|
||||||
defer pool.mu.Unlock()
|
defer pool.mu.Unlock()
|
||||||
|
|
@ -1881,9 +1914,14 @@ func (pool *LegacyPool) Clear() {
|
||||||
// The transaction addition may attempt to reserve the sender addr which
|
// The transaction addition may attempt to reserve the sender addr which
|
||||||
// can't happen until Clear releases the reservation lock. Clear cannot
|
// can't happen until Clear releases the reservation lock. Clear cannot
|
||||||
// acquire the subpool lock until the transaction addition is completed.
|
// acquire the subpool lock until the transaction addition is completed.
|
||||||
for _, tx := range pool.all.txs {
|
|
||||||
senderAddr, _ := types.Sender(pool.signer, tx)
|
for addr := range pool.pending {
|
||||||
pool.reserve(senderAddr, false)
|
if _, ok := pool.queue[addr]; !ok {
|
||||||
|
pool.reserver.Release(addr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for addr := range pool.queue {
|
||||||
|
pool.reserver.Release(addr)
|
||||||
}
|
}
|
||||||
pool.all = newLookup()
|
pool.all = newLookup()
|
||||||
pool.priced = newPricedList(pool.all)
|
pool.priced = newPricedList(pool.all)
|
||||||
|
|
@ -1891,3 +1929,9 @@ func (pool *LegacyPool) Clear() {
|
||||||
pool.queue = make(map[common.Address]*list)
|
pool.queue = make(map[common.Address]*list)
|
||||||
pool.pendingNonces = newNoncer(pool.currentState)
|
pool.pendingNonces = newNoncer(pool.currentState)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// HasPendingAuth returns a flag indicating whether there are pending
|
||||||
|
// authorizations from the specific address cached in the pool.
|
||||||
|
func (pool *LegacyPool) HasPendingAuth(addr common.Address) bool {
|
||||||
|
return pool.all.hasAuth(addr)
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -86,7 +86,7 @@ func TestTransactionFutureAttack(t *testing.T) {
|
||||||
config.GlobalQueue = 100
|
config.GlobalQueue = 100
|
||||||
config.GlobalSlots = 100
|
config.GlobalSlots = 100
|
||||||
pool := New(config, blockchain)
|
pool := New(config, blockchain)
|
||||||
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
fillPool(t, pool)
|
fillPool(t, pool)
|
||||||
pending, _ := pool.Stats()
|
pending, _ := pool.Stats()
|
||||||
|
|
@ -120,7 +120,7 @@ func TestTransactionFuture1559(t *testing.T) {
|
||||||
statedb, _ := state.New(types.EmptyRootHash, state.NewDatabaseForTesting())
|
statedb, _ := state.New(types.EmptyRootHash, state.NewDatabaseForTesting())
|
||||||
blockchain := newTestBlockChain(eip1559Config, 1000000, statedb, new(event.Feed))
|
blockchain := newTestBlockChain(eip1559Config, 1000000, statedb, new(event.Feed))
|
||||||
pool := New(testTxPoolConfig, blockchain)
|
pool := New(testTxPoolConfig, blockchain)
|
||||||
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Create a number of test accounts, fund them and make transactions
|
// Create a number of test accounts, fund them and make transactions
|
||||||
|
|
@ -153,7 +153,7 @@ func TestTransactionZAttack(t *testing.T) {
|
||||||
statedb, _ := state.New(types.EmptyRootHash, state.NewDatabaseForTesting())
|
statedb, _ := state.New(types.EmptyRootHash, state.NewDatabaseForTesting())
|
||||||
blockchain := newTestBlockChain(eip1559Config, 1000000, statedb, new(event.Feed))
|
blockchain := newTestBlockChain(eip1559Config, 1000000, statedb, new(event.Feed))
|
||||||
pool := New(testTxPoolConfig, blockchain)
|
pool := New(testTxPoolConfig, blockchain)
|
||||||
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
// Create a number of test accounts, fund them and make transactions
|
// Create a number of test accounts, fund them and make transactions
|
||||||
fillPool(t, pool)
|
fillPool(t, pool)
|
||||||
|
|
@ -224,7 +224,7 @@ func BenchmarkFutureAttack(b *testing.B) {
|
||||||
config.GlobalQueue = 100
|
config.GlobalQueue = 100
|
||||||
config.GlobalSlots = 100
|
config.GlobalSlots = 100
|
||||||
pool := New(config, blockchain)
|
pool := New(config, blockchain)
|
||||||
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
fillPool(b, pool)
|
fillPool(b, pool)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -168,42 +168,52 @@ func pricedSetCodeTxWithAuth(nonce uint64, gaslimit uint64, gasFee, tip *uint256
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func makeAddressReserver() txpool.AddressReserver {
|
|
||||||
var (
|
|
||||||
reserved = make(map[common.Address]struct{})
|
|
||||||
lock sync.Mutex
|
|
||||||
)
|
|
||||||
return func(addr common.Address, reserve bool) error {
|
|
||||||
lock.Lock()
|
|
||||||
defer lock.Unlock()
|
|
||||||
|
|
||||||
_, exists := reserved[addr]
|
|
||||||
if reserve {
|
|
||||||
if exists {
|
|
||||||
panic("already reserved")
|
|
||||||
}
|
|
||||||
reserved[addr] = struct{}{}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if !exists {
|
|
||||||
panic("not reserved")
|
|
||||||
}
|
|
||||||
delete(reserved, addr)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func setupPool() (*LegacyPool, *ecdsa.PrivateKey) {
|
func setupPool() (*LegacyPool, *ecdsa.PrivateKey) {
|
||||||
return setupPoolWithConfig(params.TestChainConfig)
|
return setupPoolWithConfig(params.TestChainConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// reserver is a utility struct to sanity check that accounts are
|
||||||
|
// properly reserved by the blobpool (no duplicate reserves or unreserves).
|
||||||
|
type reserver struct {
|
||||||
|
accounts map[common.Address]struct{}
|
||||||
|
lock sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func newReserver() txpool.Reserver {
|
||||||
|
return &reserver{accounts: make(map[common.Address]struct{})}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *reserver) Hold(addr common.Address) error {
|
||||||
|
r.lock.Lock()
|
||||||
|
defer r.lock.Unlock()
|
||||||
|
if _, exists := r.accounts[addr]; exists {
|
||||||
|
panic("already reserved")
|
||||||
|
}
|
||||||
|
r.accounts[addr] = struct{}{}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *reserver) Release(addr common.Address) error {
|
||||||
|
r.lock.Lock()
|
||||||
|
defer r.lock.Unlock()
|
||||||
|
if _, exists := r.accounts[addr]; !exists {
|
||||||
|
panic("not reserved")
|
||||||
|
}
|
||||||
|
delete(r.accounts, addr)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *reserver) Has(address common.Address) bool {
|
||||||
|
return false // reserver only supports a single pool
|
||||||
|
}
|
||||||
|
|
||||||
func setupPoolWithConfig(config *params.ChainConfig) (*LegacyPool, *ecdsa.PrivateKey) {
|
func setupPoolWithConfig(config *params.ChainConfig) (*LegacyPool, *ecdsa.PrivateKey) {
|
||||||
statedb, _ := state.New(types.EmptyRootHash, state.NewDatabaseForTesting())
|
statedb, _ := state.New(types.EmptyRootHash, state.NewDatabaseForTesting())
|
||||||
blockchain := newTestBlockChain(config, 10000000, statedb, new(event.Feed))
|
blockchain := newTestBlockChain(config, 10000000, statedb, new(event.Feed))
|
||||||
|
|
||||||
key, _ := crypto.GenerateKey()
|
key, _ := crypto.GenerateKey()
|
||||||
pool := New(testTxPoolConfig, blockchain)
|
pool := New(testTxPoolConfig, blockchain)
|
||||||
if err := pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver()); err != nil {
|
if err := pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver()); err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
// wait for the pool to initialize
|
// wait for the pool to initialize
|
||||||
|
|
@ -336,7 +346,7 @@ func TestStateChangeDuringReset(t *testing.T) {
|
||||||
tx1 := transaction(1, 100000, key)
|
tx1 := transaction(1, 100000, key)
|
||||||
|
|
||||||
pool := New(testTxPoolConfig, blockchain)
|
pool := New(testTxPoolConfig, blockchain)
|
||||||
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
nonce := pool.Nonce(address)
|
nonce := pool.Nonce(address)
|
||||||
|
|
@ -753,7 +763,7 @@ func TestPostponing(t *testing.T) {
|
||||||
blockchain := newTestBlockChain(params.TestChainConfig, 1000000, statedb, new(event.Feed))
|
blockchain := newTestBlockChain(params.TestChainConfig, 1000000, statedb, new(event.Feed))
|
||||||
|
|
||||||
pool := New(testTxPoolConfig, blockchain)
|
pool := New(testTxPoolConfig, blockchain)
|
||||||
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Create two test accounts to produce different gap profiles with
|
// Create two test accounts to produce different gap profiles with
|
||||||
|
|
@ -963,7 +973,7 @@ func TestQueueGlobalLimiting(t *testing.T) {
|
||||||
config.GlobalQueue = config.AccountQueue*3 - 1 // reduce the queue limits to shorten test time (-1 to make it non divisible)
|
config.GlobalQueue = config.AccountQueue*3 - 1 // reduce the queue limits to shorten test time (-1 to make it non divisible)
|
||||||
|
|
||||||
pool := New(config, blockchain)
|
pool := New(config, blockchain)
|
||||||
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Create a number of test accounts and fund them (last one will be the local)
|
// Create a number of test accounts and fund them (last one will be the local)
|
||||||
|
|
@ -1015,7 +1025,7 @@ func TestQueueTimeLimiting(t *testing.T) {
|
||||||
config.Lifetime = time.Second
|
config.Lifetime = time.Second
|
||||||
|
|
||||||
pool := New(config, blockchain)
|
pool := New(config, blockchain)
|
||||||
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Create a test account to ensure remotes expire
|
// Create a test account to ensure remotes expire
|
||||||
|
|
@ -1176,7 +1186,7 @@ func TestPendingGlobalLimiting(t *testing.T) {
|
||||||
config.GlobalSlots = config.AccountSlots * 10
|
config.GlobalSlots = config.AccountSlots * 10
|
||||||
|
|
||||||
pool := New(config, blockchain)
|
pool := New(config, blockchain)
|
||||||
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Create a number of test accounts and fund them
|
// Create a number of test accounts and fund them
|
||||||
|
|
@ -1275,7 +1285,7 @@ func TestCapClearsFromAll(t *testing.T) {
|
||||||
config.GlobalSlots = 8
|
config.GlobalSlots = 8
|
||||||
|
|
||||||
pool := New(config, blockchain)
|
pool := New(config, blockchain)
|
||||||
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Create a number of test accounts and fund them
|
// Create a number of test accounts and fund them
|
||||||
|
|
@ -1308,7 +1318,7 @@ func TestPendingMinimumAllowance(t *testing.T) {
|
||||||
config.GlobalSlots = 1
|
config.GlobalSlots = 1
|
||||||
|
|
||||||
pool := New(config, blockchain)
|
pool := New(config, blockchain)
|
||||||
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Create a number of test accounts and fund them
|
// Create a number of test accounts and fund them
|
||||||
|
|
@ -1352,7 +1362,7 @@ func TestRepricing(t *testing.T) {
|
||||||
blockchain := newTestBlockChain(params.TestChainConfig, 1000000, statedb, new(event.Feed))
|
blockchain := newTestBlockChain(params.TestChainConfig, 1000000, statedb, new(event.Feed))
|
||||||
|
|
||||||
pool := New(testTxPoolConfig, blockchain)
|
pool := New(testTxPoolConfig, blockchain)
|
||||||
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Keep track of transaction events to ensure all executables get announced
|
// Keep track of transaction events to ensure all executables get announced
|
||||||
|
|
@ -1457,7 +1467,7 @@ func TestMinGasPriceEnforced(t *testing.T) {
|
||||||
txPoolConfig := DefaultConfig
|
txPoolConfig := DefaultConfig
|
||||||
txPoolConfig.NoLocals = true
|
txPoolConfig.NoLocals = true
|
||||||
pool := New(txPoolConfig, blockchain)
|
pool := New(txPoolConfig, blockchain)
|
||||||
pool.Init(txPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(txPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
key, _ := crypto.GenerateKey()
|
key, _ := crypto.GenerateKey()
|
||||||
|
|
@ -1606,7 +1616,7 @@ func TestUnderpricing(t *testing.T) {
|
||||||
config.GlobalQueue = 2
|
config.GlobalQueue = 2
|
||||||
|
|
||||||
pool := New(config, blockchain)
|
pool := New(config, blockchain)
|
||||||
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Keep track of transaction events to ensure all executables get announced
|
// Keep track of transaction events to ensure all executables get announced
|
||||||
|
|
@ -1696,7 +1706,7 @@ func TestStableUnderpricing(t *testing.T) {
|
||||||
config.GlobalQueue = 0
|
config.GlobalQueue = 0
|
||||||
|
|
||||||
pool := New(config, blockchain)
|
pool := New(config, blockchain)
|
||||||
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(config.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Keep track of transaction events to ensure all executables get announced
|
// Keep track of transaction events to ensure all executables get announced
|
||||||
|
|
@ -1899,7 +1909,7 @@ func TestDeduplication(t *testing.T) {
|
||||||
blockchain := newTestBlockChain(params.TestChainConfig, 1000000, statedb, new(event.Feed))
|
blockchain := newTestBlockChain(params.TestChainConfig, 1000000, statedb, new(event.Feed))
|
||||||
|
|
||||||
pool := New(testTxPoolConfig, blockchain)
|
pool := New(testTxPoolConfig, blockchain)
|
||||||
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Create a test account to add transactions with
|
// Create a test account to add transactions with
|
||||||
|
|
@ -1966,7 +1976,7 @@ func TestReplacement(t *testing.T) {
|
||||||
blockchain := newTestBlockChain(params.TestChainConfig, 1000000, statedb, new(event.Feed))
|
blockchain := newTestBlockChain(params.TestChainConfig, 1000000, statedb, new(event.Feed))
|
||||||
|
|
||||||
pool := New(testTxPoolConfig, blockchain)
|
pool := New(testTxPoolConfig, blockchain)
|
||||||
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Keep track of transaction events to ensure all executables get announced
|
// Keep track of transaction events to ensure all executables get announced
|
||||||
|
|
@ -2157,7 +2167,7 @@ func TestStatusCheck(t *testing.T) {
|
||||||
blockchain := newTestBlockChain(params.TestChainConfig, 1000000, statedb, new(event.Feed))
|
blockchain := newTestBlockChain(params.TestChainConfig, 1000000, statedb, new(event.Feed))
|
||||||
|
|
||||||
pool := New(testTxPoolConfig, blockchain)
|
pool := New(testTxPoolConfig, blockchain)
|
||||||
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Create the test accounts to check various transaction statuses with
|
// Create the test accounts to check various transaction statuses with
|
||||||
|
|
@ -2230,7 +2240,7 @@ func TestSetCodeTransactions(t *testing.T) {
|
||||||
blockchain := newTestBlockChain(params.MergedTestChainConfig, 1000000, statedb, new(event.Feed))
|
blockchain := newTestBlockChain(params.MergedTestChainConfig, 1000000, statedb, new(event.Feed))
|
||||||
|
|
||||||
pool := New(testTxPoolConfig, blockchain)
|
pool := New(testTxPoolConfig, blockchain)
|
||||||
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Create the test accounts
|
// Create the test accounts
|
||||||
|
|
@ -2254,9 +2264,8 @@ func TestSetCodeTransactions(t *testing.T) {
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
// Check that only one in-flight transaction is allowed for accounts
|
// Check that only one in-flight transaction is allowed for accounts
|
||||||
// with delegation set. Also verify the accepted transaction can be
|
// with delegation set.
|
||||||
// replaced by fee.
|
name: "accept-one-inflight-tx-of-delegated-account",
|
||||||
name: "only-one-in-flight",
|
|
||||||
pending: 1,
|
pending: 1,
|
||||||
run: func(name string) {
|
run: func(name string) {
|
||||||
aa := common.Address{0xaa, 0xaa}
|
aa := common.Address{0xaa, 0xaa}
|
||||||
|
|
@ -2271,17 +2280,82 @@ func TestSetCodeTransactions(t *testing.T) {
|
||||||
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), keyA)); err != nil {
|
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), keyA)); err != nil {
|
||||||
t.Fatalf("%s: failed to add remote transaction: %v", name, err)
|
t.Fatalf("%s: failed to add remote transaction: %v", name, err)
|
||||||
}
|
}
|
||||||
if err := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(1), keyA)); !errors.Is(err, ErrInflightTxLimitReached) {
|
// Second and further transactions shall be rejected
|
||||||
t.Fatalf("%s: error mismatch: want %v, have %v", name, ErrInflightTxLimitReached, err)
|
if err := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(1), keyA)); !errors.Is(err, txpool.ErrInflightTxLimitReached) {
|
||||||
|
t.Fatalf("%s: error mismatch: want %v, have %v", name, txpool.ErrInflightTxLimitReached, err)
|
||||||
}
|
}
|
||||||
// Check gapped transaction again.
|
// Check gapped transaction again.
|
||||||
if err := pool.addRemoteSync(pricedTransaction(2, 100000, big.NewInt(1), keyA)); !errors.Is(err, ErrInflightTxLimitReached) {
|
if err := pool.addRemoteSync(pricedTransaction(2, 100000, big.NewInt(1), keyA)); !errors.Is(err, txpool.ErrInflightTxLimitReached) {
|
||||||
t.Fatalf("%s: error mismatch: want %v, have %v", name, ErrInflightTxLimitReached, err)
|
t.Fatalf("%s: error mismatch: want %v, have %v", name, txpool.ErrInflightTxLimitReached, err)
|
||||||
}
|
}
|
||||||
// Replace by fee.
|
// Replace by fee.
|
||||||
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(10), keyA)); err != nil {
|
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(10), keyA)); err != nil {
|
||||||
t.Fatalf("%s: failed to replace with remote transaction: %v", name, err)
|
t.Fatalf("%s: failed to replace with remote transaction: %v", name, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reset the delegation, avoid leaking state into the other tests
|
||||||
|
statedb.SetCode(addrA, nil)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// This test is analogous to the previous one, but the delegation is pending
|
||||||
|
// instead of set.
|
||||||
|
name: "allow-one-tx-from-pooled-delegation",
|
||||||
|
pending: 2,
|
||||||
|
run: func(name string) {
|
||||||
|
// Create a pending delegation request from B.
|
||||||
|
if err := pool.addRemoteSync(setCodeTx(0, keyA, []unsignedAuth{{0, keyB}})); err != nil {
|
||||||
|
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
||||||
|
}
|
||||||
|
// First transaction from B is accepted.
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), keyB)); err != nil {
|
||||||
|
t.Fatalf("%s: failed to add remote transaction: %v", name, err)
|
||||||
|
}
|
||||||
|
// Second transaction fails due to limit.
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(1), keyB)); !errors.Is(err, txpool.ErrInflightTxLimitReached) {
|
||||||
|
t.Fatalf("%s: error mismatch: want %v, have %v", name, txpool.ErrInflightTxLimitReached, err)
|
||||||
|
}
|
||||||
|
// Replace by fee for first transaction from B works.
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(2), keyB)); err != nil {
|
||||||
|
t.Fatalf("%s: failed to add remote transaction: %v", name, err)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// This is the symmetric case of the previous one, where the delegation request
|
||||||
|
// is received after the transaction. The resulting state shall be the same.
|
||||||
|
name: "accept-authorization-from-sender-of-one-inflight-tx",
|
||||||
|
pending: 2,
|
||||||
|
run: func(name string) {
|
||||||
|
// The first in-flight transaction is accepted.
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), keyB)); err != nil {
|
||||||
|
t.Fatalf("%s: failed to add with pending delegation: %v", name, err)
|
||||||
|
}
|
||||||
|
// Delegation is accepted.
|
||||||
|
if err := pool.addRemoteSync(setCodeTx(0, keyA, []unsignedAuth{{0, keyB}})); err != nil {
|
||||||
|
t.Fatalf("%s: failed to add remote transaction: %v", name, err)
|
||||||
|
}
|
||||||
|
// The second in-flight transaction is rejected.
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(1), keyB)); !errors.Is(err, txpool.ErrInflightTxLimitReached) {
|
||||||
|
t.Fatalf("%s: error mismatch: want %v, have %v", name, txpool.ErrInflightTxLimitReached, err)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "reject-authorization-from-sender-with-more-than-one-inflight-tx",
|
||||||
|
pending: 2,
|
||||||
|
run: func(name string) {
|
||||||
|
// Submit two transactions.
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), keyB)); err != nil {
|
||||||
|
t.Fatalf("%s: failed to add with pending delegation: %v", name, err)
|
||||||
|
}
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(1), keyB)); err != nil {
|
||||||
|
t.Fatalf("%s: failed to add with pending delegation: %v", name, err)
|
||||||
|
}
|
||||||
|
// Delegation rejected since two txs are already in-flight.
|
||||||
|
if err := pool.addRemoteSync(setCodeTx(0, keyA, []unsignedAuth{{0, keyB}})); !errors.Is(err, ErrAuthorityReserved) {
|
||||||
|
t.Fatalf("%s: error mismatch: want %v, have %v", name, ErrAuthorityReserved, err)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
@ -2289,7 +2363,7 @@ func TestSetCodeTransactions(t *testing.T) {
|
||||||
pending: 2,
|
pending: 2,
|
||||||
run: func(name string) {
|
run: func(name string) {
|
||||||
// Send two transactions where the first has no conflicting delegations and
|
// Send two transactions where the first has no conflicting delegations and
|
||||||
// the second should be allowed despite conflicting with the authorities in 1).
|
// the second should be allowed despite conflicting with the authorities in the first.
|
||||||
if err := pool.addRemoteSync(setCodeTx(0, keyA, []unsignedAuth{{1, keyC}})); err != nil {
|
if err := pool.addRemoteSync(setCodeTx(0, keyA, []unsignedAuth{{1, keyC}})); err != nil {
|
||||||
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
||||||
}
|
}
|
||||||
|
|
@ -2298,28 +2372,10 @@ func TestSetCodeTransactions(t *testing.T) {
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
|
||||||
name: "allow-one-tx-from-pooled-delegation",
|
|
||||||
pending: 2,
|
|
||||||
run: func(name string) {
|
|
||||||
// Verify C cannot originate another transaction when it has a pooled delegation.
|
|
||||||
if err := pool.addRemoteSync(setCodeTx(0, keyA, []unsignedAuth{{0, keyC}})); err != nil {
|
|
||||||
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
|
||||||
}
|
|
||||||
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), keyC)); err != nil {
|
|
||||||
t.Fatalf("%s: failed to add with pending delegatio: %v", name, err)
|
|
||||||
}
|
|
||||||
// Also check gapped transaction is rejected.
|
|
||||||
if err := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(1), keyC)); !errors.Is(err, ErrInflightTxLimitReached) {
|
|
||||||
t.Fatalf("%s: error mismatch: want %v, have %v", name, ErrInflightTxLimitReached, err)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
name: "replace-by-fee-setcode-tx",
|
name: "replace-by-fee-setcode-tx",
|
||||||
pending: 1,
|
pending: 1,
|
||||||
run: func(name string) {
|
run: func(name string) {
|
||||||
// 4. Fee bump the setcode tx send.
|
|
||||||
if err := pool.addRemoteSync(setCodeTx(0, keyB, []unsignedAuth{{1, keyC}})); err != nil {
|
if err := pool.addRemoteSync(setCodeTx(0, keyB, []unsignedAuth{{1, keyC}})); err != nil {
|
||||||
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
||||||
}
|
}
|
||||||
|
|
@ -2329,44 +2385,85 @@ func TestSetCodeTransactions(t *testing.T) {
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "allow-tx-from-replaced-authority",
|
name: "allow-more-than-one-tx-from-replaced-authority",
|
||||||
pending: 2,
|
pending: 3,
|
||||||
run: func(name string) {
|
run: func(name string) {
|
||||||
// Fee bump with a different auth list. Make sure that unlocks the authorities.
|
// Send transaction from A with B as an authority.
|
||||||
if err := pool.addRemoteSync(pricedSetCodeTx(0, 250000, uint256.NewInt(10), uint256.NewInt(3), keyA, []unsignedAuth{{0, keyB}})); err != nil {
|
if err := pool.addRemoteSync(pricedSetCodeTx(0, 250000, uint256.NewInt(10), uint256.NewInt(3), keyA, []unsignedAuth{{0, keyB}})); err != nil {
|
||||||
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
||||||
}
|
}
|
||||||
|
// Replace transaction with another having C as an authority.
|
||||||
if err := pool.addRemoteSync(pricedSetCodeTx(0, 250000, uint256.NewInt(3000), uint256.NewInt(300), keyA, []unsignedAuth{{0, keyC}})); err != nil {
|
if err := pool.addRemoteSync(pricedSetCodeTx(0, 250000, uint256.NewInt(3000), uint256.NewInt(300), keyA, []unsignedAuth{{0, keyC}})); err != nil {
|
||||||
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
||||||
}
|
}
|
||||||
// Now send a regular tx from B.
|
// B should not be considred as having an in-flight delegation, so
|
||||||
|
// should allow more than one pooled transaction.
|
||||||
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(10), keyB)); err != nil {
|
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(10), keyB)); err != nil {
|
||||||
t.Fatalf("%s: failed to replace with remote transaction: %v", name, err)
|
t.Fatalf("%s: failed to replace with remote transaction: %v", name, err)
|
||||||
}
|
}
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(10), keyB)); err != nil {
|
||||||
|
t.Fatalf("%s: failed to replace with remote transaction: %v", name, err)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
// This test is analogous to the previous one, but the the replaced
|
||||||
|
// transaction is self-sponsored.
|
||||||
name: "allow-tx-from-replaced-self-sponsor-authority",
|
name: "allow-tx-from-replaced-self-sponsor-authority",
|
||||||
pending: 2,
|
pending: 3,
|
||||||
run: func(name string) {
|
run: func(name string) {
|
||||||
//
|
// Send transaction from A with A as an authority.
|
||||||
if err := pool.addRemoteSync(pricedSetCodeTx(0, 250000, uint256.NewInt(10), uint256.NewInt(3), keyA, []unsignedAuth{{0, keyA}})); err != nil {
|
if err := pool.addRemoteSync(pricedSetCodeTx(0, 250000, uint256.NewInt(10), uint256.NewInt(3), keyA, []unsignedAuth{{0, keyA}})); err != nil {
|
||||||
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
||||||
}
|
}
|
||||||
|
// Replace transaction with a transaction with B as an authority.
|
||||||
if err := pool.addRemoteSync(pricedSetCodeTx(0, 250000, uint256.NewInt(30), uint256.NewInt(30), keyA, []unsignedAuth{{0, keyB}})); err != nil {
|
if err := pool.addRemoteSync(pricedSetCodeTx(0, 250000, uint256.NewInt(30), uint256.NewInt(30), keyA, []unsignedAuth{{0, keyB}})); err != nil {
|
||||||
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
||||||
}
|
}
|
||||||
// Now send a regular tx from keyA.
|
// The one in-flight transaction limit from A no longer applies, so we
|
||||||
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1000), keyA)); err != nil {
|
// can stack a second transaction for the account.
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(1000), keyA)); err != nil {
|
||||||
t.Fatalf("%s: failed to replace with remote transaction: %v", name, err)
|
t.Fatalf("%s: failed to replace with remote transaction: %v", name, err)
|
||||||
}
|
}
|
||||||
// Make sure we can still send from keyB.
|
// B should still be able to send transactions.
|
||||||
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1000), keyB)); err != nil {
|
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1000), keyB)); err != nil {
|
||||||
t.Fatalf("%s: failed to replace with remote transaction: %v", name, err)
|
t.Fatalf("%s: failed to replace with remote transaction: %v", name, err)
|
||||||
}
|
}
|
||||||
|
// However B still has the limitation to one in-flight transaction.
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(1), keyB)); !errors.Is(err, txpool.ErrInflightTxLimitReached) {
|
||||||
|
t.Fatalf("%s: error mismatch: want %v, have %v", name, txpool.ErrInflightTxLimitReached, err)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
name: "replacements-respect-inflight-tx-count",
|
||||||
|
pending: 2,
|
||||||
|
run: func(name string) {
|
||||||
|
// Send transaction from A with B as an authority.
|
||||||
|
if err := pool.addRemoteSync(pricedSetCodeTx(0, 250000, uint256.NewInt(10), uint256.NewInt(3), keyA, []unsignedAuth{{0, keyB}})); err != nil {
|
||||||
|
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
||||||
|
}
|
||||||
|
// Send two transactions from B. Only the first should be accepted due
|
||||||
|
// to in-flight limit.
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), keyB)); err != nil {
|
||||||
|
t.Fatalf("%s: failed to add remote transaction: %v", name, err)
|
||||||
|
}
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(1), keyB)); !errors.Is(err, txpool.ErrInflightTxLimitReached) {
|
||||||
|
t.Fatalf("%s: error mismatch: want %v, have %v", name, txpool.ErrInflightTxLimitReached, err)
|
||||||
|
}
|
||||||
|
// Replace the in-flight transaction from B.
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(30), keyB)); err != nil {
|
||||||
|
t.Fatalf("%s: failed to replace with remote transaction: %v", name, err)
|
||||||
|
}
|
||||||
|
// Ensure the in-flight limit for B is still in place.
|
||||||
|
if err := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(1), keyB)); !errors.Is(err, txpool.ErrInflightTxLimitReached) {
|
||||||
|
t.Fatalf("%s: error mismatch: want %v, have %v", name, txpool.ErrInflightTxLimitReached, err)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Since multiple authorizations can be pending simultaneously, replacing
|
||||||
|
// one of them should not break the one in-flight-transaction limit.
|
||||||
name: "track-multiple-conflicting-delegations",
|
name: "track-multiple-conflicting-delegations",
|
||||||
pending: 3,
|
pending: 3,
|
||||||
run: func(name string) {
|
run: func(name string) {
|
||||||
|
|
@ -2386,20 +2483,7 @@ func TestSetCodeTransactions(t *testing.T) {
|
||||||
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1000), keyC)); err != nil {
|
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1000), keyC)); err != nil {
|
||||||
t.Fatalf("%s: failed to added single pooled for account with pending delegation: %v", name, err)
|
t.Fatalf("%s: failed to added single pooled for account with pending delegation: %v", name, err)
|
||||||
}
|
}
|
||||||
if err, want := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(1000), keyC)), ErrInflightTxLimitReached; !errors.Is(err, want) {
|
if err, want := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(1000), keyC)), txpool.ErrInflightTxLimitReached; !errors.Is(err, want) {
|
||||||
t.Fatalf("%s: error mismatch: want %v, have %v", name, want, err)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "reject-delegation-from-pending-account",
|
|
||||||
pending: 1,
|
|
||||||
run: func(name string) {
|
|
||||||
// Attempt to submit a delegation from an account with a pending tx.
|
|
||||||
if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1000), keyC)); err != nil {
|
|
||||||
t.Fatalf("%s: failed to add with remote setcode transaction: %v", name, err)
|
|
||||||
}
|
|
||||||
if err, want := pool.addRemoteSync(setCodeTx(0, keyA, []unsignedAuth{{1, keyC}})), ErrAuthorityReserved; !errors.Is(err, want) {
|
|
||||||
t.Fatalf("%s: error mismatch: want %v, have %v", name, want, err)
|
t.Fatalf("%s: error mismatch: want %v, have %v", name, want, err)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
@ -2454,7 +2538,7 @@ func TestSetCodeTransactionsReorg(t *testing.T) {
|
||||||
blockchain := newTestBlockChain(params.MergedTestChainConfig, 1000000, statedb, new(event.Feed))
|
blockchain := newTestBlockChain(params.MergedTestChainConfig, 1000000, statedb, new(event.Feed))
|
||||||
|
|
||||||
pool := New(testTxPoolConfig, blockchain)
|
pool := New(testTxPoolConfig, blockchain)
|
||||||
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), makeAddressReserver())
|
pool.Init(testTxPoolConfig.PriceLimit, blockchain.CurrentBlock(), newReserver())
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
// Create the test accounts
|
// Create the test accounts
|
||||||
|
|
@ -2489,8 +2573,8 @@ func TestSetCodeTransactionsReorg(t *testing.T) {
|
||||||
t.Fatalf("failed to add with remote setcode transaction: %v", err)
|
t.Fatalf("failed to add with remote setcode transaction: %v", err)
|
||||||
}
|
}
|
||||||
// Try to add a transactions in
|
// Try to add a transactions in
|
||||||
if err := pool.addRemoteSync(pricedTransaction(2, 100000, big.NewInt(1000), keyA)); !errors.Is(err, ErrInflightTxLimitReached) {
|
if err := pool.addRemoteSync(pricedTransaction(2, 100000, big.NewInt(1000), keyA)); !errors.Is(err, txpool.ErrInflightTxLimitReached) {
|
||||||
t.Fatalf("unexpected error %v, expecting %v", err, ErrInflightTxLimitReached)
|
t.Fatalf("unexpected error %v, expecting %v", err, txpool.ErrInflightTxLimitReached)
|
||||||
}
|
}
|
||||||
// Simulate the chain moving
|
// Simulate the chain moving
|
||||||
blockchain.statedb.SetNonce(addrA, 2, tracing.NonceChangeAuthorization)
|
blockchain.statedb.SetNonce(addrA, 2, tracing.NonceChangeAuthorization)
|
||||||
|
|
|
||||||
138
core/txpool/reserver.go
Normal file
138
core/txpool/reserver.go
Normal file
|
|
@ -0,0 +1,138 @@
|
||||||
|
// Copyright 2025 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 txpool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/ethereum/go-ethereum/common"
|
||||||
|
"github.com/ethereum/go-ethereum/log"
|
||||||
|
"github.com/ethereum/go-ethereum/metrics"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// reservationsGaugeName is the prefix of a per-subpool address reservation
|
||||||
|
// metric.
|
||||||
|
//
|
||||||
|
// This is mostly a sanity metric to ensure there's no bug that would make
|
||||||
|
// some subpool hog all the reservations due to mis-accounting.
|
||||||
|
reservationsGaugeName = "txpool/reservations"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReservationTracker is a struct shared between different subpools. It is used to reserve
|
||||||
|
// the account and ensure that one address cannot initiate transactions, authorizations,
|
||||||
|
// and other state-changing behaviors in different pools at the same time.
|
||||||
|
type ReservationTracker struct {
|
||||||
|
accounts map[common.Address]int
|
||||||
|
lock sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewReservationTracker initializes the account reservation tracker.
|
||||||
|
func NewReservationTracker() *ReservationTracker {
|
||||||
|
return &ReservationTracker{
|
||||||
|
accounts: make(map[common.Address]int),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHandle creates a named handle on the ReservationTracker. The handle
|
||||||
|
// identifies the subpool so ownership of reservations can be determined.
|
||||||
|
func (r *ReservationTracker) NewHandle(id int) *ReservationHandle {
|
||||||
|
return &ReservationHandle{r, id}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reserver is an interface for creating and releasing owned reservations in the
|
||||||
|
// ReservationTracker struct, which is shared between subpools.
|
||||||
|
type Reserver interface {
|
||||||
|
// Hold attempts to reserve the specified account address for the given pool.
|
||||||
|
// Returns an error if the account is already reserved.
|
||||||
|
Hold(addr common.Address) error
|
||||||
|
|
||||||
|
// Release attempts to release the reservation for the specified account.
|
||||||
|
// Returns an error if the address is not reserved or is reserved by another pool.
|
||||||
|
Release(addr common.Address) error
|
||||||
|
|
||||||
|
// Has returns a flag indicating if the address has been reserved by a pool
|
||||||
|
// other than one with the current Reserver handle.
|
||||||
|
Has(address common.Address) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReservationHandle is a named handle on ReservationTracker. It is held by subpools to
|
||||||
|
// make reservations for accounts it is tracking. The id is used to determine
|
||||||
|
// which pool owns an address and disallows non-owners to hold or release
|
||||||
|
// addresses it doesn't own.
|
||||||
|
type ReservationHandle struct {
|
||||||
|
tracker *ReservationTracker
|
||||||
|
id int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hold implements the Reserver interface.
|
||||||
|
func (h *ReservationHandle) Hold(addr common.Address) error {
|
||||||
|
h.tracker.lock.Lock()
|
||||||
|
defer h.tracker.lock.Unlock()
|
||||||
|
|
||||||
|
// Double reservations are forbidden even from the same pool to
|
||||||
|
// avoid subtle bugs in the long term.
|
||||||
|
owner, exists := h.tracker.accounts[addr]
|
||||||
|
if exists {
|
||||||
|
if owner == h.id {
|
||||||
|
log.Error("pool attempted to reserve already-owned address", "address", addr)
|
||||||
|
return nil // Ignore fault to give the pool a chance to recover while the bug gets fixed
|
||||||
|
}
|
||||||
|
return ErrAlreadyReserved
|
||||||
|
}
|
||||||
|
h.tracker.accounts[addr] = h.id
|
||||||
|
if metrics.Enabled() {
|
||||||
|
m := fmt.Sprintf("%s/%d", reservationsGaugeName, h.id)
|
||||||
|
metrics.GetOrRegisterGauge(m, nil).Inc(1)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Release implements the Reserver interface.
|
||||||
|
func (h *ReservationHandle) Release(addr common.Address) error {
|
||||||
|
h.tracker.lock.Lock()
|
||||||
|
defer h.tracker.lock.Unlock()
|
||||||
|
|
||||||
|
// Ensure subpools only attempt to unreserve their own owned addresses,
|
||||||
|
// otherwise flag as a programming error.
|
||||||
|
owner, exists := h.tracker.accounts[addr]
|
||||||
|
if !exists {
|
||||||
|
log.Error("pool attempted to unreserve non-reserved address", "address", addr)
|
||||||
|
return errors.New("address not reserved")
|
||||||
|
}
|
||||||
|
if owner != h.id {
|
||||||
|
log.Error("pool attempted to unreserve non-owned address", "address", addr)
|
||||||
|
return errors.New("address not owned")
|
||||||
|
}
|
||||||
|
delete(h.tracker.accounts, addr)
|
||||||
|
if metrics.Enabled() {
|
||||||
|
m := fmt.Sprintf("%s/%d", reservationsGaugeName, h.id)
|
||||||
|
metrics.GetOrRegisterGauge(m, nil).Dec(1)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Has implements the Reserver interface.
|
||||||
|
func (h *ReservationHandle) Has(address common.Address) bool {
|
||||||
|
h.tracker.lock.RLock()
|
||||||
|
defer h.tracker.lock.RUnlock()
|
||||||
|
|
||||||
|
id, exists := h.tracker.accounts[address]
|
||||||
|
return exists && id != h.id
|
||||||
|
}
|
||||||
|
|
@ -67,10 +67,6 @@ type LazyResolver interface {
|
||||||
Get(hash common.Hash) *types.Transaction
|
Get(hash common.Hash) *types.Transaction
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddressReserver is passed by the main transaction pool to subpools, so they
|
|
||||||
// may request (and relinquish) exclusive access to certain addresses.
|
|
||||||
type AddressReserver func(addr common.Address, reserve bool) error
|
|
||||||
|
|
||||||
// PendingFilter is a collection of filter rules to allow retrieving a subset
|
// PendingFilter is a collection of filter rules to allow retrieving a subset
|
||||||
// of transactions for announcement or mining.
|
// of transactions for announcement or mining.
|
||||||
//
|
//
|
||||||
|
|
@ -86,6 +82,12 @@ type PendingFilter struct {
|
||||||
OnlyBlobTxs bool // Return only blob transactions (block blob-space filling)
|
OnlyBlobTxs bool // Return only blob transactions (block blob-space filling)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TxMetadata denotes the metadata of a transaction.
|
||||||
|
type TxMetadata struct {
|
||||||
|
Type uint8 // The type of the transaction
|
||||||
|
Size uint64 // The length of the 'rlp encoding' of a transaction
|
||||||
|
}
|
||||||
|
|
||||||
// SubPool represents a specialized transaction pool that lives on its own (e.g.
|
// SubPool represents a specialized transaction pool that lives on its own (e.g.
|
||||||
// blob pool). Since independent of how many specialized pools we have, they do
|
// blob pool). Since independent of how many specialized pools we have, they do
|
||||||
// need to be updated in lockstep and assemble into one coherent view for block
|
// need to be updated in lockstep and assemble into one coherent view for block
|
||||||
|
|
@ -103,7 +105,7 @@ type SubPool interface {
|
||||||
// These should not be passed as a constructor argument - nor should the pools
|
// These should not be passed as a constructor argument - nor should the pools
|
||||||
// start by themselves - in order to keep multiple subpools in lockstep with
|
// start by themselves - in order to keep multiple subpools in lockstep with
|
||||||
// one another.
|
// one another.
|
||||||
Init(gasTip uint64, head *types.Header, reserve AddressReserver) error
|
Init(gasTip uint64, head *types.Header, reserver Reserver) error
|
||||||
|
|
||||||
// Close terminates any background processing threads and releases any held
|
// Close terminates any background processing threads and releases any held
|
||||||
// resources.
|
// resources.
|
||||||
|
|
@ -127,6 +129,10 @@ type SubPool interface {
|
||||||
// GetRLP returns a RLP-encoded transaction if it is contained in the pool.
|
// GetRLP returns a RLP-encoded transaction if it is contained in the pool.
|
||||||
GetRLP(hash common.Hash) []byte
|
GetRLP(hash common.Hash) []byte
|
||||||
|
|
||||||
|
// GetMetadata returns the transaction type and transaction size with the
|
||||||
|
// given transaction hash.
|
||||||
|
GetMetadata(hash common.Hash) *TxMetadata
|
||||||
|
|
||||||
// GetBlobs returns a number of blobs are proofs for the given versioned hashes.
|
// GetBlobs returns a number of blobs are proofs for the given versioned hashes.
|
||||||
// This is a utility method for the engine API, enabling consensus clients to
|
// This is a utility method for the engine API, enabling consensus clients to
|
||||||
// retrieve blobs from the pools directly instead of the network.
|
// retrieve blobs from the pools directly instead of the network.
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,6 @@ import (
|
||||||
"github.com/ethereum/go-ethereum/crypto/kzg4844"
|
"github.com/ethereum/go-ethereum/crypto/kzg4844"
|
||||||
"github.com/ethereum/go-ethereum/event"
|
"github.com/ethereum/go-ethereum/event"
|
||||||
"github.com/ethereum/go-ethereum/log"
|
"github.com/ethereum/go-ethereum/log"
|
||||||
"github.com/ethereum/go-ethereum/metrics"
|
|
||||||
"github.com/ethereum/go-ethereum/params"
|
"github.com/ethereum/go-ethereum/params"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -43,15 +42,6 @@ const (
|
||||||
TxStatusIncluded
|
TxStatusIncluded
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
|
||||||
// reservationsGaugeName is the prefix of a per-subpool address reservation
|
|
||||||
// metric.
|
|
||||||
//
|
|
||||||
// This is mostly a sanity metric to ensure there's no bug that would make
|
|
||||||
// some subpool hog all the reservations due to mis-accounting.
|
|
||||||
reservationsGaugeName = "txpool/reservations"
|
|
||||||
)
|
|
||||||
|
|
||||||
// BlockChain defines the minimal set of methods needed to back a tx pool with
|
// BlockChain defines the minimal set of methods needed to back a tx pool with
|
||||||
// a chain. Exists to allow mocking the live chain out of tests.
|
// a chain. Exists to allow mocking the live chain out of tests.
|
||||||
type BlockChain interface {
|
type BlockChain interface {
|
||||||
|
|
@ -81,9 +71,6 @@ type TxPool struct {
|
||||||
stateLock sync.RWMutex // The lock for protecting state instance
|
stateLock sync.RWMutex // The lock for protecting state instance
|
||||||
state *state.StateDB // Current state at the blockchain head
|
state *state.StateDB // Current state at the blockchain head
|
||||||
|
|
||||||
reservations map[common.Address]SubPool // Map with the account to pool reservations
|
|
||||||
reserveLock sync.Mutex // Lock protecting the account reservations
|
|
||||||
|
|
||||||
subs event.SubscriptionScope // Subscription scope to unsubscribe all on shutdown
|
subs event.SubscriptionScope // Subscription scope to unsubscribe all on shutdown
|
||||||
quit chan chan error // Quit channel to tear down the head updater
|
quit chan chan error // Quit channel to tear down the head updater
|
||||||
term chan struct{} // Termination channel to detect a closed pool
|
term chan struct{} // Termination channel to detect a closed pool
|
||||||
|
|
@ -114,13 +101,13 @@ func New(gasTip uint64, chain BlockChain, subpools []SubPool) (*TxPool, error) {
|
||||||
chain: chain,
|
chain: chain,
|
||||||
signer: types.LatestSigner(chain.Config()),
|
signer: types.LatestSigner(chain.Config()),
|
||||||
state: statedb,
|
state: statedb,
|
||||||
reservations: make(map[common.Address]SubPool),
|
|
||||||
quit: make(chan chan error),
|
quit: make(chan chan error),
|
||||||
term: make(chan struct{}),
|
term: make(chan struct{}),
|
||||||
sync: make(chan chan error),
|
sync: make(chan chan error),
|
||||||
}
|
}
|
||||||
|
reserver := NewReservationTracker()
|
||||||
for i, subpool := range subpools {
|
for i, subpool := range subpools {
|
||||||
if err := subpool.Init(gasTip, head, pool.reserver(i, subpool)); err != nil {
|
if err := subpool.Init(gasTip, head, reserver.NewHandle(i)); err != nil {
|
||||||
for j := i - 1; j >= 0; j-- {
|
for j := i - 1; j >= 0; j-- {
|
||||||
subpools[j].Close()
|
subpools[j].Close()
|
||||||
}
|
}
|
||||||
|
|
@ -131,52 +118,6 @@ func New(gasTip uint64, chain BlockChain, subpools []SubPool) (*TxPool, error) {
|
||||||
return pool, nil
|
return pool, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// reserver is a method to create an address reservation callback to exclusively
|
|
||||||
// assign/deassign addresses to/from subpools. This can ensure that at any point
|
|
||||||
// in time, only a single subpool is able to manage an account, avoiding cross
|
|
||||||
// subpool eviction issues and nonce conflicts.
|
|
||||||
func (p *TxPool) reserver(id int, subpool SubPool) AddressReserver {
|
|
||||||
return func(addr common.Address, reserve bool) error {
|
|
||||||
p.reserveLock.Lock()
|
|
||||||
defer p.reserveLock.Unlock()
|
|
||||||
|
|
||||||
owner, exists := p.reservations[addr]
|
|
||||||
if reserve {
|
|
||||||
// Double reservations are forbidden even from the same pool to
|
|
||||||
// avoid subtle bugs in the long term.
|
|
||||||
if exists {
|
|
||||||
if owner == subpool {
|
|
||||||
log.Error("pool attempted to reserve already-owned address", "address", addr)
|
|
||||||
return nil // Ignore fault to give the pool a chance to recover while the bug gets fixed
|
|
||||||
}
|
|
||||||
return ErrAlreadyReserved
|
|
||||||
}
|
|
||||||
p.reservations[addr] = subpool
|
|
||||||
if metrics.Enabled() {
|
|
||||||
m := fmt.Sprintf("%s/%d", reservationsGaugeName, id)
|
|
||||||
metrics.GetOrRegisterGauge(m, nil).Inc(1)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
// Ensure subpools only attempt to unreserve their own owned addresses,
|
|
||||||
// otherwise flag as a programming error.
|
|
||||||
if !exists {
|
|
||||||
log.Error("pool attempted to unreserve non-reserved address", "address", addr)
|
|
||||||
return errors.New("address not reserved")
|
|
||||||
}
|
|
||||||
if subpool != owner {
|
|
||||||
log.Error("pool attempted to unreserve non-owned address", "address", addr)
|
|
||||||
return errors.New("address not owned")
|
|
||||||
}
|
|
||||||
delete(p.reservations, addr)
|
|
||||||
if metrics.Enabled() {
|
|
||||||
m := fmt.Sprintf("%s/%d", reservationsGaugeName, id)
|
|
||||||
metrics.GetOrRegisterGauge(m, nil).Dec(1)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close terminates the transaction pool and all its subpools.
|
// Close terminates the transaction pool and all its subpools.
|
||||||
func (p *TxPool) Close() error {
|
func (p *TxPool) Close() error {
|
||||||
var errs []error
|
var errs []error
|
||||||
|
|
@ -354,6 +295,17 @@ func (p *TxPool) GetRLP(hash common.Hash) []byte {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetMetadata returns the transaction type and transaction size with the given
|
||||||
|
// hash.
|
||||||
|
func (p *TxPool) GetMetadata(hash common.Hash) *TxMetadata {
|
||||||
|
for _, subpool := range p.subpools {
|
||||||
|
if meta := subpool.GetMetadata(hash); meta != nil {
|
||||||
|
return meta
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// GetBlobs returns a number of blobs are proofs for the given versioned hashes.
|
// GetBlobs returns a number of blobs are proofs for the given versioned hashes.
|
||||||
// This is a utility method for the engine API, enabling consensus clients to
|
// This is a utility method for the engine API, enabling consensus clients to
|
||||||
// retrieve blobs from the pools directly instead of the network.
|
// retrieve blobs from the pools directly instead of the network.
|
||||||
|
|
@ -398,6 +350,9 @@ func (p *TxPool) ValidateTxBasics(tx *types.Transaction) error {
|
||||||
// Add enqueues a batch of transactions into the pool if they are valid. Due
|
// Add enqueues a batch of transactions into the pool if they are valid. Due
|
||||||
// to the large transaction churn, add may postpone fully integrating the tx
|
// to the large transaction churn, add may postpone fully integrating the tx
|
||||||
// to a later point to batch multiple ones together.
|
// to a later point to batch multiple ones together.
|
||||||
|
//
|
||||||
|
// Note, if sync is set the method will block until all internal maintenance
|
||||||
|
// related to the add is finished. Only use this during tests for determinism.
|
||||||
func (p *TxPool) Add(txs []*types.Transaction, sync bool) []error {
|
func (p *TxPool) Add(txs []*types.Transaction, sync bool) []error {
|
||||||
// Split the input transactions between the subpools. It shouldn't really
|
// Split the input transactions between the subpools. It shouldn't really
|
||||||
// happen that we receive merged batches, but better graceful than strange
|
// happen that we receive merged batches, but better graceful than strange
|
||||||
|
|
@ -551,8 +506,8 @@ func (p *TxPool) Status(hash common.Hash) TxStatus {
|
||||||
// internal background reset operations. This method will run an explicit reset
|
// internal background reset operations. This method will run an explicit reset
|
||||||
// operation to ensure the pool stabilises, thus avoiding flakey behavior.
|
// operation to ensure the pool stabilises, thus avoiding flakey behavior.
|
||||||
//
|
//
|
||||||
// Note, do not use this in production / live code. In live code, the pool is
|
// Note, this method is only used for testing and is susceptible to DoS vectors.
|
||||||
// meant to reset on a separate thread to avoid DoS vectors.
|
// In production code, the pool is meant to reset on a separate thread.
|
||||||
func (p *TxPool) Sync() error {
|
func (p *TxPool) Sync() error {
|
||||||
sync := make(chan error)
|
sync := make(chan error)
|
||||||
select {
|
select {
|
||||||
|
|
@ -564,6 +519,10 @@ func (p *TxPool) Sync() error {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear removes all tracked txs from the subpools.
|
// Clear removes all tracked txs from the subpools.
|
||||||
|
//
|
||||||
|
// Note, this method invokes Sync() and is only used for testing, because it is
|
||||||
|
// susceptible to DoS vectors. In production code, the pool is meant to reset on
|
||||||
|
// a separate thread.
|
||||||
func (p *TxPool) Clear() {
|
func (p *TxPool) Clear() {
|
||||||
// Invoke Sync to ensure that txs pending addition don't get added to the pool after
|
// Invoke Sync to ensure that txs pending addition don't get added to the pool after
|
||||||
// the subpools are subsequently cleared
|
// the subpools are subsequently cleared
|
||||||
|
|
|
||||||
|
|
@ -971,6 +971,23 @@ func opPush1(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]by
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// opPush2 is a specialized version of pushN
|
||||||
|
func opPush2(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byte, error) {
|
||||||
|
var (
|
||||||
|
codeLen = uint64(len(scope.Contract.Code))
|
||||||
|
integer = new(uint256.Int)
|
||||||
|
)
|
||||||
|
if *pc+2 < codeLen {
|
||||||
|
scope.Stack.push(integer.SetBytes2(scope.Contract.Code[*pc+1 : *pc+3]))
|
||||||
|
} else if *pc+1 < codeLen {
|
||||||
|
scope.Stack.push(integer.SetUint64(uint64(scope.Contract.Code[*pc+1]) << 8))
|
||||||
|
} else {
|
||||||
|
scope.Stack.push(integer.Clear())
|
||||||
|
}
|
||||||
|
*pc += 2
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
// make push instruction function
|
// make push instruction function
|
||||||
func makePush(size uint64, pushByteSize int) executionFunc {
|
func makePush(size uint64, pushByteSize int) executionFunc {
|
||||||
return func(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byte, error) {
|
return func(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byte, error) {
|
||||||
|
|
|
||||||
|
|
@ -631,7 +631,7 @@ func newFrontierInstructionSet() JumpTable {
|
||||||
maxStack: maxStack(0, 1),
|
maxStack: maxStack(0, 1),
|
||||||
},
|
},
|
||||||
PUSH2: {
|
PUSH2: {
|
||||||
execute: makePush(2, 2),
|
execute: opPush2,
|
||||||
constantGas: GasFastestStep,
|
constantGas: GasFastestStep,
|
||||||
minStack: minStack(0, 1),
|
minStack: minStack(0, 1),
|
||||||
maxStack: maxStack(0, 1),
|
maxStack: maxStack(0, 1),
|
||||||
|
|
|
||||||
|
|
@ -34,6 +34,7 @@ import (
|
||||||
"github.com/ethereum/go-ethereum/core/txpool"
|
"github.com/ethereum/go-ethereum/core/txpool"
|
||||||
"github.com/ethereum/go-ethereum/core/types"
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
"github.com/ethereum/go-ethereum/core/vm"
|
"github.com/ethereum/go-ethereum/core/vm"
|
||||||
|
"github.com/ethereum/go-ethereum/eth/ethconfig"
|
||||||
"github.com/ethereum/go-ethereum/eth/gasprice"
|
"github.com/ethereum/go-ethereum/eth/gasprice"
|
||||||
"github.com/ethereum/go-ethereum/eth/tracers"
|
"github.com/ethereum/go-ethereum/eth/tracers"
|
||||||
"github.com/ethereum/go-ethereum/ethdb"
|
"github.com/ethereum/go-ethereum/ethdb"
|
||||||
|
|
@ -91,7 +92,13 @@ func (b *EthAPIBackend) HeaderByNumber(ctx context.Context, number rpc.BlockNumb
|
||||||
}
|
}
|
||||||
return block, nil
|
return block, nil
|
||||||
}
|
}
|
||||||
return b.eth.blockchain.GetHeaderByNumber(uint64(number)), nil
|
var bn uint64
|
||||||
|
if number == rpc.EarliestBlockNumber {
|
||||||
|
bn = b.HistoryPruningCutoff()
|
||||||
|
} else {
|
||||||
|
bn = uint64(number)
|
||||||
|
}
|
||||||
|
return b.eth.blockchain.GetHeaderByNumber(bn), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *EthAPIBackend) HeaderByNumberOrHash(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (*types.Header, error) {
|
func (b *EthAPIBackend) HeaderByNumberOrHash(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (*types.Header, error) {
|
||||||
|
|
@ -143,11 +150,27 @@ func (b *EthAPIBackend) BlockByNumber(ctx context.Context, number rpc.BlockNumbe
|
||||||
}
|
}
|
||||||
return b.eth.blockchain.GetBlock(header.Hash(), header.Number.Uint64()), nil
|
return b.eth.blockchain.GetBlock(header.Hash(), header.Number.Uint64()), nil
|
||||||
}
|
}
|
||||||
return b.eth.blockchain.GetBlockByNumber(uint64(number)), nil
|
bn := uint64(number) // the resolved number
|
||||||
|
if number == rpc.EarliestBlockNumber {
|
||||||
|
bn = b.HistoryPruningCutoff()
|
||||||
|
}
|
||||||
|
block := b.eth.blockchain.GetBlockByNumber(bn)
|
||||||
|
if block == nil && bn < b.HistoryPruningCutoff() {
|
||||||
|
return nil, ðconfig.PrunedHistoryError{}
|
||||||
|
}
|
||||||
|
return block, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *EthAPIBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
|
func (b *EthAPIBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
|
||||||
return b.eth.blockchain.GetBlockByHash(hash), nil
|
number := b.eth.blockchain.GetBlockNumber(hash)
|
||||||
|
if number == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
block := b.eth.blockchain.GetBlock(hash, *number)
|
||||||
|
if block == nil && *number < b.HistoryPruningCutoff() {
|
||||||
|
return nil, ðconfig.PrunedHistoryError{}
|
||||||
|
}
|
||||||
|
return block, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetBody returns body of a block. It does not resolve special block numbers.
|
// GetBody returns body of a block. It does not resolve special block numbers.
|
||||||
|
|
@ -155,11 +178,15 @@ func (b *EthAPIBackend) GetBody(ctx context.Context, hash common.Hash, number rp
|
||||||
if number < 0 || hash == (common.Hash{}) {
|
if number < 0 || hash == (common.Hash{}) {
|
||||||
return nil, errors.New("invalid arguments; expect hash and no special block numbers")
|
return nil, errors.New("invalid arguments; expect hash and no special block numbers")
|
||||||
}
|
}
|
||||||
if body := b.eth.blockchain.GetBody(hash); body != nil {
|
body := b.eth.blockchain.GetBody(hash)
|
||||||
return body, nil
|
if body == nil {
|
||||||
|
if uint64(number) < b.HistoryPruningCutoff() {
|
||||||
|
return nil, ðconfig.PrunedHistoryError{}
|
||||||
}
|
}
|
||||||
return nil, errors.New("block body not found")
|
return nil, errors.New("block body not found")
|
||||||
}
|
}
|
||||||
|
return body, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (b *EthAPIBackend) BlockByNumberOrHash(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (*types.Block, error) {
|
func (b *EthAPIBackend) BlockByNumberOrHash(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (*types.Block, error) {
|
||||||
if blockNr, ok := blockNrOrHash.Number(); ok {
|
if blockNr, ok := blockNrOrHash.Number(); ok {
|
||||||
|
|
@ -175,6 +202,9 @@ func (b *EthAPIBackend) BlockByNumberOrHash(ctx context.Context, blockNrOrHash r
|
||||||
}
|
}
|
||||||
block := b.eth.blockchain.GetBlock(hash, header.Number.Uint64())
|
block := b.eth.blockchain.GetBlock(hash, header.Number.Uint64())
|
||||||
if block == nil {
|
if block == nil {
|
||||||
|
if header.Number.Uint64() < b.HistoryPruningCutoff() {
|
||||||
|
return nil, ðconfig.PrunedHistoryError{}
|
||||||
|
}
|
||||||
return nil, errors.New("header found, but block body is missing")
|
return nil, errors.New("header found, but block body is missing")
|
||||||
}
|
}
|
||||||
return block, nil
|
return block, nil
|
||||||
|
|
@ -234,6 +264,11 @@ func (b *EthAPIBackend) StateAndHeaderByNumberOrHash(ctx context.Context, blockN
|
||||||
return nil, nil, errors.New("invalid arguments; neither block nor hash specified")
|
return nil, nil, errors.New("invalid arguments; neither block nor hash specified")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (b *EthAPIBackend) HistoryPruningCutoff() uint64 {
|
||||||
|
bn, _ := b.eth.blockchain.HistoryPruningCutoff()
|
||||||
|
return bn
|
||||||
|
}
|
||||||
|
|
||||||
func (b *EthAPIBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
|
func (b *EthAPIBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
|
||||||
return b.eth.blockchain.GetReceiptsByHash(hash), nil
|
return b.eth.blockchain.GetReceiptsByHash(hash), nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -154,13 +154,18 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate history pruning configuration.
|
// Validate history pruning configuration.
|
||||||
var historyPruningCutoff uint64
|
var (
|
||||||
|
cutoffNumber uint64
|
||||||
|
cutoffHash common.Hash
|
||||||
|
)
|
||||||
if config.HistoryMode == ethconfig.PostMergeHistory {
|
if config.HistoryMode == ethconfig.PostMergeHistory {
|
||||||
prunecfg, ok := ethconfig.HistoryPrunePoints[genesisHash]
|
prunecfg, ok := ethconfig.HistoryPrunePoints[genesisHash]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("no history pruning point is defined for genesis %x", genesisHash)
|
return nil, fmt.Errorf("no history pruning point is defined for genesis %x", genesisHash)
|
||||||
}
|
}
|
||||||
historyPruningCutoff = prunecfg.BlockNumber
|
cutoffNumber = prunecfg.BlockNumber
|
||||||
|
cutoffHash = prunecfg.BlockHash
|
||||||
|
log.Info("Chain cutoff configured", "number", cutoffNumber, "hash", cutoffHash)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set networkID to chainID by default.
|
// Set networkID to chainID by default.
|
||||||
|
|
@ -213,7 +218,8 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
|
||||||
Preimages: config.Preimages,
|
Preimages: config.Preimages,
|
||||||
StateHistory: config.StateHistory,
|
StateHistory: config.StateHistory,
|
||||||
StateScheme: scheme,
|
StateScheme: scheme,
|
||||||
HistoryPruningCutoff: historyPruningCutoff,
|
HistoryPruningCutoffNumber: cutoffNumber,
|
||||||
|
HistoryPruningCutoffHash: cutoffHash,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
if config.VMTrace != "" {
|
if config.VMTrace != "" {
|
||||||
|
|
@ -246,7 +252,7 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
|
||||||
HashScheme: scheme == rawdb.HashScheme,
|
HashScheme: scheme == rawdb.HashScheme,
|
||||||
}
|
}
|
||||||
chainView := eth.newChainView(eth.blockchain.CurrentBlock())
|
chainView := eth.newChainView(eth.blockchain.CurrentBlock())
|
||||||
historyCutoff := eth.blockchain.HistoryPruningCutoff()
|
historyCutoff, _ := eth.blockchain.HistoryPruningCutoff()
|
||||||
var finalBlock uint64
|
var finalBlock uint64
|
||||||
if fb := eth.blockchain.CurrentFinalBlock(); fb != nil {
|
if fb := eth.blockchain.CurrentFinalBlock(); fb != nil {
|
||||||
finalBlock = fb.Number.Uint64()
|
finalBlock = fb.Number.Uint64()
|
||||||
|
|
@ -254,16 +260,16 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
|
||||||
eth.filterMaps = filtermaps.NewFilterMaps(chainDb, chainView, historyCutoff, finalBlock, filtermaps.DefaultParams, fmConfig)
|
eth.filterMaps = filtermaps.NewFilterMaps(chainDb, chainView, historyCutoff, finalBlock, filtermaps.DefaultParams, fmConfig)
|
||||||
eth.closeFilterMaps = make(chan chan struct{})
|
eth.closeFilterMaps = make(chan chan struct{})
|
||||||
|
|
||||||
if config.BlobPool.Datadir != "" {
|
|
||||||
config.BlobPool.Datadir = stack.ResolvePath(config.BlobPool.Datadir)
|
|
||||||
}
|
|
||||||
blobPool := blobpool.New(config.BlobPool, eth.blockchain)
|
|
||||||
|
|
||||||
if config.TxPool.Journal != "" {
|
if config.TxPool.Journal != "" {
|
||||||
config.TxPool.Journal = stack.ResolvePath(config.TxPool.Journal)
|
config.TxPool.Journal = stack.ResolvePath(config.TxPool.Journal)
|
||||||
}
|
}
|
||||||
legacyPool := legacypool.New(config.TxPool, eth.blockchain)
|
legacyPool := legacypool.New(config.TxPool, eth.blockchain)
|
||||||
|
|
||||||
|
if config.BlobPool.Datadir != "" {
|
||||||
|
config.BlobPool.Datadir = stack.ResolvePath(config.BlobPool.Datadir)
|
||||||
|
}
|
||||||
|
blobPool := blobpool.New(config.BlobPool, eth.blockchain, legacyPool.HasPendingAuth)
|
||||||
|
|
||||||
eth.txPool, err = txpool.New(config.TxPool.PriceLimit, eth.blockchain, []txpool.SubPool{legacyPool, blobPool})
|
eth.txPool, err = txpool.New(config.TxPool.PriceLimit, eth.blockchain, []txpool.SubPool{legacyPool, blobPool})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|
@ -443,7 +449,7 @@ func (s *Ethereum) updateFilterMapsHeads() {
|
||||||
if head == nil || newHead.Hash() != head.Hash() {
|
if head == nil || newHead.Hash() != head.Hash() {
|
||||||
head = newHead
|
head = newHead
|
||||||
chainView := s.newChainView(head)
|
chainView := s.newChainView(head)
|
||||||
historyCutoff := s.blockchain.HistoryPruningCutoff()
|
historyCutoff, _ := s.blockchain.HistoryPruningCutoff()
|
||||||
var finalBlock uint64
|
var finalBlock uint64
|
||||||
if fb := s.blockchain.CurrentFinalBlock(); fb != nil {
|
if fb := s.blockchain.CurrentFinalBlock(); fb != nil {
|
||||||
finalBlock = fb.Number.Uint64()
|
finalBlock = fb.Number.Uint64()
|
||||||
|
|
|
||||||
|
|
@ -447,6 +447,9 @@ func startEthService(t *testing.T, genesis *core.Genesis, blocks []*types.Block)
|
||||||
n.Close()
|
n.Close()
|
||||||
t.Fatal("can't import test blocks:", err)
|
t.Fatal("can't import test blocks:", err)
|
||||||
}
|
}
|
||||||
|
if err := ethservice.TxPool().Sync(); err != nil {
|
||||||
|
t.Fatal("failed to sync txpool after initial blockchain import:", err)
|
||||||
|
}
|
||||||
|
|
||||||
ethservice.SetSynced()
|
ethservice.SetSynced()
|
||||||
return n, ethservice
|
return n, ethservice
|
||||||
|
|
|
||||||
|
|
@ -273,8 +273,7 @@ func (d *Downloader) findBeaconAncestor() (uint64, error) {
|
||||||
// fetchHeaders feeds skeleton headers to the downloader queue for scheduling
|
// fetchHeaders feeds skeleton headers to the downloader queue for scheduling
|
||||||
// until sync errors or is finished.
|
// until sync errors or is finished.
|
||||||
func (d *Downloader) fetchHeaders(from uint64) error {
|
func (d *Downloader) fetchHeaders(from uint64) error {
|
||||||
var head *types.Header
|
head, tail, _, err := d.skeleton.Bounds()
|
||||||
_, tail, _, err := d.skeleton.Bounds()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -294,6 +293,27 @@ func (d *Downloader) fetchHeaders(from uint64) error {
|
||||||
fsHeaderContCheckTimer := time.NewTimer(fsHeaderContCheck)
|
fsHeaderContCheckTimer := time.NewTimer(fsHeaderContCheck)
|
||||||
defer fsHeaderContCheckTimer.Stop()
|
defer fsHeaderContCheckTimer.Stop()
|
||||||
|
|
||||||
|
// Verify the header at configured chain cutoff, ensuring it's matched with
|
||||||
|
// the configured hash. Skip the check if the configured cutoff is even higher
|
||||||
|
// than the sync target, which is definitely not a common case.
|
||||||
|
if d.chainCutoffNumber != 0 && d.chainCutoffNumber >= from && d.chainCutoffNumber <= head.Number.Uint64() {
|
||||||
|
h := d.skeleton.Header(d.chainCutoffNumber)
|
||||||
|
if h == nil {
|
||||||
|
if d.chainCutoffNumber < tail.Number.Uint64() {
|
||||||
|
dist := tail.Number.Uint64() - d.chainCutoffNumber
|
||||||
|
if len(localHeaders) >= int(dist) {
|
||||||
|
h = localHeaders[dist-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if h == nil {
|
||||||
|
return fmt.Errorf("header at chain cutoff is not available, cutoff: %d", d.chainCutoffNumber)
|
||||||
|
}
|
||||||
|
if h.Hash() != d.chainCutoffHash {
|
||||||
|
return fmt.Errorf("header at chain cutoff mismatched, want: %v, got: %v", d.chainCutoffHash, h.Hash())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for {
|
for {
|
||||||
// Some beacon headers might have appeared since the last cycle, make
|
// Some beacon headers might have appeared since the last cycle, make
|
||||||
// sure we're always syncing to all available ones
|
// sure we're always syncing to all available ones
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,7 @@ package downloader
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"sort"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
@ -120,6 +121,12 @@ type Downloader struct {
|
||||||
committed atomic.Bool
|
committed atomic.Bool
|
||||||
ancientLimit uint64 // The maximum block number which can be regarded as ancient data.
|
ancientLimit uint64 // The maximum block number which can be regarded as ancient data.
|
||||||
|
|
||||||
|
// The cutoff block number and hash before which chain segments (bodies
|
||||||
|
// and receipts) are skipped during synchronization. 0 means the entire
|
||||||
|
// chain segment is aimed for synchronization.
|
||||||
|
chainCutoffNumber uint64
|
||||||
|
chainCutoffHash common.Hash
|
||||||
|
|
||||||
// Channels
|
// Channels
|
||||||
headerProcCh chan *headerTask // Channel to feed the header processor new tasks
|
headerProcCh chan *headerTask // Channel to feed the header processor new tasks
|
||||||
|
|
||||||
|
|
@ -163,9 +170,6 @@ type BlockChain interface {
|
||||||
// CurrentHeader retrieves the head header from the local chain.
|
// CurrentHeader retrieves the head header from the local chain.
|
||||||
CurrentHeader() *types.Header
|
CurrentHeader() *types.Header
|
||||||
|
|
||||||
// InsertHeaderChain inserts a batch of headers into the local chain.
|
|
||||||
InsertHeaderChain([]*types.Header) (int, error)
|
|
||||||
|
|
||||||
// SetHead rewinds the local chain to a new head.
|
// SetHead rewinds the local chain to a new head.
|
||||||
SetHead(uint64) error
|
SetHead(uint64) error
|
||||||
|
|
||||||
|
|
@ -187,10 +191,17 @@ type BlockChain interface {
|
||||||
// SnapSyncCommitHead directly commits the head block to a certain entity.
|
// SnapSyncCommitHead directly commits the head block to a certain entity.
|
||||||
SnapSyncCommitHead(common.Hash) error
|
SnapSyncCommitHead(common.Hash) error
|
||||||
|
|
||||||
|
// InsertHeadersBeforeCutoff inserts a batch of headers before the configured
|
||||||
|
// chain cutoff into the ancient store.
|
||||||
|
InsertHeadersBeforeCutoff([]*types.Header) (int, error)
|
||||||
|
|
||||||
// InsertChain inserts a batch of blocks into the local chain.
|
// InsertChain inserts a batch of blocks into the local chain.
|
||||||
InsertChain(types.Blocks) (int, error)
|
InsertChain(types.Blocks) (int, error)
|
||||||
|
|
||||||
// InsertReceiptChain inserts a batch of receipts into the local chain.
|
// InsertReceiptChain inserts a batch of blocks along with their receipts
|
||||||
|
// into the local chain. Blocks older than the specified `ancientLimit`
|
||||||
|
// are stored directly in the ancient store, while newer blocks are stored
|
||||||
|
// in the live key-value store.
|
||||||
InsertReceiptChain(types.Blocks, []types.Receipts, uint64) (int, error)
|
InsertReceiptChain(types.Blocks, []types.Receipts, uint64) (int, error)
|
||||||
|
|
||||||
// Snapshots returns the blockchain snapshot tree to paused it during sync.
|
// Snapshots returns the blockchain snapshot tree to paused it during sync.
|
||||||
|
|
@ -199,16 +210,23 @@ type BlockChain interface {
|
||||||
// TrieDB retrieves the low level trie database used for interacting
|
// TrieDB retrieves the low level trie database used for interacting
|
||||||
// with trie nodes.
|
// with trie nodes.
|
||||||
TrieDB() *triedb.Database
|
TrieDB() *triedb.Database
|
||||||
|
|
||||||
|
// HistoryPruningCutoff returns the configured history pruning point.
|
||||||
|
// Block bodies along with the receipts will be skipped for synchronization.
|
||||||
|
HistoryPruningCutoff() (uint64, common.Hash)
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a new downloader to fetch hashes and blocks from remote peers.
|
// New creates a new downloader to fetch hashes and blocks from remote peers.
|
||||||
func New(stateDb ethdb.Database, mux *event.TypeMux, chain BlockChain, dropPeer peerDropFn, success func()) *Downloader {
|
func New(stateDb ethdb.Database, mux *event.TypeMux, chain BlockChain, dropPeer peerDropFn, success func()) *Downloader {
|
||||||
|
cutoffNumber, cutoffHash := chain.HistoryPruningCutoff()
|
||||||
dl := &Downloader{
|
dl := &Downloader{
|
||||||
stateDB: stateDb,
|
stateDB: stateDb,
|
||||||
mux: mux,
|
mux: mux,
|
||||||
queue: newQueue(blockCacheMaxItems, blockCacheInitialItems),
|
queue: newQueue(blockCacheMaxItems, blockCacheInitialItems),
|
||||||
peers: newPeerSet(),
|
peers: newPeerSet(),
|
||||||
blockchain: chain,
|
blockchain: chain,
|
||||||
|
chainCutoffNumber: cutoffNumber,
|
||||||
|
chainCutoffHash: cutoffHash,
|
||||||
dropPeer: dropPeer,
|
dropPeer: dropPeer,
|
||||||
headerProcCh: make(chan *headerTask, 1),
|
headerProcCh: make(chan *headerTask, 1),
|
||||||
quitCh: make(chan struct{}),
|
quitCh: make(chan struct{}),
|
||||||
|
|
@ -503,6 +521,12 @@ func (d *Downloader) syncToHead() (err error) {
|
||||||
} else {
|
} else {
|
||||||
d.ancientLimit = 0
|
d.ancientLimit = 0
|
||||||
}
|
}
|
||||||
|
// Extend the ancient chain segment range if the ancient limit is even
|
||||||
|
// below the pre-configured chain cutoff.
|
||||||
|
if d.chainCutoffNumber != 0 && d.chainCutoffNumber > d.ancientLimit {
|
||||||
|
d.ancientLimit = d.chainCutoffNumber
|
||||||
|
log.Info("Extend the ancient range with configured cutoff", "cutoff", d.chainCutoffNumber)
|
||||||
|
}
|
||||||
frozen, _ := d.stateDB.Ancients() // Ignore the error here since light client can also hit here.
|
frozen, _ := d.stateDB.Ancients() // Ignore the error here since light client can also hit here.
|
||||||
|
|
||||||
// If a part of blockchain data has already been written into active store,
|
// If a part of blockchain data has already been written into active store,
|
||||||
|
|
@ -521,14 +545,23 @@ func (d *Downloader) syncToHead() (err error) {
|
||||||
log.Info("Truncated excess ancient chain segment", "oldhead", frozen-1, "newhead", origin)
|
log.Info("Truncated excess ancient chain segment", "oldhead", frozen-1, "newhead", origin)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Skip ancient chain segments if Geth is running with a configured chain cutoff.
|
||||||
|
// These segments are not guaranteed to be available in the network.
|
||||||
|
chainOffset := origin + 1
|
||||||
|
if mode == ethconfig.SnapSync && d.chainCutoffNumber != 0 {
|
||||||
|
if chainOffset < d.chainCutoffNumber {
|
||||||
|
chainOffset = d.chainCutoffNumber
|
||||||
|
log.Info("Skip chain segment before cutoff", "origin", origin, "cutoff", d.chainCutoffNumber)
|
||||||
|
}
|
||||||
|
}
|
||||||
// Initiate the sync using a concurrent header and content retrieval algorithm
|
// Initiate the sync using a concurrent header and content retrieval algorithm
|
||||||
d.queue.Prepare(origin+1, mode)
|
d.queue.Prepare(chainOffset, mode)
|
||||||
|
|
||||||
// In beacon mode, headers are served by the skeleton syncer
|
// In beacon mode, headers are served by the skeleton syncer
|
||||||
fetchers := []func() error{
|
fetchers := []func() error{
|
||||||
func() error { return d.fetchHeaders(origin + 1) }, // Headers are always retrieved
|
func() error { return d.fetchHeaders(origin + 1) }, // Headers are always retrieved
|
||||||
func() error { return d.fetchBodies(origin + 1) }, // Bodies are retrieved during normal and snap sync
|
func() error { return d.fetchBodies(chainOffset) }, // Bodies are retrieved during normal and snap sync
|
||||||
func() error { return d.fetchReceipts(origin + 1) }, // Receipts are retrieved during snap sync
|
func() error { return d.fetchReceipts(chainOffset) }, // Receipts are retrieved during snap sync
|
||||||
func() error { return d.processHeaders(origin + 1) },
|
func() error { return d.processHeaders(origin + 1) },
|
||||||
}
|
}
|
||||||
if mode == ethconfig.SnapSync {
|
if mode == ethconfig.SnapSync {
|
||||||
|
|
@ -666,7 +699,7 @@ func (d *Downloader) processHeaders(origin uint64) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
// Otherwise split the chunk of headers into batches and process them
|
// Otherwise split the chunk of headers into batches and process them
|
||||||
headers, hashes := task.headers, task.hashes
|
headers, hashes, scheduled := task.headers, task.hashes, false
|
||||||
|
|
||||||
for len(headers) > 0 {
|
for len(headers) > 0 {
|
||||||
// Terminate if something failed in between processing chunks
|
// Terminate if something failed in between processing chunks
|
||||||
|
|
@ -683,17 +716,21 @@ func (d *Downloader) processHeaders(origin uint64) error {
|
||||||
chunkHeaders := headers[:limit]
|
chunkHeaders := headers[:limit]
|
||||||
chunkHashes := hashes[:limit]
|
chunkHashes := hashes[:limit]
|
||||||
|
|
||||||
// In case of header only syncing, validate the chunk immediately
|
// Split the headers around the chain cutoff
|
||||||
if mode == ethconfig.SnapSync {
|
var cutoff int
|
||||||
// Although the received headers might be all valid, a legacy
|
if mode == ethconfig.SnapSync && d.chainCutoffNumber != 0 {
|
||||||
// PoW/PoA sync must not accept post-merge headers. Make sure
|
cutoff = sort.Search(len(chunkHeaders), func(i int) bool {
|
||||||
// that any transition is rejected at this point.
|
return chunkHeaders[i].Number.Uint64() >= d.chainCutoffNumber
|
||||||
if len(chunkHeaders) > 0 {
|
})
|
||||||
if n, err := d.blockchain.InsertHeaderChain(chunkHeaders); err != nil {
|
}
|
||||||
log.Warn("Invalid header encountered", "number", chunkHeaders[n].Number, "hash", chunkHashes[n], "parent", chunkHeaders[n].ParentHash, "err", err)
|
// Insert the header chain into the ancient store (with block bodies and
|
||||||
|
// receipts set to nil) if they fall before the cutoff.
|
||||||
|
if mode == ethconfig.SnapSync && cutoff != 0 {
|
||||||
|
if n, err := d.blockchain.InsertHeadersBeforeCutoff(chunkHeaders[:cutoff]); err != nil {
|
||||||
|
log.Warn("Failed to insert ancient header chain", "number", chunkHeaders[n].Number, "hash", chunkHashes[n], "parent", chunkHeaders[n].ParentHash, "err", err)
|
||||||
return fmt.Errorf("%w: %v", errInvalidChain, err)
|
return fmt.Errorf("%w: %v", errInvalidChain, err)
|
||||||
}
|
}
|
||||||
}
|
log.Debug("Inserted headers before cutoff", "number", chunkHeaders[cutoff-1].Number, "hash", chunkHashes[cutoff-1])
|
||||||
}
|
}
|
||||||
// If we've reached the allowed number of pending headers, stall a bit
|
// If we've reached the allowed number of pending headers, stall a bit
|
||||||
for d.queue.PendingBodies() >= maxQueuedHeaders || d.queue.PendingReceipts() >= maxQueuedHeaders {
|
for d.queue.PendingBodies() >= maxQueuedHeaders || d.queue.PendingReceipts() >= maxQueuedHeaders {
|
||||||
|
|
@ -704,12 +741,21 @@ func (d *Downloader) processHeaders(origin uint64) error {
|
||||||
case <-timer.C:
|
case <-timer.C:
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Otherwise insert the headers for content retrieval
|
// Otherwise, schedule the headers for content retrieval (block bodies and
|
||||||
inserts := d.queue.Schedule(chunkHeaders, chunkHashes, origin)
|
// potentially receipts in snap sync).
|
||||||
if len(inserts) != len(chunkHeaders) {
|
//
|
||||||
|
// Skip the bodies/receipts retrieval scheduling before the cutoff in snap
|
||||||
|
// sync if chain pruning is configured.
|
||||||
|
if mode == ethconfig.SnapSync && cutoff != 0 {
|
||||||
|
chunkHeaders = chunkHeaders[cutoff:]
|
||||||
|
chunkHashes = chunkHashes[cutoff:]
|
||||||
|
}
|
||||||
|
if len(chunkHeaders) > 0 {
|
||||||
|
scheduled = true
|
||||||
|
if d.queue.Schedule(chunkHeaders, chunkHashes, origin+uint64(cutoff)) != len(chunkHeaders) {
|
||||||
return fmt.Errorf("%w: stale headers", errBadPeer)
|
return fmt.Errorf("%w: stale headers", errBadPeer)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
headers = headers[limit:]
|
headers = headers[limit:]
|
||||||
hashes = hashes[limit:]
|
hashes = hashes[limit:]
|
||||||
origin += uint64(limit)
|
origin += uint64(limit)
|
||||||
|
|
@ -721,7 +767,8 @@ func (d *Downloader) processHeaders(origin uint64) error {
|
||||||
}
|
}
|
||||||
d.syncStatsLock.Unlock()
|
d.syncStatsLock.Unlock()
|
||||||
|
|
||||||
// Signal the content downloaders of the availability of new tasks
|
// Signal the downloader of the availability of new tasks
|
||||||
|
if scheduled {
|
||||||
for _, ch := range []chan bool{d.queue.blockWakeCh, d.queue.receiptWakeCh} {
|
for _, ch := range []chan bool{d.queue.blockWakeCh, d.queue.receiptWakeCh} {
|
||||||
select {
|
select {
|
||||||
case ch <- true:
|
case ch <- true:
|
||||||
|
|
@ -731,6 +778,7 @@ func (d *Downloader) processHeaders(origin uint64) error {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// processFullSyncContent takes fetch results from the queue and imports them into the chain.
|
// processFullSyncContent takes fetch results from the queue and imports them into the chain.
|
||||||
func (d *Downloader) processFullSyncContent() error {
|
func (d *Downloader) processFullSyncContent() error {
|
||||||
|
|
@ -1085,10 +1133,20 @@ func (d *Downloader) reportSnapSyncProgress(force bool) {
|
||||||
header = d.blockchain.CurrentHeader()
|
header = d.blockchain.CurrentHeader()
|
||||||
block = d.blockchain.CurrentSnapBlock()
|
block = d.blockchain.CurrentSnapBlock()
|
||||||
)
|
)
|
||||||
syncedBlocks := block.Number.Uint64() - d.syncStartBlock
|
// Prevent reporting if nothing has been synchronized yet
|
||||||
if syncedBlocks == 0 {
|
if block.Number.Uint64() <= d.syncStartBlock {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// Prevent reporting noise if the actual chain synchronization (headers
|
||||||
|
// and bodies) hasn't started yet. Inserting the ancient header chain is
|
||||||
|
// fast enough and would introduce significant bias if included in the count.
|
||||||
|
if d.chainCutoffNumber != 0 && block.Number.Uint64() <= d.chainCutoffNumber {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fetchedBlocks := block.Number.Uint64() - d.syncStartBlock
|
||||||
|
if d.chainCutoffNumber != 0 && d.chainCutoffNumber > d.syncStartBlock {
|
||||||
|
fetchedBlocks = block.Number.Uint64() - d.chainCutoffNumber
|
||||||
|
}
|
||||||
// Retrieve the current chain head and calculate the ETA
|
// Retrieve the current chain head and calculate the ETA
|
||||||
latest, _, _, err := d.skeleton.Bounds()
|
latest, _, _, err := d.skeleton.Bounds()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -1103,7 +1161,7 @@ func (d *Downloader) reportSnapSyncProgress(force bool) {
|
||||||
}
|
}
|
||||||
var (
|
var (
|
||||||
left = latest.Number.Uint64() - block.Number.Uint64()
|
left = latest.Number.Uint64() - block.Number.Uint64()
|
||||||
eta = time.Since(d.syncStartTime) / time.Duration(syncedBlocks) * time.Duration(left)
|
eta = time.Since(d.syncStartTime) / time.Duration(fetchedBlocks) * time.Duration(left)
|
||||||
|
|
||||||
progress = fmt.Sprintf("%.2f%%", float64(block.Number.Uint64())*100/float64(latest.Number.Uint64()))
|
progress = fmt.Sprintf("%.2f%%", float64(block.Number.Uint64())*100/float64(latest.Number.Uint64()))
|
||||||
headers = fmt.Sprintf("%v@%v", log.FormatLogfmtUint64(header.Number.Uint64()), common.StorageSize(headerBytes).TerminalString())
|
headers = fmt.Sprintf("%v@%v", log.FormatLogfmtUint64(header.Number.Uint64()), common.StorageSize(headerBytes).TerminalString())
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,6 @@ import (
|
||||||
var (
|
var (
|
||||||
headerInMeter = metrics.NewRegisteredMeter("eth/downloader/headers/in", nil)
|
headerInMeter = metrics.NewRegisteredMeter("eth/downloader/headers/in", nil)
|
||||||
headerReqTimer = metrics.NewRegisteredTimer("eth/downloader/headers/req", nil)
|
headerReqTimer = metrics.NewRegisteredTimer("eth/downloader/headers/req", nil)
|
||||||
headerDropMeter = metrics.NewRegisteredMeter("eth/downloader/headers/drop", nil)
|
|
||||||
headerTimeoutMeter = metrics.NewRegisteredMeter("eth/downloader/headers/timeout", nil)
|
headerTimeoutMeter = metrics.NewRegisteredMeter("eth/downloader/headers/timeout", nil)
|
||||||
|
|
||||||
bodyInMeter = metrics.NewRegisteredMeter("eth/downloader/bodies/in", nil)
|
bodyInMeter = metrics.NewRegisteredMeter("eth/downloader/bodies/in", nil)
|
||||||
|
|
|
||||||
|
|
@ -73,7 +73,7 @@ type fetchResult struct {
|
||||||
Withdrawals types.Withdrawals
|
Withdrawals types.Withdrawals
|
||||||
}
|
}
|
||||||
|
|
||||||
func newFetchResult(header *types.Header, fastSync bool) *fetchResult {
|
func newFetchResult(header *types.Header, snapSync bool) *fetchResult {
|
||||||
item := &fetchResult{
|
item := &fetchResult{
|
||||||
Header: header,
|
Header: header,
|
||||||
}
|
}
|
||||||
|
|
@ -82,7 +82,7 @@ func newFetchResult(header *types.Header, fastSync bool) *fetchResult {
|
||||||
} else if header.WithdrawalsHash != nil {
|
} else if header.WithdrawalsHash != nil {
|
||||||
item.Withdrawals = make(types.Withdrawals, 0)
|
item.Withdrawals = make(types.Withdrawals, 0)
|
||||||
}
|
}
|
||||||
if fastSync && !header.EmptyReceipts() {
|
if snapSync && !header.EmptyReceipts() {
|
||||||
item.pending.Store(item.pending.Load() | (1 << receiptType))
|
item.pending.Store(item.pending.Load() | (1 << receiptType))
|
||||||
}
|
}
|
||||||
return item
|
return item
|
||||||
|
|
@ -125,18 +125,7 @@ func (f *fetchResult) Done(kind uint) bool {
|
||||||
// queue represents hashes that are either need fetching or are being fetched
|
// queue represents hashes that are either need fetching or are being fetched
|
||||||
type queue struct {
|
type queue struct {
|
||||||
mode SyncMode // Synchronisation mode to decide on the block parts to schedule for fetching
|
mode SyncMode // Synchronisation mode to decide on the block parts to schedule for fetching
|
||||||
|
|
||||||
// Headers are "special", they download in batches, supported by a skeleton chain
|
|
||||||
headerHead common.Hash // Hash of the last queued header to verify order
|
headerHead common.Hash // Hash of the last queued header to verify order
|
||||||
headerTaskPool map[uint64]*types.Header // Pending header retrieval tasks, mapping starting indexes to skeleton headers
|
|
||||||
headerTaskQueue *prque.Prque[int64, uint64] // Priority queue of the skeleton indexes to fetch the filling headers for
|
|
||||||
headerPeerMiss map[string]map[uint64]struct{} // Set of per-peer header batches known to be unavailable
|
|
||||||
headerPendPool map[string]*fetchRequest // Currently pending header retrieval operations
|
|
||||||
headerResults []*types.Header // Result cache accumulating the completed headers
|
|
||||||
headerHashes []common.Hash // Result cache accumulating the completed header hashes
|
|
||||||
headerProced int // Number of headers already processed from the results
|
|
||||||
headerOffset uint64 // Number of the first header in the result cache
|
|
||||||
headerContCh chan bool // Channel to notify when header download finishes
|
|
||||||
|
|
||||||
// All data retrievals below are based on an already assembles header chain
|
// All data retrievals below are based on an already assembles header chain
|
||||||
blockTaskPool map[common.Hash]*types.Header // Pending block (body) retrieval tasks, mapping hashes to headers
|
blockTaskPool map[common.Hash]*types.Header // Pending block (body) retrieval tasks, mapping hashes to headers
|
||||||
|
|
@ -163,7 +152,6 @@ type queue struct {
|
||||||
func newQueue(blockCacheLimit int, thresholdInitialSize int) *queue {
|
func newQueue(blockCacheLimit int, thresholdInitialSize int) *queue {
|
||||||
lock := new(sync.RWMutex)
|
lock := new(sync.RWMutex)
|
||||||
q := &queue{
|
q := &queue{
|
||||||
headerContCh: make(chan bool, 1),
|
|
||||||
blockTaskQueue: prque.New[int64, *types.Header](nil),
|
blockTaskQueue: prque.New[int64, *types.Header](nil),
|
||||||
blockWakeCh: make(chan bool, 1),
|
blockWakeCh: make(chan bool, 1),
|
||||||
receiptTaskQueue: prque.New[int64, *types.Header](nil),
|
receiptTaskQueue: prque.New[int64, *types.Header](nil),
|
||||||
|
|
@ -182,9 +170,7 @@ func (q *queue) Reset(blockCacheLimit int, thresholdInitialSize int) {
|
||||||
|
|
||||||
q.closed = false
|
q.closed = false
|
||||||
q.mode = ethconfig.FullSync
|
q.mode = ethconfig.FullSync
|
||||||
|
|
||||||
q.headerHead = common.Hash{}
|
q.headerHead = common.Hash{}
|
||||||
q.headerPendPool = make(map[string]*fetchRequest)
|
|
||||||
|
|
||||||
q.blockTaskPool = make(map[common.Hash]*types.Header)
|
q.blockTaskPool = make(map[common.Hash]*types.Header)
|
||||||
q.blockTaskQueue.Reset()
|
q.blockTaskQueue.Reset()
|
||||||
|
|
@ -207,14 +193,6 @@ func (q *queue) Close() {
|
||||||
q.lock.Unlock()
|
q.lock.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// PendingHeaders retrieves the number of header requests pending for retrieval.
|
|
||||||
func (q *queue) PendingHeaders() int {
|
|
||||||
q.lock.Lock()
|
|
||||||
defer q.lock.Unlock()
|
|
||||||
|
|
||||||
return q.headerTaskQueue.Size()
|
|
||||||
}
|
|
||||||
|
|
||||||
// PendingBodies retrieves the number of block body requests pending for retrieval.
|
// PendingBodies retrieves the number of block body requests pending for retrieval.
|
||||||
func (q *queue) PendingBodies() int {
|
func (q *queue) PendingBodies() int {
|
||||||
q.lock.Lock()
|
q.lock.Lock()
|
||||||
|
|
@ -260,54 +238,14 @@ func (q *queue) Idle() bool {
|
||||||
return (queued + pending) == 0
|
return (queued + pending) == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// ScheduleSkeleton adds a batch of header retrieval tasks to the queue to fill
|
|
||||||
// up an already retrieved header skeleton.
|
|
||||||
func (q *queue) ScheduleSkeleton(from uint64, skeleton []*types.Header) {
|
|
||||||
q.lock.Lock()
|
|
||||||
defer q.lock.Unlock()
|
|
||||||
|
|
||||||
// No skeleton retrieval can be in progress, fail hard if so (huge implementation bug)
|
|
||||||
if q.headerResults != nil {
|
|
||||||
panic("skeleton assembly already in progress")
|
|
||||||
}
|
|
||||||
// Schedule all the header retrieval tasks for the skeleton assembly
|
|
||||||
q.headerTaskPool = make(map[uint64]*types.Header)
|
|
||||||
q.headerTaskQueue = prque.New[int64, uint64](nil)
|
|
||||||
q.headerPeerMiss = make(map[string]map[uint64]struct{}) // Reset availability to correct invalid chains
|
|
||||||
q.headerResults = make([]*types.Header, len(skeleton)*MaxHeaderFetch)
|
|
||||||
q.headerHashes = make([]common.Hash, len(skeleton)*MaxHeaderFetch)
|
|
||||||
q.headerProced = 0
|
|
||||||
q.headerOffset = from
|
|
||||||
q.headerContCh = make(chan bool, 1)
|
|
||||||
|
|
||||||
for i, header := range skeleton {
|
|
||||||
index := from + uint64(i*MaxHeaderFetch)
|
|
||||||
|
|
||||||
q.headerTaskPool[index] = header
|
|
||||||
q.headerTaskQueue.Push(index, -int64(index))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// RetrieveHeaders retrieves the header chain assemble based on the scheduled
|
|
||||||
// skeleton.
|
|
||||||
func (q *queue) RetrieveHeaders() ([]*types.Header, []common.Hash, int) {
|
|
||||||
q.lock.Lock()
|
|
||||||
defer q.lock.Unlock()
|
|
||||||
|
|
||||||
headers, hashes, proced := q.headerResults, q.headerHashes, q.headerProced
|
|
||||||
q.headerResults, q.headerHashes, q.headerProced = nil, nil, 0
|
|
||||||
|
|
||||||
return headers, hashes, proced
|
|
||||||
}
|
|
||||||
|
|
||||||
// Schedule adds a set of headers for the download queue for scheduling, returning
|
// Schedule adds a set of headers for the download queue for scheduling, returning
|
||||||
// the new headers encountered.
|
// the new headers encountered.
|
||||||
func (q *queue) Schedule(headers []*types.Header, hashes []common.Hash, from uint64) []*types.Header {
|
func (q *queue) Schedule(headers []*types.Header, hashes []common.Hash, from uint64) int {
|
||||||
q.lock.Lock()
|
q.lock.Lock()
|
||||||
defer q.lock.Unlock()
|
defer q.lock.Unlock()
|
||||||
|
|
||||||
// Insert all the headers prioritised by the contained block number
|
// Insert all the headers prioritised by the contained block number
|
||||||
inserts := make([]*types.Header, 0, len(headers))
|
var inserts int
|
||||||
for i, header := range headers {
|
for i, header := range headers {
|
||||||
// Make sure chain order is honoured and preserved throughout
|
// Make sure chain order is honoured and preserved throughout
|
||||||
hash := hashes[i]
|
hash := hashes[i]
|
||||||
|
|
@ -337,7 +275,7 @@ func (q *queue) Schedule(headers []*types.Header, hashes []common.Hash, from uin
|
||||||
q.receiptTaskQueue.Push(header, -int64(header.Number.Uint64()))
|
q.receiptTaskQueue.Push(header, -int64(header.Number.Uint64()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
inserts = append(inserts, header)
|
inserts++
|
||||||
q.headerHead = hash
|
q.headerHead = hash
|
||||||
from++
|
from++
|
||||||
}
|
}
|
||||||
|
|
@ -428,46 +366,6 @@ func (q *queue) stats() []interface{} {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReserveHeaders reserves a set of headers for the given peer, skipping any
|
|
||||||
// previously failed batches.
|
|
||||||
func (q *queue) ReserveHeaders(p *peerConnection, count int) *fetchRequest {
|
|
||||||
q.lock.Lock()
|
|
||||||
defer q.lock.Unlock()
|
|
||||||
|
|
||||||
// Short circuit if the peer's already downloading something (sanity check to
|
|
||||||
// not corrupt state)
|
|
||||||
if _, ok := q.headerPendPool[p.id]; ok {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
// Retrieve a batch of hashes, skipping previously failed ones
|
|
||||||
send, skip := uint64(0), []uint64{}
|
|
||||||
for send == 0 && !q.headerTaskQueue.Empty() {
|
|
||||||
from, _ := q.headerTaskQueue.Pop()
|
|
||||||
if q.headerPeerMiss[p.id] != nil {
|
|
||||||
if _, ok := q.headerPeerMiss[p.id][from]; ok {
|
|
||||||
skip = append(skip, from)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
send = from
|
|
||||||
}
|
|
||||||
// Merge all the skipped batches back
|
|
||||||
for _, from := range skip {
|
|
||||||
q.headerTaskQueue.Push(from, -int64(from))
|
|
||||||
}
|
|
||||||
// Assemble and return the block download request
|
|
||||||
if send == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
request := &fetchRequest{
|
|
||||||
Peer: p,
|
|
||||||
From: send,
|
|
||||||
Time: time.Now(),
|
|
||||||
}
|
|
||||||
q.headerPendPool[p.id] = request
|
|
||||||
return request
|
|
||||||
}
|
|
||||||
|
|
||||||
// ReserveBodies reserves a set of body fetches for the given peer, skipping any
|
// ReserveBodies reserves a set of body fetches for the given peer, skipping any
|
||||||
// previously failed downloads. Beside the next batch of needed fetches, it also
|
// previously failed downloads. Beside the next batch of needed fetches, it also
|
||||||
// returns a flag whether empty blocks were queued requiring processing.
|
// returns a flag whether empty blocks were queued requiring processing.
|
||||||
|
|
@ -594,10 +492,6 @@ func (q *queue) Revoke(peerID string) {
|
||||||
q.lock.Lock()
|
q.lock.Lock()
|
||||||
defer q.lock.Unlock()
|
defer q.lock.Unlock()
|
||||||
|
|
||||||
if request, ok := q.headerPendPool[peerID]; ok {
|
|
||||||
q.headerTaskQueue.Push(request.From, -int64(request.From))
|
|
||||||
delete(q.headerPendPool, peerID)
|
|
||||||
}
|
|
||||||
if request, ok := q.blockPendPool[peerID]; ok {
|
if request, ok := q.blockPendPool[peerID]; ok {
|
||||||
for _, header := range request.Headers {
|
for _, header := range request.Headers {
|
||||||
q.blockTaskQueue.Push(header, -int64(header.Number.Uint64()))
|
q.blockTaskQueue.Push(header, -int64(header.Number.Uint64()))
|
||||||
|
|
@ -612,16 +506,6 @@ func (q *queue) Revoke(peerID string) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExpireHeaders cancels a request that timed out and moves the pending fetch
|
|
||||||
// task back into the queue for rescheduling.
|
|
||||||
func (q *queue) ExpireHeaders(peer string) int {
|
|
||||||
q.lock.Lock()
|
|
||||||
defer q.lock.Unlock()
|
|
||||||
|
|
||||||
headerTimeoutMeter.Mark(1)
|
|
||||||
return q.expire(peer, q.headerPendPool, q.headerTaskQueue)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExpireBodies checks for in flight block body requests that exceeded a timeout
|
// ExpireBodies checks for in flight block body requests that exceeded a timeout
|
||||||
// allowance, canceling them and returning the responsible peers for penalisation.
|
// allowance, canceling them and returning the responsible peers for penalisation.
|
||||||
func (q *queue) ExpireBodies(peer string) int {
|
func (q *queue) ExpireBodies(peer string) int {
|
||||||
|
|
@ -670,116 +554,6 @@ func (q *queue) expire(peer string, pendPool map[string]*fetchRequest, taskQueue
|
||||||
return len(req.Headers)
|
return len(req.Headers)
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeliverHeaders injects a header retrieval response into the header results
|
|
||||||
// cache. This method either accepts all headers it received, or none of them
|
|
||||||
// if they do not map correctly to the skeleton.
|
|
||||||
//
|
|
||||||
// If the headers are accepted, the method makes an attempt to deliver the set
|
|
||||||
// of ready headers to the processor to keep the pipeline full. However, it will
|
|
||||||
// not block to prevent stalling other pending deliveries.
|
|
||||||
func (q *queue) DeliverHeaders(id string, headers []*types.Header, hashes []common.Hash, headerProcCh chan *headerTask) (int, error) {
|
|
||||||
q.lock.Lock()
|
|
||||||
defer q.lock.Unlock()
|
|
||||||
|
|
||||||
var logger log.Logger
|
|
||||||
if len(id) < 16 {
|
|
||||||
// Tests use short IDs, don't choke on them
|
|
||||||
logger = log.New("peer", id)
|
|
||||||
} else {
|
|
||||||
logger = log.New("peer", id[:16])
|
|
||||||
}
|
|
||||||
// Short circuit if the data was never requested
|
|
||||||
request := q.headerPendPool[id]
|
|
||||||
if request == nil {
|
|
||||||
headerDropMeter.Mark(int64(len(headers)))
|
|
||||||
return 0, errNoFetchesPending
|
|
||||||
}
|
|
||||||
delete(q.headerPendPool, id)
|
|
||||||
|
|
||||||
headerReqTimer.UpdateSince(request.Time)
|
|
||||||
headerInMeter.Mark(int64(len(headers)))
|
|
||||||
|
|
||||||
// Ensure headers can be mapped onto the skeleton chain
|
|
||||||
target := q.headerTaskPool[request.From].Hash()
|
|
||||||
|
|
||||||
accepted := len(headers) == MaxHeaderFetch
|
|
||||||
if accepted {
|
|
||||||
if headers[0].Number.Uint64() != request.From {
|
|
||||||
logger.Trace("First header broke chain ordering", "number", headers[0].Number, "hash", hashes[0], "expected", request.From)
|
|
||||||
accepted = false
|
|
||||||
} else if hashes[len(headers)-1] != target {
|
|
||||||
logger.Trace("Last header broke skeleton structure ", "number", headers[len(headers)-1].Number, "hash", hashes[len(headers)-1], "expected", target)
|
|
||||||
accepted = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if accepted {
|
|
||||||
parentHash := hashes[0]
|
|
||||||
for i, header := range headers[1:] {
|
|
||||||
hash := hashes[i+1]
|
|
||||||
if want := request.From + 1 + uint64(i); header.Number.Uint64() != want {
|
|
||||||
logger.Warn("Header broke chain ordering", "number", header.Number, "hash", hash, "expected", want)
|
|
||||||
accepted = false
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if parentHash != header.ParentHash {
|
|
||||||
logger.Warn("Header broke chain ancestry", "number", header.Number, "hash", hash)
|
|
||||||
accepted = false
|
|
||||||
break
|
|
||||||
}
|
|
||||||
// Set-up parent hash for next round
|
|
||||||
parentHash = hash
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// If the batch of headers wasn't accepted, mark as unavailable
|
|
||||||
if !accepted {
|
|
||||||
logger.Trace("Skeleton filling not accepted", "from", request.From)
|
|
||||||
headerDropMeter.Mark(int64(len(headers)))
|
|
||||||
|
|
||||||
miss := q.headerPeerMiss[id]
|
|
||||||
if miss == nil {
|
|
||||||
q.headerPeerMiss[id] = make(map[uint64]struct{})
|
|
||||||
miss = q.headerPeerMiss[id]
|
|
||||||
}
|
|
||||||
miss[request.From] = struct{}{}
|
|
||||||
|
|
||||||
q.headerTaskQueue.Push(request.From, -int64(request.From))
|
|
||||||
return 0, errors.New("delivery not accepted")
|
|
||||||
}
|
|
||||||
// Clean up a successful fetch and try to deliver any sub-results
|
|
||||||
copy(q.headerResults[request.From-q.headerOffset:], headers)
|
|
||||||
copy(q.headerHashes[request.From-q.headerOffset:], hashes)
|
|
||||||
|
|
||||||
delete(q.headerTaskPool, request.From)
|
|
||||||
|
|
||||||
ready := 0
|
|
||||||
for q.headerProced+ready < len(q.headerResults) && q.headerResults[q.headerProced+ready] != nil {
|
|
||||||
ready += MaxHeaderFetch
|
|
||||||
}
|
|
||||||
if ready > 0 {
|
|
||||||
// Headers are ready for delivery, gather them and push forward (non blocking)
|
|
||||||
processHeaders := make([]*types.Header, ready)
|
|
||||||
copy(processHeaders, q.headerResults[q.headerProced:q.headerProced+ready])
|
|
||||||
|
|
||||||
processHashes := make([]common.Hash, ready)
|
|
||||||
copy(processHashes, q.headerHashes[q.headerProced:q.headerProced+ready])
|
|
||||||
|
|
||||||
select {
|
|
||||||
case headerProcCh <- &headerTask{
|
|
||||||
headers: processHeaders,
|
|
||||||
hashes: processHashes,
|
|
||||||
}:
|
|
||||||
logger.Trace("Pre-scheduled new headers", "count", len(processHeaders), "from", processHeaders[0].Number)
|
|
||||||
q.headerProced += len(processHeaders)
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Check for termination and return
|
|
||||||
if len(q.headerTaskPool) == 0 {
|
|
||||||
q.headerContCh <- false
|
|
||||||
}
|
|
||||||
return len(headers), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeliverBodies injects a block body retrieval response into the results queue.
|
// DeliverBodies injects a block body retrieval response into the results queue.
|
||||||
// The method returns the number of blocks bodies accepted from the delivery and
|
// The method returns the number of blocks bodies accepted from the delivery and
|
||||||
// also wakes any threads waiting for data delivery.
|
// also wakes any threads waiting for data delivery.
|
||||||
|
|
|
||||||
|
|
@ -76,7 +76,7 @@ func (r *resultStore) SetThrottleThreshold(threshold uint64) uint64 {
|
||||||
// throttled - if true, the store is at capacity, this particular header is not prio now
|
// throttled - if true, the store is at capacity, this particular header is not prio now
|
||||||
// item - the result to store data into
|
// item - the result to store data into
|
||||||
// err - any error that occurred
|
// err - any error that occurred
|
||||||
func (r *resultStore) AddFetch(header *types.Header, fastSync bool) (stale, throttled bool, item *fetchResult, err error) {
|
func (r *resultStore) AddFetch(header *types.Header, snapSync bool) (stale, throttled bool, item *fetchResult, err error) {
|
||||||
r.lock.Lock()
|
r.lock.Lock()
|
||||||
defer r.lock.Unlock()
|
defer r.lock.Unlock()
|
||||||
|
|
||||||
|
|
@ -86,7 +86,7 @@ func (r *resultStore) AddFetch(header *types.Header, fastSync bool) (stale, thro
|
||||||
return stale, throttled, item, err
|
return stale, throttled, item, err
|
||||||
}
|
}
|
||||||
if item == nil {
|
if item == nil {
|
||||||
item = newFetchResult(header, fastSync)
|
item = newFetchResult(header, snapSync)
|
||||||
r.items[index] = item
|
r.items[index] = item
|
||||||
}
|
}
|
||||||
return stale, throttled, item, err
|
return stale, throttled, item, err
|
||||||
|
|
|
||||||
|
|
@ -275,7 +275,7 @@ func (s *skeleton) startup() {
|
||||||
for {
|
for {
|
||||||
// If the sync cycle terminated or was terminated, propagate up when
|
// If the sync cycle terminated or was terminated, propagate up when
|
||||||
// higher layers request termination. There's no fancy explicit error
|
// higher layers request termination. There's no fancy explicit error
|
||||||
// signalling as the sync loop should never terminate (TM).
|
// signaling as the sync loop should never terminate (TM).
|
||||||
newhead, err := s.sync(head)
|
newhead, err := s.sync(head)
|
||||||
switch {
|
switch {
|
||||||
case err == errSyncLinked:
|
case err == errSyncLinked:
|
||||||
|
|
|
||||||
|
|
@ -90,3 +90,9 @@ var HistoryPrunePoints = map[common.Hash]*HistoryPrunePoint{
|
||||||
BlockHash: common.HexToHash("0x229f6b18ca1552f1d5146deceb5387333f40dc6275aebee3f2c5c4ece07d02db"),
|
BlockHash: common.HexToHash("0x229f6b18ca1552f1d5146deceb5387333f40dc6275aebee3f2c5c4ece07d02db"),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PrunedHistoryError is returned when the requested history is pruned.
|
||||||
|
type PrunedHistoryError struct{}
|
||||||
|
|
||||||
|
func (e *PrunedHistoryError) Error() string { return "pruned history unavailable" }
|
||||||
|
func (e *PrunedHistoryError) ErrorCode() int { return 4444 }
|
||||||
|
|
|
||||||
|
|
@ -203,21 +203,22 @@ type TxFetcher struct {
|
||||||
dropPeer func(string) // Drops a peer in case of announcement violation
|
dropPeer func(string) // Drops a peer in case of announcement violation
|
||||||
|
|
||||||
step chan struct{} // Notification channel when the fetcher loop iterates
|
step chan struct{} // Notification channel when the fetcher loop iterates
|
||||||
clock mclock.Clock // Time wrapper to simulate in tests
|
clock mclock.Clock // Monotonic clock or simulated clock for tests
|
||||||
|
realTime func() time.Time // Real system time or simulated time for tests
|
||||||
rand *mrand.Rand // Randomizer to use in tests instead of map range loops (soft-random)
|
rand *mrand.Rand // Randomizer to use in tests instead of map range loops (soft-random)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewTxFetcher creates a transaction fetcher to retrieve transaction
|
// NewTxFetcher creates a transaction fetcher to retrieve transaction
|
||||||
// based on hash announcements.
|
// based on hash announcements.
|
||||||
func NewTxFetcher(hasTx func(common.Hash) bool, addTxs func([]*types.Transaction) []error, fetchTxs func(string, []common.Hash) error, dropPeer func(string)) *TxFetcher {
|
func NewTxFetcher(hasTx func(common.Hash) bool, addTxs func([]*types.Transaction) []error, fetchTxs func(string, []common.Hash) error, dropPeer func(string)) *TxFetcher {
|
||||||
return NewTxFetcherForTests(hasTx, addTxs, fetchTxs, dropPeer, mclock.System{}, nil)
|
return NewTxFetcherForTests(hasTx, addTxs, fetchTxs, dropPeer, mclock.System{}, time.Now, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewTxFetcherForTests is a testing method to mock out the realtime clock with
|
// NewTxFetcherForTests is a testing method to mock out the realtime clock with
|
||||||
// a simulated version and the internal randomness with a deterministic one.
|
// a simulated version and the internal randomness with a deterministic one.
|
||||||
func NewTxFetcherForTests(
|
func NewTxFetcherForTests(
|
||||||
hasTx func(common.Hash) bool, addTxs func([]*types.Transaction) []error, fetchTxs func(string, []common.Hash) error, dropPeer func(string),
|
hasTx func(common.Hash) bool, addTxs func([]*types.Transaction) []error, fetchTxs func(string, []common.Hash) error, dropPeer func(string),
|
||||||
clock mclock.Clock, rand *mrand.Rand) *TxFetcher {
|
clock mclock.Clock, realTime func() time.Time, rand *mrand.Rand) *TxFetcher {
|
||||||
return &TxFetcher{
|
return &TxFetcher{
|
||||||
notify: make(chan *txAnnounce),
|
notify: make(chan *txAnnounce),
|
||||||
cleanup: make(chan *txDelivery),
|
cleanup: make(chan *txDelivery),
|
||||||
|
|
@ -237,6 +238,7 @@ func NewTxFetcherForTests(
|
||||||
fetchTxs: fetchTxs,
|
fetchTxs: fetchTxs,
|
||||||
dropPeer: dropPeer,
|
dropPeer: dropPeer,
|
||||||
clock: clock,
|
clock: clock,
|
||||||
|
realTime: realTime,
|
||||||
rand: rand,
|
rand: rand,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -293,7 +295,7 @@ func (f *TxFetcher) Notify(peer string, types []byte, sizes []uint32, hashes []c
|
||||||
// isKnownUnderpriced reports whether a transaction hash was recently found to be underpriced.
|
// isKnownUnderpriced reports whether a transaction hash was recently found to be underpriced.
|
||||||
func (f *TxFetcher) isKnownUnderpriced(hash common.Hash) bool {
|
func (f *TxFetcher) isKnownUnderpriced(hash common.Hash) bool {
|
||||||
prevTime, ok := f.underpriced.Peek(hash)
|
prevTime, ok := f.underpriced.Peek(hash)
|
||||||
if ok && prevTime.Before(time.Now().Add(-maxTxUnderpricedTimeout)) {
|
if ok && prevTime.Before(f.realTime().Add(-maxTxUnderpricedTimeout)) {
|
||||||
f.underpriced.Remove(hash)
|
f.underpriced.Remove(hash)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2150,9 +2150,22 @@ func containsHashInAnnounces(slice []announce, hash common.Hash) bool {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tests that a transaction is forgotten after the timeout.
|
// TestTransactionForgotten verifies that underpriced transactions are properly
|
||||||
|
// forgotten after the timeout period, testing both the exact timeout boundary
|
||||||
|
// and the cleanup of the underpriced cache.
|
||||||
func TestTransactionForgotten(t *testing.T) {
|
func TestTransactionForgotten(t *testing.T) {
|
||||||
fetcher := NewTxFetcher(
|
// Test ensures that underpriced transactions are properly forgotten after a timeout period,
|
||||||
|
// including checks for timeout boundary and cache cleanup.
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
// Create a mock clock for deterministic time control
|
||||||
|
mockClock := new(mclock.Simulated)
|
||||||
|
mockTime := func() time.Time {
|
||||||
|
nanoTime := int64(mockClock.Now())
|
||||||
|
return time.Unix(nanoTime/1000000000, nanoTime%1000000000)
|
||||||
|
}
|
||||||
|
|
||||||
|
fetcher := NewTxFetcherForTests(
|
||||||
func(common.Hash) bool { return false },
|
func(common.Hash) bool { return false },
|
||||||
func(txs []*types.Transaction) []error {
|
func(txs []*types.Transaction) []error {
|
||||||
errs := make([]error, len(txs))
|
errs := make([]error, len(txs))
|
||||||
|
|
@ -2163,24 +2176,83 @@ func TestTransactionForgotten(t *testing.T) {
|
||||||
},
|
},
|
||||||
func(string, []common.Hash) error { return nil },
|
func(string, []common.Hash) error { return nil },
|
||||||
func(string) {},
|
func(string) {},
|
||||||
|
mockClock,
|
||||||
|
mockTime,
|
||||||
|
rand.New(rand.NewSource(0)), // Use fixed seed for deterministic behavior
|
||||||
)
|
)
|
||||||
fetcher.Start()
|
fetcher.Start()
|
||||||
defer fetcher.Stop()
|
defer fetcher.Stop()
|
||||||
// Create one TX which is 5 minutes old, and one which is recent
|
|
||||||
tx1 := types.NewTx(&types.LegacyTx{Nonce: 0})
|
|
||||||
tx1.SetTime(time.Now().Add(-maxTxUnderpricedTimeout - 1*time.Second))
|
|
||||||
tx2 := types.NewTx(&types.LegacyTx{Nonce: 1})
|
|
||||||
|
|
||||||
// Enqueue both in the fetcher. They will be immediately tagged as underpriced
|
// Create two test transactions with the same timestamp
|
||||||
if err := fetcher.Enqueue("asdf", []*types.Transaction{tx1, tx2}, false); err != nil {
|
tx1 := types.NewTransaction(0, common.Address{}, big.NewInt(100), 21000, big.NewInt(1), nil)
|
||||||
|
tx2 := types.NewTransaction(1, common.Address{}, big.NewInt(100), 21000, big.NewInt(1), nil)
|
||||||
|
|
||||||
|
now := mockTime()
|
||||||
|
tx1.SetTime(now)
|
||||||
|
tx2.SetTime(now)
|
||||||
|
|
||||||
|
// Initial state: both transactions should be marked as underpriced
|
||||||
|
if err := fetcher.Enqueue("peer", []*types.Transaction{tx1, tx2}, false); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
// isKnownUnderpriced should trigger removal of the first tx (no longer be known underpriced)
|
if !fetcher.isKnownUnderpriced(tx1.Hash()) {
|
||||||
if fetcher.isKnownUnderpriced(tx1.Hash()) {
|
t.Error("tx1 should be underpriced")
|
||||||
t.Fatal("transaction should be forgotten by now")
|
|
||||||
}
|
}
|
||||||
// isKnownUnderpriced should not trigger removal of the second
|
|
||||||
if !fetcher.isKnownUnderpriced(tx2.Hash()) {
|
if !fetcher.isKnownUnderpriced(tx2.Hash()) {
|
||||||
t.Fatal("transaction should be known underpriced")
|
t.Error("tx2 should be underpriced")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify cache size
|
||||||
|
if size := fetcher.underpriced.Len(); size != 2 {
|
||||||
|
t.Errorf("wrong underpriced cache size: got %d, want %d", size, 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Just before timeout: transactions should still be underpriced
|
||||||
|
mockClock.Run(maxTxUnderpricedTimeout - time.Second)
|
||||||
|
if !fetcher.isKnownUnderpriced(tx1.Hash()) {
|
||||||
|
t.Error("tx1 should still be underpriced before timeout")
|
||||||
|
}
|
||||||
|
if !fetcher.isKnownUnderpriced(tx2.Hash()) {
|
||||||
|
t.Error("tx2 should still be underpriced before timeout")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exactly at timeout boundary: transactions should still be present
|
||||||
|
mockClock.Run(time.Second)
|
||||||
|
if !fetcher.isKnownUnderpriced(tx1.Hash()) {
|
||||||
|
t.Error("tx1 should be present exactly at timeout")
|
||||||
|
}
|
||||||
|
if !fetcher.isKnownUnderpriced(tx2.Hash()) {
|
||||||
|
t.Error("tx2 should be present exactly at timeout")
|
||||||
|
}
|
||||||
|
|
||||||
|
// After timeout: transactions should be forgotten
|
||||||
|
mockClock.Run(time.Second)
|
||||||
|
if fetcher.isKnownUnderpriced(tx1.Hash()) {
|
||||||
|
t.Error("tx1 should be forgotten after timeout")
|
||||||
|
}
|
||||||
|
if fetcher.isKnownUnderpriced(tx2.Hash()) {
|
||||||
|
t.Error("tx2 should be forgotten after timeout")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify cache is empty
|
||||||
|
if size := fetcher.underpriced.Len(); size != 0 {
|
||||||
|
t.Errorf("wrong underpriced cache size after timeout: got %d, want 0", size)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-enqueue tx1 with updated timestamp
|
||||||
|
tx1.SetTime(mockTime())
|
||||||
|
if err := fetcher.Enqueue("peer", []*types.Transaction{tx1}, false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !fetcher.isKnownUnderpriced(tx1.Hash()) {
|
||||||
|
t.Error("tx1 should be underpriced after re-enqueueing with new timestamp")
|
||||||
|
}
|
||||||
|
if fetcher.isKnownUnderpriced(tx2.Hash()) {
|
||||||
|
t.Error("tx2 should remain forgotten")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify final cache state
|
||||||
|
if size := fetcher.underpriced.Len(); size != 1 {
|
||||||
|
t.Errorf("wrong final underpriced cache size: got %d, want 1", size)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ import (
|
||||||
"github.com/ethereum/go-ethereum/common"
|
"github.com/ethereum/go-ethereum/common"
|
||||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||||
"github.com/ethereum/go-ethereum/core/types"
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
|
"github.com/ethereum/go-ethereum/eth/ethconfig"
|
||||||
"github.com/ethereum/go-ethereum/internal/ethapi"
|
"github.com/ethereum/go-ethereum/internal/ethapi"
|
||||||
"github.com/ethereum/go-ethereum/rpc"
|
"github.com/ethereum/go-ethereum/rpc"
|
||||||
)
|
)
|
||||||
|
|
@ -354,9 +355,13 @@ func (api *FilterAPI) GetLogs(ctx context.Context, crit FilterCriteria) ([]*type
|
||||||
if crit.ToBlock != nil {
|
if crit.ToBlock != nil {
|
||||||
end = crit.ToBlock.Int64()
|
end = crit.ToBlock.Int64()
|
||||||
}
|
}
|
||||||
|
// Block numbers below 0 are special cases.
|
||||||
if begin > 0 && end > 0 && begin > end {
|
if begin > 0 && end > 0 && begin > end {
|
||||||
return nil, errInvalidBlockRange
|
return nil, errInvalidBlockRange
|
||||||
}
|
}
|
||||||
|
if begin > 0 && begin < int64(api.events.backend.HistoryPruningCutoff()) {
|
||||||
|
return nil, ðconfig.PrunedHistoryError{}
|
||||||
|
}
|
||||||
// Construct the range filter
|
// Construct the range filter
|
||||||
filter = api.sys.NewRangeFilter(begin, end, crit.Addresses, crit.Topics)
|
filter = api.sys.NewRangeFilter(begin, end, crit.Addresses, crit.Topics)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,7 @@ import (
|
||||||
"github.com/ethereum/go-ethereum/common"
|
"github.com/ethereum/go-ethereum/common"
|
||||||
"github.com/ethereum/go-ethereum/core/filtermaps"
|
"github.com/ethereum/go-ethereum/core/filtermaps"
|
||||||
"github.com/ethereum/go-ethereum/core/types"
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
|
"github.com/ethereum/go-ethereum/eth/ethconfig"
|
||||||
"github.com/ethereum/go-ethereum/log"
|
"github.com/ethereum/go-ethereum/log"
|
||||||
"github.com/ethereum/go-ethereum/rpc"
|
"github.com/ethereum/go-ethereum/rpc"
|
||||||
)
|
)
|
||||||
|
|
@ -86,6 +87,9 @@ func (f *Filter) Logs(ctx context.Context) ([]*types.Log, error) {
|
||||||
if header == nil {
|
if header == nil {
|
||||||
return nil, errors.New("unknown block")
|
return nil, errors.New("unknown block")
|
||||||
}
|
}
|
||||||
|
if header.Number.Uint64() < f.sys.backend.HistoryPruningCutoff() {
|
||||||
|
return nil, ðconfig.PrunedHistoryError{}
|
||||||
|
}
|
||||||
return f.blockLogs(ctx, header)
|
return f.blockLogs(ctx, header)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -114,12 +118,20 @@ func (f *Filter) Logs(ctx context.Context) ([]*types.Log, error) {
|
||||||
return 0, errors.New("safe header not found")
|
return 0, errors.New("safe header not found")
|
||||||
}
|
}
|
||||||
return hdr.Number.Uint64(), nil
|
return hdr.Number.Uint64(), nil
|
||||||
|
case rpc.EarliestBlockNumber.Int64():
|
||||||
|
earliest := f.sys.backend.HistoryPruningCutoff()
|
||||||
|
hdr, _ := f.sys.backend.HeaderByNumber(ctx, rpc.BlockNumber(earliest))
|
||||||
|
if hdr == nil {
|
||||||
|
return 0, errors.New("earliest header not found")
|
||||||
}
|
}
|
||||||
|
return hdr.Number.Uint64(), nil
|
||||||
|
default:
|
||||||
if number < 0 {
|
if number < 0 {
|
||||||
return 0, errors.New("negative block number")
|
return 0, errors.New("negative block number")
|
||||||
}
|
}
|
||||||
return uint64(number), nil
|
return uint64(number), nil
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// range query need to resolve the special begin/end block number
|
// range query need to resolve the special begin/end block number
|
||||||
begin, err := resolveSpecial(f.begin)
|
begin, err := resolveSpecial(f.begin)
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,7 @@ import (
|
||||||
"github.com/ethereum/go-ethereum/core"
|
"github.com/ethereum/go-ethereum/core"
|
||||||
"github.com/ethereum/go-ethereum/core/filtermaps"
|
"github.com/ethereum/go-ethereum/core/filtermaps"
|
||||||
"github.com/ethereum/go-ethereum/core/types"
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
|
"github.com/ethereum/go-ethereum/eth/ethconfig"
|
||||||
"github.com/ethereum/go-ethereum/ethdb"
|
"github.com/ethereum/go-ethereum/ethdb"
|
||||||
"github.com/ethereum/go-ethereum/event"
|
"github.com/ethereum/go-ethereum/event"
|
||||||
"github.com/ethereum/go-ethereum/log"
|
"github.com/ethereum/go-ethereum/log"
|
||||||
|
|
@ -64,6 +65,7 @@ type Backend interface {
|
||||||
|
|
||||||
CurrentHeader() *types.Header
|
CurrentHeader() *types.Header
|
||||||
ChainConfig() *params.ChainConfig
|
ChainConfig() *params.ChainConfig
|
||||||
|
HistoryPruningCutoff() uint64
|
||||||
SubscribeNewTxsEvent(chan<- core.NewTxsEvent) event.Subscription
|
SubscribeNewTxsEvent(chan<- core.NewTxsEvent) event.Subscription
|
||||||
SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription
|
SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription
|
||||||
SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription
|
SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription
|
||||||
|
|
@ -304,6 +306,14 @@ func (es *EventSystem) SubscribeLogs(crit ethereum.FilterQuery, logs chan []*typ
|
||||||
return nil, errPendingLogsUnsupported
|
return nil, errPendingLogsUnsupported
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if from == rpc.EarliestBlockNumber {
|
||||||
|
from = rpc.BlockNumber(es.backend.HistoryPruningCutoff())
|
||||||
|
}
|
||||||
|
// Queries beyond the pruning cutoff are not supported.
|
||||||
|
if uint64(from) < es.backend.HistoryPruningCutoff() {
|
||||||
|
return nil, ðconfig.PrunedHistoryError{}
|
||||||
|
}
|
||||||
|
|
||||||
// only interested in new mined logs
|
// only interested in new mined logs
|
||||||
if from == rpc.LatestBlockNumber && to == rpc.LatestBlockNumber {
|
if from == rpc.LatestBlockNumber && to == rpc.LatestBlockNumber {
|
||||||
return es.subscribeLogs(crit, logs), nil
|
return es.subscribeLogs(crit, logs), nil
|
||||||
|
|
|
||||||
|
|
@ -181,6 +181,10 @@ func (b *testBackend) setPending(block *types.Block, receipts types.Receipts) {
|
||||||
b.pendingReceipts = receipts
|
b.pendingReceipts = receipts
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (b *testBackend) HistoryPruningCutoff() uint64 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
func newTestFilterSystem(db ethdb.Database, cfg Config) (*testBackend, *FilterSystem) {
|
func newTestFilterSystem(db ethdb.Database, cfg Config) (*testBackend, *FilterSystem) {
|
||||||
backend := &testBackend{db: db}
|
backend := &testBackend{db: db}
|
||||||
sys := NewFilterSystem(backend, cfg)
|
sys := NewFilterSystem(backend, cfg)
|
||||||
|
|
|
||||||
|
|
@ -71,6 +71,10 @@ type txPool interface {
|
||||||
// with given tx hash.
|
// with given tx hash.
|
||||||
GetRLP(hash common.Hash) []byte
|
GetRLP(hash common.Hash) []byte
|
||||||
|
|
||||||
|
// GetMetadata returns the transaction type and transaction size with the
|
||||||
|
// given transaction hash.
|
||||||
|
GetMetadata(hash common.Hash) *txpool.TxMetadata
|
||||||
|
|
||||||
// Add should add the given transactions to the pool.
|
// Add should add the given transactions to the pool.
|
||||||
Add(txs []*types.Transaction, sync bool) []error
|
Add(txs []*types.Transaction, sync bool) []error
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -93,6 +93,22 @@ func (p *testTxPool) GetRLP(hash common.Hash) []byte {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetMetadata returns the transaction type and transaction size with the given
|
||||||
|
// hash.
|
||||||
|
func (p *testTxPool) GetMetadata(hash common.Hash) *txpool.TxMetadata {
|
||||||
|
p.lock.Lock()
|
||||||
|
defer p.lock.Unlock()
|
||||||
|
|
||||||
|
tx := p.pool[hash]
|
||||||
|
if tx != nil {
|
||||||
|
return &txpool.TxMetadata{
|
||||||
|
Type: tx.Type(),
|
||||||
|
Size: tx.Size(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// Add appends a batch of transactions to the pool, and notifies any
|
// Add appends a batch of transactions to the pool, and notifies any
|
||||||
// listeners if the addition channel is non nil
|
// listeners if the addition channel is non nil
|
||||||
func (p *testTxPool) Add(txs []*types.Transaction, sync bool) []error {
|
func (p *testTxPool) Add(txs []*types.Transaction, sync bool) []error {
|
||||||
|
|
|
||||||
|
|
@ -116,10 +116,10 @@ func (p *Peer) announceTransactions() {
|
||||||
size common.StorageSize
|
size common.StorageSize
|
||||||
)
|
)
|
||||||
for count = 0; count < len(queue) && size < maxTxPacketSize; count++ {
|
for count = 0; count < len(queue) && size < maxTxPacketSize; count++ {
|
||||||
if tx := p.txpool.Get(queue[count]); tx != nil {
|
if meta := p.txpool.GetMetadata(queue[count]); meta != nil {
|
||||||
pending = append(pending, queue[count])
|
pending = append(pending, queue[count])
|
||||||
pendingTypes = append(pendingTypes, tx.Type())
|
pendingTypes = append(pendingTypes, meta.Type)
|
||||||
pendingSizes = append(pendingSizes, uint32(tx.Size()))
|
pendingSizes = append(pendingSizes, uint32(meta.Size))
|
||||||
size += common.HashLength
|
size += common.HashLength
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -22,6 +22,7 @@ import (
|
||||||
|
|
||||||
"github.com/ethereum/go-ethereum/common"
|
"github.com/ethereum/go-ethereum/common"
|
||||||
"github.com/ethereum/go-ethereum/core"
|
"github.com/ethereum/go-ethereum/core"
|
||||||
|
"github.com/ethereum/go-ethereum/core/txpool"
|
||||||
"github.com/ethereum/go-ethereum/core/types"
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
"github.com/ethereum/go-ethereum/metrics"
|
"github.com/ethereum/go-ethereum/metrics"
|
||||||
"github.com/ethereum/go-ethereum/p2p"
|
"github.com/ethereum/go-ethereum/p2p"
|
||||||
|
|
@ -90,6 +91,10 @@ type TxPool interface {
|
||||||
// GetRLP retrieves the RLP-encoded transaction from the local txpool with
|
// GetRLP retrieves the RLP-encoded transaction from the local txpool with
|
||||||
// the given hash.
|
// the given hash.
|
||||||
GetRLP(hash common.Hash) []byte
|
GetRLP(hash common.Hash) []byte
|
||||||
|
|
||||||
|
// GetMetadata returns the transaction type and transaction size with the
|
||||||
|
// given transaction hash.
|
||||||
|
GetMetadata(hash common.Hash) *txpool.TxMetadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// MakeProtocols constructs the P2P protocol definitions for `eth`.
|
// MakeProtocols constructs the P2P protocol definitions for `eth`.
|
||||||
|
|
|
||||||
|
|
@ -135,7 +135,7 @@ func newTestBackendWithGenerator(blocks int, shanghai bool, cancun bool, generat
|
||||||
storage, _ := os.MkdirTemp("", "blobpool-")
|
storage, _ := os.MkdirTemp("", "blobpool-")
|
||||||
defer os.RemoveAll(storage)
|
defer os.RemoveAll(storage)
|
||||||
|
|
||||||
blobPool := blobpool.New(blobpool.Config{Datadir: storage}, chain)
|
blobPool := blobpool.New(blobpool.Config{Datadir: storage}, chain, nil)
|
||||||
legacyPool := legacypool.New(txconfig, chain)
|
legacyPool := legacypool.New(txconfig, chain)
|
||||||
txpool, _ := txpool.New(txconfig.PriceLimit, chain, []txpool.SubPool{legacyPool, blobPool})
|
txpool, _ := txpool.New(txconfig.PriceLimit, chain, []txpool.SubPool{legacyPool, blobPool})
|
||||||
|
|
||||||
|
|
@ -297,6 +297,34 @@ func testGetBlockHeaders(t *testing.T, protocol uint) {
|
||||||
backend.chain.GetBlockByNumber(0).Hash(),
|
backend.chain.GetBlockByNumber(0).Hash(),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
// Check a corner case where skipping causes overflow with reverse=false
|
||||||
|
{
|
||||||
|
&GetBlockHeadersRequest{Origin: HashOrNumber{Number: 1}, Amount: 2, Reverse: false, Skip: math.MaxUint64 - 1},
|
||||||
|
[]common.Hash{
|
||||||
|
backend.chain.GetBlockByNumber(1).Hash(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// Check a corner case where skipping causes overflow with reverse=true
|
||||||
|
{
|
||||||
|
&GetBlockHeadersRequest{Origin: HashOrNumber{Number: 1}, Amount: 2, Reverse: true, Skip: math.MaxUint64 - 1},
|
||||||
|
[]common.Hash{
|
||||||
|
backend.chain.GetBlockByNumber(1).Hash(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// Check another corner case where skipping causes overflow with reverse=false
|
||||||
|
{
|
||||||
|
&GetBlockHeadersRequest{Origin: HashOrNumber{Number: 1}, Amount: 2, Reverse: false, Skip: math.MaxUint64},
|
||||||
|
[]common.Hash{
|
||||||
|
backend.chain.GetBlockByNumber(1).Hash(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// Check another corner case where skipping causes overflow with reverse=true
|
||||||
|
{
|
||||||
|
&GetBlockHeadersRequest{Origin: HashOrNumber{Number: 1}, Amount: 2, Reverse: true, Skip: math.MaxUint64},
|
||||||
|
[]common.Hash{
|
||||||
|
backend.chain.GetBlockByNumber(1).Hash(),
|
||||||
|
},
|
||||||
|
},
|
||||||
// Check a corner case where skipping overflow loops back into the chain start
|
// Check a corner case where skipping overflow loops back into the chain start
|
||||||
{
|
{
|
||||||
&GetBlockHeadersRequest{Origin: HashOrNumber{Hash: backend.chain.GetBlockByNumber(3).Hash()}, Amount: 2, Reverse: false, Skip: math.MaxUint64 - 1},
|
&GetBlockHeadersRequest{Origin: HashOrNumber{Hash: backend.chain.GetBlockByNumber(3).Hash()}, Amount: 2, Reverse: false, Skip: math.MaxUint64 - 1},
|
||||||
|
|
|
||||||
|
|
@ -128,15 +128,22 @@ func serviceNonContiguousBlockHeaderQuery(chain *core.BlockChain, query *GetBloc
|
||||||
}
|
}
|
||||||
case query.Reverse:
|
case query.Reverse:
|
||||||
// Number based traversal towards the genesis block
|
// Number based traversal towards the genesis block
|
||||||
if query.Origin.Number >= query.Skip+1 {
|
current := query.Origin.Number
|
||||||
query.Origin.Number -= query.Skip + 1
|
ancestor := current - (query.Skip + 1)
|
||||||
} else {
|
if ancestor >= current { // check for underflow
|
||||||
unknown = true
|
unknown = true
|
||||||
|
} else {
|
||||||
|
query.Origin.Number = ancestor
|
||||||
}
|
}
|
||||||
|
|
||||||
case !query.Reverse:
|
case !query.Reverse:
|
||||||
// Number based traversal towards the leaf block
|
current := query.Origin.Number
|
||||||
query.Origin.Number += query.Skip + 1
|
next := current + query.Skip + 1
|
||||||
|
if next <= current { // check for overflow
|
||||||
|
unknown = true
|
||||||
|
} else {
|
||||||
|
query.Origin.Number = next
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return headers
|
return headers
|
||||||
|
|
|
||||||
|
|
@ -144,7 +144,7 @@ func (l panicLogger) Fatalf(format string, args ...interface{}) {
|
||||||
|
|
||||||
// New returns a wrapped pebble DB object. The namespace is the prefix that the
|
// New returns a wrapped pebble DB object. The namespace is the prefix that the
|
||||||
// metrics reporting should use for surfacing internal stats.
|
// metrics reporting should use for surfacing internal stats.
|
||||||
func New(file string, cache int, handles int, namespace string, readonly bool) (*Database, error) {
|
func New(file string, cache int, handles int, namespace string, readonly bool, ephemeral bool) (*Database, error) {
|
||||||
// Ensure we have some minimal caching and file guarantees
|
// Ensure we have some minimal caching and file guarantees
|
||||||
if cache < minCache {
|
if cache < minCache {
|
||||||
cache = minCache
|
cache = minCache
|
||||||
|
|
@ -185,7 +185,7 @@ func New(file string, cache int, handles int, namespace string, readonly bool) (
|
||||||
fn: file,
|
fn: file,
|
||||||
log: logger,
|
log: logger,
|
||||||
quitChan: make(chan chan error),
|
quitChan: make(chan chan error),
|
||||||
writeOptions: &pebble.WriteOptions{Sync: false},
|
writeOptions: &pebble.WriteOptions{Sync: !ephemeral},
|
||||||
}
|
}
|
||||||
opt := &pebble.Options{
|
opt := &pebble.Options{
|
||||||
// Pebble has a single combined cache area and the write
|
// Pebble has a single combined cache area and the write
|
||||||
|
|
|
||||||
|
|
@ -34,7 +34,7 @@ type Database struct {
|
||||||
|
|
||||||
func (db *Database) Has(key []byte) (bool, error) {
|
func (db *Database) Has(key []byte) (bool, error) {
|
||||||
if _, err := db.Get(key); err != nil {
|
if _, err := db.Get(key); err != nil {
|
||||||
return false, nil
|
return false, err
|
||||||
}
|
}
|
||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
@ -50,7 +50,7 @@ func (db *Database) Get(key []byte) ([]byte, error) {
|
||||||
|
|
||||||
func (db *Database) HasAncient(kind string, number uint64) (bool, error) {
|
func (db *Database) HasAncient(kind string, number uint64) (bool, error) {
|
||||||
if _, err := db.Ancient(kind, number); err != nil {
|
if _, err := db.Ancient(kind, number); err != nil {
|
||||||
return false, nil
|
return false, err
|
||||||
}
|
}
|
||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
@ -144,7 +144,8 @@ func (db *Database) Close() error {
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(client *rpc.Client) ethdb.Database {
|
func New(client *rpc.Client) ethdb.Database {
|
||||||
return &Database{
|
if client == nil {
|
||||||
remote: client,
|
return nil
|
||||||
}
|
}
|
||||||
|
return &Database{remote: client}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -219,3 +219,15 @@ func (r *Reader) FindAll(want uint16) ([]*Entry, error) {
|
||||||
off += int64(headerSize + length)
|
off += int64(headerSize + length)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SkipN skips `n` entries starting from `offset` and returns the new offset.
|
||||||
|
func (r *Reader) SkipN(offset int64, n uint64) (int64, error) {
|
||||||
|
for i := uint64(0); i < n; i++ {
|
||||||
|
length, err := r.LengthAt(offset)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
offset += length
|
||||||
|
}
|
||||||
|
return offset, nil
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -70,7 +70,7 @@ func ReadDir(dir, network string) ([]string, error) {
|
||||||
}
|
}
|
||||||
parts := strings.Split(entry.Name(), "-")
|
parts := strings.Split(entry.Name(), "-")
|
||||||
if len(parts) != 3 || parts[0] != network {
|
if len(parts) != 3 || parts[0] != network {
|
||||||
// invalid era1 filename, skip
|
// Invalid era1 filename, skip.
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if epoch, err := strconv.ParseUint(parts[1], 10, 64); err != nil {
|
if epoch, err := strconv.ParseUint(parts[1], 10, 64); err != nil {
|
||||||
|
|
@ -126,6 +126,29 @@ func (e *Era) Close() error {
|
||||||
return e.f.Close()
|
return e.f.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetHeaderByNumber returns the header for the given block number.
|
||||||
|
func (e *Era) GetHeaderByNumber(num uint64) (*types.Header, error) {
|
||||||
|
if e.m.start > num || e.m.start+e.m.count <= num {
|
||||||
|
return nil, errors.New("out-of-bounds")
|
||||||
|
}
|
||||||
|
off, err := e.readOffset(num)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read and decompress header.
|
||||||
|
r, _, err := newSnappyReader(e.s, TypeCompressedHeader, off)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var header types.Header
|
||||||
|
if err := rlp.Decode(r, &header); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &header, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetBlockByNumber returns the block for the given block number.
|
||||||
func (e *Era) GetBlockByNumber(num uint64) (*types.Block, error) {
|
func (e *Era) GetBlockByNumber(num uint64) (*types.Block, error) {
|
||||||
if e.m.start > num || e.m.start+e.m.count <= num {
|
if e.m.start > num || e.m.start+e.m.count <= num {
|
||||||
return nil, errors.New("out-of-bounds")
|
return nil, errors.New("out-of-bounds")
|
||||||
|
|
@ -154,6 +177,34 @@ func (e *Era) GetBlockByNumber(num uint64) (*types.Block, error) {
|
||||||
return types.NewBlockWithHeader(&header).WithBody(body), nil
|
return types.NewBlockWithHeader(&header).WithBody(body), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetReceiptsByNumber returns the receipts for the given block number.
|
||||||
|
func (e *Era) GetReceiptsByNumber(num uint64) (types.Receipts, error) {
|
||||||
|
if e.m.start > num || e.m.start+e.m.count <= num {
|
||||||
|
return nil, errors.New("out-of-bounds")
|
||||||
|
}
|
||||||
|
off, err := e.readOffset(num)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip over header and body.
|
||||||
|
off, err = e.s.SkipN(off, 2)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read and decompress receipts.
|
||||||
|
r, _, err := newSnappyReader(e.s, TypeCompressedReceipts, off)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var receipts types.Receipts
|
||||||
|
if err := rlp.Decode(r, &receipts); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return receipts, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Accumulator reads the accumulator entry in the Era1 file.
|
// Accumulator reads the accumulator entry in the Era1 file.
|
||||||
func (e *Era) Accumulator() (common.Hash, error) {
|
func (e *Era) Accumulator() (common.Hash, error) {
|
||||||
entry, err := e.s.Find(TypeAccumulator)
|
entry, err := e.s.Find(TypeAccumulator)
|
||||||
|
|
@ -187,14 +238,11 @@ func (e *Era) InitialTD() (*big.Int, error) {
|
||||||
}
|
}
|
||||||
off += n
|
off += n
|
||||||
|
|
||||||
// Skip over next two records.
|
// Skip over header and body.
|
||||||
for i := 0; i < 2; i++ {
|
off, err = e.s.SkipN(off, 2)
|
||||||
length, err := e.s.LengthAt(off)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
off += length
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read total difficulty after first block.
|
// Read total difficulty after first block.
|
||||||
if r, _, err = e.s.ReaderAt(TypeTotalDifficulty, off); err != nil {
|
if r, _, err = e.s.ReaderAt(TypeTotalDifficulty, off); err != nil {
|
||||||
|
|
|
||||||
|
|
@ -18,12 +18,15 @@ package era
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"math/big"
|
"math/big"
|
||||||
"os"
|
"os"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/ethereum/go-ethereum/common"
|
"github.com/ethereum/go-ethereum/common"
|
||||||
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
|
"github.com/ethereum/go-ethereum/rlp"
|
||||||
)
|
)
|
||||||
|
|
||||||
type testchain struct {
|
type testchain struct {
|
||||||
|
|
@ -48,9 +51,9 @@ func TestEra1Builder(t *testing.T) {
|
||||||
chain = testchain{}
|
chain = testchain{}
|
||||||
)
|
)
|
||||||
for i := 0; i < 128; i++ {
|
for i := 0; i < 128; i++ {
|
||||||
chain.headers = append(chain.headers, []byte{byte('h'), byte(i)})
|
chain.headers = append(chain.headers, mustEncode(&types.Header{Number: big.NewInt(int64(i))}))
|
||||||
chain.bodies = append(chain.bodies, []byte{byte('b'), byte(i)})
|
chain.bodies = append(chain.bodies, mustEncode(&types.Body{Transactions: []*types.Transaction{types.NewTransaction(0, common.Address{byte(i)}, nil, 0, nil, nil)}}))
|
||||||
chain.receipts = append(chain.receipts, []byte{byte('r'), byte(i)})
|
chain.receipts = append(chain.receipts, mustEncode(&types.Receipts{{CumulativeGasUsed: uint64(i)}}))
|
||||||
chain.tds = append(chain.tds, big.NewInt(int64(i)))
|
chain.tds = append(chain.tds, big.NewInt(int64(i)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -91,13 +94,25 @@ func TestEra1Builder(t *testing.T) {
|
||||||
t.Fatalf("unexpected error %v", it.Error())
|
t.Fatalf("unexpected error %v", it.Error())
|
||||||
}
|
}
|
||||||
// Check headers.
|
// Check headers.
|
||||||
header, err := io.ReadAll(it.Header)
|
rawHeader, err := io.ReadAll(it.Header)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("error reading header from iterator: %v", err)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(rawHeader, chain.headers[i]) {
|
||||||
|
t.Fatalf("mismatched header: want %s, got %s", chain.headers[i], rawHeader)
|
||||||
|
}
|
||||||
|
header, err := e.GetHeaderByNumber(i)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("error reading header: %v", err)
|
t.Fatalf("error reading header: %v", err)
|
||||||
}
|
}
|
||||||
if !bytes.Equal(header, chain.headers[i]) {
|
encHeader, err := rlp.EncodeToBytes(header)
|
||||||
t.Fatalf("mismatched header: want %s, got %s", chain.headers[i], header)
|
if err != nil {
|
||||||
|
t.Fatalf("error encoding header: %v", err)
|
||||||
}
|
}
|
||||||
|
if !bytes.Equal(encHeader, chain.headers[i]) {
|
||||||
|
t.Fatalf("mismatched header: want %s, got %s", chain.headers[i], encHeader)
|
||||||
|
}
|
||||||
|
|
||||||
// Check bodies.
|
// Check bodies.
|
||||||
body, err := io.ReadAll(it.Body)
|
body, err := io.ReadAll(it.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -106,13 +121,25 @@ func TestEra1Builder(t *testing.T) {
|
||||||
if !bytes.Equal(body, chain.bodies[i]) {
|
if !bytes.Equal(body, chain.bodies[i]) {
|
||||||
t.Fatalf("mismatched body: want %s, got %s", chain.bodies[i], body)
|
t.Fatalf("mismatched body: want %s, got %s", chain.bodies[i], body)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check receipts.
|
// Check receipts.
|
||||||
receipts, err := io.ReadAll(it.Receipts)
|
rawReceipts, err := io.ReadAll(it.Receipts)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("error reading receipts from iterator: %v", err)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(rawReceipts, chain.receipts[i]) {
|
||||||
|
t.Fatalf("mismatched receipts: want %s, got %s", chain.receipts[i], rawReceipts)
|
||||||
|
}
|
||||||
|
receipts, err := e.GetReceiptsByNumber(i)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("error reading receipts: %v", err)
|
t.Fatalf("error reading receipts: %v", err)
|
||||||
}
|
}
|
||||||
if !bytes.Equal(receipts, chain.receipts[i]) {
|
encReceipts, err := rlp.EncodeToBytes(receipts)
|
||||||
t.Fatalf("mismatched receipts: want %s, got %s", chain.receipts[i], receipts)
|
if err != nil {
|
||||||
|
t.Fatalf("error encoding receipts: %v", err)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(encReceipts, chain.receipts[i]) {
|
||||||
|
t.Fatalf("mismatched receipts: want %s, got %s", chain.receipts[i], encReceipts)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check total difficulty.
|
// Check total difficulty.
|
||||||
|
|
@ -144,3 +171,11 @@ func TestEraFilename(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func mustEncode(obj any) []byte {
|
||||||
|
b, err := rlp.EncodeToBytes(obj)
|
||||||
|
if err != nil {
|
||||||
|
panic(fmt.Sprintf("failed in encode obj: %v", err))
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -549,21 +549,23 @@ func (api *BlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, block
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
|
// GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
|
||||||
func (api *BlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
|
func (api *BlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) (*hexutil.Uint, error) {
|
||||||
if block, _ := api.b.BlockByNumber(ctx, blockNr); block != nil {
|
block, err := api.b.BlockByNumber(ctx, blockNr)
|
||||||
|
if block != nil {
|
||||||
n := hexutil.Uint(len(block.Uncles()))
|
n := hexutil.Uint(len(block.Uncles()))
|
||||||
return &n
|
return &n, nil
|
||||||
}
|
}
|
||||||
return nil
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
|
// GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
|
||||||
func (api *BlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
|
func (api *BlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) (*hexutil.Uint, error) {
|
||||||
if block, _ := api.b.BlockByHash(ctx, blockHash); block != nil {
|
block, err := api.b.BlockByHash(ctx, blockHash)
|
||||||
|
if block != nil {
|
||||||
n := hexutil.Uint(len(block.Uncles()))
|
n := hexutil.Uint(len(block.Uncles()))
|
||||||
return &n
|
return &n, nil
|
||||||
}
|
}
|
||||||
return nil
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetCode returns the code stored at the given address in the state for the given block number.
|
// GetCode returns the code stored at the given address in the state for the given block number.
|
||||||
|
|
@ -596,9 +598,7 @@ func (api *BlockChainAPI) GetStorageAt(ctx context.Context, address common.Addre
|
||||||
func (api *BlockChainAPI) GetBlockReceipts(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) ([]map[string]interface{}, error) {
|
func (api *BlockChainAPI) GetBlockReceipts(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) ([]map[string]interface{}, error) {
|
||||||
block, err := api.b.BlockByNumberOrHash(ctx, blockNrOrHash)
|
block, err := api.b.BlockByNumberOrHash(ctx, blockNrOrHash)
|
||||||
if block == nil || err != nil {
|
if block == nil || err != nil {
|
||||||
// When the block doesn't exist, the RPC method should return JSON null
|
return nil, err
|
||||||
// as per specification.
|
|
||||||
return nil, nil
|
|
||||||
}
|
}
|
||||||
receipts, err := api.b.GetReceipts(ctx, block.Hash())
|
receipts, err := api.b.GetReceipts(ctx, block.Hash())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -1258,37 +1258,41 @@ func NewTransactionAPI(b Backend, nonceLock *AddrLocker) *TransactionAPI {
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
|
// GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
|
||||||
func (api *TransactionAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
|
func (api *TransactionAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*hexutil.Uint, error) {
|
||||||
if block, _ := api.b.BlockByNumber(ctx, blockNr); block != nil {
|
block, err := api.b.BlockByNumber(ctx, blockNr)
|
||||||
|
if block != nil {
|
||||||
n := hexutil.Uint(len(block.Transactions()))
|
n := hexutil.Uint(len(block.Transactions()))
|
||||||
return &n
|
return &n, nil
|
||||||
}
|
}
|
||||||
return nil
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
|
// GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
|
||||||
func (api *TransactionAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
|
func (api *TransactionAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) (*hexutil.Uint, error) {
|
||||||
if block, _ := api.b.BlockByHash(ctx, blockHash); block != nil {
|
block, err := api.b.BlockByHash(ctx, blockHash)
|
||||||
|
if block != nil {
|
||||||
n := hexutil.Uint(len(block.Transactions()))
|
n := hexutil.Uint(len(block.Transactions()))
|
||||||
return &n
|
return &n, nil
|
||||||
}
|
}
|
||||||
return nil
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
|
// GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
|
||||||
func (api *TransactionAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
|
func (api *TransactionAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (*RPCTransaction, error) {
|
||||||
if block, _ := api.b.BlockByNumber(ctx, blockNr); block != nil {
|
block, err := api.b.BlockByNumber(ctx, blockNr)
|
||||||
return newRPCTransactionFromBlockIndex(block, uint64(index), api.b.ChainConfig())
|
if block != nil {
|
||||||
|
return newRPCTransactionFromBlockIndex(block, uint64(index), api.b.ChainConfig()), nil
|
||||||
}
|
}
|
||||||
return nil
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
|
// GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
|
||||||
func (api *TransactionAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
|
func (api *TransactionAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (*RPCTransaction, error) {
|
||||||
if block, _ := api.b.BlockByHash(ctx, blockHash); block != nil {
|
block, err := api.b.BlockByHash(ctx, blockHash)
|
||||||
return newRPCTransactionFromBlockIndex(block, uint64(index), api.b.ChainConfig())
|
if block != nil {
|
||||||
|
return newRPCTransactionFromBlockIndex(block, uint64(index), api.b.ChainConfig()), nil
|
||||||
}
|
}
|
||||||
return nil
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
|
// GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
|
||||||
|
|
|
||||||
|
|
@ -520,8 +520,12 @@ func (b testBackend) BlockByNumber(ctx context.Context, number rpc.BlockNumber)
|
||||||
if number == rpc.PendingBlockNumber {
|
if number == rpc.PendingBlockNumber {
|
||||||
return b.pending, nil
|
return b.pending, nil
|
||||||
}
|
}
|
||||||
|
if number == rpc.EarliestBlockNumber {
|
||||||
|
number = 0
|
||||||
|
}
|
||||||
return b.chain.GetBlockByNumber(uint64(number)), nil
|
return b.chain.GetBlockByNumber(uint64(number)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b testBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
|
func (b testBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
|
||||||
return b.chain.GetBlockByHash(hash), nil
|
return b.chain.GetBlockByHash(hash), nil
|
||||||
}
|
}
|
||||||
|
|
@ -618,6 +622,12 @@ func (b testBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscripti
|
||||||
func (b testBackend) NewMatcherBackend() filtermaps.MatcherBackend {
|
func (b testBackend) NewMatcherBackend() filtermaps.MatcherBackend {
|
||||||
panic("implement me")
|
panic("implement me")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (b testBackend) HistoryPruningCutoff() uint64 {
|
||||||
|
bn, _ := b.chain.HistoryPruningCutoff()
|
||||||
|
return bn
|
||||||
|
}
|
||||||
|
|
||||||
func TestEstimateGas(t *testing.T) {
|
func TestEstimateGas(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
// Initialize test accounts
|
// Initialize test accounts
|
||||||
|
|
|
||||||
|
|
@ -85,6 +85,7 @@ type Backend interface {
|
||||||
|
|
||||||
ChainConfig() *params.ChainConfig
|
ChainConfig() *params.ChainConfig
|
||||||
Engine() consensus.Engine
|
Engine() consensus.Engine
|
||||||
|
HistoryPruningCutoff() uint64
|
||||||
|
|
||||||
// This is copied from filters.Backend
|
// This is copied from filters.Backend
|
||||||
// eth/filters needs to be initialized from this backend type, so methods needed by
|
// eth/filters needs to be initialized from this backend type, so methods needed by
|
||||||
|
|
|
||||||
|
|
@ -402,3 +402,5 @@ func (b *backendMock) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent)
|
||||||
func (b *backendMock) Engine() consensus.Engine { return nil }
|
func (b *backendMock) Engine() consensus.Engine { return nil }
|
||||||
|
|
||||||
func (b *backendMock) NewMatcherBackend() filtermaps.MatcherBackend { return nil }
|
func (b *backendMock) NewMatcherBackend() filtermaps.MatcherBackend { return nil }
|
||||||
|
|
||||||
|
func (b *backendMock) HistoryPruningCutoff() uint64 { return 0 }
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@
|
||||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
// This file contains the code snippets from the developer's guide embedded into
|
// This file contains the code snippets from the developer's guide embedded into
|
||||||
// Go tests. This ensures that any code published in out guides will not break
|
// Go tests. This ensures that any code published in our guides will not break
|
||||||
// accidentally via some code update. If some API changes nonetheless that needs
|
// accidentally via some code update. If some API changes nonetheless that needs
|
||||||
// modifying this file, please port any modification over into the developer's
|
// modifying this file, please port any modification over into the developer's
|
||||||
// guide wiki pages too!
|
// guide wiki pages too!
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,6 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/ethereum/go-ethereum/log"
|
"github.com/ethereum/go-ethereum/log"
|
||||||
)
|
)
|
||||||
|
|
@ -32,12 +31,21 @@ const (
|
||||||
termTimeFormat = "01-02|15:04:05.000"
|
termTimeFormat = "01-02|15:04:05.000"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// T wraps methods from testing.T used by the test logger into an interface.
|
||||||
|
// It is specified so that unit tests can instantiate the logger with an
|
||||||
|
// implementation of T which can capture the output of logging statements
|
||||||
|
// from T.Logf, as this cannot be using testing.T.
|
||||||
|
type T interface {
|
||||||
|
Logf(format string, args ...any)
|
||||||
|
Helper()
|
||||||
|
}
|
||||||
|
|
||||||
// logger implements log.Logger such that all output goes to the unit test log via
|
// logger implements log.Logger such that all output goes to the unit test log via
|
||||||
// t.Logf(). All methods in between logger.Trace, logger.Debug, etc. are marked as test
|
// t.Logf(). All methods in between logger.Trace, logger.Debug, etc. are marked as test
|
||||||
// helpers, so the file and line number in unit test output correspond to the call site
|
// helpers, so the file and line number in unit test output correspond to the call site
|
||||||
// which emitted the log message.
|
// which emitted the log message.
|
||||||
type logger struct {
|
type logger struct {
|
||||||
t *testing.T
|
t T
|
||||||
l log.Logger
|
l log.Logger
|
||||||
mu *sync.Mutex
|
mu *sync.Mutex
|
||||||
h *bufHandler
|
h *bufHandler
|
||||||
|
|
@ -78,7 +86,7 @@ func (h *bufHandler) WithGroup(_ string) slog.Handler {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Logger returns a logger which logs to the unit test log of t.
|
// Logger returns a logger which logs to the unit test log of t.
|
||||||
func Logger(t *testing.T, level slog.Level) log.Logger {
|
func Logger(t T, level slog.Level) log.Logger {
|
||||||
handler := bufHandler{
|
handler := bufHandler{
|
||||||
buf: []slog.Record{},
|
buf: []slog.Record{},
|
||||||
attrs: []slog.Attr{},
|
attrs: []slog.Attr{},
|
||||||
|
|
@ -92,17 +100,6 @@ func Logger(t *testing.T, level slog.Level) log.Logger {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// LoggerWithHandler returns
|
|
||||||
func LoggerWithHandler(t *testing.T, handler slog.Handler) log.Logger {
|
|
||||||
var bh bufHandler
|
|
||||||
return &logger{
|
|
||||||
t: t,
|
|
||||||
l: log.NewLogger(handler),
|
|
||||||
mu: new(sync.Mutex),
|
|
||||||
h: &bh,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *logger) Handler() slog.Handler {
|
func (l *logger) Handler() slog.Handler {
|
||||||
return l.l.Handler()
|
return l.l.Handler()
|
||||||
}
|
}
|
||||||
|
|
@ -170,7 +167,8 @@ func (l *logger) Crit(msg string, ctx ...interface{}) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *logger) With(ctx ...interface{}) log.Logger {
|
func (l *logger) With(ctx ...interface{}) log.Logger {
|
||||||
return &logger{l.t, l.l.With(ctx...), l.mu, l.h}
|
newLogger := l.l.With(ctx...)
|
||||||
|
return &logger{l.t, newLogger, l.mu, newLogger.Handler().(*bufHandler)}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *logger) New(ctx ...interface{}) log.Logger {
|
func (l *logger) New(ctx ...interface{}) log.Logger {
|
||||||
|
|
|
||||||
67
internal/testlog/testlog_test.go
Normal file
67
internal/testlog/testlog_test.go
Normal file
|
|
@ -0,0 +1,67 @@
|
||||||
|
package testlog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/ethereum/go-ethereum/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
type mockT struct {
|
||||||
|
out io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *mockT) Helper() {
|
||||||
|
// noop for the purposes of unit tests
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *mockT) Logf(format string, args ...any) {
|
||||||
|
// we could gate this operation in a mutex, but because testlogger
|
||||||
|
// only calls Logf with its internal mutex held, we just write output here
|
||||||
|
var lineBuf bytes.Buffer
|
||||||
|
if _, err := fmt.Fprintf(&lineBuf, format, args...); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
// The timestamp is locale-dependent, so we want to trim that off
|
||||||
|
// "INFO [01-01|00:00:00.000] a message ..." -> "a message..."
|
||||||
|
sanitized := strings.Split(lineBuf.String(), "]")[1]
|
||||||
|
if _, err := t.out.Write([]byte(sanitized)); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogging(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
expected string
|
||||||
|
run func(t *mockT)
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
"SubLogger",
|
||||||
|
` Visible
|
||||||
|
Hide and seek foobar=123
|
||||||
|
Also visible
|
||||||
|
`,
|
||||||
|
func(t *mockT) {
|
||||||
|
l := Logger(t, log.LevelInfo)
|
||||||
|
subLogger := l.New("foobar", 123)
|
||||||
|
|
||||||
|
l.Info("Visible")
|
||||||
|
subLogger.Info("Hide and seek")
|
||||||
|
l.Info("Also visible")
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
outp := bytes.Buffer{}
|
||||||
|
mock := mockT{&outp}
|
||||||
|
tc.run(&mock)
|
||||||
|
if outp.String() != tc.expected {
|
||||||
|
fmt.Printf("output mismatch.\nwant: '%s'\ngot: '%s'\n", tc.expected, outp.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -36,6 +36,11 @@ type openOptions struct {
|
||||||
Cache int // the capacity(in megabytes) of the data caching
|
Cache int // the capacity(in megabytes) of the data caching
|
||||||
Handles int // number of files to be open simultaneously
|
Handles int // number of files to be open simultaneously
|
||||||
ReadOnly bool
|
ReadOnly bool
|
||||||
|
|
||||||
|
// Ephemeral means that filesystem sync operations should be avoided:
|
||||||
|
// data integrity in the face of a crash is not important. This option
|
||||||
|
// should typically be used in tests.
|
||||||
|
Ephemeral bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// openDatabase opens both a disk-based key-value database such as leveldb or pebble, but also
|
// openDatabase opens both a disk-based key-value database such as leveldb or pebble, but also
|
||||||
|
|
@ -78,7 +83,7 @@ func openKeyValueDatabase(o openOptions) (ethdb.Database, error) {
|
||||||
}
|
}
|
||||||
if o.Type == rawdb.DBPebble || existingDb == rawdb.DBPebble {
|
if o.Type == rawdb.DBPebble || existingDb == rawdb.DBPebble {
|
||||||
log.Info("Using pebble as the backing database")
|
log.Info("Using pebble as the backing database")
|
||||||
return newPebbleDBDatabase(o.Directory, o.Cache, o.Handles, o.Namespace, o.ReadOnly)
|
return newPebbleDBDatabase(o.Directory, o.Cache, o.Handles, o.Namespace, o.ReadOnly, o.Ephemeral)
|
||||||
}
|
}
|
||||||
if o.Type == rawdb.DBLeveldb || existingDb == rawdb.DBLeveldb {
|
if o.Type == rawdb.DBLeveldb || existingDb == rawdb.DBLeveldb {
|
||||||
log.Info("Using leveldb as the backing database")
|
log.Info("Using leveldb as the backing database")
|
||||||
|
|
@ -86,7 +91,7 @@ func openKeyValueDatabase(o openOptions) (ethdb.Database, error) {
|
||||||
}
|
}
|
||||||
// No pre-existing database, no user-requested one either. Default to Pebble.
|
// No pre-existing database, no user-requested one either. Default to Pebble.
|
||||||
log.Info("Defaulting to pebble as the backing database")
|
log.Info("Defaulting to pebble as the backing database")
|
||||||
return newPebbleDBDatabase(o.Directory, o.Cache, o.Handles, o.Namespace, o.ReadOnly)
|
return newPebbleDBDatabase(o.Directory, o.Cache, o.Handles, o.Namespace, o.ReadOnly, o.Ephemeral)
|
||||||
}
|
}
|
||||||
|
|
||||||
// newLevelDBDatabase creates a persistent key-value database without a freezer
|
// newLevelDBDatabase creates a persistent key-value database without a freezer
|
||||||
|
|
@ -102,8 +107,8 @@ func newLevelDBDatabase(file string, cache int, handles int, namespace string, r
|
||||||
|
|
||||||
// newPebbleDBDatabase creates a persistent key-value database without a freezer
|
// newPebbleDBDatabase creates a persistent key-value database without a freezer
|
||||||
// moving immutable chain segments into cold storage.
|
// moving immutable chain segments into cold storage.
|
||||||
func newPebbleDBDatabase(file string, cache int, handles int, namespace string, readonly bool) (ethdb.Database, error) {
|
func newPebbleDBDatabase(file string, cache int, handles int, namespace string, readonly bool, ephemeral bool) (ethdb.Database, error) {
|
||||||
db, err := pebble.New(file, cache, handles, namespace, readonly)
|
db, err := pebble.New(file, cache, handles, namespace, readonly, ephemeral)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -39,7 +39,7 @@ const talkHandlerLaunchTimeout = 400 * time.Millisecond
|
||||||
// Note that talk handlers are expected to come up with a response very quickly, within at
|
// Note that talk handlers are expected to come up with a response very quickly, within at
|
||||||
// most 200ms or so. If the handler takes longer than that, the remote end may time out
|
// most 200ms or so. If the handler takes longer than that, the remote end may time out
|
||||||
// and wont receive the response.
|
// and wont receive the response.
|
||||||
type TalkRequestHandler func(enode.ID, *net.UDPAddr, []byte) []byte
|
type TalkRequestHandler func(*enode.Node, *net.UDPAddr, []byte) []byte
|
||||||
|
|
||||||
type talkSystem struct {
|
type talkSystem struct {
|
||||||
transport *UDPv5
|
transport *UDPv5
|
||||||
|
|
@ -72,13 +72,19 @@ func (t *talkSystem) register(protocol string, handler TalkRequestHandler) {
|
||||||
|
|
||||||
// handleRequest handles a talk request.
|
// handleRequest handles a talk request.
|
||||||
func (t *talkSystem) handleRequest(id enode.ID, addr netip.AddrPort, req *v5wire.TalkRequest) {
|
func (t *talkSystem) handleRequest(id enode.ID, addr netip.AddrPort, req *v5wire.TalkRequest) {
|
||||||
|
n := t.transport.codec.SessionNode(id, addr.String())
|
||||||
|
if n == nil {
|
||||||
|
// The node must be contained in the session here, since we wouldn't have
|
||||||
|
// received the request otherwise.
|
||||||
|
panic("missing node in session")
|
||||||
|
}
|
||||||
t.mutex.Lock()
|
t.mutex.Lock()
|
||||||
handler, ok := t.handlers[req.Protocol]
|
handler, ok := t.handlers[req.Protocol]
|
||||||
t.mutex.Unlock()
|
t.mutex.Unlock()
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
resp := &v5wire.TalkResponse{ReqID: req.ReqID}
|
resp := &v5wire.TalkResponse{ReqID: req.ReqID}
|
||||||
t.transport.sendResponse(id, addr, resp)
|
t.transport.sendResponse(n.ID(), addr, resp)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -90,9 +96,9 @@ func (t *talkSystem) handleRequest(id enode.ID, addr netip.AddrPort, req *v5wire
|
||||||
go func() {
|
go func() {
|
||||||
defer func() { t.slots <- struct{}{} }()
|
defer func() { t.slots <- struct{}{} }()
|
||||||
udpAddr := &net.UDPAddr{IP: addr.Addr().AsSlice(), Port: int(addr.Port())}
|
udpAddr := &net.UDPAddr{IP: addr.Addr().AsSlice(), Port: int(addr.Port())}
|
||||||
respMessage := handler(id, udpAddr, req.Message)
|
respMessage := handler(n, udpAddr, req.Message)
|
||||||
resp := &v5wire.TalkResponse{ReqID: req.ReqID, Message: respMessage}
|
resp := &v5wire.TalkResponse{ReqID: req.ReqID, Message: respMessage}
|
||||||
t.transport.sendFromAnotherThread(id, addr, resp)
|
t.transport.sendFromAnotherThread(n.ID(), addr, resp)
|
||||||
}()
|
}()
|
||||||
case <-timeout.C:
|
case <-timeout.C:
|
||||||
// Couldn't get it in time, drop the request.
|
// Couldn't get it in time, drop the request.
|
||||||
|
|
|
||||||
|
|
@ -64,6 +64,9 @@ type codecV5 interface {
|
||||||
// CurrentChallenge returns the most recent WHOAREYOU challenge that was encoded to given node.
|
// CurrentChallenge returns the most recent WHOAREYOU challenge that was encoded to given node.
|
||||||
// This will return a non-nil value if there is an active handshake attempt with the node, and nil otherwise.
|
// This will return a non-nil value if there is an active handshake attempt with the node, and nil otherwise.
|
||||||
CurrentChallenge(id enode.ID, addr string) *v5wire.Whoareyou
|
CurrentChallenge(id enode.ID, addr string) *v5wire.Whoareyou
|
||||||
|
|
||||||
|
// SessionNode returns a node that has completed the handshake.
|
||||||
|
SessionNode(id enode.ID, addr string) *enode.Node
|
||||||
}
|
}
|
||||||
|
|
||||||
// UDPv5 is the implementation of protocol version 5.
|
// UDPv5 is the implementation of protocol version 5.
|
||||||
|
|
|
||||||
|
|
@ -181,29 +181,35 @@ func TestUDPv5_handshakeRepeatChallenge(t *testing.T) {
|
||||||
nonce1 := v5wire.Nonce{1}
|
nonce1 := v5wire.Nonce{1}
|
||||||
nonce2 := v5wire.Nonce{2}
|
nonce2 := v5wire.Nonce{2}
|
||||||
nonce3 := v5wire.Nonce{3}
|
nonce3 := v5wire.Nonce{3}
|
||||||
check := func(p *v5wire.Whoareyou, wantNonce v5wire.Nonce) {
|
var firstAuthTag *v5wire.Nonce
|
||||||
|
check := func(p *v5wire.Whoareyou, authTag, wantNonce v5wire.Nonce) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
if p.Nonce != wantNonce {
|
if p.Nonce != wantNonce {
|
||||||
t.Error("wrong nonce in WHOAREYOU:", p.Nonce, wantNonce)
|
t.Error("wrong nonce in WHOAREYOU:", p.Nonce, "want:", wantNonce)
|
||||||
|
}
|
||||||
|
if firstAuthTag == nil {
|
||||||
|
firstAuthTag = &authTag
|
||||||
|
} else if authTag != *firstAuthTag {
|
||||||
|
t.Error("wrong auth tag in WHOAREYOU header:", authTag, "want:", *firstAuthTag)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unknown packet from unknown node.
|
// Unknown packet from unknown node.
|
||||||
test.packetIn(&v5wire.Unknown{Nonce: nonce1})
|
test.packetIn(&v5wire.Unknown{Nonce: nonce1})
|
||||||
test.waitPacketOut(func(p *v5wire.Whoareyou, addr netip.AddrPort, _ v5wire.Nonce) {
|
test.waitPacketOut(func(p *v5wire.Whoareyou, addr netip.AddrPort, authTag v5wire.Nonce) {
|
||||||
check(p, nonce1)
|
check(p, authTag, nonce1)
|
||||||
})
|
})
|
||||||
|
|
||||||
// Second unknown packet. Here we expect the response to reference the
|
// Second unknown packet. Here we expect the response to reference the
|
||||||
// first unknown packet.
|
// first unknown packet.
|
||||||
test.packetIn(&v5wire.Unknown{Nonce: nonce2})
|
test.packetIn(&v5wire.Unknown{Nonce: nonce2})
|
||||||
test.waitPacketOut(func(p *v5wire.Whoareyou, addr netip.AddrPort, _ v5wire.Nonce) {
|
test.waitPacketOut(func(p *v5wire.Whoareyou, addr netip.AddrPort, authTag v5wire.Nonce) {
|
||||||
check(p, nonce1)
|
check(p, authTag, nonce1)
|
||||||
})
|
})
|
||||||
// Third unknown packet. This should still return the first nonce.
|
// Third unknown packet. This should still return the first nonce.
|
||||||
test.packetIn(&v5wire.Unknown{Nonce: nonce3})
|
test.packetIn(&v5wire.Unknown{Nonce: nonce3})
|
||||||
test.waitPacketOut(func(p *v5wire.Whoareyou, addr netip.AddrPort, _ v5wire.Nonce) {
|
test.waitPacketOut(func(p *v5wire.Whoareyou, addr netip.AddrPort, authTag v5wire.Nonce) {
|
||||||
check(p, nonce1)
|
check(p, authTag, nonce1)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -486,7 +492,7 @@ func TestUDPv5_talkHandling(t *testing.T) {
|
||||||
defer test.close()
|
defer test.close()
|
||||||
|
|
||||||
var recvMessage []byte
|
var recvMessage []byte
|
||||||
test.udp.RegisterTalkHandler("test", func(id enode.ID, addr *net.UDPAddr, message []byte) []byte {
|
test.udp.RegisterTalkHandler("test", func(n *enode.Node, addr *net.UDPAddr, message []byte) []byte {
|
||||||
recvMessage = message
|
recvMessage = message
|
||||||
return []byte("test response")
|
return []byte("test response")
|
||||||
})
|
})
|
||||||
|
|
@ -766,20 +772,30 @@ type testCodecFrame struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *testCodec) Encode(toID enode.ID, addr string, p v5wire.Packet, _ *v5wire.Whoareyou) ([]byte, v5wire.Nonce, error) {
|
func (c *testCodec) Encode(toID enode.ID, addr string, p v5wire.Packet, _ *v5wire.Whoareyou) ([]byte, v5wire.Nonce, error) {
|
||||||
|
// To match the behavior of v5wire.Codec, we return the cached encoding of
|
||||||
|
// WHOAREYOU challenges.
|
||||||
|
if wp, ok := p.(*v5wire.Whoareyou); ok && len(wp.Encoded) > 0 {
|
||||||
|
return wp.Encoded, wp.Nonce, nil
|
||||||
|
}
|
||||||
|
|
||||||
c.ctr++
|
c.ctr++
|
||||||
var authTag v5wire.Nonce
|
var authTag v5wire.Nonce
|
||||||
binary.BigEndian.PutUint64(authTag[:], c.ctr)
|
binary.BigEndian.PutUint64(authTag[:], c.ctr)
|
||||||
|
penc, _ := rlp.EncodeToBytes(p)
|
||||||
|
frame, err := rlp.EncodeToBytes(testCodecFrame{c.id, authTag, p.Kind(), penc})
|
||||||
|
if err != nil {
|
||||||
|
return frame, authTag, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store recently sent challenges.
|
||||||
if w, ok := p.(*v5wire.Whoareyou); ok {
|
if w, ok := p.(*v5wire.Whoareyou); ok {
|
||||||
// Store recently sent Whoareyou challenges.
|
w.Nonce = authTag
|
||||||
|
w.Encoded = frame
|
||||||
if c.sentChallenges == nil {
|
if c.sentChallenges == nil {
|
||||||
c.sentChallenges = make(map[enode.ID]*v5wire.Whoareyou)
|
c.sentChallenges = make(map[enode.ID]*v5wire.Whoareyou)
|
||||||
}
|
}
|
||||||
c.sentChallenges[toID] = w
|
c.sentChallenges[toID] = w
|
||||||
}
|
}
|
||||||
|
|
||||||
penc, _ := rlp.EncodeToBytes(p)
|
|
||||||
frame, err := rlp.EncodeToBytes(testCodecFrame{c.id, authTag, p.Kind(), penc})
|
|
||||||
return frame, authTag, err
|
return frame, authTag, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -795,6 +811,10 @@ func (c *testCodec) Decode(input []byte, addr string) (enode.ID, *enode.Node, v5
|
||||||
return frame.NodeID, nil, p, nil
|
return frame.NodeID, nil, p, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *testCodec) SessionNode(id enode.ID, addr string) *enode.Node {
|
||||||
|
return c.test.nodesByID[id].Node()
|
||||||
|
}
|
||||||
|
|
||||||
func (c *testCodec) decodeFrame(input []byte) (frame testCodecFrame, p v5wire.Packet, err error) {
|
func (c *testCodec) decodeFrame(input []byte) (frame testCodecFrame, p v5wire.Packet, err error) {
|
||||||
if err = rlp.DecodeBytes(input, &frame); err != nil {
|
if err = rlp.DecodeBytes(input, &frame); err != nil {
|
||||||
return frame, nil, fmt.Errorf("invalid frame: %v", err)
|
return frame, nil, fmt.Errorf("invalid frame: %v", err)
|
||||||
|
|
|
||||||
|
|
@ -189,6 +189,11 @@ func (c *Codec) Encode(id enode.ID, addr string, packet Packet, challenge *Whoar
|
||||||
)
|
)
|
||||||
switch {
|
switch {
|
||||||
case packet.Kind() == WhoareyouPacket:
|
case packet.Kind() == WhoareyouPacket:
|
||||||
|
// just send the WHOAREYOU packet raw again, rather than the re-encoded challenge data
|
||||||
|
w := packet.(*Whoareyou)
|
||||||
|
if len(w.Encoded) > 0 {
|
||||||
|
return w.Encoded, w.Nonce, nil
|
||||||
|
}
|
||||||
head, err = c.encodeWhoareyou(id, packet.(*Whoareyou))
|
head, err = c.encodeWhoareyou(id, packet.(*Whoareyou))
|
||||||
case challenge != nil:
|
case challenge != nil:
|
||||||
// We have an unanswered challenge, send handshake.
|
// We have an unanswered challenge, send handshake.
|
||||||
|
|
@ -218,15 +223,22 @@ func (c *Codec) Encode(id enode.ID, addr string, packet Packet, challenge *Whoar
|
||||||
// Store sent WHOAREYOU challenges.
|
// Store sent WHOAREYOU challenges.
|
||||||
if challenge, ok := packet.(*Whoareyou); ok {
|
if challenge, ok := packet.(*Whoareyou); ok {
|
||||||
challenge.ChallengeData = bytesCopy(&c.buf)
|
challenge.ChallengeData = bytesCopy(&c.buf)
|
||||||
|
enc, err := c.EncodeRaw(id, head, msgData)
|
||||||
|
if err != nil {
|
||||||
|
return nil, Nonce{}, err
|
||||||
|
}
|
||||||
|
challenge.Encoded = bytes.Clone(enc)
|
||||||
c.sc.storeSentHandshake(id, addr, challenge)
|
c.sc.storeSentHandshake(id, addr, challenge)
|
||||||
} else if msgData == nil {
|
return enc, head.Nonce, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if msgData == nil {
|
||||||
headerData := c.buf.Bytes()
|
headerData := c.buf.Bytes()
|
||||||
msgData, err = c.encryptMessage(session, packet, &head, headerData)
|
msgData, err = c.encryptMessage(session, packet, &head, headerData)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, Nonce{}, err
|
return nil, Nonce{}, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
enc, err := c.EncodeRaw(id, head, msgData)
|
enc, err := c.EncodeRaw(id, head, msgData)
|
||||||
return enc, head.Nonce, err
|
return enc, head.Nonce, err
|
||||||
}
|
}
|
||||||
|
|
@ -347,7 +359,7 @@ func (c *Codec) encodeHandshakeHeader(toID enode.ID, addr string, challenge *Who
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: this should happen when the first authenticated message is received
|
// TODO: this should happen when the first authenticated message is received
|
||||||
c.sc.storeNewSession(toID, addr, session)
|
c.sc.storeNewSession(toID, addr, session, challenge.Node)
|
||||||
|
|
||||||
// Encode the auth header.
|
// Encode the auth header.
|
||||||
var (
|
var (
|
||||||
|
|
@ -522,7 +534,7 @@ func (c *Codec) decodeHandshakeMessage(fromAddr string, head *Header, headerData
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handshake OK, drop the challenge and store the new session keys.
|
// Handshake OK, drop the challenge and store the new session keys.
|
||||||
c.sc.storeNewSession(auth.h.SrcID, fromAddr, session)
|
c.sc.storeNewSession(auth.h.SrcID, fromAddr, session, node)
|
||||||
c.sc.deleteHandshake(auth.h.SrcID, fromAddr)
|
c.sc.deleteHandshake(auth.h.SrcID, fromAddr)
|
||||||
return node, msg, nil
|
return node, msg, nil
|
||||||
}
|
}
|
||||||
|
|
@ -644,6 +656,10 @@ func (c *Codec) decryptMessage(input, nonce, headerData, readKey []byte) (Packet
|
||||||
return DecodeMessage(msgdata[0], msgdata[1:])
|
return DecodeMessage(msgdata[0], msgdata[1:])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Codec) SessionNode(id enode.ID, addr string) *enode.Node {
|
||||||
|
return c.sc.readNode(id, addr)
|
||||||
|
}
|
||||||
|
|
||||||
// checkValid performs some basic validity checks on the header.
|
// checkValid performs some basic validity checks on the header.
|
||||||
// The packetLen here is the length remaining after the static header.
|
// The packetLen here is the length remaining after the static header.
|
||||||
func (h *StaticHeader) checkValid(packetLen int, protocolID [6]byte) error {
|
func (h *StaticHeader) checkValid(packetLen int, protocolID [6]byte) error {
|
||||||
|
|
|
||||||
|
|
@ -166,7 +166,7 @@ func TestHandshake_rekey(t *testing.T) {
|
||||||
readKey: []byte("BBBBBBBBBBBBBBBB"),
|
readKey: []byte("BBBBBBBBBBBBBBBB"),
|
||||||
writeKey: []byte("AAAAAAAAAAAAAAAA"),
|
writeKey: []byte("AAAAAAAAAAAAAAAA"),
|
||||||
}
|
}
|
||||||
net.nodeA.c.sc.storeNewSession(net.nodeB.id(), net.nodeB.addr(), session)
|
net.nodeA.c.sc.storeNewSession(net.nodeB.id(), net.nodeB.addr(), session, net.nodeB.n())
|
||||||
|
|
||||||
// A -> B FINDNODE (encrypted with zero keys)
|
// A -> B FINDNODE (encrypted with zero keys)
|
||||||
findnode, authTag := net.nodeA.encode(t, net.nodeB, &Findnode{})
|
findnode, authTag := net.nodeA.encode(t, net.nodeB, &Findnode{})
|
||||||
|
|
@ -209,8 +209,8 @@ func TestHandshake_rekey2(t *testing.T) {
|
||||||
readKey: []byte("CCCCCCCCCCCCCCCC"),
|
readKey: []byte("CCCCCCCCCCCCCCCC"),
|
||||||
writeKey: []byte("DDDDDDDDDDDDDDDD"),
|
writeKey: []byte("DDDDDDDDDDDDDDDD"),
|
||||||
}
|
}
|
||||||
net.nodeA.c.sc.storeNewSession(net.nodeB.id(), net.nodeB.addr(), initKeysA)
|
net.nodeA.c.sc.storeNewSession(net.nodeB.id(), net.nodeB.addr(), initKeysA, net.nodeB.n())
|
||||||
net.nodeB.c.sc.storeNewSession(net.nodeA.id(), net.nodeA.addr(), initKeysB)
|
net.nodeB.c.sc.storeNewSession(net.nodeA.id(), net.nodeA.addr(), initKeysB, net.nodeA.n())
|
||||||
|
|
||||||
// A -> B FINDNODE encrypted with initKeysA
|
// A -> B FINDNODE encrypted with initKeysA
|
||||||
findnode, authTag := net.nodeA.encode(t, net.nodeB, &Findnode{Distances: []uint{3}})
|
findnode, authTag := net.nodeA.encode(t, net.nodeB, &Findnode{Distances: []uint{3}})
|
||||||
|
|
@ -362,8 +362,8 @@ func TestTestVectorsV5(t *testing.T) {
|
||||||
ENRSeq: 2,
|
ENRSeq: 2,
|
||||||
},
|
},
|
||||||
prep: func(net *handshakeTest) {
|
prep: func(net *handshakeTest) {
|
||||||
net.nodeA.c.sc.storeNewSession(idB, addr, session)
|
net.nodeA.c.sc.storeNewSession(idB, addr, session, net.nodeB.n())
|
||||||
net.nodeB.c.sc.storeNewSession(idA, addr, session.keysFlipped())
|
net.nodeB.c.sc.storeNewSession(idA, addr, session.keysFlipped(), net.nodeA.n())
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
@ -499,8 +499,8 @@ func BenchmarkV5_DecodePing(b *testing.B) {
|
||||||
readKey: []byte{233, 203, 93, 195, 86, 47, 177, 186, 227, 43, 2, 141, 244, 230, 120, 17},
|
readKey: []byte{233, 203, 93, 195, 86, 47, 177, 186, 227, 43, 2, 141, 244, 230, 120, 17},
|
||||||
writeKey: []byte{79, 145, 252, 171, 167, 216, 252, 161, 208, 190, 176, 106, 214, 39, 178, 134},
|
writeKey: []byte{79, 145, 252, 171, 167, 216, 252, 161, 208, 190, 176, 106, 214, 39, 178, 134},
|
||||||
}
|
}
|
||||||
net.nodeA.c.sc.storeNewSession(net.nodeB.id(), net.nodeB.addr(), session)
|
net.nodeA.c.sc.storeNewSession(net.nodeB.id(), net.nodeB.addr(), session, net.nodeB.n())
|
||||||
net.nodeB.c.sc.storeNewSession(net.nodeA.id(), net.nodeA.addr(), session.keysFlipped())
|
net.nodeB.c.sc.storeNewSession(net.nodeA.id(), net.nodeA.addr(), session.keysFlipped(), net.nodeA.n())
|
||||||
addrB := net.nodeA.addr()
|
addrB := net.nodeA.addr()
|
||||||
ping := &Ping{ReqID: []byte("reqid"), ENRSeq: 5}
|
ping := &Ping{ReqID: []byte("reqid"), ENRSeq: 5}
|
||||||
enc, _, err := net.nodeA.c.Encode(net.nodeB.id(), addrB, ping, nil)
|
enc, _, err := net.nodeA.c.Encode(net.nodeB.id(), addrB, ping, nil)
|
||||||
|
|
|
||||||
|
|
@ -73,6 +73,9 @@ type (
|
||||||
Node *enode.Node
|
Node *enode.Node
|
||||||
|
|
||||||
sent mclock.AbsTime // for handshake GC.
|
sent mclock.AbsTime // for handshake GC.
|
||||||
|
|
||||||
|
// Encoded is packet raw data for sending out, but should not be include in the RLP encoding.
|
||||||
|
Encoded []byte `rlp:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// PING is sent during liveness checks.
|
// PING is sent during liveness checks.
|
||||||
|
|
|
||||||
|
|
@ -54,11 +54,12 @@ type session struct {
|
||||||
writeKey []byte
|
writeKey []byte
|
||||||
readKey []byte
|
readKey []byte
|
||||||
nonceCounter uint32
|
nonceCounter uint32
|
||||||
|
node *enode.Node
|
||||||
}
|
}
|
||||||
|
|
||||||
// keysFlipped returns a copy of s with the read and write keys flipped.
|
// keysFlipped returns a copy of s with the read and write keys flipped.
|
||||||
func (s *session) keysFlipped() *session {
|
func (s *session) keysFlipped() *session {
|
||||||
return &session{s.readKey, s.writeKey, s.nonceCounter}
|
return &session{s.readKey, s.writeKey, s.nonceCounter, s.node}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSessionCache(maxItems int, clock mclock.Clock) *SessionCache {
|
func NewSessionCache(maxItems int, clock mclock.Clock) *SessionCache {
|
||||||
|
|
@ -103,8 +104,19 @@ func (sc *SessionCache) readKey(id enode.ID, addr string) []byte {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (sc *SessionCache) readNode(id enode.ID, addr string) *enode.Node {
|
||||||
|
if s := sc.session(id, addr); s != nil {
|
||||||
|
return s.node
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// storeNewSession stores new encryption keys in the cache.
|
// storeNewSession stores new encryption keys in the cache.
|
||||||
func (sc *SessionCache) storeNewSession(id enode.ID, addr string, s *session) {
|
func (sc *SessionCache) storeNewSession(id enode.ID, addr string, s *session, n *enode.Node) {
|
||||||
|
if n == nil {
|
||||||
|
panic("nil node in storeNewSession")
|
||||||
|
}
|
||||||
|
s.node = n
|
||||||
sc.sessions.Add(sessionID{id, addr}, s)
|
sc.sessions.Add(sessionID{id, addr}, s)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -49,6 +49,9 @@ func (n *pmp) AddMapping(protocol string, extport, intport int, name string, lif
|
||||||
if lifetime <= 0 {
|
if lifetime <= 0 {
|
||||||
return 0, errors.New("lifetime must not be <= 0")
|
return 0, errors.New("lifetime must not be <= 0")
|
||||||
}
|
}
|
||||||
|
if extport == 0 {
|
||||||
|
extport = intport
|
||||||
|
}
|
||||||
// Note order of port arguments is switched between our
|
// Note order of port arguments is switched between our
|
||||||
// AddMapping and the client's AddPortMapping.
|
// AddMapping and the client's AddPortMapping.
|
||||||
res, err := n.c.AddPortMapping(strings.ToLower(protocol), intport, extport, int(lifetime/time.Second))
|
res, err := n.c.AddPortMapping(strings.ToLower(protocol), intport, extport, int(lifetime/time.Second))
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,7 @@ import (
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/ethereum/go-ethereum/log"
|
||||||
"github.com/huin/goupnp"
|
"github.com/huin/goupnp"
|
||||||
"github.com/huin/goupnp/dcps/internetgateway1"
|
"github.com/huin/goupnp/dcps/internetgateway1"
|
||||||
"github.com/huin/goupnp/dcps/internetgateway2"
|
"github.com/huin/goupnp/dcps/internetgateway2"
|
||||||
|
|
@ -34,6 +35,8 @@ import (
|
||||||
const (
|
const (
|
||||||
soapRequestTimeout = 3 * time.Second
|
soapRequestTimeout = 3 * time.Second
|
||||||
rateLimit = 200 * time.Millisecond
|
rateLimit = 200 * time.Millisecond
|
||||||
|
retryCount = 3 // number of retries after a failed AddPortMapping
|
||||||
|
randomCount = 3 // number of random ports to try
|
||||||
)
|
)
|
||||||
|
|
||||||
type upnp struct {
|
type upnp struct {
|
||||||
|
|
@ -82,41 +85,53 @@ func (n *upnp) ExternalIP() (addr net.IP, err error) {
|
||||||
func (n *upnp) AddMapping(protocol string, extport, intport int, desc string, lifetime time.Duration) (uint16, error) {
|
func (n *upnp) AddMapping(protocol string, extport, intport int, desc string, lifetime time.Duration) (uint16, error) {
|
||||||
ip, err := n.internalAddress()
|
ip, err := n.internalAddress()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, nil // TODO: Shouldn't we return the error?
|
return 0, err
|
||||||
}
|
}
|
||||||
protocol = strings.ToUpper(protocol)
|
protocol = strings.ToUpper(protocol)
|
||||||
lifetimeS := uint32(lifetime / time.Second)
|
lifetimeS := uint32(lifetime / time.Second)
|
||||||
n.DeleteMapping(protocol, extport, intport)
|
|
||||||
|
|
||||||
err = n.withRateLimit(func() error {
|
if extport == 0 {
|
||||||
|
extport = intport
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to add port mapping, preferring the specified external port.
|
||||||
|
return n.addAnyPortMapping(protocol, extport, intport, ip, desc, lifetimeS)
|
||||||
|
}
|
||||||
|
|
||||||
|
// addAnyPortMapping tries to add a port mapping with the specified external port.
|
||||||
|
// If the external port is already in use, it will try to assign another port.
|
||||||
|
func (n *upnp) addAnyPortMapping(protocol string, extport, intport int, ip net.IP, desc string, lifetimeS uint32) (uint16, error) {
|
||||||
|
if client, ok := n.client.(*internetgateway2.WANIPConnection2); ok {
|
||||||
|
return n.portWithRateLimit(func() (uint16, error) {
|
||||||
|
return client.AddAnyPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// For IGDv1 and v1 services we should first try to add with extport.
|
||||||
|
for i := 0; i < retryCount+1; i++ {
|
||||||
|
err := n.withRateLimit(func() error {
|
||||||
return n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
|
return n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
|
||||||
})
|
})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return uint16(extport), nil
|
return uint16(extport), nil
|
||||||
}
|
}
|
||||||
|
log.Debug("Failed to add port mapping", "protocol", protocol, "extport", extport, "intport", intport, "err", err)
|
||||||
return uint16(extport), n.withRateLimit(func() error {
|
|
||||||
p, err := n.addAnyPortMapping(protocol, extport, intport, ip, desc, lifetimeS)
|
|
||||||
if err == nil {
|
|
||||||
extport = int(p)
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (n *upnp) addAnyPortMapping(protocol string, extport, intport int, ip net.IP, desc string, lifetimeS uint32) (uint16, error) {
|
// If above fails, we retry with a random port.
|
||||||
if client, ok := n.client.(*internetgateway2.WANIPConnection2); ok {
|
// We retry several times because of possible port conflicts.
|
||||||
return client.AddAnyPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
|
var err error
|
||||||
}
|
for i := 0; i < randomCount; i++ {
|
||||||
// It will retry with a random port number if the client does
|
|
||||||
// not support AddAnyPortMapping.
|
|
||||||
extport = n.randomPort()
|
extport = n.randomPort()
|
||||||
err := n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
|
err := n.withRateLimit(func() error {
|
||||||
if err != nil {
|
return n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
|
||||||
return 0, err
|
})
|
||||||
}
|
if err == nil {
|
||||||
return uint16(extport), nil
|
return uint16(extport), nil
|
||||||
}
|
}
|
||||||
|
log.Debug("Failed to add random port mapping", "protocol", protocol, "extport", extport, "intport", intport, "err", err)
|
||||||
|
}
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
func (n *upnp) randomPort() int {
|
func (n *upnp) randomPort() int {
|
||||||
if n.rand == nil {
|
if n.rand == nil {
|
||||||
|
|
@ -158,6 +173,17 @@ func (n *upnp) String() string {
|
||||||
return "UPNP " + n.service
|
return "UPNP " + n.service
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (n *upnp) portWithRateLimit(pfn func() (uint16, error)) (uint16, error) {
|
||||||
|
var port uint16
|
||||||
|
var err error
|
||||||
|
fn := func() error {
|
||||||
|
port, err = pfn()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
n.withRateLimit(fn)
|
||||||
|
return port, err
|
||||||
|
}
|
||||||
|
|
||||||
func (n *upnp) withRateLimit(fn func() error) error {
|
func (n *upnp) withRateLimit(fn func() error) error {
|
||||||
n.mu.Lock()
|
n.mu.Lock()
|
||||||
defer n.mu.Unlock()
|
defer n.mu.Unlock()
|
||||||
|
|
|
||||||
|
|
@ -31,12 +31,14 @@ const (
|
||||||
portMapRefreshInterval = 8 * time.Minute
|
portMapRefreshInterval = 8 * time.Minute
|
||||||
portMapRetryInterval = 5 * time.Minute
|
portMapRetryInterval = 5 * time.Minute
|
||||||
extipRetryInterval = 2 * time.Minute
|
extipRetryInterval = 2 * time.Minute
|
||||||
|
maxRetries = 5 // max number of failed attempts to refresh the mapping
|
||||||
)
|
)
|
||||||
|
|
||||||
type portMapping struct {
|
type portMapping struct {
|
||||||
protocol string
|
protocol string
|
||||||
name string
|
name string
|
||||||
port int
|
port int
|
||||||
|
retries int // number of failed attempts to refresh the mapping
|
||||||
|
|
||||||
// for use by the portMappingLoop goroutine:
|
// for use by the portMappingLoop goroutine:
|
||||||
extPort int // the mapped port returned by the NAT interface
|
extPort int // the mapped port returned by the NAT interface
|
||||||
|
|
@ -150,25 +152,39 @@ func (srv *Server) portMappingLoop() {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
external := m.port
|
log := newLogger(m.protocol, m.extPort, m.port)
|
||||||
if m.extPort != 0 {
|
|
||||||
external = m.extPort
|
|
||||||
}
|
|
||||||
log := newLogger(m.protocol, external, m.port)
|
|
||||||
|
|
||||||
log.Trace("Attempting port mapping")
|
log.Trace("Attempting port mapping")
|
||||||
p, err := srv.NAT.AddMapping(m.protocol, external, m.port, m.name, portMapDuration)
|
p, err := srv.NAT.AddMapping(m.protocol, m.extPort, m.port, m.name, portMapDuration)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
// Failed to add or refresh port mapping.
|
||||||
|
if m.extPort == 0 {
|
||||||
log.Debug("Couldn't add port mapping", "err", err)
|
log.Debug("Couldn't add port mapping", "err", err)
|
||||||
|
} else {
|
||||||
|
// Failed refresh. Since UPnP implementation are often buggy,
|
||||||
|
// and lifetime is larger than the retry interval, this does not
|
||||||
|
// mean we lost our existing mapping. We do not reset the external
|
||||||
|
// port, as it is still our best chance, but we do retry soon.
|
||||||
|
// We could check the error code, but UPnP implementations are buggy.
|
||||||
|
log.Debug("Couldn't refresh port mapping", "err", err)
|
||||||
|
m.retries++
|
||||||
|
if m.retries > maxRetries {
|
||||||
|
m.retries = 0
|
||||||
|
err := srv.NAT.DeleteMapping(m.protocol, m.extPort, m.port)
|
||||||
|
log.Debug("Couldn't refresh port mapping, trying to delete it:", "err", err)
|
||||||
m.extPort = 0
|
m.extPort = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
m.nextTime = srv.clock.Now().Add(portMapRetryInterval)
|
m.nextTime = srv.clock.Now().Add(portMapRetryInterval)
|
||||||
|
// Note ENR is not updated here, i.e. we keep the last port.
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// It was mapped!
|
// It was mapped!
|
||||||
|
m.retries = 0
|
||||||
|
log = newLogger(m.protocol, int(p), m.port)
|
||||||
|
if int(p) != m.extPort {
|
||||||
m.extPort = int(p)
|
m.extPort = int(p)
|
||||||
m.nextTime = srv.clock.Now().Add(portMapRefreshInterval)
|
if m.port != m.extPort {
|
||||||
if external != m.extPort {
|
|
||||||
log = newLogger(m.protocol, m.extPort, m.port)
|
|
||||||
log.Info("NAT mapped alternative port")
|
log.Info("NAT mapped alternative port")
|
||||||
} else {
|
} else {
|
||||||
log.Info("NAT mapped port")
|
log.Info("NAT mapped port")
|
||||||
|
|
@ -182,6 +198,8 @@ func (srv *Server) portMappingLoop() {
|
||||||
srv.localnode.SetFallbackUDP(m.extPort)
|
srv.localnode.SetFallbackUDP(m.extPort)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
m.nextTime = srv.clock.Now().Add(portMapRefreshInterval)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -63,11 +63,11 @@ type jsonWriter interface {
|
||||||
type BlockNumber int64
|
type BlockNumber int64
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
EarliestBlockNumber = BlockNumber(-5)
|
||||||
SafeBlockNumber = BlockNumber(-4)
|
SafeBlockNumber = BlockNumber(-4)
|
||||||
FinalizedBlockNumber = BlockNumber(-3)
|
FinalizedBlockNumber = BlockNumber(-3)
|
||||||
LatestBlockNumber = BlockNumber(-2)
|
LatestBlockNumber = BlockNumber(-2)
|
||||||
PendingBlockNumber = BlockNumber(-1)
|
PendingBlockNumber = BlockNumber(-1)
|
||||||
EarliestBlockNumber = BlockNumber(0)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports:
|
// UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports:
|
||||||
|
|
|
||||||
|
|
@ -84,7 +84,12 @@ func fuzz(input []byte) int {
|
||||||
},
|
},
|
||||||
func(string, []common.Hash) error { return nil },
|
func(string, []common.Hash) error { return nil },
|
||||||
nil,
|
nil,
|
||||||
clock, rand,
|
clock,
|
||||||
|
func() time.Time {
|
||||||
|
nanoTime := int64(clock.Now())
|
||||||
|
return time.Unix(nanoTime/1000000000, nanoTime%1000000000)
|
||||||
|
},
|
||||||
|
rand,
|
||||||
)
|
)
|
||||||
f.Start()
|
f.Start()
|
||||||
defer f.Stop()
|
defer f.Stop()
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,8 @@ import (
|
||||||
// the combined trie node set from several aggregated state transitions.
|
// the combined trie node set from several aggregated state transitions.
|
||||||
type nodeSet struct {
|
type nodeSet struct {
|
||||||
size uint64 // aggregated size of the trie node
|
size uint64 // aggregated size of the trie node
|
||||||
nodes map[common.Hash]map[string]*trienode.Node // node set, mapped by owner and path
|
accountNodes map[string]*trienode.Node // account trie nodes, mapped by path
|
||||||
|
storageNodes map[common.Hash]map[string]*trienode.Node // storage trie nodes, mapped by owner and path
|
||||||
}
|
}
|
||||||
|
|
||||||
// newNodeSet constructs the set with the provided dirty trie nodes.
|
// newNodeSet constructs the set with the provided dirty trie nodes.
|
||||||
|
|
@ -46,7 +47,17 @@ func newNodeSet(nodes map[common.Hash]map[string]*trienode.Node) *nodeSet {
|
||||||
if nodes == nil {
|
if nodes == nil {
|
||||||
nodes = make(map[common.Hash]map[string]*trienode.Node)
|
nodes = make(map[common.Hash]map[string]*trienode.Node)
|
||||||
}
|
}
|
||||||
s := &nodeSet{nodes: nodes}
|
s := &nodeSet{
|
||||||
|
accountNodes: make(map[string]*trienode.Node),
|
||||||
|
storageNodes: make(map[common.Hash]map[string]*trienode.Node),
|
||||||
|
}
|
||||||
|
for owner, subset := range nodes {
|
||||||
|
if owner == (common.Hash{}) {
|
||||||
|
s.accountNodes = subset
|
||||||
|
} else {
|
||||||
|
s.storageNodes[owner] = subset
|
||||||
|
}
|
||||||
|
}
|
||||||
s.computeSize()
|
s.computeSize()
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
@ -54,13 +65,12 @@ func newNodeSet(nodes map[common.Hash]map[string]*trienode.Node) *nodeSet {
|
||||||
// computeSize calculates the database size of the held trie nodes.
|
// computeSize calculates the database size of the held trie nodes.
|
||||||
func (s *nodeSet) computeSize() {
|
func (s *nodeSet) computeSize() {
|
||||||
var size uint64
|
var size uint64
|
||||||
for owner, subset := range s.nodes {
|
for path, n := range s.accountNodes {
|
||||||
var prefix int
|
size += uint64(len(n.Blob) + len(path))
|
||||||
if owner != (common.Hash{}) {
|
|
||||||
prefix = common.HashLength // owner (32 bytes) for storage trie nodes
|
|
||||||
}
|
}
|
||||||
|
for _, subset := range s.storageNodes {
|
||||||
for path, n := range subset {
|
for path, n := range subset {
|
||||||
size += uint64(prefix + len(n.Blob) + len(path))
|
size += uint64(common.HashLength + len(n.Blob) + len(path))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
s.size = size
|
s.size = size
|
||||||
|
|
@ -79,15 +89,18 @@ func (s *nodeSet) updateSize(delta int64) {
|
||||||
|
|
||||||
// node retrieves the trie node with node path and its trie identifier.
|
// node retrieves the trie node with node path and its trie identifier.
|
||||||
func (s *nodeSet) node(owner common.Hash, path []byte) (*trienode.Node, bool) {
|
func (s *nodeSet) node(owner common.Hash, path []byte) (*trienode.Node, bool) {
|
||||||
subset, ok := s.nodes[owner]
|
// Account trie node
|
||||||
|
if owner == (common.Hash{}) {
|
||||||
|
n, ok := s.accountNodes[string(path)]
|
||||||
|
return n, ok
|
||||||
|
}
|
||||||
|
// Storage trie node
|
||||||
|
subset, ok := s.storageNodes[owner]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
n, ok := subset[string(path)]
|
n, ok := subset[string(path)]
|
||||||
if !ok {
|
return n, ok
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
return n, true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// merge integrates the provided dirty nodes into the set. The provided nodeset
|
// merge integrates the provided dirty nodes into the set. The provided nodeset
|
||||||
|
|
@ -97,15 +110,24 @@ func (s *nodeSet) merge(set *nodeSet) {
|
||||||
delta int64 // size difference resulting from node merging
|
delta int64 // size difference resulting from node merging
|
||||||
overwrite counter // counter of nodes being overwritten
|
overwrite counter // counter of nodes being overwritten
|
||||||
)
|
)
|
||||||
for owner, subset := range set.nodes {
|
|
||||||
var prefix int
|
// Merge account nodes
|
||||||
if owner != (common.Hash{}) {
|
for path, n := range set.accountNodes {
|
||||||
prefix = common.HashLength
|
if orig, exist := s.accountNodes[path]; !exist {
|
||||||
|
delta += int64(len(n.Blob) + len(path))
|
||||||
|
} else {
|
||||||
|
delta += int64(len(n.Blob) - len(orig.Blob))
|
||||||
|
overwrite.add(len(orig.Blob) + len(path))
|
||||||
}
|
}
|
||||||
current, exist := s.nodes[owner]
|
s.accountNodes[path] = n
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge storage nodes
|
||||||
|
for owner, subset := range set.storageNodes {
|
||||||
|
current, exist := s.storageNodes[owner]
|
||||||
if !exist {
|
if !exist {
|
||||||
for path, n := range subset {
|
for path, n := range subset {
|
||||||
delta += int64(prefix + len(n.Blob) + len(path))
|
delta += int64(common.HashLength + len(n.Blob) + len(path))
|
||||||
}
|
}
|
||||||
// Perform a shallow copy of the map for the subset instead of claiming it
|
// Perform a shallow copy of the map for the subset instead of claiming it
|
||||||
// directly from the provided nodeset to avoid potential concurrent map
|
// directly from the provided nodeset to avoid potential concurrent map
|
||||||
|
|
@ -113,19 +135,19 @@ func (s *nodeSet) merge(set *nodeSet) {
|
||||||
// accessible even after merging. Therefore, ownership of the nodes map
|
// accessible even after merging. Therefore, ownership of the nodes map
|
||||||
// should still belong to the original layer, and any modifications to it
|
// should still belong to the original layer, and any modifications to it
|
||||||
// should be prevented.
|
// should be prevented.
|
||||||
s.nodes[owner] = maps.Clone(subset)
|
s.storageNodes[owner] = maps.Clone(subset)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for path, n := range subset {
|
for path, n := range subset {
|
||||||
if orig, exist := current[path]; !exist {
|
if orig, exist := current[path]; !exist {
|
||||||
delta += int64(prefix + len(n.Blob) + len(path))
|
delta += int64(common.HashLength + len(n.Blob) + len(path))
|
||||||
} else {
|
} else {
|
||||||
delta += int64(len(n.Blob) - len(orig.Blob))
|
delta += int64(len(n.Blob) - len(orig.Blob))
|
||||||
overwrite.add(prefix + len(orig.Blob) + len(path))
|
overwrite.add(common.HashLength + len(orig.Blob) + len(path))
|
||||||
}
|
}
|
||||||
current[path] = n
|
current[path] = n
|
||||||
}
|
}
|
||||||
s.nodes[owner] = current
|
s.storageNodes[owner] = current
|
||||||
}
|
}
|
||||||
overwrite.report(gcTrieNodeMeter, gcTrieNodeBytesMeter)
|
overwrite.report(gcTrieNodeMeter, gcTrieNodeBytesMeter)
|
||||||
s.updateSize(delta)
|
s.updateSize(delta)
|
||||||
|
|
@ -136,36 +158,40 @@ func (s *nodeSet) merge(set *nodeSet) {
|
||||||
func (s *nodeSet) revertTo(db ethdb.KeyValueReader, nodes map[common.Hash]map[string]*trienode.Node) {
|
func (s *nodeSet) revertTo(db ethdb.KeyValueReader, nodes map[common.Hash]map[string]*trienode.Node) {
|
||||||
var delta int64
|
var delta int64
|
||||||
for owner, subset := range nodes {
|
for owner, subset := range nodes {
|
||||||
current, ok := s.nodes[owner]
|
if owner == (common.Hash{}) {
|
||||||
|
// Account trie nodes
|
||||||
|
for path, n := range subset {
|
||||||
|
orig, ok := s.accountNodes[path]
|
||||||
|
if !ok {
|
||||||
|
blob := rawdb.ReadAccountTrieNode(db, []byte(path))
|
||||||
|
if bytes.Equal(blob, n.Blob) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
panic(fmt.Sprintf("non-existent account node (%v) blob: %v", path, crypto.Keccak256Hash(n.Blob).Hex()))
|
||||||
|
}
|
||||||
|
s.accountNodes[path] = n
|
||||||
|
delta += int64(len(n.Blob)) - int64(len(orig.Blob))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Storage trie nodes
|
||||||
|
current, ok := s.storageNodes[owner]
|
||||||
if !ok {
|
if !ok {
|
||||||
panic(fmt.Sprintf("non-existent subset (%x)", owner))
|
panic(fmt.Sprintf("non-existent subset (%x)", owner))
|
||||||
}
|
}
|
||||||
for path, n := range subset {
|
for path, n := range subset {
|
||||||
orig, ok := current[path]
|
orig, ok := current[path]
|
||||||
if !ok {
|
if !ok {
|
||||||
// There is a special case in merkle tree that one child is removed
|
blob := rawdb.ReadStorageTrieNode(db, owner, []byte(path))
|
||||||
// from a fullNode which only has two children, and then a new child
|
|
||||||
// with different position is immediately inserted into the fullNode.
|
|
||||||
// In this case, the clean child of the fullNode will also be marked
|
|
||||||
// as dirty because of node collapse and expansion. In case of database
|
|
||||||
// rollback, don't panic if this "clean" node occurs which is not
|
|
||||||
// present in buffer.
|
|
||||||
var blob []byte
|
|
||||||
if owner == (common.Hash{}) {
|
|
||||||
blob = rawdb.ReadAccountTrieNode(db, []byte(path))
|
|
||||||
} else {
|
|
||||||
blob = rawdb.ReadStorageTrieNode(db, owner, []byte(path))
|
|
||||||
}
|
|
||||||
// Ignore the clean node in the case described above.
|
|
||||||
if bytes.Equal(blob, n.Blob) {
|
if bytes.Equal(blob, n.Blob) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
panic(fmt.Sprintf("non-existent node (%x %v) blob: %v", owner, path, crypto.Keccak256Hash(n.Blob).Hex()))
|
panic(fmt.Sprintf("non-existent storage node (%x %v) blob: %v", owner, path, crypto.Keccak256Hash(n.Blob).Hex()))
|
||||||
}
|
}
|
||||||
current[path] = n
|
current[path] = n
|
||||||
delta += int64(len(n.Blob)) - int64(len(orig.Blob))
|
delta += int64(len(n.Blob)) - int64(len(orig.Blob))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
s.updateSize(delta)
|
s.updateSize(delta)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -184,8 +210,21 @@ type journalNodes struct {
|
||||||
|
|
||||||
// encode serializes the content of trie nodes into the provided writer.
|
// encode serializes the content of trie nodes into the provided writer.
|
||||||
func (s *nodeSet) encode(w io.Writer) error {
|
func (s *nodeSet) encode(w io.Writer) error {
|
||||||
nodes := make([]journalNodes, 0, len(s.nodes))
|
nodes := make([]journalNodes, 0, len(s.storageNodes)+1)
|
||||||
for owner, subset := range s.nodes {
|
|
||||||
|
// Encode account nodes
|
||||||
|
if len(s.accountNodes) > 0 {
|
||||||
|
entry := journalNodes{Owner: common.Hash{}}
|
||||||
|
for path, node := range s.accountNodes {
|
||||||
|
entry.Nodes = append(entry.Nodes, journalNode{
|
||||||
|
Path: []byte(path),
|
||||||
|
Blob: node.Blob,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
nodes = append(nodes, entry)
|
||||||
|
}
|
||||||
|
// Encode storage nodes
|
||||||
|
for owner, subset := range s.storageNodes {
|
||||||
entry := journalNodes{Owner: owner}
|
entry := journalNodes{Owner: owner}
|
||||||
for path, node := range subset {
|
for path, node := range subset {
|
||||||
entry.Nodes = append(entry.Nodes, journalNode{
|
entry.Nodes = append(entry.Nodes, journalNode{
|
||||||
|
|
@ -204,8 +243,21 @@ func (s *nodeSet) decode(r *rlp.Stream) error {
|
||||||
if err := r.Decode(&encoded); err != nil {
|
if err := r.Decode(&encoded); err != nil {
|
||||||
return fmt.Errorf("load nodes: %v", err)
|
return fmt.Errorf("load nodes: %v", err)
|
||||||
}
|
}
|
||||||
nodes := make(map[common.Hash]map[string]*trienode.Node)
|
s.accountNodes = make(map[string]*trienode.Node)
|
||||||
|
s.storageNodes = make(map[common.Hash]map[string]*trienode.Node)
|
||||||
|
|
||||||
for _, entry := range encoded {
|
for _, entry := range encoded {
|
||||||
|
if entry.Owner == (common.Hash{}) {
|
||||||
|
// Account nodes
|
||||||
|
for _, n := range entry.Nodes {
|
||||||
|
if len(n.Blob) > 0 {
|
||||||
|
s.accountNodes[string(n.Path)] = trienode.New(crypto.Keccak256Hash(n.Blob), n.Blob)
|
||||||
|
} else {
|
||||||
|
s.accountNodes[string(n.Path)] = trienode.NewDeleted()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Storage nodes
|
||||||
subset := make(map[string]*trienode.Node)
|
subset := make(map[string]*trienode.Node)
|
||||||
for _, n := range entry.Nodes {
|
for _, n := range entry.Nodes {
|
||||||
if len(n.Blob) > 0 {
|
if len(n.Blob) > 0 {
|
||||||
|
|
@ -214,33 +266,38 @@ func (s *nodeSet) decode(r *rlp.Stream) error {
|
||||||
subset[string(n.Path)] = trienode.NewDeleted()
|
subset[string(n.Path)] = trienode.NewDeleted()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
nodes[entry.Owner] = subset
|
s.storageNodes[entry.Owner] = subset
|
||||||
|
}
|
||||||
}
|
}
|
||||||
s.nodes = nodes
|
|
||||||
s.computeSize()
|
s.computeSize()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// write flushes nodes into the provided database batch as a whole.
|
// write flushes nodes into the provided database batch as a whole.
|
||||||
func (s *nodeSet) write(batch ethdb.Batch, clean *fastcache.Cache) int {
|
func (s *nodeSet) write(batch ethdb.Batch, clean *fastcache.Cache) int {
|
||||||
return writeNodes(batch, s.nodes, clean)
|
nodes := make(map[common.Hash]map[string]*trienode.Node)
|
||||||
|
if len(s.accountNodes) > 0 {
|
||||||
|
nodes[common.Hash{}] = s.accountNodes
|
||||||
|
}
|
||||||
|
for owner, subset := range s.storageNodes {
|
||||||
|
nodes[owner] = subset
|
||||||
|
}
|
||||||
|
return writeNodes(batch, nodes, clean)
|
||||||
}
|
}
|
||||||
|
|
||||||
// reset clears all cached trie node data.
|
// reset clears all cached trie node data.
|
||||||
func (s *nodeSet) reset() {
|
func (s *nodeSet) reset() {
|
||||||
s.nodes = make(map[common.Hash]map[string]*trienode.Node)
|
s.accountNodes = make(map[string]*trienode.Node)
|
||||||
|
s.storageNodes = make(map[common.Hash]map[string]*trienode.Node)
|
||||||
s.size = 0
|
s.size = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// dbsize returns the approximate size of db write.
|
// dbsize returns the approximate size of db write.
|
||||||
func (s *nodeSet) dbsize() int {
|
func (s *nodeSet) dbsize() int {
|
||||||
var m int
|
var m int
|
||||||
for owner, nodes := range s.nodes {
|
m += len(s.accountNodes) * len(rawdb.TrieNodeAccountPrefix) // database key prefix
|
||||||
if owner == (common.Hash{}) {
|
for _, nodes := range s.storageNodes {
|
||||||
m += len(nodes) * len(rawdb.TrieNodeAccountPrefix) // database key prefix
|
|
||||||
} else {
|
|
||||||
m += len(nodes) * (len(rawdb.TrieNodeStoragePrefix)) // database key prefix
|
m += len(nodes) * (len(rawdb.TrieNodeStoragePrefix)) // database key prefix
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return m + int(s.size)
|
return m + int(s.size)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,6 @@ package version
|
||||||
const (
|
const (
|
||||||
Major = 1 // Major version component of the current release
|
Major = 1 // Major version component of the current release
|
||||||
Minor = 15 // Minor version component of the current release
|
Minor = 15 // Minor version component of the current release
|
||||||
Patch = 7 // Patch version component of the current release
|
Patch = 8 // Patch version component of the current release
|
||||||
Meta = "stable" // Version metadata to append to the version string
|
Meta = "stable" // Version metadata to append to the version string
|
||||||
)
|
)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue