dev: fix: thelper and tparallel lint

This commit is contained in:
marcello33 2023-06-14 16:29:26 +02:00
parent f1e7f6db28
commit 631efbe675
82 changed files with 990 additions and 222 deletions

View file

@ -1345,6 +1345,8 @@ func TestForkResendTx(t *testing.T) {
} }
func TestCommitReturnValue(t *testing.T) { func TestCommitReturnValue(t *testing.T) {
t.Parallel()
testAddr := crypto.PubkeyToAddress(testKey.PublicKey) testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
sim := simTestBackend(testAddr) sim := simTestBackend(testAddr)
defer sim.Close() defer sim.Close()
@ -1386,6 +1388,8 @@ func TestCommitReturnValue(t *testing.T) {
// TestAdjustTimeAfterFork ensures that after a fork, AdjustTime uses the pending fork // TestAdjustTimeAfterFork ensures that after a fork, AdjustTime uses the pending fork
// block's parent rather than the canonical head's parent. // block's parent rather than the canonical head's parent.
func TestAdjustTimeAfterFork(t *testing.T) { func TestAdjustTimeAfterFork(t *testing.T) {
t.Parallel()
testAddr := crypto.PubkeyToAddress(testKey.PublicKey) testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
sim := simTestBackend(testAddr) sim := simTestBackend(testAddr)
defer sim.Close() defer sim.Close()

View file

@ -115,6 +115,8 @@ func (mc *mockPendingCaller) PendingCallContract(ctx context.Context, call ether
} }
func TestPassingBlockNumber(t *testing.T) { func TestPassingBlockNumber(t *testing.T) {
t.Parallel()
mc := &mockPendingCaller{ mc := &mockPendingCaller{
mockCaller: &mockCaller{ mockCaller: &mockCaller{
codeAtBytes: []byte{1, 2, 3}, codeAtBytes: []byte{1, 2, 3},
@ -187,6 +189,8 @@ func TestUnpackIndexedStringTyLogIntoMap(t *testing.T) {
} }
func TestUnpackAnonymousLogIntoMap(t *testing.T) { func TestUnpackAnonymousLogIntoMap(t *testing.T) {
t.Parallel()
mockLog := newMockLog(nil, common.HexToHash("0x0")) mockLog := newMockLog(nil, common.HexToHash("0x0"))
abiString := `[{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"received","type":"event"}]` abiString := `[{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"received","type":"event"}]`
@ -377,6 +381,8 @@ func newMockLog(topics []common.Hash, txHash common.Hash) types.Log {
} }
func TestCall(t *testing.T) { func TestCall(t *testing.T) {
t.Parallel()
var method, methodWithArg = "something", "somethingArrrrg" var method, methodWithArg = "something", "somethingArrrrg"
tests := []struct { tests := []struct {
name, method string name, method string
@ -507,6 +513,8 @@ func TestCall(t *testing.T) {
// TestCrashers contains some strings which previously caused the abi codec to crash. // TestCrashers contains some strings which previously caused the abi codec to crash.
func TestCrashers(t *testing.T) { func TestCrashers(t *testing.T) {
t.Parallel()
abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"_1"}]}]}]`)) abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"_1"}]}]}]`))
abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"&"}]}]}]`)) abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"&"}]}]}]`))
abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"----"}]}]}]`)) abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"----"}]}]}]`))

View file

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

View file

@ -946,6 +946,8 @@ func TestOOMMaliciousInput(t *testing.T) {
} }
func TestPackAndUnpackIncompatibleNumber(t *testing.T) { func TestPackAndUnpackIncompatibleNumber(t *testing.T) {
t.Parallel()
var encodeABI Arguments var encodeABI Arguments
uint256Ty, err := NewType("uint256", "", nil) uint256Ty, err := NewType("uint256", "", nil)
if err != nil { if err != nil {

View file

@ -8,6 +8,8 @@ import (
) )
func TestNameFilter(t *testing.T) { func TestNameFilter(t *testing.T) {
t.Parallel()
_, err := newNameFilter("Foo") _, err := newNameFilter("Foo")
require.Error(t, err) require.Error(t, err)
_, err = newNameFilter("too/many:colons:Foo") _, err = newNameFilter("too/many:colons:Foo")

View file

@ -31,7 +31,9 @@ func TestImportRaw(t *testing.T) {
t.Cleanup(func() { os.Remove(keyPath) }) t.Cleanup(func() { os.Remove(keyPath) })
t.Parallel() t.Parallel()
t.Run("happy-path", func(t *testing.T) { t.Run("happy-path", func(t *testing.T) {
t.Parallel()
// Run clef importraw // Run clef importraw
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath) clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath)
clef.input("myverylongpassword").input("myverylongpassword") clef.input("myverylongpassword").input("myverylongpassword")
@ -43,6 +45,7 @@ func TestImportRaw(t *testing.T) {
}) })
// tests clef --importraw with mismatched passwords. // tests clef --importraw with mismatched passwords.
t.Run("pw-mismatch", func(t *testing.T) { t.Run("pw-mismatch", func(t *testing.T) {
t.Parallel()
// Run clef importraw // Run clef importraw
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath) clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath)
clef.input("myverylongpassword1").input("myverylongpassword2").WaitExit() clef.input("myverylongpassword1").input("myverylongpassword2").WaitExit()
@ -52,6 +55,7 @@ func TestImportRaw(t *testing.T) {
}) })
// tests clef --importraw with a too short password. // tests clef --importraw with a too short password.
t.Run("short-pw", func(t *testing.T) { t.Run("short-pw", func(t *testing.T) {
t.Parallel()
// Run clef importraw // Run clef importraw
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath) clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath)
clef.input("shorty").input("shorty").WaitExit() clef.input("shorty").input("shorty").WaitExit()
@ -69,7 +73,9 @@ func TestListAccounts(t *testing.T) {
t.Cleanup(func() { os.Remove(keyPath) }) t.Cleanup(func() { os.Remove(keyPath) })
t.Parallel() t.Parallel()
t.Run("no-accounts", func(t *testing.T) { t.Run("no-accounts", func(t *testing.T) {
t.Parallel()
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "list-accounts") clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "list-accounts")
if out := string(clef.Output()); !strings.Contains(out, "The keystore is empty.") { if out := string(clef.Output()); !strings.Contains(out, "The keystore is empty.") {
t.Logf("Output\n%v", out) t.Logf("Output\n%v", out)
@ -77,6 +83,7 @@ func TestListAccounts(t *testing.T) {
} }
}) })
t.Run("one-account", func(t *testing.T) { t.Run("one-account", func(t *testing.T) {
t.Parallel()
// First, we need to import // First, we need to import
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath) clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath)
clef.input("myverylongpassword").input("myverylongpassword").WaitExit() clef.input("myverylongpassword").input("myverylongpassword").WaitExit()
@ -96,7 +103,9 @@ func TestListWallets(t *testing.T) {
t.Cleanup(func() { os.Remove(keyPath) }) t.Cleanup(func() { os.Remove(keyPath) })
t.Parallel() t.Parallel()
t.Run("no-accounts", func(t *testing.T) { t.Run("no-accounts", func(t *testing.T) {
t.Parallel()
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "list-wallets") clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "list-wallets")
if out := string(clef.Output()); !strings.Contains(out, "There are no wallets.") { if out := string(clef.Output()); !strings.Contains(out, "There are no wallets.") {
t.Logf("Output\n%v", out) t.Logf("Output\n%v", out)
@ -104,6 +113,7 @@ func TestListWallets(t *testing.T) {
} }
}) })
t.Run("one-account", func(t *testing.T) { t.Run("one-account", func(t *testing.T) {
t.Parallel()
// First, we need to import // First, we need to import
clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath) clef := runClef(t, "--suppress-bootwarn", "--lightkdf", "importraw", keyPath)
clef.input("myverylongpassword").input("myverylongpassword").WaitExit() clef.input("myverylongpassword").input("myverylongpassword").WaitExit()

View file

@ -57,6 +57,8 @@ func TestMain(m *testing.M) {
// This method creates a temporary keystore folder which will be removed after // This method creates a temporary keystore folder which will be removed after
// the test exits. // the test exits.
func runClef(t *testing.T, args ...string) *testproc { func runClef(t *testing.T, args ...string) *testproc {
t.Helper()
ddir, err := os.MkdirTemp("", "cleftest-*") ddir, err := os.MkdirTemp("", "cleftest-*")
if err != nil { if err != nil {
return nil return nil
@ -71,6 +73,8 @@ func runClef(t *testing.T, args ...string) *testproc {
// This method does _not_ create the keystore folder, but it _does_ add the arg // This method does _not_ create the keystore folder, but it _does_ add the arg
// to the args. // to the args.
func runWithKeystore(t *testing.T, keystore string, args ...string) *testproc { func runWithKeystore(t *testing.T, keystore string, args ...string) *testproc {
t.Helper()
args = append([]string{"--keystore", keystore}, args...) args = append([]string{"--keystore", keystore}, args...)
tt := &testproc{Datadir: keystore} tt := &testproc{Datadir: keystore}
tt.TestCmd = cmdtest.NewTestCmd(t, tt) tt.TestCmd = cmdtest.NewTestCmd(t, tt)

View file

@ -118,6 +118,8 @@ func TestAccountImport(t *testing.T) {
} }
func TestAccountHelp(t *testing.T) { func TestAccountHelp(t *testing.T) {
t.Parallel()
geth := runGeth(t, "account", "-h") geth := runGeth(t, "account", "-h")
geth.WaitExit() geth.WaitExit()
if have, want := geth.ExitStatus(), 0; have != want { if have, want := geth.ExitStatus(), 0; have != want {

View file

@ -61,6 +61,8 @@ func TestRemoteDbWithHeaders(t *testing.T) {
} }
func testReceiveHeaders(t *testing.T, ln net.Listener, gethArgs ...string) { func testReceiveHeaders(t *testing.T, ln net.Listener, gethArgs ...string) {
t.Helper()
var ok uint32 var ok uint32
server := &http.Server{ server := &http.Server{
Addr: "localhost:0", Addr: "localhost:0",

View file

@ -27,6 +27,8 @@ import (
// TestExport does a basic test of "geth export", exporting the test-genesis. // TestExport does a basic test of "geth export", exporting the test-genesis.
func TestExport(t *testing.T) { func TestExport(t *testing.T) {
t.Parallel()
outfile := fmt.Sprintf("%v/testExport.out", os.TempDir()) outfile := fmt.Sprintf("%v/testExport.out", os.TempDir())
defer os.Remove(outfile) defer os.Remove(outfile)
geth := runGeth(t, "--datadir", initGeth(t), "export", outfile) geth := runGeth(t, "--datadir", initGeth(t), "export", outfile)

View file

@ -102,6 +102,8 @@ func TestBasicLRU(t *testing.T) {
} }
func TestBasicLRUAddExistingKey(t *testing.T) { func TestBasicLRUAddExistingKey(t *testing.T) {
t.Parallel()
cache := NewBasicLRU[int, int](1) cache := NewBasicLRU[int, int](1)
cache.Add(1, 1) cache.Add(1, 1)
@ -115,6 +117,8 @@ func TestBasicLRUAddExistingKey(t *testing.T) {
// This test checks GetOldest and RemoveOldest. // This test checks GetOldest and RemoveOldest.
func TestBasicLRUGetOldest(t *testing.T) { func TestBasicLRUGetOldest(t *testing.T) {
t.Parallel()
cache := NewBasicLRU[int, int](128) cache := NewBasicLRU[int, int](128)
for i := 0; i < 256; i++ { for i := 0; i < 256; i++ {
cache.Add(i, i) cache.Add(i, i)
@ -147,6 +151,8 @@ func TestBasicLRUGetOldest(t *testing.T) {
// Test that Add returns true/false if an eviction occurred // Test that Add returns true/false if an eviction occurred
func TestBasicLRUAddReturnValue(t *testing.T) { func TestBasicLRUAddReturnValue(t *testing.T) {
t.Parallel()
cache := NewBasicLRU[int, int](1) cache := NewBasicLRU[int, int](1)
if cache.Add(1, 1) { if cache.Add(1, 1) {
t.Errorf("first add shouldn't have evicted") t.Errorf("first add shouldn't have evicted")
@ -158,6 +164,8 @@ func TestBasicLRUAddReturnValue(t *testing.T) {
// This test verifies that Contains doesn't change item recency. // This test verifies that Contains doesn't change item recency.
func TestBasicLRUContains(t *testing.T) { func TestBasicLRUContains(t *testing.T) {
t.Parallel()
cache := NewBasicLRU[int, int](2) cache := NewBasicLRU[int, int](2)
cache.Add(1, 1) cache.Add(1, 1)
cache.Add(2, 2) cache.Add(2, 2)

View file

@ -30,6 +30,8 @@ func mkKey(i int) (key testKey) {
} }
func TestSizeConstrainedCache(t *testing.T) { func TestSizeConstrainedCache(t *testing.T) {
t.Parallel()
lru := NewSizeConstrainedCache[testKey, []byte](100) lru := NewSizeConstrainedCache[testKey, []byte](100)
var want uint64 var want uint64
// Add 11 items of 10 byte each. First item should be swapped out // Add 11 items of 10 byte each. First item should be swapped out
@ -68,6 +70,8 @@ func TestSizeConstrainedCache(t *testing.T) {
// This test adds inserting an element exceeding the max size. // This test adds inserting an element exceeding the max size.
func TestSizeConstrainedCacheOverflow(t *testing.T) { func TestSizeConstrainedCacheOverflow(t *testing.T) {
t.Parallel()
lru := NewSizeConstrainedCache[testKey, []byte](100) lru := NewSizeConstrainedCache[testKey, []byte](100)
// Add 10 items of 10 byte each, filling the cache // Add 10 items of 10 byte each, filling the cache
@ -107,6 +111,8 @@ func TestSizeConstrainedCacheOverflow(t *testing.T) {
// This checks what happens when inserting the same k/v multiple times. // This checks what happens when inserting the same k/v multiple times.
func TestSizeConstrainedCacheSameItem(t *testing.T) { func TestSizeConstrainedCacheSameItem(t *testing.T) {
t.Parallel()
lru := NewSizeConstrainedCache[testKey, []byte](100) lru := NewSizeConstrainedCache[testKey, []byte](100)
// Add one 10 byte-item 10 times. // Add one 10 byte-item 10 times.
@ -124,6 +130,8 @@ func TestSizeConstrainedCacheSameItem(t *testing.T) {
// This tests that empty/nil values are handled correctly. // This tests that empty/nil values are handled correctly.
func TestSizeConstrainedCacheEmpties(t *testing.T) { func TestSizeConstrainedCacheEmpties(t *testing.T) {
t.Parallel()
lru := NewSizeConstrainedCache[testKey, []byte](100) lru := NewSizeConstrainedCache[testKey, []byte](100)
// This test abuses the lru a bit, using different keys for identical value(s). // This test abuses the lru a bit, using different keys for identical value(s).

View file

@ -20,6 +20,8 @@ import "testing"
// This test checks basic functionality of Alarm. // This test checks basic functionality of Alarm.
func TestAlarm(t *testing.T) { func TestAlarm(t *testing.T) {
t.Parallel()
clk := new(Simulated) clk := new(Simulated)
clk.Run(20) clk.Run(20)
a := NewAlarm(clk) a := NewAlarm(clk)
@ -64,6 +66,8 @@ func TestAlarm(t *testing.T) {
// This test checks that scheduling an Alarm to an earlier time than the // This test checks that scheduling an Alarm to an earlier time than the
// one already scheduled works properly. // one already scheduled works properly.
func TestAlarmScheduleEarlier(t *testing.T) { func TestAlarmScheduleEarlier(t *testing.T) {
t.Parallel()
clk := new(Simulated) clk := new(Simulated)
clk.Run(20) clk.Run(20)
a := NewAlarm(clk) a := NewAlarm(clk)
@ -80,6 +84,8 @@ func TestAlarmScheduleEarlier(t *testing.T) {
// This test checks that scheduling an Alarm to a later time than the // This test checks that scheduling an Alarm to a later time than the
// one already scheduled works properly. // one already scheduled works properly.
func TestAlarmScheduleLater(t *testing.T) { func TestAlarmScheduleLater(t *testing.T) {
t.Parallel()
clk := new(Simulated) clk := new(Simulated)
clk.Run(20) clk.Run(20)
a := NewAlarm(clk) a := NewAlarm(clk)
@ -95,6 +101,8 @@ func TestAlarmScheduleLater(t *testing.T) {
// This test checks that scheduling an Alarm in the past makes it fire immediately. // This test checks that scheduling an Alarm in the past makes it fire immediately.
func TestAlarmNegative(t *testing.T) { func TestAlarmNegative(t *testing.T) {
t.Parallel()
clk := new(Simulated) clk := new(Simulated)
clk.Run(50) clk.Run(50)
a := NewAlarm(clk) a := NewAlarm(clk)

View file

@ -40,6 +40,8 @@ func TestStorageSizeString(t *testing.T) {
} }
func TestStorageSizeTerminalString(t *testing.T) { func TestStorageSizeTerminalString(t *testing.T) {
t.Parallel()
tests := []struct { tests := []struct {
size StorageSize size StorageSize
str string str string

View file

@ -161,6 +161,8 @@ func BenchmarkAddressHex(b *testing.B) {
// but not the pointer level, so that this customized marshalled can be used // but not the pointer level, so that this customized marshalled can be used
// for both MixedcaseAddress object and pointer. // for both MixedcaseAddress object and pointer.
func TestMixedcaseAddressMarshal(t *testing.T) { func TestMixedcaseAddressMarshal(t *testing.T) {
t.Parallel()
var ( var (
output string output string
input = "0xae967917c465db8578ca9024c205720b1a3651A9" input = "0xae967917c465db8578ca9024c205720b1a3651A9"

View file

@ -183,7 +183,7 @@ type lru[T cacheOrDataset] struct {
// newlru create a new least-recently-used cache for either the verification caches // newlru create a new least-recently-used cache for either the verification caches
// or the mining datasets. // or the mining datasets.
func newlru[T cacheOrDataset](maxItems int, new func(epoch uint64) T) *lru[T] { func newlru[T cacheOrDataset](maxItems int, newLru func(epoch uint64) T) *lru[T] {
var what string var what string
switch any(T(nil)).(type) { switch any(T(nil)).(type) {
case *cache: case *cache:
@ -195,7 +195,7 @@ func newlru[T cacheOrDataset](maxItems int, new func(epoch uint64) T) *lru[T] {
} }
return &lru[T]{ return &lru[T]{
what: what, what: what,
new: new, new: newLru,
cache: lrupkg.NewBasicLRU[uint64, T](maxItems), cache: lrupkg.NewBasicLRU[uint64, T](maxItems),
} }
} }

View file

@ -25,6 +25,8 @@ import (
) )
func TestCalcBlobFee(t *testing.T) { func TestCalcBlobFee(t *testing.T) {
t.Parallel()
tests := []struct { tests := []struct {
excessDataGas int64 excessDataGas int64
blobfee int64 blobfee int64
@ -47,6 +49,8 @@ func TestCalcBlobFee(t *testing.T) {
} }
func TestFakeExponential(t *testing.T) { func TestFakeExponential(t *testing.T) {
t.Parallel()
tests := []struct { tests := []struct {
factor int64 factor int64
numerator int64 numerator int64

View file

@ -3858,6 +3858,8 @@ func TestCanonicalHashMarker(t *testing.T) {
// TestTxIndexer tests the tx indexes are updated correctly. // TestTxIndexer tests the tx indexes are updated correctly.
func TestTxIndexer(t *testing.T) { func TestTxIndexer(t *testing.T) {
t.Parallel()
var ( var (
testBankKey, _ = crypto.GenerateKey() testBankKey, _ = crypto.GenerateKey()
testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey) testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
@ -4063,6 +4065,8 @@ func TestTxIndexer(t *testing.T) {
} }
func TestCreateThenDeletePreByzantium(t *testing.T) { func TestCreateThenDeletePreByzantium(t *testing.T) {
t.Parallel()
// We use Ropsten chain config instead of Testchain config, this is // We use Ropsten chain config instead of Testchain config, this is
// deliberate: we want to use pre-byz rules where we have intermediate state roots // deliberate: we want to use pre-byz rules where we have intermediate state roots
// between transactions. // between transactions.
@ -4076,12 +4080,15 @@ func TestCreateThenDeletePreByzantium(t *testing.T) {
}) })
} }
func TestCreateThenDeletePostByzantium(t *testing.T) { func TestCreateThenDeletePostByzantium(t *testing.T) {
t.Parallel()
testCreateThenDelete(t, params.TestChainConfig) testCreateThenDelete(t, params.TestChainConfig)
} }
// testCreateThenDelete tests a creation and subsequent deletion of a contract, happening // testCreateThenDelete tests a creation and subsequent deletion of a contract, happening
// within the same block. // within the same block.
func testCreateThenDelete(t *testing.T, config *params.ChainConfig) { func testCreateThenDelete(t *testing.T, config *params.ChainConfig) {
t.Helper()
var ( var (
engine = ethash.NewFaker() engine = ethash.NewFaker()
// A sender who makes transactions, has some funds // A sender who makes transactions, has some funds
@ -4158,6 +4165,8 @@ func testCreateThenDelete(t *testing.T, config *params.ChainConfig) {
// TestTransientStorageReset ensures the transient storage is wiped correctly // TestTransientStorageReset ensures the transient storage is wiped correctly
// between transactions. // between transactions.
func TestTransientStorageReset(t *testing.T) { func TestTransientStorageReset(t *testing.T) {
t.Parallel()
var ( var (
engine = ethash.NewFaker() engine = ethash.NewFaker()
key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
@ -4250,6 +4259,8 @@ func TestTransientStorageReset(t *testing.T) {
} }
func TestEIP3651(t *testing.T) { func TestEIP3651(t *testing.T) {
t.Parallel()
var ( var (
aa = common.HexToAddress("0x000000000000000000000000000000000000aaaa") aa = common.HexToAddress("0x000000000000000000000000000000000000aaaa")
bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb") bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb")

View file

@ -32,6 +32,8 @@ import (
) )
func TestGenerateWithdrawalChain(t *testing.T) { func TestGenerateWithdrawalChain(t *testing.T) {
t.Parallel()
var ( var (
keyHex = "9c647b8b7c4e7c3490668fb6c11473619db80c93704c70893d3813af4090c39c" keyHex = "9c647b8b7c4e7c3490668fb6c11473619db80c93704c70893d3813af4090c39c"
key, _ = crypto.HexToECDSA(keyHex) key, _ = crypto.HexToECDSA(keyHex)

View file

@ -576,7 +576,10 @@ func InspectDatabase(db ethdb.Database, keyPrefix, keyStart []byte) error {
for _, ancient := range ancients { for _, ancient := range ancients {
for _, table := range ancient.sizes { for _, table := range ancient.sizes {
stats = append(stats, []string{ stats = append(stats, []string{
fmt.Sprintf("Ancient store (%s)", strings.Title(ancient.name)), fmt.Sprintf("Ancient store (%s)",
//nolint: staticcheck
strings.Title(ancient.name)),
//nolint: staticcheck
strings.Title(table.name), strings.Title(table.name),
table.size.String(), table.size.String(),
fmt.Sprintf("%d", ancient.count()), fmt.Sprintf("%d", ancient.count()),

View file

@ -25,6 +25,8 @@ import (
) )
func TestResetFreezer(t *testing.T) { func TestResetFreezer(t *testing.T) {
t.Parallel()
items := []struct { items := []struct {
id uint64 id uint64
blob []byte blob []byte
@ -78,6 +80,8 @@ func TestResetFreezer(t *testing.T) {
} }
func TestFreezerCleanup(t *testing.T) { func TestFreezerCleanup(t *testing.T) {
t.Parallel()
items := []struct { items := []struct {
id uint64 id uint64
blob []byte blob []byte

View file

@ -509,6 +509,7 @@ func (dl *diskLayer) checkAndFlush(ctx *generatorContext, current []byte) error
// generateStorages generates the missing storage slots of the specific contract. // generateStorages generates the missing storage slots of the specific contract.
// It's supposed to restart the generation from the given origin position. // It's supposed to restart the generation from the given origin position.
func generateStorages(ctx *generatorContext, dl *diskLayer, stateRoot common.Hash, account common.Hash, storageRoot common.Hash, storeMarker []byte) error { func generateStorages(ctx *generatorContext, dl *diskLayer, stateRoot common.Hash, account common.Hash, storageRoot common.Hash, storeMarker []byte) error {
//nolint: predeclared
onStorage := func(key []byte, val []byte, write bool, delete bool) error { onStorage := func(key []byte, val []byte, write bool, delete bool) error {
defer func(start time.Time) { defer func(start time.Time) {
snapStorageWriteCounter.Inc(time.Since(start).Nanoseconds()) snapStorageWriteCounter.Inc(time.Since(start).Nanoseconds())

View file

@ -813,6 +813,8 @@ func populateDangling(disk ethdb.KeyValueStore) {
// //
// This test will populate some dangling storages to see if they can be cleaned up. // This test will populate some dangling storages to see if they can be cleaned up.
func TestGenerateCompleteSnapshotWithDanglingStorage(t *testing.T) { func TestGenerateCompleteSnapshotWithDanglingStorage(t *testing.T) {
t.Parallel()
var helper = newHelper() var helper = newHelper()
stRoot := helper.makeStorageTrie(common.Hash{}, hashData([]byte("acc-1")), []string{"key-1", "key-2", "key-3"}, []string{"val-1", "val-2", "val-3"}, true) stRoot := helper.makeStorageTrie(common.Hash{}, hashData([]byte("acc-1")), []string{"key-1", "key-2", "key-3"}, []string{"val-1", "val-2", "val-3"}, true)
@ -848,6 +850,8 @@ func TestGenerateCompleteSnapshotWithDanglingStorage(t *testing.T) {
// //
// This test will populate some dangling storages to see if they can be cleaned up. // This test will populate some dangling storages to see if they can be cleaned up.
func TestGenerateBrokenSnapshotWithDanglingStorage(t *testing.T) { func TestGenerateBrokenSnapshotWithDanglingStorage(t *testing.T) {
t.Parallel()
var helper = newHelper() var helper = newHelper()
stRoot := helper.makeStorageTrie(common.Hash{}, hashData([]byte("acc-1")), []string{"key-1", "key-2", "key-3"}, []string{"val-1", "val-2", "val-3"}, true) stRoot := helper.makeStorageTrie(common.Hash{}, hashData([]byte("acc-1")), []string{"key-1", "key-2", "key-3"}, []string{"val-1", "val-2", "val-3"}, true)

View file

@ -25,6 +25,8 @@ import (
) )
func TestIteratorHold(t *testing.T) { func TestIteratorHold(t *testing.T) {
t.Parallel()
// Create the key-value data store // Create the key-value data store
var ( var (
content = map[string]string{"k1": "v1", "k2": "v2", "k3": "v3"} content = map[string]string{"k1": "v1", "k2": "v2", "k3": "v3"}
@ -87,6 +89,8 @@ func TestIteratorHold(t *testing.T) {
} }
func TestReopenIterator(t *testing.T) { func TestReopenIterator(t *testing.T) {
t.Parallel()
var ( var (
content = map[common.Hash]string{ content = map[common.Hash]string{
common.HexToHash("a1"): "v1", common.HexToHash("a1"): "v1",

View file

@ -1382,6 +1382,8 @@ func TestStateDBAccessList(t *testing.T) {
// Tests that account and storage tries are flushed in the correct order and that // Tests that account and storage tries are flushed in the correct order and that
// no data loss occurs. // no data loss occurs.
func TestFlushOrderDataLoss(t *testing.T) { func TestFlushOrderDataLoss(t *testing.T) {
t.Parallel()
// Create a state trie with many accounts and slots // Create a state trie with many accounts and slots
var ( var (
memdb = rawdb.NewMemoryDatabase() memdb = rawdb.NewMemoryDatabase()
@ -1420,6 +1422,8 @@ func TestFlushOrderDataLoss(t *testing.T) {
} }
func TestStateDBTransientStorage(t *testing.T) { func TestStateDBTransientStorage(t *testing.T) {
t.Parallel()
memDb := rawdb.NewMemoryDatabase() memDb := rawdb.NewMemoryDatabase()
db := NewDatabase(memDb) db := NewDatabase(memDb)
state, _ := New(common.Hash{}, db, nil) state, _ := New(common.Hash{}, db, nil)

View file

@ -29,6 +29,8 @@ import (
// Tests that transactions can be added to strict lists and list contents and // Tests that transactions can be added to strict lists and list contents and
// nonce boundaries are correctly maintained. // nonce boundaries are correctly maintained.
func TestStrictListAdd(t *testing.T) { func TestStrictListAdd(t *testing.T) {
t.Parallel()
// Generate a list of transactions to insert // Generate a list of transactions to insert
key, _ := crypto.GenerateKey() key, _ := crypto.GenerateKey()

View file

@ -42,8 +42,8 @@ func count(t *testing.T, pool *TxPool) (pending int, queued int) {
return pending, queued return pending, queued
} }
func fillPool(t testing.TB, pool *TxPool) { func fillPool(tb testing.TB, pool *TxPool) {
t.Helper() tb.Helper()
// Create a number of test accounts, fund them and make transactions // Create a number of test accounts, fund them and make transactions
executableTxs := types.Transactions{} executableTxs := types.Transactions{}
nonExecutableTxs := types.Transactions{} nonExecutableTxs := types.Transactions{}
@ -62,14 +62,14 @@ func fillPool(t testing.TB, pool *TxPool) {
slots := pool.all.Slots() slots := pool.all.Slots()
// sanity-check that the test prerequisites are ok (pending full) // sanity-check that the test prerequisites are ok (pending full)
if have, want := pending, slots; have != want { if have, want := pending, slots; have != want {
t.Fatalf("have %d, want %d", have, want) tb.Fatalf("have %d, want %d", have, want)
} }
if have, want := queued, 0; have != want { if have, want := queued, 0; have != want {
t.Fatalf("have %d, want %d", have, want) tb.Fatalf("have %d, want %d", have, want)
} }
t.Logf("pool.config: GlobalSlots=%d, GlobalQueue=%d\n", pool.config.GlobalSlots, pool.config.GlobalQueue) tb.Logf("pool.config: GlobalSlots=%d, GlobalQueue=%d\n", pool.config.GlobalSlots, pool.config.GlobalQueue)
t.Logf("pending: %d queued: %d, all: %d\n", pending, queued, slots) tb.Logf("pending: %d queued: %d, all: %d\n", pending, queued, slots)
} }
// Tests that if a batch high-priced of non-executables arrive, they do not kick out // Tests that if a batch high-priced of non-executables arrive, they do not kick out

View file

@ -1019,13 +1019,16 @@ func TestAllowUnprotectedTransactionWhenSet(t *testing.T) {
// This logic should not hold for local transactions, unless the local tracking // This logic should not hold for local transactions, unless the local tracking
// mechanism is disabled. // mechanism is disabled.
func TestQueueGlobalLimiting(t *testing.T) { func TestQueueGlobalLimiting(t *testing.T) {
t.Parallel()
testQueueGlobalLimiting(t, false) testQueueGlobalLimiting(t, false)
} }
func TestQueueGlobalLimitingNoLocals(t *testing.T) { func TestQueueGlobalLimitingNoLocals(t *testing.T) {
t.Parallel()
testQueueGlobalLimiting(t, true) testQueueGlobalLimiting(t, true)
} }
func testQueueGlobalLimiting(t *testing.T, nolocals bool) { func testQueueGlobalLimiting(t *testing.T, nolocals bool) {
t.Helper()
t.Parallel() t.Parallel()
// Create the pool to test the limit enforcement with // Create the pool to test the limit enforcement with
@ -1110,9 +1113,11 @@ func testQueueGlobalLimiting(t *testing.T, nolocals bool) {
// This logic should not hold for local transactions, unless the local tracking // This logic should not hold for local transactions, unless the local tracking
// mechanism is disabled. // mechanism is disabled.
func TestQueueTimeLimiting(t *testing.T) { func TestQueueTimeLimiting(t *testing.T) {
t.Parallel()
testQueueTimeLimiting(t, false) testQueueTimeLimiting(t, false)
} }
func TestQueueTimeLimitingNoLocals(t *testing.T) { func TestQueueTimeLimitingNoLocals(t *testing.T) {
t.Parallel()
testQueueTimeLimiting(t, true) testQueueTimeLimiting(t, true)
} }
@ -2495,10 +2500,17 @@ func TestReplacementDynamicFee(t *testing.T) {
// Tests that local transactions are journaled to disk, but remote transactions // Tests that local transactions are journaled to disk, but remote transactions
// get discarded between restarts. // get discarded between restarts.
func TestJournaling(t *testing.T) { testJournaling(t, false) } func TestJournaling(t *testing.T) {
func TestJournalingNoLocals(t *testing.T) { testJournaling(t, true) } t.Parallel()
testJournaling(t, false)
}
func TestJournalingNoLocals(t *testing.T) {
t.Parallel()
testJournaling(t, true)
}
func testJournaling(t *testing.T, nolocals bool) { func testJournaling(t *testing.T, nolocals bool) {
t.Helper()
t.Parallel() t.Parallel()
// Create a temporary file for the journal // Create a temporary file for the journal
@ -2741,6 +2753,8 @@ func BenchmarkBatchLocalInsert10000(b *testing.B) { benchmarkBatchInsert(b, 1000
// Benchmarks the speed of batched transaction insertion. // Benchmarks the speed of batched transaction insertion.
func benchmarkBatchInsert(b *testing.B, size int, local bool) { func benchmarkBatchInsert(b *testing.B, size int, local bool) {
b.Helper()
// Generate a batch of transactions to enqueue into the pool // Generate a batch of transactions to enqueue into the pool
pool, key := setupPool() pool, key := setupPool()
defer pool.Stop() defer pool.Stop()

View file

@ -557,6 +557,8 @@ func assertEqual(orig *Transaction, cpy *Transaction) error {
} }
func TestTransactionSizes(t *testing.T) { func TestTransactionSizes(t *testing.T) {
t.Parallel()
signer := NewLondonSigner(big.NewInt(123)) signer := NewLondonSigner(big.NewInt(123))
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
to := common.HexToAddress("0x01") to := common.HexToAddress("0x01")

View file

@ -131,6 +131,8 @@ var createGasTests = []struct {
} }
func TestCreateGas(t *testing.T) { func TestCreateGas(t *testing.T) {
t.Parallel()
for i, tt := range createGasTests { for i, tt := range createGasTests {
var gasUsed = uint64(0) var gasUsed = uint64(0)
doCheck := func(testGas int) bool { doCheck := func(testGas int) bool {

View file

@ -578,6 +578,8 @@ func BenchmarkOpMstore(bench *testing.B) {
} }
func TestOpTstore(t *testing.T) { func TestOpTstore(t *testing.T) {
t.Parallel()
var ( var (
statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
env = NewEVM(BlockContext{}, TxContext{}, statedb, params.TestChainConfig, Config{}) env = NewEVM(BlockContext{}, TxContext{}, statedb, params.TestChainConfig, Config{})

View file

@ -24,6 +24,8 @@ import (
// TestJumpTableCopy tests that deep copy is necessery to prevent modify shared jump table // TestJumpTableCopy tests that deep copy is necessery to prevent modify shared jump table
func TestJumpTableCopy(t *testing.T) { func TestJumpTableCopy(t *testing.T) {
t.Parallel()
tbl := newMergeInstructionSet() tbl := newMergeInstructionSet()
require.Equal(t, uint64(0), tbl[SLOAD].constantGas) require.Equal(t, uint64(0), tbl[SLOAD].constantGas)

View file

@ -389,45 +389,45 @@ func TestEth2DeepReorg(t *testing.T) {
// TODO (MariusVanDerWijden) TestEth2DeepReorg is currently broken, because it tries to reorg // TODO (MariusVanDerWijden) TestEth2DeepReorg is currently broken, because it tries to reorg
// before the totalTerminalDifficulty threshold // before the totalTerminalDifficulty threshold
/* /*
genesis, preMergeBlocks := generateMergeChain(core.TriesInMemory * 2, false) genesis, preMergeBlocks := generateMergeChain(core.TriesInMemory * 2, false)
n, ethservice := startEthService(t, genesis, preMergeBlocks) n, ethservice := startEthService(t, genesis, preMergeBlocks)
defer n.Close() defer n.Close()
var ( var (
api = NewConsensusAPI(ethservice, nil) api = NewConsensusAPI(ethservice, nil)
parent = preMergeBlocks[len(preMergeBlocks)-core.TriesInMemory-1] parent = preMergeBlocks[len(preMergeBlocks)-core.TriesInMemory-1]
head = ethservice.BlockChain().CurrentBlock().Number.Uint64()() head = ethservice.BlockChain().CurrentBlock().Number.Uint64()()
) )
if ethservice.BlockChain().HasBlockAndState(parent.Hash(), parent.NumberU64()) { if ethservice.BlockChain().HasBlockAndState(parent.Hash(), parent.NumberU64()) {
t.Errorf("Block %d not pruned", parent.NumberU64()) t.Errorf("Block %d not pruned", parent.NumberU64())
}
for i := 0; i < 10; i++ {
execData, err := api.assembleBlock(AssembleBlockParams{
ParentHash: parent.Hash(),
Timestamp: parent.Time() + 5,
})
if err != nil {
t.Fatalf("Failed to create the executable data %v", err)
}
block, err := ExecutableDataToBlock(ethservice.BlockChain().Config(), parent.Header(), *execData)
if err != nil {
t.Fatalf("Failed to convert executable data to block %v", err)
}
newResp, err := api.ExecutePayload(*execData)
if err != nil || newResp.Status != "VALID" {
t.Fatalf("Failed to insert block: %v", err)
}
if ethservice.BlockChain().CurrentBlock().Number.Uint64()() != head {
t.Fatalf("Chain head shouldn't be updated")
}
if err := api.setHead(block.Hash()); err != nil {
t.Fatalf("Failed to set head: %v", err)
}
if ethservice.BlockChain().CurrentBlock().Number.Uint64()() != block.NumberU64() {
t.Fatalf("Chain head should be updated")
}
parent, head = block, block.NumberU64()
} }
for i := 0; i < 10; i++ {
execData, err := api.assembleBlock(AssembleBlockParams{
ParentHash: parent.Hash(),
Timestamp: parent.Time() + 5,
})
if err != nil {
t.Fatalf("Failed to create the executable data %v", err)
}
block, err := ExecutableDataToBlock(ethservice.BlockChain().Config(), parent.Header(), *execData)
if err != nil {
t.Fatalf("Failed to convert executable data to block %v", err)
}
newResp, err := api.ExecutePayload(*execData)
if err != nil || newResp.Status != "VALID" {
t.Fatalf("Failed to insert block: %v", err)
}
if ethservice.BlockChain().CurrentBlock().Number.Uint64()() != head {
t.Fatalf("Chain head shouldn't be updated")
}
if err := api.setHead(block.Hash()); err != nil {
t.Fatalf("Failed to set head: %v", err)
}
if ethservice.BlockChain().CurrentBlock().Number.Uint64()() != block.NumberU64() {
t.Fatalf("Chain head should be updated")
}
parent, head = block, block.NumberU64()
}
*/ */
} }
@ -584,6 +584,8 @@ We expect
P1'' P1''
*/ */
func TestNewPayloadOnInvalidChain(t *testing.T) { func TestNewPayloadOnInvalidChain(t *testing.T) {
t.Parallel()
genesis, preMergeBlocks := generateMergeChain(10, false) genesis, preMergeBlocks := generateMergeChain(10, false)
n, ethservice := startEthService(t, genesis, preMergeBlocks) n, ethservice := startEthService(t, genesis, preMergeBlocks)
defer n.Close() defer n.Close()
@ -679,6 +681,8 @@ func assembleBlock(api *ConsensusAPI, parentHash common.Hash, params *engine.Pay
} }
func TestEmptyBlocks(t *testing.T) { func TestEmptyBlocks(t *testing.T) {
t.Parallel()
genesis, preMergeBlocks := generateMergeChain(10, false) genesis, preMergeBlocks := generateMergeChain(10, false)
n, ethservice := startEthService(t, genesis, preMergeBlocks) n, ethservice := startEthService(t, genesis, preMergeBlocks)
defer n.Close() defer n.Close()
@ -739,6 +743,8 @@ func TestEmptyBlocks(t *testing.T) {
} }
func getNewPayload(t *testing.T, api *ConsensusAPI, parent *types.Header, withdrawals []*types.Withdrawal) *engine.ExecutableData { func getNewPayload(t *testing.T, api *ConsensusAPI, parent *types.Header, withdrawals []*types.Withdrawal) *engine.ExecutableData {
t.Helper()
params := engine.PayloadAttributes{ params := engine.PayloadAttributes{
Timestamp: parent.Time + 1, Timestamp: parent.Time + 1,
Random: crypto.Keccak256Hash([]byte{byte(1)}), Random: crypto.Keccak256Hash([]byte{byte(1)}),
@ -794,6 +800,8 @@ func decodeTransactions(enc [][]byte) ([]*types.Transaction, error) {
} }
func TestTrickRemoteBlockCache(t *testing.T) { func TestTrickRemoteBlockCache(t *testing.T) {
t.Parallel()
// Setup two nodes // Setup two nodes
genesis, preMergeBlocks := generateMergeChain(10, false) genesis, preMergeBlocks := generateMergeChain(10, false)
nodeA, ethserviceA := startEthService(t, genesis, preMergeBlocks) nodeA, ethserviceA := startEthService(t, genesis, preMergeBlocks)
@ -858,6 +866,8 @@ func TestTrickRemoteBlockCache(t *testing.T) {
} }
func TestInvalidBloom(t *testing.T) { func TestInvalidBloom(t *testing.T) {
t.Parallel()
genesis, preMergeBlocks := generateMergeChain(10, false) genesis, preMergeBlocks := generateMergeChain(10, false)
n, ethservice := startEthService(t, genesis, preMergeBlocks) n, ethservice := startEthService(t, genesis, preMergeBlocks)
ethservice.Merger().ReachTTD() ethservice.Merger().ReachTTD()
@ -882,6 +892,8 @@ func TestInvalidBloom(t *testing.T) {
} }
func TestNewPayloadOnInvalidTerminalBlock(t *testing.T) { func TestNewPayloadOnInvalidTerminalBlock(t *testing.T) {
t.Parallel()
genesis, preMergeBlocks := generateMergeChain(100, false) genesis, preMergeBlocks := generateMergeChain(100, false)
n, ethservice := startEthService(t, genesis, preMergeBlocks) n, ethservice := startEthService(t, genesis, preMergeBlocks)
defer n.Close() defer n.Close()
@ -949,6 +961,8 @@ func TestNewPayloadOnInvalidTerminalBlock(t *testing.T) {
// newPayLoad and forkchoiceUpdate. This is to test that the api behaves // newPayLoad and forkchoiceUpdate. This is to test that the api behaves
// well even of the caller is not being 'serial'. // well even of the caller is not being 'serial'.
func TestSimultaneousNewBlock(t *testing.T) { func TestSimultaneousNewBlock(t *testing.T) {
t.Parallel()
genesis, preMergeBlocks := generateMergeChain(10, false) genesis, preMergeBlocks := generateMergeChain(10, false)
n, ethservice := startEthService(t, genesis, preMergeBlocks) n, ethservice := startEthService(t, genesis, preMergeBlocks)
defer n.Close() defer n.Close()
@ -1036,6 +1050,8 @@ func TestSimultaneousNewBlock(t *testing.T) {
// TestWithdrawals creates and verifies two post-Shanghai blocks. The first // TestWithdrawals creates and verifies two post-Shanghai blocks. The first
// includes zero withdrawals and the second includes two. // includes zero withdrawals and the second includes two.
func TestWithdrawals(t *testing.T) { func TestWithdrawals(t *testing.T) {
t.Parallel()
genesis, blocks := generateMergeChain(10, true) genesis, blocks := generateMergeChain(10, true)
// Set shanghai time to last block + 5 seconds (first post-merge block) // Set shanghai time to last block + 5 seconds (first post-merge block)
time := blocks[len(blocks)-1].Time() + 5 time := blocks[len(blocks)-1].Time() + 5
@ -1150,6 +1166,8 @@ func TestWithdrawals(t *testing.T) {
} }
func TestNilWithdrawals(t *testing.T) { func TestNilWithdrawals(t *testing.T) {
t.Parallel()
genesis, blocks := generateMergeChain(10, true) genesis, blocks := generateMergeChain(10, true)
// Set shanghai time to last block + 4 seconds (first post-merge block) // Set shanghai time to last block + 4 seconds (first post-merge block)
time := blocks[len(blocks)-1].Time() + 4 time := blocks[len(blocks)-1].Time() + 4
@ -1262,6 +1280,8 @@ func TestNilWithdrawals(t *testing.T) {
} }
func setupBodies(t *testing.T) (*node.Node, *eth.Ethereum, []*types.Block) { func setupBodies(t *testing.T) (*node.Node, *eth.Ethereum, []*types.Block) {
t.Helper()
genesis, blocks := generateMergeChain(10, true) genesis, blocks := generateMergeChain(10, true)
// enable shanghai on the last block // enable shanghai on the last block
time := blocks[len(blocks)-1].Header().Time + 1 time := blocks[len(blocks)-1].Header().Time + 1
@ -1316,6 +1336,8 @@ func allBodies(blocks []*types.Block) []*types.Body {
} }
func TestGetBlockBodiesByHash(t *testing.T) { func TestGetBlockBodiesByHash(t *testing.T) {
t.Parallel()
node, eth, blocks := setupBodies(t) node, eth, blocks := setupBodies(t)
api := NewConsensusAPI(eth) api := NewConsensusAPI(eth)
defer node.Close() defer node.Close()
@ -1372,6 +1394,8 @@ func TestGetBlockBodiesByHash(t *testing.T) {
} }
func TestGetBlockBodiesByRange(t *testing.T) { func TestGetBlockBodiesByRange(t *testing.T) {
t.Parallel()
node, eth, blocks := setupBodies(t) node, eth, blocks := setupBodies(t)
api := NewConsensusAPI(eth) api := NewConsensusAPI(eth)
defer node.Close() defer node.Close()
@ -1453,6 +1477,8 @@ func TestGetBlockBodiesByRange(t *testing.T) {
} }
func TestGetBlockBodiesByRangeInvalidParams(t *testing.T) { func TestGetBlockBodiesByRangeInvalidParams(t *testing.T) {
t.Parallel()
node, eth, _ := setupBodies(t) node, eth, _ := setupBodies(t)
api := NewConsensusAPI(eth) api := NewConsensusAPI(eth)
defer node.Close() defer node.Close()

View file

@ -38,6 +38,7 @@ type DownloaderAPI struct {
// listens for events from the downloader through the global event mux. In case it receives one of // listens for events from the downloader through the global event mux. In case it receives one of
// these events it broadcasts it to all syncing subscriptions that are installed through the // these events it broadcasts it to all syncing subscriptions that are installed through the
// installSyncSubscription channel. // installSyncSubscription channel.
// nolint: staticcheck
func NewDownloaderAPI(d *Downloader, m *event.TypeMux) *DownloaderAPI { func NewDownloaderAPI(d *Downloader, m *event.TypeMux) *DownloaderAPI {
api := &DownloaderAPI{ api := &DownloaderAPI{
d: d, d: d,

View file

@ -58,6 +58,7 @@ type downloadTester struct {
// newTester creates a new downloader test mocker. // newTester creates a new downloader test mocker.
func newTester(t *testing.T) *downloadTester { func newTester(t *testing.T) *downloadTester {
t.Helper()
return newTesterWithNotification(t, nil) return newTesterWithNotification(t, nil)
} }
@ -393,7 +394,7 @@ func (dlp *downloadTesterPeer) RequestStorageRanges(id uint64, root common.Hash,
go dlp.dl.downloader.SnapSyncer.OnStorage(dlp, id, hashes, slots, proofs) go dlp.dl.downloader.SnapSyncer.OnStorage(dlp, id, hashes, slots, proofs)
return nil return nil
} }
// RequestByteCodes fetches a batch of bytecodes by hash. // RequestByteCodes fetches a batch of bytecodes by hash.
func (dlp *downloadTesterPeer) RequestByteCodes(id uint64, hashes []common.Hash, bytes uint64) error { func (dlp *downloadTesterPeer) RequestByteCodes(id uint64, hashes []common.Hash, bytes uint64) error {
@ -401,7 +402,7 @@ func (dlp *downloadTesterPeer) RequestByteCodes(id uint64, hashes []common.Hash,
ID: id, ID: id,
Hashes: hashes, Hashes: hashes,
Bytes: bytes, Bytes: bytes,
} }
codes := snap.ServiceGetByteCodesQuery(dlp.chain, req) codes := snap.ServiceGetByteCodesQuery(dlp.chain, req)
go dlp.dl.downloader.SnapSyncer.OnByteCodes(dlp, id, codes) go dlp.dl.downloader.SnapSyncer.OnByteCodes(dlp, id, codes)
return nil return nil
@ -447,12 +448,30 @@ func assertOwnChain(t *testing.T, tester *downloadTester, length int) {
} }
} }
func TestCanonicalSynchronisation66Full(t *testing.T) { testCanonSync(t, eth.ETH66, FullSync) } func TestCanonicalSynchronisation66Full(t *testing.T) {
func TestCanonicalSynchronisation66Snap(t *testing.T) { testCanonSync(t, eth.ETH66, SnapSync) } t.Parallel()
func TestCanonicalSynchronisation66Light(t *testing.T) { testCanonSync(t, eth.ETH66, LightSync) } testCanonSync(t, eth.ETH66, FullSync)
func TestCanonicalSynchronisation67Full(t *testing.T) { testCanonSync(t, eth.ETH67, FullSync) } }
func TestCanonicalSynchronisation67Snap(t *testing.T) { testCanonSync(t, eth.ETH67, SnapSync) } func TestCanonicalSynchronisation66Snap(t *testing.T) {
func TestCanonicalSynchronisation67Light(t *testing.T) { testCanonSync(t, eth.ETH67, LightSync) } t.Parallel()
testCanonSync(t, eth.ETH66, SnapSync)
}
func TestCanonicalSynchronisation66Light(t *testing.T) {
t.Parallel()
testCanonSync(t, eth.ETH66, LightSync)
}
func TestCanonicalSynchronisation67Full(t *testing.T) {
t.Parallel()
testCanonSync(t, eth.ETH67, FullSync)
}
func TestCanonicalSynchronisation67Snap(t *testing.T) {
t.Parallel()
testCanonSync(t, eth.ETH67, SnapSync)
}
func TestCanonicalSynchronisation67Light(t *testing.T) {
t.Parallel()
testCanonSync(t, eth.ETH67, LightSync)
}
func testCanonSync(t *testing.T, protocol uint, mode SyncMode) { func testCanonSync(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -471,10 +490,22 @@ func testCanonSync(t *testing.T, protocol uint, mode SyncMode) {
// Tests that if a large batch of blocks are being downloaded, it is throttled // Tests that if a large batch of blocks are being downloaded, it is throttled
// until the cached blocks are retrieved. // until the cached blocks are retrieved.
func TestThrottling66Full(t *testing.T) { testThrottling(t, eth.ETH66, FullSync) } func TestThrottling66Full(t *testing.T) {
func TestThrottling66Snap(t *testing.T) { testThrottling(t, eth.ETH66, SnapSync) } t.Parallel()
func TestThrottling67Full(t *testing.T) { testThrottling(t, eth.ETH67, FullSync) } testThrottling(t, eth.ETH66, FullSync)
func TestThrottling67Snap(t *testing.T) { testThrottling(t, eth.ETH67, SnapSync) } }
func TestThrottling66Snap(t *testing.T) {
t.Parallel()
testThrottling(t, eth.ETH66, SnapSync)
}
func TestThrottling67Full(t *testing.T) {
t.Parallel()
testThrottling(t, eth.ETH67, FullSync)
}
func TestThrottling67Snap(t *testing.T) {
t.Parallel()
testThrottling(t, eth.ETH67, SnapSync)
}
func testThrottling(t *testing.T, protocol uint, mode SyncMode) { func testThrottling(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -553,12 +584,30 @@ func testThrottling(t *testing.T, protocol uint, mode SyncMode) {
// Tests that simple synchronization against a forked chain works correctly. In // Tests that simple synchronization against a forked chain works correctly. In
// this test common ancestor lookup should *not* be short circuited, and a full // this test common ancestor lookup should *not* be short circuited, and a full
// binary search should be executed. // binary search should be executed.
func TestForkedSync66Full(t *testing.T) { testForkedSync(t, eth.ETH66, FullSync) } func TestForkedSync66Full(t *testing.T) {
func TestForkedSync66Snap(t *testing.T) { testForkedSync(t, eth.ETH66, SnapSync) } t.Parallel()
func TestForkedSync66Light(t *testing.T) { testForkedSync(t, eth.ETH66, LightSync) } testForkedSync(t, eth.ETH66, FullSync)
func TestForkedSync67Full(t *testing.T) { testForkedSync(t, eth.ETH67, FullSync) } }
func TestForkedSync67Snap(t *testing.T) { testForkedSync(t, eth.ETH67, SnapSync) } func TestForkedSync66Snap(t *testing.T) {
func TestForkedSync67Light(t *testing.T) { testForkedSync(t, eth.ETH67, LightSync) } t.Parallel()
testForkedSync(t, eth.ETH66, SnapSync)
}
func TestForkedSync66Light(t *testing.T) {
t.Parallel()
testForkedSync(t, eth.ETH66, LightSync)
}
func TestForkedSync67Full(t *testing.T) {
t.Parallel()
testForkedSync(t, eth.ETH67, FullSync)
}
func TestForkedSync67Snap(t *testing.T) {
t.Parallel()
testForkedSync(t, eth.ETH67, SnapSync)
}
func TestForkedSync67Light(t *testing.T) {
t.Parallel()
testForkedSync(t, eth.ETH67, LightSync)
}
func testForkedSync(t *testing.T, protocol uint, mode SyncMode) { func testForkedSync(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -583,12 +632,30 @@ func testForkedSync(t *testing.T, protocol uint, mode SyncMode) {
// Tests that synchronising against a much shorter but much heavier fork works // Tests that synchronising against a much shorter but much heavier fork works
// currently and is not dropped. // currently and is not dropped.
func TestHeavyForkedSync66Full(t *testing.T) { testHeavyForkedSync(t, eth.ETH66, FullSync) } func TestHeavyForkedSync66Full(t *testing.T) {
func TestHeavyForkedSync66Snap(t *testing.T) { testHeavyForkedSync(t, eth.ETH66, SnapSync) } t.Parallel()
func TestHeavyForkedSync66Light(t *testing.T) { testHeavyForkedSync(t, eth.ETH66, LightSync) } testHeavyForkedSync(t, eth.ETH66, FullSync)
func TestHeavyForkedSync67Full(t *testing.T) { testHeavyForkedSync(t, eth.ETH67, FullSync) } }
func TestHeavyForkedSync67Snap(t *testing.T) { testHeavyForkedSync(t, eth.ETH67, SnapSync) } func TestHeavyForkedSync66Snap(t *testing.T) {
func TestHeavyForkedSync67Light(t *testing.T) { testHeavyForkedSync(t, eth.ETH67, LightSync) } t.Parallel()
testHeavyForkedSync(t, eth.ETH66, SnapSync)
}
func TestHeavyForkedSync66Light(t *testing.T) {
t.Parallel()
testHeavyForkedSync(t, eth.ETH66, LightSync)
}
func TestHeavyForkedSync67Full(t *testing.T) {
t.Parallel()
testHeavyForkedSync(t, eth.ETH67, FullSync)
}
func TestHeavyForkedSync67Snap(t *testing.T) {
t.Parallel()
testHeavyForkedSync(t, eth.ETH67, SnapSync)
}
func TestHeavyForkedSync67Light(t *testing.T) {
t.Parallel()
testHeavyForkedSync(t, eth.ETH67, LightSync)
}
func testHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) { func testHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -615,12 +682,30 @@ func testHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) {
// Tests that chain forks are contained within a certain interval of the current // Tests that chain forks are contained within a certain interval of the current
// chain head, ensuring that malicious peers cannot waste resources by feeding // chain head, ensuring that malicious peers cannot waste resources by feeding
// long dead chains. // long dead chains.
func TestBoundedForkedSync66Full(t *testing.T) { testBoundedForkedSync(t, eth.ETH66, FullSync) } func TestBoundedForkedSync66Full(t *testing.T) {
func TestBoundedForkedSync66Snap(t *testing.T) { testBoundedForkedSync(t, eth.ETH66, SnapSync) } t.Parallel()
func TestBoundedForkedSync66Light(t *testing.T) { testBoundedForkedSync(t, eth.ETH66, LightSync) } testBoundedForkedSync(t, eth.ETH66, FullSync)
func TestBoundedForkedSync67Full(t *testing.T) { testBoundedForkedSync(t, eth.ETH67, FullSync) } }
func TestBoundedForkedSync67Snap(t *testing.T) { testBoundedForkedSync(t, eth.ETH67, SnapSync) } func TestBoundedForkedSync66Snap(t *testing.T) {
func TestBoundedForkedSync67Light(t *testing.T) { testBoundedForkedSync(t, eth.ETH67, LightSync) } t.Parallel()
testBoundedForkedSync(t, eth.ETH66, SnapSync)
}
func TestBoundedForkedSync66Light(t *testing.T) {
t.Parallel()
testBoundedForkedSync(t, eth.ETH66, LightSync)
}
func TestBoundedForkedSync67Full(t *testing.T) {
t.Parallel()
testBoundedForkedSync(t, eth.ETH67, FullSync)
}
func TestBoundedForkedSync67Snap(t *testing.T) {
t.Parallel()
testBoundedForkedSync(t, eth.ETH67, SnapSync)
}
func TestBoundedForkedSync67Light(t *testing.T) {
t.Parallel()
testBoundedForkedSync(t, eth.ETH67, LightSync)
}
func testBoundedForkedSync(t *testing.T, protocol uint, mode SyncMode) { func testBoundedForkedSync(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -647,21 +732,27 @@ func testBoundedForkedSync(t *testing.T, protocol uint, mode SyncMode) {
// chain head for short but heavy forks too. These are a bit special because they // chain head for short but heavy forks too. These are a bit special because they
// take different ancestor lookup paths. // take different ancestor lookup paths.
func TestBoundedHeavyForkedSync66Full(t *testing.T) { func TestBoundedHeavyForkedSync66Full(t *testing.T) {
t.Parallel()
testBoundedHeavyForkedSync(t, eth.ETH66, FullSync) testBoundedHeavyForkedSync(t, eth.ETH66, FullSync)
} }
func TestBoundedHeavyForkedSync66Snap(t *testing.T) { func TestBoundedHeavyForkedSync66Snap(t *testing.T) {
t.Parallel()
testBoundedHeavyForkedSync(t, eth.ETH66, SnapSync) testBoundedHeavyForkedSync(t, eth.ETH66, SnapSync)
} }
func TestBoundedHeavyForkedSync66Light(t *testing.T) { func TestBoundedHeavyForkedSync66Light(t *testing.T) {
t.Parallel()
testBoundedHeavyForkedSync(t, eth.ETH66, LightSync) testBoundedHeavyForkedSync(t, eth.ETH66, LightSync)
} }
func TestBoundedHeavyForkedSync67Full(t *testing.T) { func TestBoundedHeavyForkedSync67Full(t *testing.T) {
t.Parallel()
testBoundedHeavyForkedSync(t, eth.ETH67, FullSync) testBoundedHeavyForkedSync(t, eth.ETH67, FullSync)
} }
func TestBoundedHeavyForkedSync67Snap(t *testing.T) { func TestBoundedHeavyForkedSync67Snap(t *testing.T) {
t.Parallel()
testBoundedHeavyForkedSync(t, eth.ETH67, SnapSync) testBoundedHeavyForkedSync(t, eth.ETH67, SnapSync)
} }
func TestBoundedHeavyForkedSync67Light(t *testing.T) { func TestBoundedHeavyForkedSync67Light(t *testing.T) {
t.Parallel()
testBoundedHeavyForkedSync(t, eth.ETH67, LightSync) testBoundedHeavyForkedSync(t, eth.ETH67, LightSync)
} }
@ -688,12 +779,30 @@ func testBoundedHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) {
} }
// Tests that a canceled download wipes all previously accumulated state. // Tests that a canceled download wipes all previously accumulated state.
func TestCancel66Full(t *testing.T) { testCancel(t, eth.ETH66, FullSync) } func TestCancel66Full(t *testing.T) {
func TestCancel66Snap(t *testing.T) { testCancel(t, eth.ETH66, SnapSync) } t.Parallel()
func TestCancel66Light(t *testing.T) { testCancel(t, eth.ETH66, LightSync) } testCancel(t, eth.ETH66, FullSync)
func TestCancel67Full(t *testing.T) { testCancel(t, eth.ETH67, FullSync) } }
func TestCancel67Snap(t *testing.T) { testCancel(t, eth.ETH67, SnapSync) } func TestCancel66Snap(t *testing.T) {
func TestCancel67Light(t *testing.T) { testCancel(t, eth.ETH67, LightSync) } t.Parallel()
testCancel(t, eth.ETH66, SnapSync)
}
func TestCancel66Light(t *testing.T) {
t.Parallel()
testCancel(t, eth.ETH66, LightSync)
}
func TestCancel67Full(t *testing.T) {
t.Parallel()
testCancel(t, eth.ETH67, FullSync)
}
func TestCancel67Snap(t *testing.T) {
t.Parallel()
testCancel(t, eth.ETH67, SnapSync)
}
func TestCancel67Light(t *testing.T) {
t.Parallel()
testCancel(t, eth.ETH67, LightSync)
}
func testCancel(t *testing.T, protocol uint, mode SyncMode) { func testCancel(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -718,12 +827,30 @@ func testCancel(t *testing.T, protocol uint, mode SyncMode) {
} }
// Tests that synchronisation from multiple peers works as intended (multi thread sanity test). // Tests that synchronisation from multiple peers works as intended (multi thread sanity test).
func TestMultiSynchronisation66Full(t *testing.T) { testMultiSynchronisation(t, eth.ETH66, FullSync) } func TestMultiSynchronisation66Full(t *testing.T) {
func TestMultiSynchronisation66Snap(t *testing.T) { testMultiSynchronisation(t, eth.ETH66, SnapSync) } t.Parallel()
func TestMultiSynchronisation66Light(t *testing.T) { testMultiSynchronisation(t, eth.ETH66, LightSync) } testMultiSynchronisation(t, eth.ETH66, FullSync)
func TestMultiSynchronisation67Full(t *testing.T) { testMultiSynchronisation(t, eth.ETH67, FullSync) } }
func TestMultiSynchronisation67Snap(t *testing.T) { testMultiSynchronisation(t, eth.ETH67, SnapSync) } func TestMultiSynchronisation66Snap(t *testing.T) {
func TestMultiSynchronisation67Light(t *testing.T) { testMultiSynchronisation(t, eth.ETH67, LightSync) } t.Parallel()
testMultiSynchronisation(t, eth.ETH66, SnapSync)
}
func TestMultiSynchronisation66Light(t *testing.T) {
t.Parallel()
testMultiSynchronisation(t, eth.ETH66, LightSync)
}
func TestMultiSynchronisation67Full(t *testing.T) {
t.Parallel()
testMultiSynchronisation(t, eth.ETH67, FullSync)
}
func TestMultiSynchronisation67Snap(t *testing.T) {
t.Parallel()
testMultiSynchronisation(t, eth.ETH67, SnapSync)
}
func TestMultiSynchronisation67Light(t *testing.T) {
t.Parallel()
testMultiSynchronisation(t, eth.ETH67, LightSync)
}
func testMultiSynchronisation(t *testing.T, protocol uint, mode SyncMode) { func testMultiSynchronisation(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -745,12 +872,30 @@ func testMultiSynchronisation(t *testing.T, protocol uint, mode SyncMode) {
// Tests that synchronisations behave well in multi-version protocol environments // Tests that synchronisations behave well in multi-version protocol environments
// and not wreak havoc on other nodes in the network. // and not wreak havoc on other nodes in the network.
func TestMultiProtoSynchronisation66Full(t *testing.T) { testMultiProtoSync(t, eth.ETH66, FullSync) } func TestMultiProtoSynchronisation66Full(t *testing.T) {
func TestMultiProtoSynchronisation66Snap(t *testing.T) { testMultiProtoSync(t, eth.ETH66, SnapSync) } t.Parallel()
func TestMultiProtoSynchronisation66Light(t *testing.T) { testMultiProtoSync(t, eth.ETH66, LightSync) } testMultiProtoSync(t, eth.ETH66, FullSync)
func TestMultiProtoSynchronisation67Full(t *testing.T) { testMultiProtoSync(t, eth.ETH67, FullSync) } }
func TestMultiProtoSynchronisation67Snap(t *testing.T) { testMultiProtoSync(t, eth.ETH67, SnapSync) } func TestMultiProtoSynchronisation66Snap(t *testing.T) {
func TestMultiProtoSynchronisation67Light(t *testing.T) { testMultiProtoSync(t, eth.ETH67, LightSync) } t.Parallel()
testMultiProtoSync(t, eth.ETH66, SnapSync)
}
func TestMultiProtoSynchronisation66Light(t *testing.T) {
t.Parallel()
testMultiProtoSync(t, eth.ETH66, LightSync)
}
func TestMultiProtoSynchronisation67Full(t *testing.T) {
t.Parallel()
testMultiProtoSync(t, eth.ETH67, FullSync)
}
func TestMultiProtoSynchronisation67Snap(t *testing.T) {
t.Parallel()
testMultiProtoSync(t, eth.ETH67, SnapSync)
}
func TestMultiProtoSynchronisation67Light(t *testing.T) {
t.Parallel()
testMultiProtoSync(t, eth.ETH67, LightSync)
}
func testMultiProtoSync(t *testing.T, protocol uint, mode SyncMode) { func testMultiProtoSync(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -780,12 +925,30 @@ func testMultiProtoSync(t *testing.T, protocol uint, mode SyncMode) {
// Tests that if a block is empty (e.g. header only), no body request should be // Tests that if a block is empty (e.g. header only), no body request should be
// made, and instead the header should be assembled into a whole block in itself. // made, and instead the header should be assembled into a whole block in itself.
func TestEmptyShortCircuit66Full(t *testing.T) { testEmptyShortCircuit(t, eth.ETH66, FullSync) } func TestEmptyShortCircuit66Full(t *testing.T) {
func TestEmptyShortCircuit66Snap(t *testing.T) { testEmptyShortCircuit(t, eth.ETH66, SnapSync) } t.Parallel()
func TestEmptyShortCircuit66Light(t *testing.T) { testEmptyShortCircuit(t, eth.ETH66, LightSync) } testEmptyShortCircuit(t, eth.ETH66, FullSync)
func TestEmptyShortCircuit67Full(t *testing.T) { testEmptyShortCircuit(t, eth.ETH67, FullSync) } }
func TestEmptyShortCircuit67Snap(t *testing.T) { testEmptyShortCircuit(t, eth.ETH67, SnapSync) } func TestEmptyShortCircuit66Snap(t *testing.T) {
func TestEmptyShortCircuit67Light(t *testing.T) { testEmptyShortCircuit(t, eth.ETH67, LightSync) } t.Parallel()
testEmptyShortCircuit(t, eth.ETH66, SnapSync)
}
func TestEmptyShortCircuit66Light(t *testing.T) {
t.Parallel()
testEmptyShortCircuit(t, eth.ETH66, LightSync)
}
func TestEmptyShortCircuit67Full(t *testing.T) {
t.Parallel()
testEmptyShortCircuit(t, eth.ETH67, FullSync)
}
func TestEmptyShortCircuit67Snap(t *testing.T) {
t.Parallel()
testEmptyShortCircuit(t, eth.ETH67, SnapSync)
}
func TestEmptyShortCircuit67Light(t *testing.T) {
t.Parallel()
testEmptyShortCircuit(t, eth.ETH67, LightSync)
}
func testEmptyShortCircuit(t *testing.T, protocol uint, mode SyncMode) { func testEmptyShortCircuit(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -831,12 +994,30 @@ func testEmptyShortCircuit(t *testing.T, protocol uint, mode SyncMode) {
// Tests that headers are enqueued continuously, preventing malicious nodes from // Tests that headers are enqueued continuously, preventing malicious nodes from
// stalling the downloader by feeding gapped header chains. // stalling the downloader by feeding gapped header chains.
func TestMissingHeaderAttack66Full(t *testing.T) { testMissingHeaderAttack(t, eth.ETH66, FullSync) } func TestMissingHeaderAttack66Full(t *testing.T) {
func TestMissingHeaderAttack66Snap(t *testing.T) { testMissingHeaderAttack(t, eth.ETH66, SnapSync) } t.Parallel()
func TestMissingHeaderAttack66Light(t *testing.T) { testMissingHeaderAttack(t, eth.ETH66, LightSync) } testMissingHeaderAttack(t, eth.ETH66, FullSync)
func TestMissingHeaderAttack67Full(t *testing.T) { testMissingHeaderAttack(t, eth.ETH67, FullSync) } }
func TestMissingHeaderAttack67Snap(t *testing.T) { testMissingHeaderAttack(t, eth.ETH67, SnapSync) } func TestMissingHeaderAttack66Snap(t *testing.T) {
func TestMissingHeaderAttack67Light(t *testing.T) { testMissingHeaderAttack(t, eth.ETH67, LightSync) } t.Parallel()
testMissingHeaderAttack(t, eth.ETH66, SnapSync)
}
func TestMissingHeaderAttack66Light(t *testing.T) {
t.Parallel()
testMissingHeaderAttack(t, eth.ETH66, LightSync)
}
func TestMissingHeaderAttack67Full(t *testing.T) {
t.Parallel()
testMissingHeaderAttack(t, eth.ETH67, FullSync)
}
func TestMissingHeaderAttack67Snap(t *testing.T) {
t.Parallel()
testMissingHeaderAttack(t, eth.ETH67, SnapSync)
}
func TestMissingHeaderAttack67Light(t *testing.T) {
t.Parallel()
testMissingHeaderAttack(t, eth.ETH67, LightSync)
}
func testMissingHeaderAttack(t *testing.T, protocol uint, mode SyncMode) { func testMissingHeaderAttack(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -860,12 +1041,30 @@ func testMissingHeaderAttack(t *testing.T, protocol uint, mode SyncMode) {
// Tests that if requested headers are shifted (i.e. first is missing), the queue // Tests that if requested headers are shifted (i.e. first is missing), the queue
// detects the invalid numbering. // detects the invalid numbering.
func TestShiftedHeaderAttack66Full(t *testing.T) { testShiftedHeaderAttack(t, eth.ETH66, FullSync) } func TestShiftedHeaderAttack66Full(t *testing.T) {
func TestShiftedHeaderAttack66Snap(t *testing.T) { testShiftedHeaderAttack(t, eth.ETH66, SnapSync) } t.Parallel()
func TestShiftedHeaderAttack66Light(t *testing.T) { testShiftedHeaderAttack(t, eth.ETH66, LightSync) } testShiftedHeaderAttack(t, eth.ETH66, FullSync)
func TestShiftedHeaderAttack67Full(t *testing.T) { testShiftedHeaderAttack(t, eth.ETH67, FullSync) } }
func TestShiftedHeaderAttack67Snap(t *testing.T) { testShiftedHeaderAttack(t, eth.ETH67, SnapSync) } func TestShiftedHeaderAttack66Snap(t *testing.T) {
func TestShiftedHeaderAttack67Light(t *testing.T) { testShiftedHeaderAttack(t, eth.ETH67, LightSync) } t.Parallel()
testShiftedHeaderAttack(t, eth.ETH66, SnapSync)
}
func TestShiftedHeaderAttack66Light(t *testing.T) {
t.Parallel()
testShiftedHeaderAttack(t, eth.ETH66, LightSync)
}
func TestShiftedHeaderAttack67Full(t *testing.T) {
t.Parallel()
testShiftedHeaderAttack(t, eth.ETH67, FullSync)
}
func TestShiftedHeaderAttack67Snap(t *testing.T) {
t.Parallel()
testShiftedHeaderAttack(t, eth.ETH67, SnapSync)
}
func TestShiftedHeaderAttack67Light(t *testing.T) {
t.Parallel()
testShiftedHeaderAttack(t, eth.ETH67, LightSync)
}
func testShiftedHeaderAttack(t *testing.T, protocol uint, mode SyncMode) { func testShiftedHeaderAttack(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -891,8 +1090,14 @@ func testShiftedHeaderAttack(t *testing.T, protocol uint, mode SyncMode) {
// Tests that upon detecting an invalid header, the recent ones are rolled back // Tests that upon detecting an invalid header, the recent ones are rolled back
// for various failure scenarios. Afterwards a full sync is attempted to make // for various failure scenarios. Afterwards a full sync is attempted to make
// sure no state was corrupted. // sure no state was corrupted.
func TestInvalidHeaderRollback66Snap(t *testing.T) { testInvalidHeaderRollback(t, eth.ETH66, SnapSync) } func TestInvalidHeaderRollback66Snap(t *testing.T) {
func TestInvalidHeaderRollback67Snap(t *testing.T) { testInvalidHeaderRollback(t, eth.ETH67, SnapSync) } t.Parallel()
testInvalidHeaderRollback(t, eth.ETH66, SnapSync)
}
func TestInvalidHeaderRollback67Snap(t *testing.T) {
t.Parallel()
testInvalidHeaderRollback(t, eth.ETH67, SnapSync)
}
func testInvalidHeaderRollback(t *testing.T, protocol uint, mode SyncMode) { func testInvalidHeaderRollback(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -971,21 +1176,27 @@ func testInvalidHeaderRollback(t *testing.T, protocol uint, mode SyncMode) {
// Tests that a peer advertising a high TD doesn't get to stall the downloader // Tests that a peer advertising a high TD doesn't get to stall the downloader
// afterwards by not sending any useful hashes. // afterwards by not sending any useful hashes.
func TestHighTDStarvationAttack66Full(t *testing.T) { func TestHighTDStarvationAttack66Full(t *testing.T) {
t.Parallel()
testHighTDStarvationAttack(t, eth.ETH66, FullSync) testHighTDStarvationAttack(t, eth.ETH66, FullSync)
} }
func TestHighTDStarvationAttack66Snap(t *testing.T) { func TestHighTDStarvationAttack66Snap(t *testing.T) {
t.Parallel()
testHighTDStarvationAttack(t, eth.ETH66, SnapSync) testHighTDStarvationAttack(t, eth.ETH66, SnapSync)
} }
func TestHighTDStarvationAttack66Light(t *testing.T) { func TestHighTDStarvationAttack66Light(t *testing.T) {
t.Parallel()
testHighTDStarvationAttack(t, eth.ETH66, LightSync) testHighTDStarvationAttack(t, eth.ETH66, LightSync)
} }
func TestHighTDStarvationAttack67Full(t *testing.T) { func TestHighTDStarvationAttack67Full(t *testing.T) {
t.Parallel()
testHighTDStarvationAttack(t, eth.ETH67, FullSync) testHighTDStarvationAttack(t, eth.ETH67, FullSync)
} }
func TestHighTDStarvationAttack67Snap(t *testing.T) { func TestHighTDStarvationAttack67Snap(t *testing.T) {
t.Parallel()
testHighTDStarvationAttack(t, eth.ETH67, SnapSync) testHighTDStarvationAttack(t, eth.ETH67, SnapSync)
} }
func TestHighTDStarvationAttack67Light(t *testing.T) { func TestHighTDStarvationAttack67Light(t *testing.T) {
t.Parallel()
testHighTDStarvationAttack(t, eth.ETH67, LightSync) testHighTDStarvationAttack(t, eth.ETH67, LightSync)
} }
@ -1001,8 +1212,14 @@ func testHighTDStarvationAttack(t *testing.T, protocol uint, mode SyncMode) {
} }
// Tests that misbehaving peers are disconnected, whilst behaving ones are not. // Tests that misbehaving peers are disconnected, whilst behaving ones are not.
func TestBlockHeaderAttackerDropping66(t *testing.T) { testBlockHeaderAttackerDropping(t, eth.ETH66) } func TestBlockHeaderAttackerDropping66(t *testing.T) {
func TestBlockHeaderAttackerDropping67(t *testing.T) { testBlockHeaderAttackerDropping(t, eth.ETH67) } t.Parallel()
testBlockHeaderAttackerDropping(t, eth.ETH66)
}
func TestBlockHeaderAttackerDropping67(t *testing.T) {
t.Parallel()
testBlockHeaderAttackerDropping(t, eth.ETH67)
}
func testBlockHeaderAttackerDropping(t *testing.T, protocol uint) { func testBlockHeaderAttackerDropping(t *testing.T, protocol uint) {
// Define the disconnection requirement for individual hash fetch errors // Define the disconnection requirement for individual hash fetch errors
@ -1050,12 +1267,30 @@ func testBlockHeaderAttackerDropping(t *testing.T, protocol uint) {
// Tests that synchronisation progress (origin block number, current block number // Tests that synchronisation progress (origin block number, current block number
// and highest block number) is tracked and updated correctly. // and highest block number) is tracked and updated correctly.
func TestSyncProgress66Full(t *testing.T) { testSyncProgress(t, eth.ETH66, FullSync) } func TestSyncProgress66Full(t *testing.T) {
func TestSyncProgress66Snap(t *testing.T) { testSyncProgress(t, eth.ETH66, SnapSync) } t.Parallel()
func TestSyncProgress66Light(t *testing.T) { testSyncProgress(t, eth.ETH66, LightSync) } testSyncProgress(t, eth.ETH66, FullSync)
func TestSyncProgress67Full(t *testing.T) { testSyncProgress(t, eth.ETH67, FullSync) } }
func TestSyncProgress67Snap(t *testing.T) { testSyncProgress(t, eth.ETH67, SnapSync) } func TestSyncProgress66Snap(t *testing.T) {
func TestSyncProgress67Light(t *testing.T) { testSyncProgress(t, eth.ETH67, LightSync) } t.Parallel()
testSyncProgress(t, eth.ETH66, SnapSync)
}
func TestSyncProgress66Light(t *testing.T) {
t.Parallel()
testSyncProgress(t, eth.ETH66, LightSync)
}
func TestSyncProgress67Full(t *testing.T) {
t.Parallel()
testSyncProgress(t, eth.ETH67, FullSync)
}
func TestSyncProgress67Snap(t *testing.T) {
t.Parallel()
testSyncProgress(t, eth.ETH67, SnapSync)
}
func TestSyncProgress67Light(t *testing.T) {
t.Parallel()
testSyncProgress(t, eth.ETH67, LightSync)
}
func testSyncProgress(t *testing.T, protocol uint, mode SyncMode) { func testSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -1130,12 +1365,30 @@ func checkProgress(t *testing.T, d *Downloader, stage string, want ethereum.Sync
// Tests that synchronisation progress (origin block number and highest block // Tests that synchronisation progress (origin block number and highest block
// number) is tracked and updated correctly in case of a fork (or manual head // number) is tracked and updated correctly in case of a fork (or manual head
// revertal). // revertal).
func TestForkedSyncProgress66Full(t *testing.T) { testForkedSyncProgress(t, eth.ETH66, FullSync) } func TestForkedSyncProgress66Full(t *testing.T) {
func TestForkedSyncProgress66Snap(t *testing.T) { testForkedSyncProgress(t, eth.ETH66, SnapSync) } t.Parallel()
func TestForkedSyncProgress66Light(t *testing.T) { testForkedSyncProgress(t, eth.ETH66, LightSync) } testForkedSyncProgress(t, eth.ETH66, FullSync)
func TestForkedSyncProgress67Full(t *testing.T) { testForkedSyncProgress(t, eth.ETH67, FullSync) } }
func TestForkedSyncProgress67Snap(t *testing.T) { testForkedSyncProgress(t, eth.ETH67, SnapSync) } func TestForkedSyncProgress66Snap(t *testing.T) {
func TestForkedSyncProgress67Light(t *testing.T) { testForkedSyncProgress(t, eth.ETH67, LightSync) } t.Parallel()
testForkedSyncProgress(t, eth.ETH66, SnapSync)
}
func TestForkedSyncProgress66Light(t *testing.T) {
t.Parallel()
testForkedSyncProgress(t, eth.ETH66, LightSync)
}
func TestForkedSyncProgress67Full(t *testing.T) {
t.Parallel()
testForkedSyncProgress(t, eth.ETH67, FullSync)
}
func TestForkedSyncProgress67Snap(t *testing.T) {
t.Parallel()
testForkedSyncProgress(t, eth.ETH67, SnapSync)
}
func TestForkedSyncProgress67Light(t *testing.T) {
t.Parallel()
testForkedSyncProgress(t, eth.ETH67, LightSync)
}
func testForkedSyncProgress(t *testing.T, protocol uint, mode SyncMode) { func testForkedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -1204,12 +1457,30 @@ func testForkedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
// Tests that if synchronisation is aborted due to some failure, then the progress // Tests that if synchronisation is aborted due to some failure, then the progress
// origin is not updated in the next sync cycle, as it should be considered the // origin is not updated in the next sync cycle, as it should be considered the
// continuation of the previous sync and not a new instance. // continuation of the previous sync and not a new instance.
func TestFailedSyncProgress66Full(t *testing.T) { testFailedSyncProgress(t, eth.ETH66, FullSync) } func TestFailedSyncProgress66Full(t *testing.T) {
func TestFailedSyncProgress66Snap(t *testing.T) { testFailedSyncProgress(t, eth.ETH66, SnapSync) } t.Parallel()
func TestFailedSyncProgress66Light(t *testing.T) { testFailedSyncProgress(t, eth.ETH66, LightSync) } testFailedSyncProgress(t, eth.ETH66, FullSync)
func TestFailedSyncProgress67Full(t *testing.T) { testFailedSyncProgress(t, eth.ETH67, FullSync) } }
func TestFailedSyncProgress67Snap(t *testing.T) { testFailedSyncProgress(t, eth.ETH67, SnapSync) } func TestFailedSyncProgress66Snap(t *testing.T) {
func TestFailedSyncProgress67Light(t *testing.T) { testFailedSyncProgress(t, eth.ETH67, LightSync) } t.Parallel()
testFailedSyncProgress(t, eth.ETH66, SnapSync)
}
func TestFailedSyncProgress66Light(t *testing.T) {
t.Parallel()
testFailedSyncProgress(t, eth.ETH66, LightSync)
}
func TestFailedSyncProgress67Full(t *testing.T) {
t.Parallel()
testFailedSyncProgress(t, eth.ETH67, FullSync)
}
func TestFailedSyncProgress67Snap(t *testing.T) {
t.Parallel()
testFailedSyncProgress(t, eth.ETH67, SnapSync)
}
func TestFailedSyncProgress67Light(t *testing.T) {
t.Parallel()
testFailedSyncProgress(t, eth.ETH67, LightSync)
}
func testFailedSyncProgress(t *testing.T, protocol uint, mode SyncMode) { func testFailedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -1273,12 +1544,30 @@ func testFailedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
// Tests that if an attacker fakes a chain height, after the attack is detected, // Tests that if an attacker fakes a chain height, after the attack is detected,
// the progress height is successfully reduced at the next sync invocation. // the progress height is successfully reduced at the next sync invocation.
func TestFakedSyncProgress66Full(t *testing.T) { testFakedSyncProgress(t, eth.ETH66, FullSync) } func TestFakedSyncProgress66Full(t *testing.T) {
func TestFakedSyncProgress66Snap(t *testing.T) { testFakedSyncProgress(t, eth.ETH66, SnapSync) } t.Parallel()
func TestFakedSyncProgress66Light(t *testing.T) { testFakedSyncProgress(t, eth.ETH66, LightSync) } testFakedSyncProgress(t, eth.ETH66, FullSync)
func TestFakedSyncProgress67Full(t *testing.T) { testFakedSyncProgress(t, eth.ETH67, FullSync) } }
func TestFakedSyncProgress67Snap(t *testing.T) { testFakedSyncProgress(t, eth.ETH67, SnapSync) } func TestFakedSyncProgress66Snap(t *testing.T) {
func TestFakedSyncProgress67Light(t *testing.T) { testFakedSyncProgress(t, eth.ETH67, LightSync) } t.Parallel()
testFakedSyncProgress(t, eth.ETH66, SnapSync)
}
func TestFakedSyncProgress66Light(t *testing.T) {
t.Parallel()
testFakedSyncProgress(t, eth.ETH66, LightSync)
}
func TestFakedSyncProgress67Full(t *testing.T) {
t.Parallel()
testFakedSyncProgress(t, eth.ETH67, FullSync)
}
func TestFakedSyncProgress67Snap(t *testing.T) {
t.Parallel()
testFakedSyncProgress(t, eth.ETH67, SnapSync)
}
func TestFakedSyncProgress67Light(t *testing.T) {
t.Parallel()
testFakedSyncProgress(t, eth.ETH67, LightSync)
}
func testFakedSyncProgress(t *testing.T, protocol uint, mode SyncMode) { func testFakedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester(t) tester := newTester(t)
@ -1424,14 +1713,28 @@ func TestRemoteHeaderRequestSpan(t *testing.T) {
// Tests that peers below a pre-configured checkpoint block are prevented from // Tests that peers below a pre-configured checkpoint block are prevented from
// being fast-synced from, avoiding potential cheap eclipse attacks. // being fast-synced from, avoiding potential cheap eclipse attacks.
func TestCheckpointEnforcement66Full(t *testing.T) { testCheckpointEnforcement(t, eth.ETH66, FullSync) } func TestCheckpointEnforcement66Full(t *testing.T) {
func TestCheckpointEnforcement66Snap(t *testing.T) { testCheckpointEnforcement(t, eth.ETH66, SnapSync) } t.Parallel()
testCheckpointEnforcement(t, eth.ETH66, FullSync)
}
func TestCheckpointEnforcement66Snap(t *testing.T) {
t.Parallel()
testCheckpointEnforcement(t, eth.ETH66, SnapSync)
}
func TestCheckpointEnforcement66Light(t *testing.T) { func TestCheckpointEnforcement66Light(t *testing.T) {
t.Parallel()
testCheckpointEnforcement(t, eth.ETH66, LightSync) testCheckpointEnforcement(t, eth.ETH66, LightSync)
} }
func TestCheckpointEnforcement67Full(t *testing.T) { testCheckpointEnforcement(t, eth.ETH67, FullSync) } func TestCheckpointEnforcement67Full(t *testing.T) {
func TestCheckpointEnforcement67Snap(t *testing.T) { testCheckpointEnforcement(t, eth.ETH67, SnapSync) } t.Parallel()
testCheckpointEnforcement(t, eth.ETH67, FullSync)
}
func TestCheckpointEnforcement67Snap(t *testing.T) {
t.Parallel()
testCheckpointEnforcement(t, eth.ETH67, SnapSync)
}
func TestCheckpointEnforcement67Light(t *testing.T) { func TestCheckpointEnforcement67Light(t *testing.T) {
t.Parallel()
testCheckpointEnforcement(t, eth.ETH67, LightSync) testCheckpointEnforcement(t, eth.ETH67, LightSync)
} }
@ -1464,10 +1767,18 @@ func testCheckpointEnforcement(t *testing.T, protocol uint, mode SyncMode) {
// Tests that peers below a pre-configured checkpoint block are prevented from // Tests that peers below a pre-configured checkpoint block are prevented from
// being fast-synced from, avoiding potential cheap eclipse attacks. // being fast-synced from, avoiding potential cheap eclipse attacks.
func TestBeaconSync66Full(t *testing.T) { testBeaconSync(t, eth.ETH66, FullSync) } func TestBeaconSync66Full(t *testing.T) {
func TestBeaconSync66Snap(t *testing.T) { testBeaconSync(t, eth.ETH66, SnapSync) } t.Parallel()
testBeaconSync(t, eth.ETH66, FullSync)
}
func TestBeaconSync66Snap(t *testing.T) {
t.Parallel()
testBeaconSync(t, eth.ETH66, SnapSync)
}
func testBeaconSync(t *testing.T, protocol uint, mode SyncMode) { func testBeaconSync(t *testing.T, protocol uint, mode SyncMode) {
t.Helper()
t.Parallel()
//log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true)))) //log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
var cases = []struct { var cases = []struct {
@ -1481,6 +1792,8 @@ func testBeaconSync(t *testing.T, protocol uint, mode SyncMode) {
} }
for _, c := range cases { for _, c := range cases {
t.Run(c.name, func(t *testing.T) { t.Run(c.name, func(t *testing.T) {
t.Parallel()
success := make(chan struct{}) success := make(chan struct{})
tester := newTesterWithNotification(t, func() { tester := newTesterWithNotification(t, func() {
close(success) close(success)

View file

@ -80,17 +80,18 @@ type txPool interface {
// handlerConfig is the collection of initialization parameters to create a full // handlerConfig is the collection of initialization parameters to create a full
// node network handler. // node network handler.
type handlerConfig struct { type handlerConfig struct {
Database ethdb.Database // Database for direct sync insertions Database ethdb.Database // Database for direct sync insertions
Chain *core.BlockChain // Blockchain to serve data from Chain *core.BlockChain // Blockchain to serve data from
TxPool txPool // Transaction pool to propagate from TxPool txPool // Transaction pool to propagate from
Merger *consensus.Merger // The manager for eth1/2 transition Merger *consensus.Merger // The manager for eth1/2 transition
Network uint64 // Network identifier to adfvertise Network uint64 // Network identifier to adfvertise
Sync downloader.SyncMode // Whether to snap or full sync Sync downloader.SyncMode // Whether to snap or full sync
BloomCache uint64 // Megabytes to alloc for snap sync bloom BloomCache uint64 // Megabytes to alloc for snap sync bloom
//nolint: staticcheck
EventMux *event.TypeMux // Legacy event mux, deprecate for `feed` EventMux *event.TypeMux // Legacy event mux, deprecate for `feed`
Checkpoint *params.TrustedCheckpoint // Hard coded checkpoint for sync challenges Checkpoint *params.TrustedCheckpoint // Hard coded checkpoint for sync challenges
RequiredBlocks map[uint64]common.Hash // Hard coded map of required block hashes for sync challenges RequiredBlocks map[uint64]common.Hash // Hard coded map of required block hashes for sync challenges
EthAPI *ethapi.BlockChainAPI // EthAPI to interact EthAPI *ethapi.BlockChainAPI // EthAPI to interact
checker ethereum.ChainValidator checker ethereum.ChainValidator
txArrivalWait time.Duration // Maximum duration to wait for an announced tx before requesting it txArrivalWait time.Duration // Maximum duration to wait for an announced tx before requesting it
} }
@ -148,7 +149,7 @@ func newHandler(config *handlerConfig) (*handler, error) {
chain: config.Chain, chain: config.Chain,
peers: newPeerSet(), peers: newPeerSet(),
merger: config.Merger, merger: config.Merger,
ethAPI: config.EthAPI, ethAPI: config.EthAPI,
requiredBlocks: config.RequiredBlocks, requiredBlocks: config.RequiredBlocks,
quitSync: make(chan struct{}), quitSync: make(chan struct{}),
} }

View file

@ -84,9 +84,18 @@ func (h *testEthHandler) Handle(peer *eth.Peer, packet eth.Packet) error {
// Tests that peers are correctly accepted (or rejected) based on the advertised // Tests that peers are correctly accepted (or rejected) based on the advertised
// fork IDs in the protocol handshake. // fork IDs in the protocol handshake.
func TestForkIDSplit66(t *testing.T) { testForkIDSplit(t, eth.ETH66) } func TestForkIDSplit66(t *testing.T) {
func TestForkIDSplit67(t *testing.T) { testForkIDSplit(t, eth.ETH67) } t.Parallel()
func TestForkIDSplit68(t *testing.T) { testForkIDSplit(t, eth.ETH68) } testForkIDSplit(t, eth.ETH66)
}
func TestForkIDSplit67(t *testing.T) {
t.Parallel()
testForkIDSplit(t, eth.ETH67)
}
func TestForkIDSplit68(t *testing.T) {
t.Parallel()
testForkIDSplit(t, eth.ETH68)
}
func testForkIDSplit(t *testing.T, protocol uint) { func testForkIDSplit(t *testing.T, protocol uint) {
t.Parallel() t.Parallel()
@ -240,9 +249,18 @@ func testForkIDSplit(t *testing.T, protocol uint) {
} }
// Tests that received transactions are added to the local pool. // Tests that received transactions are added to the local pool.
func TestRecvTransactions66(t *testing.T) { testRecvTransactions(t, eth.ETH66) } func TestRecvTransactions66(t *testing.T) {
func TestRecvTransactions67(t *testing.T) { testRecvTransactions(t, eth.ETH67) } t.Parallel()
func TestRecvTransactions68(t *testing.T) { testRecvTransactions(t, eth.ETH68) } testRecvTransactions(t, eth.ETH66)
}
func TestRecvTransactions67(t *testing.T) {
t.Parallel()
testRecvTransactions(t, eth.ETH67)
}
func TestRecvTransactions68(t *testing.T) {
t.Parallel()
testRecvTransactions(t, eth.ETH68)
}
func testRecvTransactions(t *testing.T, protocol uint) { func testRecvTransactions(t *testing.T, protocol uint) {
t.Parallel() t.Parallel()
@ -299,9 +317,18 @@ func testRecvTransactions(t *testing.T, protocol uint) {
} }
// This test checks that pending transactions are sent. // This test checks that pending transactions are sent.
func TestSendTransactions66(t *testing.T) { testSendTransactions(t, eth.ETH66) } func TestSendTransactions66(t *testing.T) {
func TestSendTransactions67(t *testing.T) { testSendTransactions(t, eth.ETH67) } t.Parallel()
func TestSendTransactions68(t *testing.T) { testSendTransactions(t, eth.ETH68) } testSendTransactions(t, eth.ETH66)
}
func TestSendTransactions67(t *testing.T) {
t.Parallel()
testSendTransactions(t, eth.ETH67)
}
func TestSendTransactions68(t *testing.T) {
t.Parallel()
testSendTransactions(t, eth.ETH68)
}
func testSendTransactions(t *testing.T, protocol uint) { func testSendTransactions(t *testing.T, protocol uint) {
t.Parallel() t.Parallel()
@ -386,9 +413,18 @@ func testSendTransactions(t *testing.T, protocol uint) {
// Tests that transactions get propagated to all attached peers, either via direct // Tests that transactions get propagated to all attached peers, either via direct
// broadcasts or via announcements/retrievals. // broadcasts or via announcements/retrievals.
func TestTransactionPropagation66(t *testing.T) { testTransactionPropagation(t, eth.ETH66) } func TestTransactionPropagation66(t *testing.T) {
func TestTransactionPropagation67(t *testing.T) { testTransactionPropagation(t, eth.ETH67) } t.Parallel()
func TestTransactionPropagation68(t *testing.T) { testTransactionPropagation(t, eth.ETH68) } testTransactionPropagation(t, eth.ETH66)
}
func TestTransactionPropagation67(t *testing.T) {
t.Parallel()
testTransactionPropagation(t, eth.ETH67)
}
func TestTransactionPropagation68(t *testing.T) {
t.Parallel()
testTransactionPropagation(t, eth.ETH68)
}
func testTransactionPropagation(t *testing.T, protocol uint) { func testTransactionPropagation(t *testing.T, protocol uint) {
t.Parallel() t.Parallel()
@ -690,9 +726,18 @@ func testBroadcastBlock(t *testing.T, peers, bcasts int) {
// Tests that a propagated malformed block (uncles or transactions don't match // Tests that a propagated malformed block (uncles or transactions don't match
// with the hashes in the header) gets discarded and not broadcast forward. // with the hashes in the header) gets discarded and not broadcast forward.
func TestBroadcastMalformedBlock66(t *testing.T) { testBroadcastMalformedBlock(t, eth.ETH66) } func TestBroadcastMalformedBlock66(t *testing.T) {
func TestBroadcastMalformedBlock67(t *testing.T) { testBroadcastMalformedBlock(t, eth.ETH67) } t.Parallel()
func TestBroadcastMalformedBlock68(t *testing.T) { testBroadcastMalformedBlock(t, eth.ETH68) } testBroadcastMalformedBlock(t, eth.ETH66)
}
func TestBroadcastMalformedBlock67(t *testing.T) {
t.Parallel()
testBroadcastMalformedBlock(t, eth.ETH67)
}
func TestBroadcastMalformedBlock68(t *testing.T) {
t.Parallel()
testBroadcastMalformedBlock(t, eth.ETH68)
}
func testBroadcastMalformedBlock(t *testing.T, protocol uint) { func testBroadcastMalformedBlock(t *testing.T, protocol uint) {
t.Parallel() t.Parallel()

View file

@ -148,9 +148,18 @@ func (b *testBackend) Handle(*Peer, Packet) error {
} }
// Tests that block headers can be retrieved from a remote chain based on user queries. // Tests that block headers can be retrieved from a remote chain based on user queries.
func TestGetBlockHeaders66(t *testing.T) { testGetBlockHeaders(t, ETH66) } func TestGetBlockHeaders66(t *testing.T) {
func TestGetBlockHeaders67(t *testing.T) { testGetBlockHeaders(t, ETH67) } t.Parallel()
func TestGetBlockHeaders68(t *testing.T) { testGetBlockHeaders(t, ETH68) } testGetBlockHeaders(t, ETH66)
}
func TestGetBlockHeaders67(t *testing.T) {
t.Parallel()
testGetBlockHeaders(t, ETH67)
}
func TestGetBlockHeaders68(t *testing.T) {
t.Parallel()
testGetBlockHeaders(t, ETH68)
}
func testGetBlockHeaders(t *testing.T, protocol uint) { func testGetBlockHeaders(t *testing.T, protocol uint) {
t.Parallel() t.Parallel()
@ -335,9 +344,18 @@ func testGetBlockHeaders(t *testing.T, protocol uint) {
} }
// Tests that block contents can be retrieved from a remote chain based on their hashes. // Tests that block contents can be retrieved from a remote chain based on their hashes.
func TestGetBlockBodies66(t *testing.T) { testGetBlockBodies(t, ETH66) } func TestGetBlockBodies66(t *testing.T) {
func TestGetBlockBodies67(t *testing.T) { testGetBlockBodies(t, ETH67) } t.Parallel()
func TestGetBlockBodies68(t *testing.T) { testGetBlockBodies(t, ETH68) } testGetBlockBodies(t, ETH66)
}
func TestGetBlockBodies67(t *testing.T) {
t.Parallel()
testGetBlockBodies(t, ETH67)
}
func TestGetBlockBodies68(t *testing.T) {
t.Parallel()
testGetBlockBodies(t, ETH68)
}
func testGetBlockBodies(t *testing.T, protocol uint) { func testGetBlockBodies(t *testing.T, protocol uint) {
t.Parallel() t.Parallel()
@ -431,11 +449,21 @@ func testGetBlockBodies(t *testing.T, protocol uint) {
} }
// Tests that the state trie nodes can be retrieved based on hashes. // Tests that the state trie nodes can be retrieved based on hashes.
func TestGetNodeData66(t *testing.T) { testGetNodeData(t, ETH66, false) } func TestGetNodeData66(t *testing.T) {
func TestGetNodeData67(t *testing.T) { testGetNodeData(t, ETH67, true) } t.Parallel()
func TestGetNodeData68(t *testing.T) { testGetNodeData(t, ETH68, true) } testGetNodeData(t, ETH66, false)
}
func TestGetNodeData67(t *testing.T) {
t.Parallel()
testGetNodeData(t, ETH67, true)
}
func TestGetNodeData68(t *testing.T) {
t.Parallel()
testGetNodeData(t, ETH68, true)
}
func testGetNodeData(t *testing.T, protocol uint, drop bool) { func testGetNodeData(t *testing.T, protocol uint, drop bool) {
t.Helper()
t.Parallel() t.Parallel()
// Define three accounts to simulate transactions with // Define three accounts to simulate transactions with
@ -549,9 +577,18 @@ func testGetNodeData(t *testing.T, protocol uint, drop bool) {
} }
// Tests that the transaction receipts can be retrieved based on hashes. // Tests that the transaction receipts can be retrieved based on hashes.
func TestGetBlockReceipts66(t *testing.T) { testGetBlockReceipts(t, ETH66) } func TestGetBlockReceipts66(t *testing.T) {
func TestGetBlockReceipts67(t *testing.T) { testGetBlockReceipts(t, ETH67) } t.Parallel()
func TestGetBlockReceipts68(t *testing.T) { testGetBlockReceipts(t, ETH68) } testGetBlockReceipts(t, ETH66)
}
func TestGetBlockReceipts67(t *testing.T) {
t.Parallel()
testGetBlockReceipts(t, ETH67)
}
func TestGetBlockReceipts68(t *testing.T) {
t.Parallel()
testGetBlockReceipts(t, ETH68)
}
func testGetBlockReceipts(t *testing.T, protocol uint) { func testGetBlockReceipts(t *testing.T, protocol uint) {
t.Parallel() t.Parallel()

View file

@ -37,6 +37,8 @@ func hexToNibbles(s string) []byte {
} }
func TestRequestSorting(t *testing.T) { func TestRequestSorting(t *testing.T) {
t.Parallel()
// - Path 0x9 -> {0x19} // - Path 0x9 -> {0x19}
// - Path 0x99 -> {0x0099} // - Path 0x99 -> {0x0099}
// - Path 0x01234567890123456789012345678901012345678901234567890123456789019 -> {0x0123456789012345678901234567890101234567890123456789012345678901, 0x19} // - Path 0x01234567890123456789012345678901012345678901234567890123456789019 -> {0x0123456789012345678901234567890101234567890123456789012345678901, 0x19}

View file

@ -29,8 +29,14 @@ import (
) )
// Tests that snap sync is disabled after a successful sync cycle. // Tests that snap sync is disabled after a successful sync cycle.
func TestSnapSyncDisabling66(t *testing.T) { testSnapSyncDisabling(t, eth.ETH66, snap.SNAP1) } func TestSnapSyncDisabling66(t *testing.T) {
func TestSnapSyncDisabling67(t *testing.T) { testSnapSyncDisabling(t, eth.ETH67, snap.SNAP1) } t.Parallel()
testSnapSyncDisabling(t, eth.ETH66, snap.SNAP1)
}
func TestSnapSyncDisabling67(t *testing.T) {
t.Parallel()
testSnapSyncDisabling(t, eth.ETH67, snap.SNAP1)
}
// Tests that snap sync gets disabled as soon as a real block is successfully // Tests that snap sync gets disabled as soon as a real block is successfully
// imported into the blockchain. // imported into the blockchain.

View file

@ -1306,43 +1306,43 @@ func APIs(backend Backend) []rpc.API {
// along with a boolean that indicates whether the copy is canonical (equivalent to the original). // along with a boolean that indicates whether the copy is canonical (equivalent to the original).
// Note: the Clique-part is _not_ deep copied // Note: the Clique-part is _not_ deep copied
func overrideConfig(original *params.ChainConfig, override *params.ChainConfig) (*params.ChainConfig, bool) { func overrideConfig(original *params.ChainConfig, override *params.ChainConfig) (*params.ChainConfig, bool) {
copy := new(params.ChainConfig) chainConfigCopy := new(params.ChainConfig)
*copy = *original *chainConfigCopy = *original
canon := true canon := true
// Apply forks (after Berlin) to the copy. // Apply forks (after Berlin) to the chainConfigCopy.
if block := override.BerlinBlock; block != nil { if block := override.BerlinBlock; block != nil {
copy.BerlinBlock = block chainConfigCopy.BerlinBlock = block
canon = false canon = false
} }
if block := override.LondonBlock; block != nil { if block := override.LondonBlock; block != nil {
copy.LondonBlock = block chainConfigCopy.LondonBlock = block
canon = false canon = false
} }
if block := override.ArrowGlacierBlock; block != nil { if block := override.ArrowGlacierBlock; block != nil {
copy.ArrowGlacierBlock = block chainConfigCopy.ArrowGlacierBlock = block
canon = false canon = false
} }
if block := override.GrayGlacierBlock; block != nil { if block := override.GrayGlacierBlock; block != nil {
copy.GrayGlacierBlock = block chainConfigCopy.GrayGlacierBlock = block
canon = false canon = false
} }
if block := override.MergeNetsplitBlock; block != nil { if block := override.MergeNetsplitBlock; block != nil {
copy.MergeNetsplitBlock = block chainConfigCopy.MergeNetsplitBlock = block
canon = false canon = false
} }
if timestamp := override.ShanghaiTime; timestamp != nil { if timestamp := override.ShanghaiTime; timestamp != nil {
copy.ShanghaiTime = timestamp chainConfigCopy.ShanghaiTime = timestamp
canon = false canon = false
} }
if timestamp := override.CancunTime; timestamp != nil { if timestamp := override.CancunTime; timestamp != nil {
copy.CancunTime = timestamp chainConfigCopy.CancunTime = timestamp
canon = false canon = false
} }
if timestamp := override.PragueTime; timestamp != nil { if timestamp := override.PragueTime; timestamp != nil {
copy.PragueTime = timestamp chainConfigCopy.PragueTime = timestamp
canon = false canon = false
} }
return copy, canon return chainConfigCopy, canon
} }

View file

@ -848,10 +848,10 @@ func TestTracingWithOverrides(t *testing.T) {
} }
continue continue
} }
if err != nil { if err != nil {
t.Errorf("test %d: want no error, have %v", i, err) t.Errorf("test %d: want no error, have %v", i, err)
continue continue
} }
// Turn result into res-struct // Turn result into res-struct
var ( var (
have res have res
@ -910,6 +910,8 @@ func newStates(keys []common.Hash, vals []common.Hash) *map[common.Hash]common.H
} }
func TestTraceChain(t *testing.T) { func TestTraceChain(t *testing.T) {
t.Parallel()
// Initialize test accounts // Initialize test accounts
accounts := newAccounts(3) accounts := newAccounts(3)
genesis := &core.Genesis{ genesis := &core.Genesis{

View file

@ -90,6 +90,7 @@ func TestCallTracerNative(t *testing.T) {
} }
func TestCallTracerNativeWithLog(t *testing.T) { func TestCallTracerNativeWithLog(t *testing.T) {
t.Parallel()
testCallTracer("callTracer", "call_tracer_withLog", t) testCallTracer("callTracer", "call_tracer_withLog", t)
} }
@ -261,6 +262,8 @@ func benchTracer(tracerName string, test *callTracerTest, b *testing.B) {
} }
func TestInternals(t *testing.T) { func TestInternals(t *testing.T) {
t.Parallel()
var ( var (
to = common.HexToAddress("0x00000000000000000000000000000000deadbeef") to = common.HexToAddress("0x00000000000000000000000000000000deadbeef")
origin = common.HexToAddress("0x00000000000000000000000000000000feed") origin = common.HexToAddress("0x00000000000000000000000000000000feed")

View file

@ -71,7 +71,9 @@ type flatCallTracerTest struct {
Result []flatCallTrace `json:"result"` Result []flatCallTrace `json:"result"`
} }
func flatCallTracerTestRunner(tracerName string, filename string, dirPath string, t testing.TB) error { func flatCallTracerTestRunner(tb testing.TB, tracerName string, filename string, dirPath string) error {
tb.Helper()
// Call tracer test found, read if from disk // Call tracer test found, read if from disk
blob, err := os.ReadFile(filepath.Join("testdata", dirPath, filename)) blob, err := os.ReadFile(filepath.Join("testdata", dirPath, filename))
if err != nil { if err != nil {
@ -130,21 +132,21 @@ func flatCallTracerTestRunner(tracerName string, filename string, dirPath string
return fmt.Errorf("failed to unmarshal trace result: %v", err) return fmt.Errorf("failed to unmarshal trace result: %v", err)
} }
if !jsonEqualFlat(ret, test.Result) { if !jsonEqualFlat(ret, test.Result) {
t.Logf("tracer name: %s", tracerName) tb.Logf("tracer name: %s", tracerName)
// uncomment this for easier debugging // uncomment this for easier debugging
// have, _ := json.MarshalIndent(ret, "", " ") // have, _ := json.MarshalIndent(ret, "", " ")
// want, _ := json.MarshalIndent(test.Result, "", " ") // want, _ := json.MarshalIndent(test.Result, "", " ")
// t.Logf("trace mismatch: \nhave %+v\nwant %+v", string(have), string(want)) // tb.Logf("trace mismatch: \nhave %+v\nwant %+v", string(have), string(want))
// uncomment this for harder debugging <3 meowsbits // uncomment this for harder debugging <3 meowsbits
// lines := deep.Equal(ret, test.Result) // lines := deep.Equal(ret, test.Result)
// for _, l := range lines { // for _, l := range lines {
// t.Logf("%s", l) // tb.Logf("%s", l)
// t.FailNow() // tb.FailNow()
// } // }
t.Fatalf("trace mismatch: \nhave %+v\nwant %+v", ret, test.Result) tb.Fatalf("trace mismatch: \nhave %+v\nwant %+v", ret, test.Result)
} }
return nil return nil
} }
@ -152,10 +154,13 @@ func flatCallTracerTestRunner(tracerName string, filename string, dirPath string
// Iterates over all the input-output datasets in the tracer parity test harness and // Iterates over all the input-output datasets in the tracer parity test harness and
// runs the Native tracer against them. // runs the Native tracer against them.
func TestFlatCallTracerNative(t *testing.T) { func TestFlatCallTracerNative(t *testing.T) {
testFlatCallTracer("flatCallTracer", "call_tracer_flat", t) t.Parallel()
testFlatCallTracer(t, "flatCallTracer", "call_tracer_flat")
} }
func testFlatCallTracer(tracerName string, dirPath string, t *testing.T) { func testFlatCallTracer(t *testing.T, tracerName string, dirPath string) {
t.Helper()
files, err := os.ReadDir(filepath.Join("testdata", dirPath)) files, err := os.ReadDir(filepath.Join("testdata", dirPath))
if err != nil { if err != nil {
t.Fatalf("failed to retrieve tracer test suite: %v", err) t.Fatalf("failed to retrieve tracer test suite: %v", err)
@ -168,7 +173,7 @@ func testFlatCallTracer(tracerName string, dirPath string, t *testing.T) {
t.Run(camel(strings.TrimSuffix(file.Name(), ".json")), func(t *testing.T) { t.Run(camel(strings.TrimSuffix(file.Name(), ".json")), func(t *testing.T) {
t.Parallel() t.Parallel()
err := flatCallTracerTestRunner(tracerName, file.Name(), dirPath, t) err := flatCallTracerTestRunner(t, tracerName, file.Name(), dirPath)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -204,7 +209,7 @@ func BenchmarkFlatCallTracer(b *testing.B) {
filename := strings.TrimPrefix(file, "testdata/call_tracer_flat/") filename := strings.TrimPrefix(file, "testdata/call_tracer_flat/")
b.Run(camel(strings.TrimSuffix(filename, ".json")), func(b *testing.B) { b.Run(camel(strings.TrimSuffix(filename, ".json")), func(b *testing.B) {
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
err := flatCallTracerTestRunner("flatCallTracer", filename, "call_tracer_flat", b) err := flatCallTracerTestRunner(b, "flatCallTracer", filename, "call_tracer_flat")
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }

View file

@ -54,14 +54,17 @@ type testcase struct {
} }
func TestPrestateTracerLegacy(t *testing.T) { func TestPrestateTracerLegacy(t *testing.T) {
t.Parallel()
testPrestateDiffTracer("prestateTracerLegacy", "prestate_tracer_legacy", t) testPrestateDiffTracer("prestateTracerLegacy", "prestate_tracer_legacy", t)
} }
func TestPrestateTracer(t *testing.T) { func TestPrestateTracer(t *testing.T) {
t.Parallel()
testPrestateDiffTracer("prestateTracer", "prestate_tracer", t) testPrestateDiffTracer("prestateTracer", "prestate_tracer", t)
} }
func TestPrestateWithDiffModeTracer(t *testing.T) { func TestPrestateWithDiffModeTracer(t *testing.T) {
t.Parallel()
testPrestateDiffTracer("prestateTracer", "prestate_tracer_with_diff_mode", t) testPrestateDiffTracer("prestateTracer", "prestate_tracer_with_diff_mode", t)
} }

View file

@ -289,6 +289,8 @@ func TestEnterExit(t *testing.T) {
} }
func TestSetup(t *testing.T) { func TestSetup(t *testing.T) {
t.Parallel()
// Test empty config // Test empty config
_, err := newJsTracer(`{setup: function(cfg) { if (cfg !== "{}") { throw("invalid empty config") } }, fault: function() {}, result: function() {}}`, new(tracers.Context), nil) _, err := newJsTracer(`{setup: function(cfg) { if (cfg !== "{}") { throw("invalid empty config") } }, fault: function() {}, result: function() {}}`, new(tracers.Context), nil)
if err != nil { if err != nil {

View file

@ -78,6 +78,8 @@ func TestStoreCapture(t *testing.T) {
// Tests that blank fields don't appear in logs when JSON marshalled, to reduce // Tests that blank fields don't appear in logs when JSON marshalled, to reduce
// logs bloat and confusion. See https://github.com/ethereum/go-ethereum/issues/24487 // logs bloat and confusion. See https://github.com/ethereum/go-ethereum/issues/24487
func TestStructLogMarshalingOmitEmpty(t *testing.T) { func TestStructLogMarshalingOmitEmpty(t *testing.T) {
t.Parallel()
tests := []struct { tests := []struct {
name string name string
log *StructLog log *StructLog
@ -94,7 +96,10 @@ func TestStructLogMarshalingOmitEmpty(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
t.Parallel()
blob, err := json.Marshal(tt.log) blob, err := json.Marshal(tt.log)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View file

@ -112,6 +112,8 @@ func BenchmarkTransactionTrace(b *testing.B) {
} }
func TestMemCopying(t *testing.T) { func TestMemCopying(t *testing.T) {
t.Parallel()
for i, tc := range []struct { for i, tc := range []struct {
memsize int64 memsize int64
offset int64 offset int64

View file

@ -23,6 +23,8 @@ import (
) )
func TestTracker(t *testing.T) { func TestTracker(t *testing.T) {
t.Parallel()
var cases = []struct { var cases = []struct {
limit int limit int
calls []uint64 calls []uint64
@ -118,6 +120,8 @@ func TestTracker(t *testing.T) {
} }
func TestTrackerWait(t *testing.T) { func TestTrackerWait(t *testing.T) {
t.Parallel()
var ( var (
tracker = newStateTracker(5, 0) // limit = 5, oldest = 0 tracker = newStateTracker(5, 0) // limit = 5, oldest = 0
result = make(chan error, 1) result = make(chan error, 1)

View file

@ -122,10 +122,16 @@ func TestGethClient(t *testing.T) {
func(t *testing.T) { testGetNodeInfo(t, client) }, func(t *testing.T) { testGetNodeInfo(t, client) },
}, { }, {
"TestSubscribePendingTxHashes", "TestSubscribePendingTxHashes",
func(t *testing.T) { testSubscribePendingTransactions(t, client) }, func(t *testing.T) {
t.Helper()
testSubscribePendingTransactions(t, client)
},
}, { }, {
"TestSubscribePendingTxs", "TestSubscribePendingTxs",
func(t *testing.T) { testSubscribeFullPendingTransactions(t, client) }, func(t *testing.T) {
t.Helper()
testSubscribeFullPendingTransactions(t, client)
},
}, { }, {
"TestCallContract", "TestCallContract",
func(t *testing.T) { testCallContract(t, client) }, func(t *testing.T) { testCallContract(t, client) },
@ -136,10 +142,16 @@ func TestGethClient(t *testing.T) {
// Hence: this test should be last, execute the tests serially. // Hence: this test should be last, execute the tests serially.
{ {
"TestAccessList", "TestAccessList",
func(t *testing.T) { testAccessList(t, client) }, func(t *testing.T) {
t.Helper()
testAccessList(t, client)
},
}, { }, {
"TestSetHead", "TestSetHead",
func(t *testing.T) { testSetHead(t, client) }, func(t *testing.T) {
t.Helper()
testSetHead(t, client)
},
}, },
} }
for _, tt := range tests { for _, tt := range tests {
@ -309,6 +321,8 @@ func testSubscribePendingTransactions(t *testing.T, client *rpc.Client) {
} }
func testSubscribeFullPendingTransactions(t *testing.T, client *rpc.Client) { func testSubscribeFullPendingTransactions(t *testing.T, client *rpc.Client) {
t.Helper()
ec := New(client) ec := New(client)
ethcl := ethclient.NewClient(client) ethcl := ethclient.NewClient(client)
// Subscribe to Transactions // Subscribe to Transactions
@ -367,6 +381,8 @@ func testCallContract(t *testing.T, client *rpc.Client) {
} }
func TestOverrideAccountMarshal(t *testing.T) { func TestOverrideAccountMarshal(t *testing.T) {
t.Parallel()
om := map[common.Address]OverrideAccount{ om := map[common.Address]OverrideAccount{
common.Address{0x11}: OverrideAccount{ common.Address{0x11}: OverrideAccount{
// Zero-valued nonce is not overriddden, but simply dropped by the encoder. // Zero-valued nonce is not overriddden, but simply dropped by the encoder.

View file

@ -381,6 +381,8 @@ func TestDatabaseSuite(t *testing.T, New func() ethdb.KeyValueStore) {
// BenchDatabaseSuite runs a suite of benchmarks against a KeyValueStore database // BenchDatabaseSuite runs a suite of benchmarks against a KeyValueStore database
// implementation. // implementation.
func BenchDatabaseSuite(b *testing.B, New func() ethdb.KeyValueStore) { func BenchDatabaseSuite(b *testing.B, New func() ethdb.KeyValueStore) {
b.Helper()
var ( var (
keys, vals = makeDataset(1_000_000, 32, 32, false) keys, vals = makeDataset(1_000_000, 32, 32, false)
sKeys, sVals = makeDataset(1_000_000, 32, 32, true) sKeys, sVals = makeDataset(1_000_000, 32, 32, true)
@ -388,6 +390,8 @@ func BenchDatabaseSuite(b *testing.B, New func() ethdb.KeyValueStore) {
// Run benchmarks sequentially // Run benchmarks sequentially
b.Run("Write", func(b *testing.B) { b.Run("Write", func(b *testing.B) {
benchWrite := func(b *testing.B, keys, vals [][]byte) { benchWrite := func(b *testing.B, keys, vals [][]byte) {
b.Helper()
b.ResetTimer() b.ResetTimer()
b.ReportAllocs() b.ReportAllocs()
@ -407,6 +411,8 @@ func BenchDatabaseSuite(b *testing.B, New func() ethdb.KeyValueStore) {
}) })
b.Run("Read", func(b *testing.B) { b.Run("Read", func(b *testing.B) {
benchRead := func(b *testing.B, keys, vals [][]byte) { benchRead := func(b *testing.B, keys, vals [][]byte) {
b.Helper()
db := New() db := New()
defer db.Close() defer db.Close()
@ -429,6 +435,8 @@ func BenchDatabaseSuite(b *testing.B, New func() ethdb.KeyValueStore) {
}) })
b.Run("Iteration", func(b *testing.B) { b.Run("Iteration", func(b *testing.B) {
benchIteration := func(b *testing.B, keys, vals [][]byte) { benchIteration := func(b *testing.B, keys, vals [][]byte) {
b.Helper()
db := New() db := New()
defer db.Close() defer db.Close()
@ -452,6 +460,8 @@ func BenchDatabaseSuite(b *testing.B, New func() ethdb.KeyValueStore) {
}) })
b.Run("BatchWrite", func(b *testing.B) { b.Run("BatchWrite", func(b *testing.B) {
benchBatchWrite := func(b *testing.B, keys, vals [][]byte) { benchBatchWrite := func(b *testing.B, keys, vals [][]byte) {
b.Helper()
b.ResetTimer() b.ResetTimer()
b.ReportAllocs() b.ReportAllocs()
@ -484,9 +494,9 @@ func iterateKeys(it ethdb.Iterator) []string {
} }
// randomHash generates a random blob of data and returns it as a hash. // randomHash generates a random blob of data and returns it as a hash.
func randBytes(len int) []byte { func randBytes(length int) []byte {
buf := make([]byte, len) buf := make([]byte, length)
if n, err := rand.Read(buf); n != len || err != nil { if n, err := rand.Read(buf); n != length || err != nil {
panic(err) panic(err)
} }
return buf return buf

View file

@ -28,7 +28,10 @@ import (
) )
func TestPebbleDB(t *testing.T) { func TestPebbleDB(t *testing.T) {
t.Parallel()
t.Run("DatabaseSuite", func(t *testing.T) { t.Run("DatabaseSuite", func(t *testing.T) {
t.Parallel()
dbtest.TestDatabaseSuite(t, func() ethdb.KeyValueStore { dbtest.TestDatabaseSuite(t, func() ethdb.KeyValueStore {
db, err := pebble.Open("", &pebble.Options{ db, err := pebble.Open("", &pebble.Options{
FS: vfs.NewMem(), FS: vfs.NewMem(),

View file

@ -23,6 +23,8 @@ import (
) )
func TestFeedOf(t *testing.T) { func TestFeedOf(t *testing.T) {
t.Parallel()
var feed FeedOf[int] var feed FeedOf[int]
var done, subscribed sync.WaitGroup var done, subscribed sync.WaitGroup
subscriber := func(i int) { subscriber := func(i int) {
@ -71,6 +73,8 @@ func TestFeedOf(t *testing.T) {
} }
func TestFeedOfSubscribeSameChannel(t *testing.T) { func TestFeedOfSubscribeSameChannel(t *testing.T) {
t.Parallel()
var ( var (
feed FeedOf[int] feed FeedOf[int]
done sync.WaitGroup done sync.WaitGroup
@ -114,6 +118,8 @@ func TestFeedOfSubscribeSameChannel(t *testing.T) {
} }
func TestFeedOfSubscribeBlockedPost(t *testing.T) { func TestFeedOfSubscribeBlockedPost(t *testing.T) {
t.Parallel()
var ( var (
feed FeedOf[int] feed FeedOf[int]
nsends = 2000 nsends = 2000
@ -147,6 +153,8 @@ func TestFeedOfSubscribeBlockedPost(t *testing.T) {
} }
func TestFeedOfUnsubscribeBlockedPost(t *testing.T) { func TestFeedOfUnsubscribeBlockedPost(t *testing.T) {
t.Parallel()
var ( var (
feed FeedOf[int] feed FeedOf[int]
nsends = 200 nsends = 200
@ -184,6 +192,8 @@ func TestFeedOfUnsubscribeBlockedPost(t *testing.T) {
// Checks that unsubscribing a channel during Send works even if that // Checks that unsubscribing a channel during Send works even if that
// channel has already been sent on. // channel has already been sent on.
func TestFeedOfUnsubscribeSentChan(t *testing.T) { func TestFeedOfUnsubscribeSentChan(t *testing.T) {
t.Parallel()
var ( var (
feed FeedOf[int] feed FeedOf[int]
ch1 = make(chan int) ch1 = make(chan int)
@ -221,6 +231,8 @@ func TestFeedOfUnsubscribeSentChan(t *testing.T) {
} }
func TestFeedOfUnsubscribeFromInbox(t *testing.T) { func TestFeedOfUnsubscribeFromInbox(t *testing.T) {
t.Parallel()
var ( var (
feed FeedOf[int] feed FeedOf[int]
ch1 = make(chan int) ch1 = make(chan int)

View file

@ -272,6 +272,8 @@ func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) {
} }
func TestGraphQLConcurrentResolvers(t *testing.T) { func TestGraphQLConcurrentResolvers(t *testing.T) {
t.Parallel()
var ( var (
key, _ = crypto.GenerateKey() key, _ = crypto.GenerateKey()
addr = crypto.PubkeyToAddress(key.PublicKey) addr = crypto.PubkeyToAddress(key.PublicKey)
@ -366,6 +368,8 @@ func TestGraphQLConcurrentResolvers(t *testing.T) {
} }
func createNode(t *testing.T) *node.Node { func createNode(t *testing.T) *node.Node {
t.Helper()
stack, err := node.New(&node.Config{ stack, err := node.New(&node.Config{
HTTPHost: "127.0.0.1", HTTPHost: "127.0.0.1",
HTTPPort: 0, HTTPPort: 0,
@ -380,6 +384,8 @@ func createNode(t *testing.T) *node.Node {
} }
func newGQLService(t *testing.T, stack *node.Node, gspec *core.Genesis, genBlocks int, genfunc func(i int, gen *core.BlockGen)) (*handler, []*types.Block) { func newGQLService(t *testing.T, stack *node.Node, gspec *core.Genesis, genBlocks int, genfunc func(i int, gen *core.BlockGen)) (*handler, []*types.Block) {
t.Helper()
ethConf := &ethconfig.Config{ ethConf := &ethconfig.Config{
Genesis: gspec, Genesis: gspec,
Ethash: ethash.Config{ Ethash: ethash.Config{

View file

@ -42,6 +42,8 @@ import (
// TestSetFeeDefaults tests the logic for filling in default fee values works as expected. // TestSetFeeDefaults tests the logic for filling in default fee values works as expected.
func TestSetFeeDefaults(t *testing.T) { func TestSetFeeDefaults(t *testing.T) {
t.Parallel()
type test struct { type test struct {
name string name string
isLondon bool isLondon bool
@ -345,41 +347,51 @@ 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) RPCRpcReturnDataLimit() uint64 { func (b *backendMock) RPCRpcReturnDataLimit() uint64 {
//nolint: staticcheck
return b.RPCRpcReturnDataLimit() return b.RPCRpcReturnDataLimit()
} }
func (b *backendMock) SubscribeStateSyncEvent(ch chan<- core.StateSyncEvent) event.Subscription { func (b *backendMock) SubscribeStateSyncEvent(ch chan<- core.StateSyncEvent) event.Subscription {
//nolint: staticcheck
return b.SubscribeStateSyncEvent(ch) return b.SubscribeStateSyncEvent(ch)
} }
func (b *backendMock) GetRootHash(ctx context.Context, starBlockNr uint64, endBlockNr uint64) (string, error) { func (b *backendMock) GetRootHash(ctx context.Context, starBlockNr uint64, endBlockNr uint64) (string, error) {
//nolint: staticcheck
return b.GetRootHash(ctx, starBlockNr, endBlockNr) return b.GetRootHash(ctx, starBlockNr, endBlockNr)
} }
func (b *backendMock) GetBorBlockReceipt(ctx context.Context, hash common.Hash) (*types.Receipt, error) { func (b *backendMock) GetBorBlockReceipt(ctx context.Context, hash common.Hash) (*types.Receipt, error) {
//nolint: staticcheck
return b.GetBorBlockReceipt(ctx, hash) return b.GetBorBlockReceipt(ctx, hash)
} }
func (b *backendMock) GetBorBlockLogs(ctx context.Context, hash common.Hash) ([]*types.Log, error) { func (b *backendMock) GetBorBlockLogs(ctx context.Context, hash common.Hash) ([]*types.Log, error) {
//nolint: staticcheck
return b.GetBorBlockLogs(ctx, hash) return b.GetBorBlockLogs(ctx, hash)
} }
func (b *backendMock) GetBorBlockTransaction(ctx context.Context, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error) { func (b *backendMock) GetBorBlockTransaction(ctx context.Context, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error) {
//nolint: staticcheck
return b.GetBorBlockTransaction(ctx, txHash) return b.GetBorBlockTransaction(ctx, txHash)
} }
func (b *backendMock) GetBorBlockTransactionWithBlockHash(ctx context.Context, txHash common.Hash, blockHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error) { func (b *backendMock) GetBorBlockTransactionWithBlockHash(ctx context.Context, txHash common.Hash, blockHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error) {
//nolint: staticcheck
return b.GetBorBlockTransactionWithBlockHash(ctx, txHash, blockHash) return b.GetBorBlockTransactionWithBlockHash(ctx, txHash, blockHash)
} }
func (b *backendMock) SubscribeChain2HeadEvent(ch chan<- core.Chain2HeadEvent) event.Subscription { func (b *backendMock) SubscribeChain2HeadEvent(ch chan<- core.Chain2HeadEvent) event.Subscription {
//nolint: staticcheck
return b.SubscribeChain2HeadEvent(ch) return b.SubscribeChain2HeadEvent(ch)
} }
func (b *backendMock) GetCheckpointWhitelist() map[uint64]common.Hash { func (b *backendMock) GetCheckpointWhitelist() map[uint64]common.Hash {
//nolint: staticcheck
return b.GetCheckpointWhitelist() return b.GetCheckpointWhitelist()
} }
func (b *backendMock) PurgeCheckpointWhitelist() { func (b *backendMock) PurgeCheckpointWhitelist() {
//nolint: staticcheck
b.PurgeCheckpointWhitelist() b.PurgeCheckpointWhitelist()
} }

View file

@ -17,13 +17,14 @@
package flags package flags
import ( import (
"os"
"os/user" "os/user"
"runtime" "runtime"
"testing" "testing"
) )
func TestPathExpansion(t *testing.T) { func TestPathExpansion(t *testing.T) {
t.Parallel()
user, _ := user.Current() user, _ := user.Current()
var tests map[string]string var tests map[string]string
@ -51,7 +52,7 @@ func TestPathExpansion(t *testing.T) {
} }
} }
os.Setenv(`DDDXXX`, `/tmp`) t.Setenv(`DDDXXX`, `/tmp`)
for test, expected := range tests { for test, expected := range tests {
got := expandPath(test) got := expandPath(test)
if got != expected { if got != expected {

View file

@ -40,6 +40,8 @@ func (no *testNativeObjectBinding) TestMethod(call goja.FunctionCall) goja.Value
} }
func newWithTestJS(t *testing.T, testjs string) *JSRE { func newWithTestJS(t *testing.T, testjs string) *JSRE {
t.Helper()
dir := t.TempDir() dir := t.TempDir()
if testjs != "" { if testjs != "" {
if err := os.WriteFile(path.Join(dir, "test.js"), []byte(testjs), os.ModePerm); err != nil { if err := os.WriteFile(path.Join(dir, "test.js"), []byte(testjs), os.ModePerm); err != nil {

View file

@ -58,6 +58,7 @@ func VCS() (VCSInfo, bool) {
func ClientName(clientIdentifier string) string { func ClientName(clientIdentifier string) string {
git, _ := VCS() git, _ := VCS()
return fmt.Sprintf("%s/v%v/%v-%v/%v", return fmt.Sprintf("%s/v%v/%v-%v/%v",
//nolint: staticcheck
strings.Title(clientIdentifier), strings.Title(clientIdentifier),
params.VersionWithCommit(git.Commit, git.Date), params.VersionWithCommit(git.Commit, git.Date),
runtime.GOOS, runtime.GOARCH, runtime.GOOS, runtime.GOARCH,

View file

@ -38,6 +38,7 @@ type DownloaderAPI struct {
// listens for events from the downloader through the global event mux. In case it receives one of // listens for events from the downloader through the global event mux. In case it receives one of
// these events it broadcasts it to all syncing subscriptions that are installed through the // these events it broadcasts it to all syncing subscriptions that are installed through the
// installSyncSubscription channel. // installSyncSubscription channel.
// nolint: staticcheck
func NewDownloaderAPI(d *Downloader, m *event.TypeMux) *DownloaderAPI { func NewDownloaderAPI(d *Downloader, m *event.TypeMux) *DownloaderAPI {
api := &DownloaderAPI{ api := &DownloaderAPI{
d: d, d: d,

View file

@ -56,6 +56,8 @@ func TestConstantTotalCapacity(t *testing.T) {
} }
func testConstantTotalCapacity(t *testing.T, nodeCount, maxCapacityNodes, randomSend int, priorityOverflow bool) { func testConstantTotalCapacity(t *testing.T, nodeCount, maxCapacityNodes, randomSend int, priorityOverflow bool) {
t.Helper()
clock := &mclock.Simulated{} clock := &mclock.Simulated{}
nodes := make([]*testNode, nodeCount) nodes := make([]*testNode, nodeCount)
var totalCapacity uint64 var totalCapacity uint64

View file

@ -38,6 +38,8 @@ func testULCAnnounceThreshold(t *testing.T, protocol int) {
// newTestLightPeer creates node with light sync mode // newTestLightPeer creates node with light sync mode
newTestLightPeer := func(t *testing.T, protocol int, ulcServers []string, ulcFraction int) (*testClient, func()) { newTestLightPeer := func(t *testing.T, protocol int, ulcServers []string, ulcFraction int) (*testClient, func()) {
t.Helper()
netconfig := testnetConfig{ netconfig := testnetConfig{
protocol: protocol, protocol: protocol,
ulcServers: ulcServers, ulcServers: ulcServers,
@ -146,6 +148,8 @@ func connect(server *serverHandler, serverId enode.ID, client *clientHandler, pr
// newTestServerPeer creates server peer. // newTestServerPeer creates server peer.
func newTestServerPeer(t *testing.T, blocks int, protocol int, indexFn indexerCallback) (*testServer, *enode.Node, func()) { func newTestServerPeer(t *testing.T, blocks int, protocol int, indexFn indexerCallback) (*testServer, *enode.Node, func()) {
t.Helper()
netconfig := testnetConfig{ netconfig := testnetConfig{
blocks: blocks, blocks: blocks,
protocol: protocol, protocol: protocol,

View file

@ -299,6 +299,7 @@ func TestEstimatedPriority(t *testing.T) {
} }
func TestPositiveBalanceCounting(t *testing.T) { func TestPositiveBalanceCounting(t *testing.T) {
t.Parallel()
b := newBalanceTestSetup(nil, nil, nil) b := newBalanceTestSetup(nil, nil, nil)
defer b.stop() defer b.stop()

View file

@ -83,6 +83,8 @@ func TestPrettyBigInt(t *testing.T) {
} }
func TestPrettyUint256(t *testing.T) { func TestPrettyUint256(t *testing.T) {
t.Parallel()
tests := []struct { tests := []struct {
int string int string
s string s string
@ -117,6 +119,8 @@ func BenchmarkPrettyUint64Logfmt(b *testing.B) {
} }
func TestSanitation(t *testing.T) { func TestSanitation(t *testing.T) {
t.Parallel()
msg := "\u001b[1G\u001b[K\u001b[1A" msg := "\u001b[1G\u001b[K\u001b[1A"
msg2 := "\u001b \u0000" msg2 := "\u001b \u0000"
msg3 := "NiceMessage" msg3 := "NiceMessage"

View file

@ -33,6 +33,7 @@ func BenchmarkCounterFloat64Parallel(b *testing.B) {
} }
func TestCounterFloat64Clear(t *testing.T) { func TestCounterFloat64Clear(t *testing.T) {
t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
c.Inc(1.0) c.Inc(1.0)
c.Clear() c.Clear()
@ -42,6 +43,7 @@ func TestCounterFloat64Clear(t *testing.T) {
} }
func TestCounterFloat64Dec1(t *testing.T) { func TestCounterFloat64Dec1(t *testing.T) {
t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
c.Dec(1.0) c.Dec(1.0)
if count := c.Count(); count != -1.0 { if count := c.Count(); count != -1.0 {
@ -50,6 +52,7 @@ func TestCounterFloat64Dec1(t *testing.T) {
} }
func TestCounterFloat64Dec2(t *testing.T) { func TestCounterFloat64Dec2(t *testing.T) {
t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
c.Dec(2.0) c.Dec(2.0)
if count := c.Count(); count != -2.0 { if count := c.Count(); count != -2.0 {
@ -58,6 +61,7 @@ func TestCounterFloat64Dec2(t *testing.T) {
} }
func TestCounterFloat64Inc1(t *testing.T) { func TestCounterFloat64Inc1(t *testing.T) {
t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
c.Inc(1.0) c.Inc(1.0)
if count := c.Count(); count != 1.0 { if count := c.Count(); count != 1.0 {
@ -66,6 +70,7 @@ func TestCounterFloat64Inc1(t *testing.T) {
} }
func TestCounterFloat64Inc2(t *testing.T) { func TestCounterFloat64Inc2(t *testing.T) {
t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
c.Inc(2.0) c.Inc(2.0)
if count := c.Count(); count != 2.0 { if count := c.Count(); count != 2.0 {
@ -74,6 +79,7 @@ func TestCounterFloat64Inc2(t *testing.T) {
} }
func TestCounterFloat64Snapshot(t *testing.T) { func TestCounterFloat64Snapshot(t *testing.T) {
t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
c.Inc(1.0) c.Inc(1.0)
snapshot := c.Snapshot() snapshot := c.Snapshot()
@ -84,6 +90,7 @@ func TestCounterFloat64Snapshot(t *testing.T) {
} }
func TestCounterFloat64Zero(t *testing.T) { func TestCounterFloat64Zero(t *testing.T) {
t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
if count := c.Count(); count != 0 { if count := c.Count(); count != 0 {
t.Errorf("c.Count(): 0 != %v\n", count) t.Errorf("c.Count(): 0 != %v\n", count)
@ -91,6 +98,7 @@ func TestCounterFloat64Zero(t *testing.T) {
} }
func TestGetOrRegisterCounterFloat64(t *testing.T) { func TestGetOrRegisterCounterFloat64(t *testing.T) {
t.Parallel()
r := NewRegistry() r := NewRegistry()
NewRegisteredCounterFloat64("foo", r).Inc(47.0) NewRegisteredCounterFloat64("foo", r).Inc(47.0)
if c := GetOrRegisterCounterFloat64("foo", r); c.Count() != 47.0 { if c := GetOrRegisterCounterFloat64("foo", r); c.Count() != 47.0 {

View file

@ -10,6 +10,7 @@ import (
const FANOUT = 128 const FANOUT = 128
func TestReadRuntimeValues(t *testing.T) { func TestReadRuntimeValues(t *testing.T) {
t.Parallel()
var v runtimeStats var v runtimeStats
readRuntimeStats(&v) readRuntimeStats(&v)
t.Logf("%+v", v) t.Logf("%+v", v)

View file

@ -26,6 +26,7 @@ type runtimeHistogramTest struct {
// This test checks the results of statistical functions implemented // This test checks the results of statistical functions implemented
// by runtimeHistogramSnapshot. // by runtimeHistogramSnapshot.
func TestRuntimeHistogramStats(t *testing.T) { func TestRuntimeHistogramStats(t *testing.T) {
t.Parallel()
tests := []runtimeHistogramTest{ tests := []runtimeHistogramTest{
0: { 0: {
h: metrics.Float64Histogram{ h: metrics.Float64Histogram{
@ -73,7 +74,10 @@ func TestRuntimeHistogramStats(t *testing.T) {
} }
for i, test := range tests { for i, test := range tests {
i, test := i, test
t.Run(fmt.Sprint(i), func(t *testing.T) { t.Run(fmt.Sprint(i), func(t *testing.T) {
t.Parallel()
s := runtimeHistogramSnapshot(test.h) s := runtimeHistogramSnapshot(test.h)
if v := s.Count(); v != test.Count { if v := s.Count(); v != test.Count {
@ -121,6 +125,7 @@ func approxEqual(x, y, ε float64) bool {
// This test verifies that requesting Percentiles in unsorted order // This test verifies that requesting Percentiles in unsorted order
// returns them in the requested order. // returns them in the requested order.
func TestRuntimeHistogramStatsPercentileOrder(t *testing.T) { func TestRuntimeHistogramStatsPercentileOrder(t *testing.T) {
t.Parallel()
p := runtimeHistogramSnapshot{ p := runtimeHistogramSnapshot{
Counts: []uint64{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, Counts: []uint64{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
Buckets: []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, Buckets: []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},

View file

@ -49,6 +49,7 @@ func TestStartRPC(t *testing.T) {
name: "all off", name: "all off",
cfg: Config{}, cfg: Config{},
fn: func(t *testing.T, n *Node, api *adminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
t.Helper()
}, },
wantReachable: false, wantReachable: false,
wantHandlers: false, wantHandlers: false,
@ -59,6 +60,7 @@ func TestStartRPC(t *testing.T) {
name: "rpc enabled through config", name: "rpc enabled through config",
cfg: Config{HTTPHost: "127.0.0.1"}, cfg: Config{HTTPHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *adminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
t.Helper()
}, },
wantReachable: true, wantReachable: true,
wantHandlers: true, wantHandlers: true,
@ -69,6 +71,8 @@ func TestStartRPC(t *testing.T) {
name: "rpc enabled through API", name: "rpc enabled through API",
cfg: Config{}, cfg: Config{},
fn: func(t *testing.T, n *Node, api *adminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
t.Helper()
_, err := api.StartHTTP(sp("127.0.0.1"), ip(0), nil, nil, nil) _, err := api.StartHTTP(sp("127.0.0.1"), ip(0), nil, nil, nil)
assert.NoError(t, err) assert.NoError(t, err)
}, },
@ -81,6 +85,8 @@ func TestStartRPC(t *testing.T) {
name: "rpc start again after failure", name: "rpc start again after failure",
cfg: Config{}, cfg: Config{},
fn: func(t *testing.T, n *Node, api *adminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
t.Helper()
// Listen on a random port. // Listen on a random port.
listener, err := net.Listen("tcp", "127.0.0.1:0") listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil { if err != nil {
@ -109,6 +115,8 @@ func TestStartRPC(t *testing.T) {
name: "rpc stopped through API", name: "rpc stopped through API",
cfg: Config{HTTPHost: "127.0.0.1"}, cfg: Config{HTTPHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *adminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
t.Helper()
_, err := api.StopHTTP() _, err := api.StopHTTP()
assert.NoError(t, err) assert.NoError(t, err)
}, },
@ -121,6 +129,8 @@ func TestStartRPC(t *testing.T) {
name: "rpc stopped twice", name: "rpc stopped twice",
cfg: Config{HTTPHost: "127.0.0.1"}, cfg: Config{HTTPHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *adminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
t.Helper()
_, err := api.StopHTTP() _, err := api.StopHTTP()
assert.NoError(t, err) assert.NoError(t, err)
@ -144,6 +154,8 @@ func TestStartRPC(t *testing.T) {
name: "ws enabled through API", name: "ws enabled through API",
cfg: Config{}, cfg: Config{},
fn: func(t *testing.T, n *Node, api *adminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
t.Helper()
_, err := api.StartWS(sp("127.0.0.1"), ip(0), nil, nil) _, err := api.StartWS(sp("127.0.0.1"), ip(0), nil, nil)
assert.NoError(t, err) assert.NoError(t, err)
}, },
@ -156,6 +168,8 @@ func TestStartRPC(t *testing.T) {
name: "ws stopped through API", name: "ws stopped through API",
cfg: Config{WSHost: "127.0.0.1"}, cfg: Config{WSHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *adminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
t.Helper()
_, err := api.StopWS() _, err := api.StopWS()
assert.NoError(t, err) assert.NoError(t, err)
}, },
@ -168,6 +182,8 @@ func TestStartRPC(t *testing.T) {
name: "ws stopped twice", name: "ws stopped twice",
cfg: Config{WSHost: "127.0.0.1"}, cfg: Config{WSHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *adminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
t.Helper()
_, err := api.StopWS() _, err := api.StopWS()
assert.NoError(t, err) assert.NoError(t, err)
@ -183,6 +199,8 @@ func TestStartRPC(t *testing.T) {
name: "ws enabled after RPC", name: "ws enabled after RPC",
cfg: Config{HTTPHost: "127.0.0.1"}, cfg: Config{HTTPHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *adminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
t.Helper()
wsport := n.http.port wsport := n.http.port
_, err := api.StartWS(sp("127.0.0.1"), ip(wsport), nil, nil) _, err := api.StartWS(sp("127.0.0.1"), ip(wsport), nil, nil)
assert.NoError(t, err) assert.NoError(t, err)
@ -196,6 +214,8 @@ func TestStartRPC(t *testing.T) {
name: "ws enabled after RPC then stopped", name: "ws enabled after RPC then stopped",
cfg: Config{HTTPHost: "127.0.0.1"}, cfg: Config{HTTPHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *adminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
t.Helper()
wsport := n.http.port wsport := n.http.port
_, err := api.StartWS(sp("127.0.0.1"), ip(wsport), nil, nil) _, err := api.StartWS(sp("127.0.0.1"), ip(wsport), nil, nil)
assert.NoError(t, err) assert.NoError(t, err)
@ -211,6 +231,8 @@ func TestStartRPC(t *testing.T) {
{ {
name: "rpc stopped with ws enabled", name: "rpc stopped with ws enabled",
fn: func(t *testing.T, n *Node, api *adminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
t.Helper()
_, err := api.StartHTTP(sp("127.0.0.1"), ip(0), nil, nil, nil) _, err := api.StartHTTP(sp("127.0.0.1"), ip(0), nil, nil, nil)
assert.NoError(t, err) assert.NoError(t, err)
@ -229,6 +251,8 @@ func TestStartRPC(t *testing.T) {
{ {
name: "rpc enabled after ws", name: "rpc enabled after ws",
fn: func(t *testing.T, n *Node, api *adminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
t.Helper()
_, err := api.StartWS(sp("127.0.0.1"), ip(0), nil, nil) _, err := api.StartWS(sp("127.0.0.1"), ip(0), nil, nil)
assert.NoError(t, err) assert.NoError(t, err)

View file

@ -92,7 +92,10 @@ func (at *authTest) Run(t *testing.T) {
} }
} }
// nolint: tparallel, paralleltest
func TestAuthEndpoints(t *testing.T) { func TestAuthEndpoints(t *testing.T) {
t.Parallel()
var secret [32]byte var secret [32]byte
if _, err := crand.Read(secret[:]); err != nil { if _, err := crand.Read(secret[:]); err != nil {
t.Fatalf("failed to create jwt secret: %v", err) t.Fatalf("failed to create jwt secret: %v", err)
@ -193,6 +196,7 @@ func TestAuthEndpoints(t *testing.T) {
} }
for _, testCase := range testCases { for _, testCase := range testCases {
t.Parallel()
t.Run(testCase.name, testCase.Run) t.Run(testCase.name, testCase.Run)
} }
} }

View file

@ -281,6 +281,8 @@ func rpcRequest(t *testing.T, url, method string, extraHeaders ...string) *http.
} }
func batchRpcRequest(t *testing.T, url string, methods []string, extraHeaders ...string) *http.Response { func batchRpcRequest(t *testing.T, url string, methods []string, extraHeaders ...string) *http.Response {
t.Helper()
reqs := make([]string, len(methods)) reqs := make([]string, len(methods))
for i, m := range methods { for i, m := range methods {
reqs[i] = fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"%s","params":[]}`, m) reqs[i] = fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"%s","params":[]}`, m)
@ -448,6 +450,8 @@ func TestJWT(t *testing.T) {
} }
func TestGzipHandler(t *testing.T) { func TestGzipHandler(t *testing.T) {
t.Parallel()
type gzipTest struct { type gzipTest struct {
name string name string
handler http.HandlerFunc handler http.HandlerFunc
@ -522,6 +526,7 @@ func TestGzipHandler(t *testing.T) {
for _, test := range tests { for _, test := range tests {
test := test test := test
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(newGzipHandler(test.handler)) srv := httptest.NewServer(newGzipHandler(test.handler))
defer srv.Close() defer srv.Close()
@ -556,6 +561,8 @@ func TestGzipHandler(t *testing.T) {
} }
func TestHTTPWriteTimeout(t *testing.T) { func TestHTTPWriteTimeout(t *testing.T) {
t.Parallel()
const ( const (
timeoutRes = `{"jsonrpc":"2.0","id":1,"error":{"code":-32002,"message":"request timed out"}}` timeoutRes = `{"jsonrpc":"2.0","id":1,"error":{"code":-32002,"message":"request timed out"}}`
greetRes = `{"jsonrpc":"2.0","id":1,"result":"Hello"}` greetRes = `{"jsonrpc":"2.0","id":1,"result":"Hello"}`
@ -568,6 +575,7 @@ func TestHTTPWriteTimeout(t *testing.T) {
// Send normal request // Send normal request
t.Run("message", func(t *testing.T) { t.Run("message", func(t *testing.T) {
t.Parallel()
resp := rpcRequest(t, url, "test_sleep") resp := rpcRequest(t, url, "test_sleep")
defer resp.Body.Close() defer resp.Body.Close()
body, err := io.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
@ -581,6 +589,7 @@ func TestHTTPWriteTimeout(t *testing.T) {
// Batch request // Batch request
t.Run("batch", func(t *testing.T) { t.Run("batch", func(t *testing.T) {
t.Parallel()
want := fmt.Sprintf("[%s,%s,%s]", greetRes, timeoutRes, timeoutRes) want := fmt.Sprintf("[%s,%s,%s]", greetRes, timeoutRes, timeoutRes)
resp := batchRpcRequest(t, url, []string{"test_greet", "test_sleep", "test_greet"}) resp := batchRpcRequest(t, url, []string{"test_greet", "test_sleep", "test_greet"})
defer resp.Body.Close() defer resp.Body.Close()

View file

@ -397,6 +397,7 @@ func TestTable_revalidateSyncRecord(t *testing.T) {
} }
func TestNodesPush(t *testing.T) { func TestNodesPush(t *testing.T) {
t.Parallel()
var target enode.ID var target enode.ID
n1 := nodeAtDistance(target, 255, intIP(1)) n1 := nodeAtDistance(target, 255, intIP(1))
n2 := nodeAtDistance(target, 254, intIP(2)) n2 := nodeAtDistance(target, 254, intIP(2))

View file

@ -519,34 +519,40 @@ func TestUDPv5_talkRequest(t *testing.T) {
// This test checks that lookupDistances works. // This test checks that lookupDistances works.
func TestUDPv5_lookupDistances(t *testing.T) { func TestUDPv5_lookupDistances(t *testing.T) {
t.Parallel()
test := newUDPV5Test(t) test := newUDPV5Test(t)
lnID := test.table.self().ID() lnID := test.table.self().ID()
t.Run("target distance of 1", func(t *testing.T) { t.Run("target distance of 1", func(t *testing.T) {
t.Parallel()
node := nodeAtDistance(lnID, 1, intIP(0)) node := nodeAtDistance(lnID, 1, intIP(0))
dists := lookupDistances(lnID, node.ID()) dists := lookupDistances(lnID, node.ID())
require.Equal(t, []uint{1, 2, 3}, dists) require.Equal(t, []uint{1, 2, 3}, dists)
}) })
t.Run("target distance of 2", func(t *testing.T) { t.Run("target distance of 2", func(t *testing.T) {
t.Parallel()
node := nodeAtDistance(lnID, 2, intIP(0)) node := nodeAtDistance(lnID, 2, intIP(0))
dists := lookupDistances(lnID, node.ID()) dists := lookupDistances(lnID, node.ID())
require.Equal(t, []uint{2, 3, 1}, dists) require.Equal(t, []uint{2, 3, 1}, dists)
}) })
t.Run("target distance of 128", func(t *testing.T) { t.Run("target distance of 128", func(t *testing.T) {
t.Parallel()
node := nodeAtDistance(lnID, 128, intIP(0)) node := nodeAtDistance(lnID, 128, intIP(0))
dists := lookupDistances(lnID, node.ID()) dists := lookupDistances(lnID, node.ID())
require.Equal(t, []uint{128, 129, 127}, dists) require.Equal(t, []uint{128, 129, 127}, dists)
}) })
t.Run("target distance of 255", func(t *testing.T) { t.Run("target distance of 255", func(t *testing.T) {
t.Parallel()
node := nodeAtDistance(lnID, 255, intIP(0)) node := nodeAtDistance(lnID, 255, intIP(0))
dists := lookupDistances(lnID, node.ID()) dists := lookupDistances(lnID, node.ID())
require.Equal(t, []uint{255, 256, 254}, dists) require.Equal(t, []uint{255, 256, 254}, dists)
}) })
t.Run("target distance of 256", func(t *testing.T) { t.Run("target distance of 256", func(t *testing.T) {
t.Parallel()
node := nodeAtDistance(lnID, 256, intIP(0)) node := nodeAtDistance(lnID, 256, intIP(0))
dists := lookupDistances(lnID, node.ID()) dists := lookupDistances(lnID, node.ID())
require.Equal(t, []uint{256, 255, 254}, dists) require.Equal(t, []uint{256, 255, 254}, dists)

View file

@ -170,6 +170,7 @@ func TestDirty(t *testing.T) {
} }
func TestSize(t *testing.T) { func TestSize(t *testing.T) {
t.Parallel()
var r Record var r Record
// Empty record size is 3 bytes. // Empty record size is 3 bytes.

View file

@ -120,6 +120,8 @@ func TestCheckCompatible(t *testing.T) {
} }
func TestConfigRules(t *testing.T) { func TestConfigRules(t *testing.T) {
t.Parallel()
c := &ChainConfig{ c := &ChainConfig{
ShanghaiTime: newUint64(500), ShanghaiTime: newUint64(500),
} }

View file

@ -61,6 +61,8 @@ func TestCountValues(t *testing.T) {
} }
func TestSplitString(t *testing.T) { func TestSplitString(t *testing.T) {
t.Parallel()
for i, test := range []string{ for i, test := range []string{
"C0", "C0",
"C100", "C100",
@ -75,6 +77,8 @@ func TestSplitString(t *testing.T) {
} }
func TestSplitList(t *testing.T) { func TestSplitList(t *testing.T) {
t.Parallel()
for i, test := range []string{ for i, test := range []string{
"80", "80",
"00", "00",
@ -305,6 +309,8 @@ func TestAppendUint64Random(t *testing.T) {
} }
func TestBytesSize(t *testing.T) { func TestBytesSize(t *testing.T) {
t.Parallel()
tests := []struct { tests := []struct {
v []byte v []byte
size uint64 size uint64

View file

@ -74,6 +74,8 @@ func TestClientResponseType(t *testing.T) {
// This test checks calling a method that returns 'null'. // This test checks calling a method that returns 'null'.
func TestClientNullResponse(t *testing.T) { func TestClientNullResponse(t *testing.T) {
t.Parallel()
server := newTestServer() server := newTestServer()
defer server.Stop() defer server.Stop()
@ -172,7 +174,10 @@ func TestClientBatchRequest(t *testing.T) {
} }
} }
// nolint: tparallel
func TestClientBatchRequest_len(t *testing.T) { func TestClientBatchRequest_len(t *testing.T) {
t.Parallel()
b, err := json.Marshal([]jsonrpcMessage{ b, err := json.Marshal([]jsonrpcMessage{
{Version: "2.0", ID: json.RawMessage("1"), Method: "foo", Result: json.RawMessage(`"0x1"`)}, {Version: "2.0", ID: json.RawMessage("1"), Method: "foo", Result: json.RawMessage(`"0x1"`)},
{Version: "2.0", ID: json.RawMessage("2"), Method: "bar", Result: json.RawMessage(`"0x2"`)}, {Version: "2.0", ID: json.RawMessage("2"), Method: "bar", Result: json.RawMessage(`"0x2"`)},
@ -195,6 +200,8 @@ func TestClientBatchRequest_len(t *testing.T) {
defer client.Close() defer client.Close()
t.Run("too-few", func(t *testing.T) { t.Run("too-few", func(t *testing.T) {
t.Parallel()
batch := []BatchElem{ batch := []BatchElem{
{Method: "foo"}, {Method: "foo"},
{Method: "bar"}, {Method: "bar"},
@ -208,6 +215,8 @@ func TestClientBatchRequest_len(t *testing.T) {
}) })
t.Run("too-many", func(t *testing.T) { t.Run("too-many", func(t *testing.T) {
t.Parallel()
batch := []BatchElem{ batch := []BatchElem{
{Method: "foo"}, {Method: "foo"},
} }

View file

@ -203,6 +203,8 @@ func TestHTTPPeerInfo(t *testing.T) {
} }
func TestNewContextWithHeaders(t *testing.T) { func TestNewContextWithHeaders(t *testing.T) {
t.Parallel()
expectedHeaders := 0 expectedHeaders := 0
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
for i := 0; i < expectedHeaders; i++ { for i := 0; i < expectedHeaders; i++ {

View file

@ -87,6 +87,8 @@ func TestBytesPadding(t *testing.T) {
} }
func TestParseAddress(t *testing.T) { func TestParseAddress(t *testing.T) {
t.Parallel()
tests := []struct { tests := []struct {
Input interface{} Input interface{}
Output []byte // nil => error Output []byte // nil => error
@ -200,6 +202,8 @@ func TestParseInteger(t *testing.T) {
} }
func TestConvertStringDataToSlice(t *testing.T) { func TestConvertStringDataToSlice(t *testing.T) {
t.Parallel()
slice := []string{"a", "b", "c"} slice := []string{"a", "b", "c"}
var it interface{} = slice var it interface{} = slice
_, err := convertDataToSlice(it) _, err := convertDataToSlice(it)
@ -209,6 +213,8 @@ func TestConvertStringDataToSlice(t *testing.T) {
} }
func TestConvertUint256DataToSlice(t *testing.T) { func TestConvertUint256DataToSlice(t *testing.T) {
t.Parallel()
slice := []*math.HexOrDecimal256{ slice := []*math.HexOrDecimal256{
math.NewHexOrDecimal256(1), math.NewHexOrDecimal256(1),
math.NewHexOrDecimal256(2), math.NewHexOrDecimal256(2),
@ -222,6 +228,8 @@ func TestConvertUint256DataToSlice(t *testing.T) {
} }
func TestConvertAddressDataToSlice(t *testing.T) { func TestConvertAddressDataToSlice(t *testing.T) {
t.Parallel()
slice := []common.Address{ slice := []common.Address{
common.HexToAddress("0x0000000000000000000000000000000000000001"), common.HexToAddress("0x0000000000000000000000000000000000000001"),
common.HexToAddress("0x0000000000000000000000000000000000000002"), common.HexToAddress("0x0000000000000000000000000000000000000002"),

View file

@ -19,6 +19,8 @@ package apitypes
import "testing" import "testing"
func TestIsPrimitive(t *testing.T) { func TestIsPrimitive(t *testing.T) {
t.Parallel()
// Expected positives // Expected positives
for i, tc := range []string{ for i, tc := range []string{
"int24", "int24[]", "uint88", "uint88[]", "uint", "uint[]", "int256", "int256[]", "int24", "int24[]", "uint88", "uint88[]", "uint", "uint[]", "int256", "int256[]",

View file

@ -829,6 +829,8 @@ func TestComplexTypedData(t *testing.T) {
} }
func TestGnosisSafe(t *testing.T) { func TestGnosisSafe(t *testing.T) {
t.Parallel()
// json missing chain id // json missing chain id
js := "{\n \"safe\": \"0x899FcB1437DE65DC6315f5a69C017dd3F2837557\",\n \"to\": \"0x899FcB1437DE65DC6315f5a69C017dd3F2837557\",\n \"value\": \"0\",\n \"data\": \"0x0d582f13000000000000000000000000d3ed2b8756b942c98c851722f3bd507a17b4745f0000000000000000000000000000000000000000000000000000000000000005\",\n \"operation\": 0,\n \"gasToken\": \"0x0000000000000000000000000000000000000000\",\n \"safeTxGas\": 0,\n \"baseGas\": 0,\n \"gasPrice\": \"0\",\n \"refundReceiver\": \"0x0000000000000000000000000000000000000000\",\n \"nonce\": 0,\n \"executionDate\": null,\n \"submissionDate\": \"2022-02-23T14:09:00.018475Z\",\n \"modified\": \"2022-12-01T15:52:21.214357Z\",\n \"blockNumber\": null,\n \"transactionHash\": null,\n \"safeTxHash\": \"0x6f0f5cffee69087c9d2471e477a63cab2ae171cf433e754315d558d8836274f4\",\n \"executor\": null,\n \"isExecuted\": false,\n \"isSuccessful\": null,\n \"ethGasPrice\": null,\n \"maxFeePerGas\": null,\n \"maxPriorityFeePerGas\": null,\n \"gasUsed\": null,\n \"fee\": null,\n \"origin\": \"https://gnosis-safe.io\",\n \"dataDecoded\": {\n \"method\": \"addOwnerWithThreshold\",\n \"parameters\": [\n {\n \"name\": \"owner\",\n \"type\": \"address\",\n \"value\": \"0xD3Ed2b8756b942c98c851722F3bd507a17B4745F\"\n },\n {\n \"name\": \"_threshold\",\n \"type\": \"uint256\",\n \"value\": \"5\"\n }\n ]\n },\n \"confirmationsRequired\": 4,\n \"confirmations\": [\n {\n \"owner\": \"0x30B714E065B879F5c042A75Bb40a220A0BE27966\",\n \"submissionDate\": \"2022-03-01T14:56:22Z\",\n \"transactionHash\": \"0x6d0a9c83ac7578ef3be1f2afce089fb83b619583dfa779b82f4422fd64ff3ee9\",\n \"signature\": \"0x00000000000000000000000030b714e065b879f5c042a75bb40a220a0be27966000000000000000000000000000000000000000000000000000000000000000001\",\n \"signatureType\": \"APPROVED_HASH\"\n },\n {\n \"owner\": \"0x8300dFEa25Da0eb744fC0D98c23283F86AB8c10C\",\n \"submissionDate\": \"2022-12-01T15:52:21.214357Z\",\n \"transactionHash\": null,\n \"signature\": \"0xbce73de4cc6ee208e933a93c794dcb8ba1810f9848d1eec416b7be4dae9854c07dbf1720e60bbd310d2159197a380c941cfdb55b3ce58f9dd69efd395d7bef881b\",\n \"signatureType\": \"EOA\"\n }\n ],\n \"trusted\": true,\n \"signatures\": null\n}\n" js := "{\n \"safe\": \"0x899FcB1437DE65DC6315f5a69C017dd3F2837557\",\n \"to\": \"0x899FcB1437DE65DC6315f5a69C017dd3F2837557\",\n \"value\": \"0\",\n \"data\": \"0x0d582f13000000000000000000000000d3ed2b8756b942c98c851722f3bd507a17b4745f0000000000000000000000000000000000000000000000000000000000000005\",\n \"operation\": 0,\n \"gasToken\": \"0x0000000000000000000000000000000000000000\",\n \"safeTxGas\": 0,\n \"baseGas\": 0,\n \"gasPrice\": \"0\",\n \"refundReceiver\": \"0x0000000000000000000000000000000000000000\",\n \"nonce\": 0,\n \"executionDate\": null,\n \"submissionDate\": \"2022-02-23T14:09:00.018475Z\",\n \"modified\": \"2022-12-01T15:52:21.214357Z\",\n \"blockNumber\": null,\n \"transactionHash\": null,\n \"safeTxHash\": \"0x6f0f5cffee69087c9d2471e477a63cab2ae171cf433e754315d558d8836274f4\",\n \"executor\": null,\n \"isExecuted\": false,\n \"isSuccessful\": null,\n \"ethGasPrice\": null,\n \"maxFeePerGas\": null,\n \"maxPriorityFeePerGas\": null,\n \"gasUsed\": null,\n \"fee\": null,\n \"origin\": \"https://gnosis-safe.io\",\n \"dataDecoded\": {\n \"method\": \"addOwnerWithThreshold\",\n \"parameters\": [\n {\n \"name\": \"owner\",\n \"type\": \"address\",\n \"value\": \"0xD3Ed2b8756b942c98c851722F3bd507a17B4745F\"\n },\n {\n \"name\": \"_threshold\",\n \"type\": \"uint256\",\n \"value\": \"5\"\n }\n ]\n },\n \"confirmationsRequired\": 4,\n \"confirmations\": [\n {\n \"owner\": \"0x30B714E065B879F5c042A75Bb40a220A0BE27966\",\n \"submissionDate\": \"2022-03-01T14:56:22Z\",\n \"transactionHash\": \"0x6d0a9c83ac7578ef3be1f2afce089fb83b619583dfa779b82f4422fd64ff3ee9\",\n \"signature\": \"0x00000000000000000000000030b714e065b879f5c042a75bb40a220a0be27966000000000000000000000000000000000000000000000000000000000000000001\",\n \"signatureType\": \"APPROVED_HASH\"\n },\n {\n \"owner\": \"0x8300dFEa25Da0eb744fC0D98c23283F86AB8c10C\",\n \"submissionDate\": \"2022-12-01T15:52:21.214357Z\",\n \"transactionHash\": null,\n \"signature\": \"0xbce73de4cc6ee208e933a93c794dcb8ba1810f9848d1eec416b7be4dae9854c07dbf1720e60bbd310d2159197a380c941cfdb55b3ce58f9dd69efd395d7bef881b\",\n \"signatureType\": \"EOA\"\n }\n ],\n \"trusted\": true,\n \"signatures\": null\n}\n"
var gnosisTx core.GnosisSafeTx var gnosisTx core.GnosisSafeTx
@ -984,6 +986,8 @@ var complexTypedDataLCRefType = `
` `
func TestComplexTypedDataWithLowercaseReftype(t *testing.T) { func TestComplexTypedDataWithLowercaseReftype(t *testing.T) {
t.Parallel()
var td apitypes.TypedData var td apitypes.TypedData
err := json.Unmarshal([]byte(complexTypedDataLCRefType), &td) err := json.Unmarshal([]byte(complexTypedDataLCRefType), &td)
if err != nil { if err != nil {

View file

@ -110,6 +110,8 @@ func TestSecureGetKey(t *testing.T) {
} }
func TestStateTrieConcurrency(t *testing.T) { func TestStateTrieConcurrency(t *testing.T) {
t.Parallel()
// Create an initial trie and copy if for concurrent access // Create an initial trie and copy if for concurrent access
_, trie, _ := makeTestStateTrie() _, trie, _ := makeTestStateTrie()

View file

@ -51,6 +51,7 @@ var (
) )
func TestTrieTracer(t *testing.T) { func TestTrieTracer(t *testing.T) {
t.Parallel()
testTrieTracer(t, tiny) testTrieTracer(t, tiny)
testTrieTracer(t, nonAligned) testTrieTracer(t, nonAligned)
testTrieTracer(t, standard) testTrieTracer(t, standard)
@ -59,6 +60,8 @@ func TestTrieTracer(t *testing.T) {
// Tests if the trie diffs are tracked correctly. Tracer should capture // Tests if the trie diffs are tracked correctly. Tracer should capture
// all non-leaf dirty nodes, no matter the node is embedded or not. // all non-leaf dirty nodes, no matter the node is embedded or not.
func testTrieTracer(t *testing.T, vals []struct{ k, v string }) { func testTrieTracer(t *testing.T, vals []struct{ k, v string }) {
t.Helper()
db := NewDatabase(rawdb.NewMemoryDatabase()) db := NewDatabase(rawdb.NewMemoryDatabase())
trie := NewEmpty(db) trie := NewEmpty(db)
@ -96,12 +99,15 @@ func testTrieTracer(t *testing.T, vals []struct{ k, v string }) {
// Test that after inserting a new batch of nodes and deleting them immediately, // Test that after inserting a new batch of nodes and deleting them immediately,
// the trie tracer should be cleared normally as no operation happened. // the trie tracer should be cleared normally as no operation happened.
func TestTrieTracerNoop(t *testing.T) { func TestTrieTracerNoop(t *testing.T) {
t.Parallel()
testTrieTracerNoop(t, tiny) testTrieTracerNoop(t, tiny)
testTrieTracerNoop(t, nonAligned) testTrieTracerNoop(t, nonAligned)
testTrieTracerNoop(t, standard) testTrieTracerNoop(t, standard)
} }
func testTrieTracerNoop(t *testing.T, vals []struct{ k, v string }) { func testTrieTracerNoop(t *testing.T, vals []struct{ k, v string }) {
t.Helper()
trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase())) trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
for _, val := range vals { for _, val := range vals {
trie.MustUpdate([]byte(val.k), []byte(val.v)) trie.MustUpdate([]byte(val.k), []byte(val.v))
@ -119,12 +125,15 @@ func testTrieTracerNoop(t *testing.T, vals []struct{ k, v string }) {
// Tests if the accessList is correctly tracked. // Tests if the accessList is correctly tracked.
func TestAccessList(t *testing.T) { func TestAccessList(t *testing.T) {
t.Parallel()
testAccessList(t, tiny) testAccessList(t, tiny)
testAccessList(t, nonAligned) testAccessList(t, nonAligned)
testAccessList(t, standard) testAccessList(t, standard)
} }
func testAccessList(t *testing.T, vals []struct{ k, v string }) { func testAccessList(t *testing.T, vals []struct{ k, v string }) {
t.Helper()
var ( var (
db = NewDatabase(rawdb.NewMemoryDatabase()) db = NewDatabase(rawdb.NewMemoryDatabase())
trie = NewEmpty(db) trie = NewEmpty(db)
@ -204,6 +213,7 @@ func testAccessList(t *testing.T, vals []struct{ k, v string }) {
// Tests origin values won't be tracked in Iterator or Prover // Tests origin values won't be tracked in Iterator or Prover
func TestAccessListLeak(t *testing.T) { func TestAccessListLeak(t *testing.T) {
t.Parallel()
var ( var (
db = NewDatabase(rawdb.NewMemoryDatabase()) db = NewDatabase(rawdb.NewMemoryDatabase())
trie = NewEmpty(db) trie = NewEmpty(db)
@ -255,6 +265,7 @@ func TestAccessListLeak(t *testing.T) {
// Tests whether the original tree node is correctly deleted after being embedded // Tests whether the original tree node is correctly deleted after being embedded
// in its parent due to the smaller size of the original tree node. // in its parent due to the smaller size of the original tree node.
func TestTinyTree(t *testing.T) { func TestTinyTree(t *testing.T) {
t.Parallel()
var ( var (
db = NewDatabase(rawdb.NewMemoryDatabase()) db = NewDatabase(rawdb.NewMemoryDatabase())
trie = NewEmpty(db) trie = NewEmpty(db)

View file

@ -402,8 +402,8 @@ func (randTest) Generate(r *rand.Rand, size int) reflect.Value {
return reflect.ValueOf(steps) return reflect.ValueOf(steps)
} }
func verifyAccessList(old *Trie, new *Trie, set *NodeSet) error { func verifyAccessList(oldTrie *Trie, newTrie *Trie, set *NodeSet) error {
deletes, inserts, updates := diffTries(old, new) deletes, inserts, updates := diffTries(oldTrie, newTrie)
// Check insertion set // Check insertion set
for path := range inserts { for path := range inserts {
@ -590,6 +590,8 @@ func BenchmarkUpdateLE(b *testing.B) { benchUpdate(b, binary.LittleEndian) }
const benchElemCount = 20000 const benchElemCount = 20000
func benchGet(b *testing.B) { func benchGet(b *testing.B) {
b.Helper()
triedb := NewDatabase(rawdb.NewMemoryDatabase()) triedb := NewDatabase(rawdb.NewMemoryDatabase())
trie := NewEmpty(triedb) trie := NewEmpty(triedb)
k := make([]byte, 32) k := make([]byte, 32)
@ -666,6 +668,8 @@ func BenchmarkCommitAfterHash(b *testing.B) {
} }
func benchmarkCommitAfterHash(b *testing.B, collectLeaf bool) { func benchmarkCommitAfterHash(b *testing.B, collectLeaf bool) {
b.Helper()
// Make the random benchmark deterministic // Make the random benchmark deterministic
addresses, accounts := makeAccounts(b.N) addresses, accounts := makeAccounts(b.N)
trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase())) trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))