all: add whitespace linter (#25312)

* golangci: typo

Signed-off-by: Delweng <delweng@gmail.com>

* golangci: add whietspace

Signed-off-by: Delweng <delweng@gmail.com>

* *: rm whitesapce using golangci-lint

Signed-off-by: Delweng <delweng@gmail.com>

* cmd/puppeth: revert accidental resurrection

Co-authored-by: Péter Szilágyi <peterke@gmail.com>
This commit is contained in:
Delweng 2022-07-25 18:14:03 +08:00 committed by GitHub
parent 6c4e5d06e7
commit b196ad1c16
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
90 changed files with 12 additions and 164 deletions

@ -28,9 +28,10 @@ linters:
- durationcheck - durationcheck
- exportloopref - exportloopref
- gosec - gosec
- whitespace
#- structcheck # lots of false positives # - structcheck # lots of false positives
#- errcheck #lot of false positives # - errcheck #lot of false positives
# - contextcheck # - contextcheck
# - errchkjson # lots of false positives # - errchkjson # lots of false positives
# - errorlint # this check crashes # - errorlint # this check crashes

@ -115,7 +115,6 @@ func (mc *mockPendingCaller) PendingCallContract(ctx context.Context, call ether
} }
func TestPassingBlockNumber(t *testing.T) { func TestPassingBlockNumber(t *testing.T) {
mc := &mockPendingCaller{ mc := &mockPendingCaller{
mockCaller: &mockCaller{ mockCaller: &mockCaller{
codeAtBytes: []byte{1, 2, 3}, codeAtBytes: []byte{1, 2, 3},

@ -73,7 +73,6 @@ func typeCheck(t Type, value reflect.Value) error {
} else { } else {
return nil return nil
} }
} }
// typeErr returns a formatted type casting error. // typeErr returns a formatted type casting error.

@ -161,7 +161,6 @@ func TestEventMultiValueWithArrayUnpack(t *testing.T) {
} }
func TestEventTupleUnpack(t *testing.T) { func TestEventTupleUnpack(t *testing.T) {
type EventTransfer struct { type EventTransfer struct {
Value *big.Int Value *big.Int
} }

@ -220,7 +220,6 @@ func mapArgNamesToStructFields(argNames []string, value reflect.Value) (map[stri
// second round ~~~ // second round ~~~
for _, argName := range argNames { for _, argName := range argNames {
structFieldName := ToCamelCase(argName) structFieldName := ToCamelCase(argName)
if structFieldName == "" { if structFieldName == "" {

@ -115,7 +115,6 @@ func ReadFixedBytes(t Type, word []byte) (interface{}, error) {
reflect.Copy(array, reflect.ValueOf(word[0:t.Size])) reflect.Copy(array, reflect.ValueOf(word[0:t.Size]))
return array.Interface(), nil return array.Interface(), nil
} }
// forEachUnpack iteratively unpack elements. // forEachUnpack iteratively unpack elements.

@ -377,7 +377,6 @@ func TestImportExport(t *testing.T) {
if _, err = ks2.Import(json, "new", "new"); err == nil { if _, err = ks2.Import(json, "new", "new"); err == nil {
t.Errorf("importing a key twice succeeded") t.Errorf("importing a key twice succeeded")
} }
} }
// TestImportRace tests the keystore on races. // TestImportRace tests the keystore on races.
@ -402,7 +401,6 @@ func TestImportRace(t *testing.T) {
if _, err := ks2.Import(json, "new", "new"); err != nil { if _, err := ks2.Import(json, "new", "new"); err != nil {
atomic.AddUint32(&atom, 1) atomic.AddUint32(&atom, 1)
} }
}() }()
} }
wg.Wait() wg.Wait()

@ -138,7 +138,6 @@ func (ks keyStorePassphrase) JoinPath(filename string) string {
// Encryptdata encrypts the data given as 'data' with the password 'auth'. // Encryptdata encrypts the data given as 'data' with the password 'auth'.
func EncryptDataV3(data, auth []byte, scryptN, scryptP int) (CryptoJSON, error) { func EncryptDataV3(data, auth []byte, scryptN, scryptP int) (CryptoJSON, error) {
salt := make([]byte, 32) salt := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, salt); err != nil { if _, err := io.ReadFull(rand.Reader, salt); err != nil {
panic("reading from crypto/rand failed: " + err.Error()) panic("reading from crypto/rand failed: " + err.Error())
@ -341,7 +340,6 @@ func getKDFKey(cryptoJSON CryptoJSON, auth string) ([]byte, error) {
r := ensureInt(cryptoJSON.KDFParams["r"]) r := ensureInt(cryptoJSON.KDFParams["r"])
p := ensureInt(cryptoJSON.KDFParams["p"]) p := ensureInt(cryptoJSON.KDFParams["p"])
return scrypt.Key(authArray, salt, n, r, p, dkLen) return scrypt.Key(authArray, salt, n, r, p, dkLen)
} else if cryptoJSON.KDF == "pbkdf2" { } else if cryptoJSON.KDF == "pbkdf2" {
c := ensureInt(cryptoJSON.KDFParams["c"]) c := ensureInt(cryptoJSON.KDFParams["c"])
prf := cryptoJSON.KDFParams["prf"].(string) prf := cryptoJSON.KDFParams["prf"].(string)

@ -526,7 +526,6 @@ func (w *wallet) signHash(account accounts.Account, hash []byte) ([]byte, error)
// SignData signs keccak256(data). The mimetype parameter describes the type of data being signed // SignData signs keccak256(data). The mimetype parameter describes the type of data being signed
func (w *wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) { func (w *wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
// Unless we are doing 712 signing, simply dispatch to signHash // Unless we are doing 712 signing, simply dispatch to signHash
if !(mimeType == accounts.MimetypeTypedData && len(data) == 66 && data[0] == 0x19 && data[1] == 0x01) { if !(mimeType == accounts.MimetypeTypedData && len(data) == 66 && data[0] == 0x19 && data[1] == 0x01) {
return w.signHash(account, crypto.Keccak256(data)) return w.signHash(account, crypto.Keccak256(data))

@ -759,7 +759,6 @@ func confirm(text string) bool {
} }
func testExternalUI(api *core.SignerAPI) { func testExternalUI(api *core.SignerAPI) {
ctx := context.WithValue(context.Background(), "remote", "clef binary") ctx := context.WithValue(context.Background(), "remote", "clef binary")
ctx = context.WithValue(ctx, "scheme", "in-proc") ctx = context.WithValue(ctx, "scheme", "in-proc")
ctx = context.WithValue(ctx, "local", "main") ctx = context.WithValue(ctx, "local", "main")
@ -859,7 +858,6 @@ func testExternalUI(api *core.SignerAPI) {
expectDeny("signdata - text", err) expectDeny("signdata - text", err)
} }
{ // Sign transaction { // Sign transaction
api.UI.ShowInfo("Please reject next transaction") api.UI.ShowInfo("Please reject next transaction")
time.Sleep(delay) time.Sleep(delay)
data := hexutil.Bytes([]byte{}) data := hexutil.Bytes([]byte{})
@ -902,7 +900,6 @@ func testExternalUI(api *core.SignerAPI) {
} }
result := fmt.Sprintf("Tests completed. %d errors:\n%s\n", len(errs), strings.Join(errs, "\n")) result := fmt.Sprintf("Tests completed. %d errors:\n%s\n", len(errs), strings.Join(errs, "\n"))
api.UI.ShowInfo(result) api.UI.ShowInfo(result)
} }
type encryptedSeedStorage struct { type encryptedSeedStorage struct {
@ -939,7 +936,6 @@ func decryptSeed(keyjson []byte, auth string) ([]byte, error) {
// GenDoc outputs examples of all structures used in json-rpc communication // GenDoc outputs examples of all structures used in json-rpc communication
func GenDoc(ctx *cli.Context) error { func GenDoc(ctx *cli.Context) error {
var ( var (
a = common.HexToAddress("0xdeadbeef000000000000000000000000deadbeef") a = common.HexToAddress("0xdeadbeef000000000000000000000000deadbeef")
b = common.HexToAddress("0x1111111122222222222233333333334444444444") b = common.HexToAddress("0x1111111122222222222233333333334444444444")
@ -1049,7 +1045,6 @@ func GenDoc(ctx *cli.Context) error {
var tx types.Transaction var tx types.Transaction
tx.UnmarshalBinary(rlpdata) tx.UnmarshalBinary(rlpdata)
add("OnApproved - SignTransactionResult", desc, &ethapi.SignTransactionResult{Raw: rlpdata, Tx: &tx}) add("OnApproved - SignTransactionResult", desc, &ethapi.SignTransactionResult{Raw: rlpdata, Tx: &tx})
} }
{ // User input { // User input
add("UserInputRequest", "Sent when clef needs the user to provide data. If 'password' is true, the input field should be treated accordingly (echo-free)", add("UserInputRequest", "Sent when clef needs the user to provide data. If 'password' is true, the input field should be treated accordingly (echo-free)",

@ -134,7 +134,6 @@ func (c *cloudflareClient) uploadRecords(name string, records map[string]string)
ttl := rootTTL ttl := rootTTL
if path != name { if path != name {
ttl = treeNodeTTLCloudflare // Max TTL permitted by Cloudflare ttl = treeNodeTTLCloudflare // Max TTL permitted by Cloudflare
} }
record := cloudflare.DNSRecord{Type: "TXT", Name: path, Content: val, TTL: ttl} record := cloudflare.DNSRecord{Type: "TXT", Name: path, Content: val, TTL: ttl}
_, err = c.CreateDNSRecord(context.Background(), c.zoneID, record) _, err = c.CreateDNSRecord(context.Background(), c.zoneID, record)

@ -119,7 +119,6 @@ func (c *Chain) GetHeaders(req GetBlockHeaders) (BlockHeaders, error) {
for i := 1; i < int(req.Amount); i++ { for i := 1; i < int(req.Amount); i++ {
blockNumber -= (1 - req.Skip) blockNumber -= (1 - req.Skip)
headers[i] = c.blocks[blockNumber].Header() headers[i] = c.blocks[blockNumber].Header()
} }
return headers, nil return headers, nil

@ -350,7 +350,6 @@ func hexToCompact(hex []byte) []byte {
// TestSnapTrieNodes various forms of GetTrieNodes requests. // TestSnapTrieNodes various forms of GetTrieNodes requests.
func (s *Suite) TestSnapTrieNodes(t *utesting.T) { func (s *Suite) TestSnapTrieNodes(t *utesting.T) {
key := common.FromHex("0x00bf49f440a1cd0527e4d06e2765654c0f56452257516d793a9b8d604dcfdf2a") key := common.FromHex("0x00bf49f440a1cd0527e4d06e2765654c0f56452257516d793a9b8d604dcfdf2a")
// helper function to iterate the key, and generate the compact-encoded // helper function to iterate the key, and generate the compact-encoded
// trie paths along the way. // trie paths along the way.

@ -315,7 +315,6 @@ func (c *Conn) ReadSnap(id uint64) (Message, error) {
return nil, fmt.Errorf("could not rlp decode message: %v", err) return nil, fmt.Errorf("could not rlp decode message: %v", err)
} }
return snpMsg.(Message), nil return snpMsg.(Message), nil
} }
return nil, fmt.Errorf("request timed out") return nil, fmt.Errorf("request timed out")
} }

@ -100,7 +100,6 @@ type rejectedTx struct {
func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig, func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
txs types.Transactions, miningReward int64, txs types.Transactions, miningReward int64,
getTracerFn func(txIndex int, txHash common.Hash) (tracer vm.EVMLogger, err error)) (*state.StateDB, *ExecutionResult, error) { getTracerFn func(txIndex int, txHash common.Hash) (tracer vm.EVMLogger, err error)) (*state.StateDB, *ExecutionResult, error) {
// Capture errors for BLOCKHASH operation, if we haven't been supplied the // Capture errors for BLOCKHASH operation, if we haven't been supplied the
// required blockhashes // required blockhashes
var hashError error var hashError error

@ -244,7 +244,6 @@ func TestT8n(t *testing.T) {
expExitCode: 3, expExitCode: 3,
}, },
} { } {
args := []string{"t8n"} args := []string{"t8n"}
args = append(args, tc.output.get()...) args = append(args, tc.output.get()...)
args = append(args, tc.input.get(tc.base)...) args = append(args, tc.input.get(tc.base)...)
@ -355,7 +354,6 @@ func TestT9n(t *testing.T) {
expExitCode: t8ntool.ErrorIO, expExitCode: t8ntool.ErrorIO,
}, },
} { } {
args := []string{"t9n"} args := []string{"t9n"}
args = append(args, tc.input.get(tc.base)...) args = append(args, tc.input.get(tc.base)...)
@ -475,7 +473,6 @@ func TestB11r(t *testing.T) {
expOut: "exp.json", expOut: "exp.json",
}, },
} { } {
args := []string{"b11r"} args := []string{"b11r"}
args = append(args, tc.input.get(tc.base)...) args = append(args, tc.input.get(tc.base)...)

@ -118,7 +118,6 @@ func TestMatching(t *testing.T) {
version, vuln.Introduced, vuln.Fixed, vuln.Name, vulnIntro, current, vulnFixed) version, vuln.Introduced, vuln.Fixed, vuln.Name, vulnIntro, current, vulnFixed)
} }
} }
} }
} }
for major := 1; major < 2; major++ { for major := 1; major < 2; major++ {

@ -171,7 +171,6 @@ func BenchmarkByteAt(b *testing.B) {
} }
func BenchmarkByteAtOld(b *testing.B) { func BenchmarkByteAtOld(b *testing.B) {
bigint := MustParseBig256("0x18F8F8F1000111000110011100222004330052300000000000000000FEFCF3CC") bigint := MustParseBig256("0x18F8F8F1000111000110011100222004330052300000000000000000FEFCF3CC")
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
PaddedBigBytes(bigint, 32) PaddedBigBytes(bigint, 32)
@ -244,7 +243,6 @@ func TestBigEndianByteAt(t *testing.T) {
if actual != test.exp { if actual != test.exp {
t.Fatalf("Expected [%v] %v:th byte to be %v, was %v.", test.x, test.y, test.exp, actual) t.Fatalf("Expected [%v] %v:th byte to be %v, was %v.", test.x, test.y, test.exp, actual)
} }
} }
} }
func TestLittleEndianByteAt(t *testing.T) { func TestLittleEndianByteAt(t *testing.T) {
@ -277,7 +275,6 @@ func TestLittleEndianByteAt(t *testing.T) {
if actual != test.exp { if actual != test.exp {
t.Fatalf("Expected [%v] %v:th byte to be %v, was %v.", test.x, test.y, test.exp, actual) t.Fatalf("Expected [%v] %v:th byte to be %v, was %v.", test.x, test.y, test.exp, actual)
} }
} }
} }

@ -155,7 +155,6 @@ func BenchmarkAddressHex(b *testing.B) {
} }
func TestMixedcaseAccount_Address(t *testing.T) { func TestMixedcaseAccount_Address(t *testing.T) {
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md
// Note: 0X{checksum_addr} is not valid according to spec above // Note: 0X{checksum_addr} is not valid according to spec above
@ -192,9 +191,7 @@ func TestMixedcaseAccount_Address(t *testing.T) {
if err := json.Unmarshal([]byte(r), &r2); err == nil { if err := json.Unmarshal([]byte(r), &r2); err == nil {
t.Errorf("Expected failure, input %v", r) t.Errorf("Expected failure, input %v", r)
} }
} }
} }
func TestHash_Scan(t *testing.T) { func TestHash_Scan(t *testing.T) {

@ -1235,7 +1235,6 @@ func TestSideLogRebirth(t *testing.T) {
chain, _ := GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 2, func(i int, gen *BlockGen) { chain, _ := GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 2, func(i int, gen *BlockGen) {
if i == 1 { if i == 1 {
gen.OffsetTime(-9) // higher block difficulty gen.OffsetTime(-9) // higher block difficulty
} }
}) })
if _, err := blockchain.InsertChain(chain); err != nil { if _, err := blockchain.InsertChain(chain); err != nil {
@ -1364,7 +1363,6 @@ done:
t.Errorf("unexpected event fired: %v", e) t.Errorf("unexpected event fired: %v", e)
case <-time.After(250 * time.Millisecond): case <-time.After(250 * time.Millisecond):
} }
} }
// Tests if the canonical block can be fetched from the database during chain insertion. // Tests if the canonical block can be fetched from the database during chain insertion.
@ -2753,7 +2751,6 @@ func benchmarkLargeNumberOfValueToNonexisting(b *testing.B, numTxs, numBlocks in
b.StopTimer() b.StopTimer()
if got := chain.CurrentBlock().Transactions().Len(); got != numTxs*numBlocks { if got := chain.CurrentBlock().Transactions().Len(); got != numTxs*numBlocks {
b.Fatalf("Transactions were not included, expected %d, got %d", numTxs*numBlocks, got) b.Fatalf("Transactions were not included, expected %d, got %d", numTxs*numBlocks, got)
} }
} }
} }
@ -3522,7 +3519,6 @@ func TestEIP2718Transition(t *testing.T) {
vm.GasQuickStep*2 + params.WarmStorageReadCostEIP2929 + params.ColdSloadCostEIP2929 vm.GasQuickStep*2 + params.WarmStorageReadCostEIP2929 + params.ColdSloadCostEIP2929
if block.GasUsed() != expected { if block.GasUsed() != expected {
t.Fatalf("incorrect amount of gas spent: expected %d, got %d", expected, block.GasUsed()) t.Fatalf("incorrect amount of gas spent: expected %d, got %d", expected, block.GasUsed())
} }
} }

@ -332,7 +332,6 @@ func BenchmarkFlatten(b *testing.B) {
value := make([]byte, 32) value := make([]byte, 32)
rand.Read(value) rand.Read(value)
accStorage[randomHash()] = value accStorage[randomHash()] = value
} }
storage[accountKey] = accStorage storage[accountKey] = accStorage
} }
@ -382,7 +381,6 @@ func BenchmarkJournal(b *testing.B) {
value := make([]byte, 32) value := make([]byte, 32)
rand.Read(value) rand.Read(value)
accStorage[randomHash()] = value accStorage[randomHash()] = value
} }
storage[accountKey] = accStorage storage[accountKey] = accStorage
} }

@ -699,7 +699,6 @@ func TestDeleteCreateRevert(t *testing.T) {
// the Commit operation fails with an error // the Commit operation fails with an error
// If we are missing trie nodes, we should not continue writing to the trie // If we are missing trie nodes, we should not continue writing to the trie
func TestMissingTrieNodes(t *testing.T) { func TestMissingTrieNodes(t *testing.T) {
// Create an initial state with a few accounts // Create an initial state with a few accounts
memDb := rawdb.NewMemoryDatabase() memDb := rawdb.NewMemoryDatabase()
db := NewDatabase(memDb) db := NewDatabase(memDb)

@ -669,7 +669,6 @@ func TestTransactionPostponing(t *testing.T) {
// Add a batch consecutive pending transactions for validation // Add a batch consecutive pending transactions for validation
txs := []*types.Transaction{} txs := []*types.Transaction{}
for i, key := range keys { for i, key := range keys {
for j := 0; j < 100; j++ { for j := 0; j < 100; j++ {
var tx *types.Transaction var tx *types.Transaction
if (i+j)%2 == 0 { if (i+j)%2 == 0 {

@ -92,7 +92,6 @@ func BenchmarkBloom9Lookup(b *testing.B) {
} }
func BenchmarkCreateBloom(b *testing.B) { func BenchmarkCreateBloom(b *testing.B) {
var txs = Transactions{ var txs = Transactions{
NewContractCreation(1, big.NewInt(1), 1, big.NewInt(1), nil), NewContractCreation(1, big.NewInt(1), 1, big.NewInt(1), nil),
NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil), NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil),

@ -111,7 +111,6 @@ func TestEIP155SigningVitalik(t *testing.T) {
if from != addr { if from != addr {
t.Errorf("%d: expected %x got %x", i, addr, from) t.Errorf("%d: expected %x got %x", i, addr, from)
} }
} }
} }

@ -114,7 +114,6 @@ func TestEIP2718TransactionSigHash(t *testing.T) {
// This test checks signature operations on access list transactions. // This test checks signature operations on access list transactions.
func TestEIP2930Signer(t *testing.T) { func TestEIP2930Signer(t *testing.T) {
var ( var (
key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
keyAddr = crypto.PubkeyToAddress(key.PublicKey) keyAddr = crypto.PubkeyToAddress(key.PublicKey)

@ -46,7 +46,6 @@ var commonParams []*twoOperandParams
var twoOpMethods map[string]executionFunc var twoOpMethods map[string]executionFunc
func init() { func init() {
// Params is a list of common edgecases that should be used for some common tests // Params is a list of common edgecases that should be used for some common tests
params := []string{ params := []string{
"0000000000000000000000000000000000000000000000000000000000000000", // 0 "0000000000000000000000000000000000000000000000000000000000000000", // 0
@ -92,7 +91,6 @@ func init() {
} }
func testTwoOperandOp(t *testing.T, tests []TwoOperandTestcase, opFn executionFunc, name string) { func testTwoOperandOp(t *testing.T, tests []TwoOperandTestcase, opFn executionFunc, name string) {
var ( var (
env = NewEVM(BlockContext{}, TxContext{}, nil, params.TestChainConfig, Config{}) env = NewEVM(BlockContext{}, TxContext{}, nil, params.TestChainConfig, Config{})
stack = newstack() stack = newstack()
@ -641,7 +639,6 @@ func TestCreate2Addreses(t *testing.T) {
expected: "0xE33C0C7F7df4809055C3ebA6c09CFe4BaF1BD9e0", expected: "0xE33C0C7F7df4809055C3ebA6c09CFe4BaF1BD9e0",
}, },
} { } {
origin := common.BytesToAddress(common.FromHex(tt.origin)) origin := common.BytesToAddress(common.FromHex(tt.origin))
salt := common.BytesToHash(common.FromHex(tt.salt)) salt := common.BytesToHash(common.FromHex(tt.salt))
code := common.FromHex(tt.code) code := common.FromHex(tt.code)

@ -114,7 +114,6 @@ func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter {
// considered a revert-and-consume-all-gas operation except for // considered a revert-and-consume-all-gas operation except for
// ErrExecutionReverted which means revert-and-keep-gas-left. // ErrExecutionReverted which means revert-and-keep-gas-left.
func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) { func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
// Increment the call depth which is restricted to 1024 // Increment the call depth which is restricted to 1024
in.evm.depth++ in.evm.depth++
defer func() { in.evm.depth-- }() defer func() { in.evm.depth-- }()

@ -73,5 +73,4 @@ func TestLoopInterrupt(t *testing.T) {
} }
} }
} }
} }

@ -198,7 +198,6 @@ func newSpuriousDragonInstructionSet() JumpTable {
instructionSet := newTangerineWhistleInstructionSet() instructionSet := newTangerineWhistleInstructionSet()
instructionSet[EXP].dynamicGas = gasExpEIP158 instructionSet[EXP].dynamicGas = gasExpEIP158
return validate(instructionSet) return validate(instructionSet)
} }
// EIP 150 a.k.a Tangerine Whistle // EIP 150 a.k.a Tangerine Whistle

@ -379,7 +379,6 @@ func benchmarkNonModifyingCode(gas uint64, code []byte, name string, tracerCode
// BenchmarkSimpleLoop test a pretty simple loop which loops until OOG // BenchmarkSimpleLoop test a pretty simple loop which loops until OOG
// 55 ms // 55 ms
func BenchmarkSimpleLoop(b *testing.B) { func BenchmarkSimpleLoop(b *testing.B) {
staticCallIdentity := []byte{ staticCallIdentity := []byte{
byte(vm.JUMPDEST), // [ count ] byte(vm.JUMPDEST), // [ count ]
// push args for the call // push args for the call
@ -498,7 +497,6 @@ func TestEip2929Cases(t *testing.T) {
t.Skip("Test only useful for generating documentation") t.Skip("Test only useful for generating documentation")
id := 1 id := 1
prettyPrint := func(comment string, code []byte) { prettyPrint := func(comment string, code []byte) {
instrs := make([]string, 0) instrs := make([]string, 0)
it := asm.NewInstructionIterator(code) it := asm.NewInstructionIterator(code)
for it.Next() { for it.Next() {

@ -102,7 +102,6 @@ func TestFieldElementEquality(t *testing.T) {
if a12.equal(b12) { if a12.equal(b12) {
t.Fatal("a != a + 1") t.Fatal("a != a + 1")
} }
} }
func TestFieldElementHelpers(t *testing.T) { func TestFieldElementHelpers(t *testing.T) {

@ -96,7 +96,6 @@ func (e *fp12) add(c, a, b *fe12) {
fp6 := e.fp6 fp6 := e.fp6
fp6.add(&c[0], &a[0], &b[0]) fp6.add(&c[0], &a[0], &b[0])
fp6.add(&c[1], &a[1], &b[1]) fp6.add(&c[1], &a[1], &b[1])
} }
func (e *fp12) double(c, a *fe12) { func (e *fp12) double(c, a *fe12) {
@ -109,7 +108,6 @@ func (e *fp12) sub(c, a, b *fe12) {
fp6 := e.fp6 fp6 := e.fp6
fp6.sub(&c[0], &a[0], &b[0]) fp6.sub(&c[0], &a[0], &b[0])
fp6.sub(&c[1], &a[1], &b[1]) fp6.sub(&c[1], &a[1], &b[1])
} }
func (e *fp12) neg(c, a *fe12) { func (e *fp12) neg(c, a *fe12) {

@ -465,7 +465,6 @@ func TestFpNonResidue(t *testing.T) {
i -= 1 i -= 1
} }
} }
} }
func TestFp2Serialization(t *testing.T) { func TestFp2Serialization(t *testing.T) {

@ -41,7 +41,6 @@ func (p *PointG2) Zero() *PointG2 {
p[1].one() p[1].one()
p[2].zero() p[2].zero()
return p return p
} }
type tempG2 struct { type tempG2 struct {

@ -334,7 +334,6 @@ func testParamSelection(t *testing.T, c testCase) {
if err == nil { if err == nil {
t.Fatalf("ecies: encryption should not have succeeded (%s)\n", c.Name) t.Fatalf("ecies: encryption should not have succeeded (%s)\n", c.Name)
} }
} }
// Ensure that the basic public key validation in the decryption operation // Ensure that the basic public key validation in the decryption operation

@ -817,7 +817,6 @@ func (q *queue) deliver(id string, taskPool map[common.Hash]*types.Header,
reqTimer metrics.Timer, resInMeter metrics.Meter, resDropMeter metrics.Meter, reqTimer metrics.Timer, resInMeter metrics.Meter, resDropMeter metrics.Meter,
results int, validate func(index int, header *types.Header) error, results int, validate func(index int, header *types.Header) error,
reconstruct func(index int, result *fetchResult)) (int, error) { reconstruct func(index int, result *fetchResult)) (int, error) {
// Short circuit if the data was never requested // Short circuit if the data was never requested
request := pendPool[id] request := pendPool[id]
if request == nil { if request == nil {

@ -185,7 +185,6 @@ func TestBasics(t *testing.T) {
if got, exp := fetchReq.Headers[0].Number.Uint64(), uint64(1); got != exp { if got, exp := fetchReq.Headers[0].Number.Uint64(), uint64(1); got != exp {
t.Fatalf("expected header %d, got %d", exp, got) t.Fatalf("expected header %d, got %d", exp, got)
} }
} }
if exp, got := q.blockTaskQueue.Size(), numOfBlocks-10; exp != got { if exp, got := q.blockTaskQueue.Size(), numOfBlocks-10; exp != got {
t.Errorf("expected block task queue to be %d, got %d", exp, got) t.Errorf("expected block task queue to be %d, got %d", exp, got)
@ -239,7 +238,6 @@ func TestEmptyBlocks(t *testing.T) {
if fetchReq != nil { if fetchReq != nil {
t.Fatal("there should be no body fetch tasks remaining") t.Fatal("there should be no body fetch tasks remaining")
} }
} }
if q.blockTaskQueue.Size() != numOfBlocks-10 { if q.blockTaskQueue.Size() != numOfBlocks-10 {
t.Errorf("expected block task queue to be %d, got %d", numOfBlocks-10, q.blockTaskQueue.Size()) t.Errorf("expected block task queue to be %d, got %d", numOfBlocks-10, q.blockTaskQueue.Size())
@ -280,7 +278,6 @@ func XTestDelivery(t *testing.T) {
world.progress(10) world.progress(10)
if false { if false {
log.Root().SetHandler(log.StdoutHandler) log.Root().SetHandler(log.StdoutHandler)
} }
q := newQueue(10, 10) q := newQueue(10, 10)
var wg sync.WaitGroup var wg sync.WaitGroup
@ -315,7 +312,6 @@ func XTestDelivery(t *testing.T) {
fmt.Printf("got %d results, %d tot\n", len(res), tot) fmt.Printf("got %d results, %d tot\n", len(res), tot)
// Now we can forget about these // Now we can forget about these
world.forget(res[len(res)-1].Header.Number.Uint64()) world.forget(res[len(res)-1].Header.Number.Uint64())
} }
}() }()
wg.Add(1) wg.Add(1)
@ -396,7 +392,6 @@ func XTestDelivery(t *testing.T) {
} }
for i := 0; i < 50; i++ { for i := 0; i < 50; i++ {
time.Sleep(2990 * time.Millisecond) time.Sleep(2990 * time.Millisecond)
} }
}() }()
wg.Add(1) wg.Add(1)
@ -447,10 +442,8 @@ func (n *network) forget(blocknum uint64) {
n.chain = n.chain[index:] n.chain = n.chain[index:]
n.receipts = n.receipts[index:] n.receipts = n.receipts[index:]
n.offset = int(blocknum) n.offset = int(blocknum)
} }
func (n *network) progress(numBlocks int) { func (n *network) progress(numBlocks int) {
n.lock.Lock() n.lock.Lock()
defer n.lock.Unlock() defer n.lock.Unlock()
//fmt.Printf("progressing...\n") //fmt.Printf("progressing...\n")
@ -458,7 +451,6 @@ func (n *network) progress(numBlocks int) {
n.chain = append(n.chain, newBlocks...) n.chain = append(n.chain, newBlocks...)
n.receipts = append(n.receipts, newR...) n.receipts = append(n.receipts, newR...)
n.cond.Broadcast() n.cond.Broadcast()
} }
func (n *network) headers(from int) []*types.Header { func (n *network) headers(from int) []*types.Header {

@ -790,7 +790,6 @@ func TestSkeletonSyncRetrievals(t *testing.T) {
check := func() error { check := func() error {
if len(progress.Subchains) != len(tt.midstate) { if len(progress.Subchains) != len(tt.midstate) {
return fmt.Errorf("test %d, mid state: subchain count mismatch: have %d, want %d", i, len(progress.Subchains), len(tt.midstate)) return fmt.Errorf("test %d, mid state: subchain count mismatch: have %d, want %d", i, len(progress.Subchains), len(tt.midstate))
} }
for j := 0; j < len(progress.Subchains); j++ { for j := 0; j < len(progress.Subchains); j++ {
if progress.Subchains[j].Head != tt.midstate[j].Head { if progress.Subchains[j].Head != tt.midstate[j].Head {

@ -692,7 +692,6 @@ func (f *BlockFetcher) loop() {
} else { } else {
f.forgetHash(hash) f.forgetHash(hash)
} }
} }
if matched { if matched {
task.transactions = append(task.transactions[:i], task.transactions[i+1:]...) task.transactions = append(task.transactions[:i], task.transactions[i+1:]...)

@ -248,7 +248,6 @@ func (api *FilterAPI) Logs(ctx context.Context, crit FilterCriteria) (*rpc.Subsc
} }
go func() { go func() {
for { for {
select { select {
case logs := <-matchedLogs: case logs := <-matchedLogs:

@ -72,7 +72,6 @@ func BenchmarkFilters(b *testing.B) {
receipt := makeReceipt(addr4) receipt := makeReceipt(addr4)
gen.AddUncheckedReceipt(receipt) gen.AddUncheckedReceipt(receipt)
gen.AddUncheckedTx(types.NewTransaction(999, common.HexToAddress("0x999"), big.NewInt(999), 999, gen.BaseFee(), nil)) gen.AddUncheckedTx(types.NewTransaction(999, common.HexToAddress("0x999"), big.NewInt(999), 999, gen.BaseFee(), nil))
} }
}) })
for i, block := range chain { for i, block := range chain {

@ -490,7 +490,6 @@ func TestCheckpointChallenge(t *testing.T) {
} }
func testCheckpointChallenge(t *testing.T, syncmode downloader.SyncMode, checkpoint bool, timeout bool, empty bool, match bool, drop bool) { func testCheckpointChallenge(t *testing.T, syncmode downloader.SyncMode, checkpoint bool, timeout bool, empty bool, match bool, drop bool) {
// Reduce the checkpoint handshake challenge timeout // Reduce the checkpoint handshake challenge timeout
defer func(old time.Duration) { syncChallengeTimeout = old }(syncChallengeTimeout) defer func(old time.Duration) { syncChallengeTimeout = old }(syncChallengeTimeout)
syncChallengeTimeout = 250 * time.Millisecond syncChallengeTimeout = 250 * time.Millisecond

@ -115,12 +115,10 @@ func TestEth66EmptyMessages(t *testing.T) {
t.Errorf("test %d, type %T, have\n\t%x\nwant\n\t%x", i, msg, have, want) t.Errorf("test %d, type %T, have\n\t%x\nwant\n\t%x", i, msg, have, want)
} }
} }
} }
// TestEth66Messages tests the encoding of all redefined eth66 messages // TestEth66Messages tests the encoding of all redefined eth66 messages
func TestEth66Messages(t *testing.T) { func TestEth66Messages(t *testing.T) {
// Some basic structs used during testing // Some basic structs used during testing
var ( var (
header *types.Header header *types.Header

@ -878,7 +878,6 @@ func (r *callframeResult) GetError() goja.Value {
return r.vm.ToValue(r.err.Error()) return r.vm.ToValue(r.err.Error())
} }
return goja.Undefined() return goja.Undefined()
} }
func (r *callframeResult) setupObject() *goja.Object { func (r *callframeResult) setupObject() *goja.Object {

@ -79,7 +79,6 @@ type StorageResult struct {
// GetProof returns the account and storage values of the specified account including the Merkle-proof. // GetProof returns the account and storage values of the specified account including the Merkle-proof.
// The block number can be nil, in which case the value is taken from the latest known block. // The block number can be nil, in which case the value is taken from the latest known block.
func (ec *Client) GetProof(ctx context.Context, account common.Address, keys []string, blockNumber *big.Int) (*AccountResult, error) { func (ec *Client) GetProof(ctx context.Context, account common.Address, keys []string, blockNumber *big.Int) (*AccountResult, error) {
type storageResult struct { type storageResult struct {
Key string `json:"key"` Key string `json:"key"`
Value *hexutil.Big `json:"value"` Value *hexutil.Big `json:"value"`

@ -222,7 +222,6 @@ func testGetProof(t *testing.T, client *rpc.Client) {
if proof.Key != testSlot.String() { if proof.Key != testSlot.String() {
t.Fatalf("invalid storage proof key, want: %v, got: %v", testSlot.String(), proof.Key) t.Fatalf("invalid storage proof key, want: %v, got: %v", testSlot.String(), proof.Key)
} }
} }
func testGCStats(t *testing.T, client *rpc.Client) { func testGCStats(t *testing.T, client *rpc.Client) {

@ -79,5 +79,4 @@ func TestParseEthstatsURL(t *testing.T) {
t.Errorf("case=%d mismatch host value, got: %v ,want: %v", i, host, c.host) t.Errorf("case=%d mismatch host value, got: %v ,want: %v", i, host, c.host)
} }
} }
} }

@ -52,7 +52,6 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.Write(responseJSON) w.Write(responseJSON)
} }
// New constructs a new GraphQL service instance. // New constructs a new GraphQL service instance.

@ -219,7 +219,6 @@ func (ctx ppctx) fields(obj *goja.Object) []string {
vals = append(vals, k) vals = append(vals, k)
} }
} }
} }
iterOwnAndConstructorKeys(ctx.vm, obj, add) iterOwnAndConstructorKeys(ctx.vm, obj, add)
sort.Strings(vals) sort.Strings(vals)

@ -340,7 +340,6 @@ func freezeClient(ctx context.Context, t *testing.T, server *rpc.Client, clientI
if err := server.CallContext(ctx, nil, "debug_freezeClient", clientID); err != nil { if err := server.CallContext(ctx, nil, "debug_freezeClient", clientID); err != nil {
t.Fatalf("Failed to freeze client: %v", err) t.Fatalf("Failed to freeze client: %v", err)
} }
} }
func setCapacity(ctx context.Context, t *testing.T, server *rpc.Client, clientID enode.ID, cap uint64) { func setCapacity(ctx context.Context, t *testing.T, server *rpc.Client, clientID enode.ID, cap uint64) {

@ -1330,7 +1330,6 @@ func (d *Downloader) fetchParts(deliveryCh chan dataPack, deliver func(dataPack)
expire func() map[string]int, pending func() int, inFlight func() bool, reserve func(*peerConnection, int) (*fetchRequest, bool, bool), expire func() map[string]int, pending func() int, inFlight func() bool, reserve func(*peerConnection, int) (*fetchRequest, bool, bool),
fetchHook func([]*types.Header), fetch func(*peerConnection, *fetchRequest) error, cancel func(*fetchRequest), capacity func(*peerConnection) int, fetchHook func([]*types.Header), fetch func(*peerConnection, *fetchRequest) error, cancel func(*fetchRequest), capacity func(*peerConnection) int,
idle func() ([]*peerConnection, int), setIdle func(*peerConnection, int, time.Time), kind string) error { idle func() ([]*peerConnection, int), setIdle func(*peerConnection, int, time.Time), kind string) error {
// Create a ticker to detect expired retrieval tasks // Create a ticker to detect expired retrieval tasks
ticker := time.NewTicker(100 * time.Millisecond) ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop() defer ticker.Stop()

@ -621,7 +621,6 @@ func testThrottling(t *testing.T, protocol uint, mode SyncMode) {
t.Fatalf("block synchronization failed: %v", err) t.Fatalf("block synchronization failed: %v", err)
} }
tester.terminate() tester.terminate()
} }
// Tests that simple synchronization against a forked chain works correctly. In // Tests that simple synchronization against a forked chain works correctly. In

@ -833,7 +833,6 @@ func (q *queue) deliver(id string, taskPool map[common.Hash]*types.Header,
taskQueue *prque.Prque, pendPool map[string]*fetchRequest, reqTimer metrics.Timer, taskQueue *prque.Prque, pendPool map[string]*fetchRequest, reqTimer metrics.Timer,
results int, validate func(index int, header *types.Header) error, results int, validate func(index int, header *types.Header) error,
reconstruct func(index int, result *fetchResult)) (int, error) { reconstruct func(index int, result *fetchResult)) (int, error) {
// Short circuit if the data was never requested // Short circuit if the data was never requested
request := pendPool[id] request := pendPool[id]
if request == nil { if request == nil {

@ -179,7 +179,6 @@ func TestBasics(t *testing.T) {
if got, exp := fetchReq.Headers[0].Number.Uint64(), uint64(1); got != exp { if got, exp := fetchReq.Headers[0].Number.Uint64(), uint64(1); got != exp {
t.Fatalf("expected header %d, got %d", exp, got) t.Fatalf("expected header %d, got %d", exp, got)
} }
} }
if exp, got := q.blockTaskQueue.Size(), numOfBlocks-10; exp != got { if exp, got := q.blockTaskQueue.Size(), numOfBlocks-10; exp != got {
t.Errorf("expected block task queue to be %d, got %d", exp, got) t.Errorf("expected block task queue to be %d, got %d", exp, got)
@ -227,7 +226,6 @@ func TestEmptyBlocks(t *testing.T) {
if fetchReq != nil { if fetchReq != nil {
t.Fatal("there should be no body fetch tasks remaining") t.Fatal("there should be no body fetch tasks remaining")
} }
} }
if q.blockTaskQueue.Size() != numOfBlocks-10 { if q.blockTaskQueue.Size() != numOfBlocks-10 {
t.Errorf("expected block task queue to be %d, got %d", numOfBlocks-10, q.blockTaskQueue.Size()) t.Errorf("expected block task queue to be %d, got %d", numOfBlocks-10, q.blockTaskQueue.Size())
@ -268,7 +266,6 @@ func XTestDelivery(t *testing.T) {
world.progress(10) world.progress(10)
if false { if false {
log.Root().SetHandler(log.StdoutHandler) log.Root().SetHandler(log.StdoutHandler)
} }
q := newQueue(10, 10) q := newQueue(10, 10)
var wg sync.WaitGroup var wg sync.WaitGroup
@ -299,7 +296,6 @@ func XTestDelivery(t *testing.T) {
fmt.Printf("got %d results, %d tot\n", len(res), tot) fmt.Printf("got %d results, %d tot\n", len(res), tot)
// Now we can forget about these // Now we can forget about these
world.forget(res[len(res)-1].Header.Number.Uint64()) world.forget(res[len(res)-1].Header.Number.Uint64())
} }
}() }()
wg.Add(1) wg.Add(1)
@ -362,7 +358,6 @@ func XTestDelivery(t *testing.T) {
} }
for i := 0; i < 50; i++ { for i := 0; i < 50; i++ {
time.Sleep(2990 * time.Millisecond) time.Sleep(2990 * time.Millisecond)
} }
}() }()
wg.Add(1) wg.Add(1)
@ -413,10 +408,8 @@ func (n *network) forget(blocknum uint64) {
n.chain = n.chain[index:] n.chain = n.chain[index:]
n.receipts = n.receipts[index:] n.receipts = n.receipts[index:]
n.offset = int(blocknum) n.offset = int(blocknum)
} }
func (n *network) progress(numBlocks int) { func (n *network) progress(numBlocks int) {
n.lock.Lock() n.lock.Lock()
defer n.lock.Unlock() defer n.lock.Unlock()
//fmt.Printf("progressing...\n") //fmt.Printf("progressing...\n")
@ -424,7 +417,6 @@ func (n *network) progress(numBlocks int) {
n.chain = append(n.chain, newBlocks...) n.chain = append(n.chain, newBlocks...)
n.receipts = append(n.receipts, newR...) n.receipts = append(n.receipts, newR...)
n.cond.Broadcast() n.cond.Broadcast()
} }
func (n *network) headers(from int) []*types.Header { func (n *network) headers(from int) []*types.Header {

@ -641,7 +641,6 @@ func (f *BlockFetcher) loop() {
} else { } else {
f.forgetHash(hash) f.forgetHash(hash)
} }
} }
if matched { if matched {
task.transactions = append(task.transactions[:i], task.transactions[i+1:]...) task.transactions = append(task.transactions[:i], task.transactions[i+1:]...)

@ -104,7 +104,6 @@ func testConstantTotalCapacity(t *testing.T, nodeCount, maxCapacityNodes, random
if ratio < 0.98 || ratio > 1.02 { if ratio < 0.98 || ratio > 1.02 {
t.Errorf("totalCost/totalCapacity/testLength ratio incorrect (expected: 1, got: %f)", ratio) t.Errorf("totalCost/totalCapacity/testLength ratio incorrect (expected: 1, got: %f)", ratio)
} }
} }
func (n *testNode) send(t *testing.T, now mclock.AbsTime) bool { func (n *testNode) send(t *testing.T, now mclock.AbsTime) bool {

@ -222,7 +222,6 @@ func (s *serverPoolIterator) Close() {
func (s *ServerPool) AddMetrics( func (s *ServerPool) AddMetrics(
suggestedTimeoutGauge, totalValueGauge, serverSelectableGauge, serverConnectedGauge metrics.Gauge, suggestedTimeoutGauge, totalValueGauge, serverSelectableGauge, serverConnectedGauge metrics.Gauge,
sessionValueMeter, serverDialedMeter metrics.Meter) { sessionValueMeter, serverDialedMeter metrics.Meter) {
s.suggestedTimeoutGauge = suggestedTimeoutGauge s.suggestedTimeoutGauge = suggestedTimeoutGauge
s.totalValueGauge = totalValueGauge s.totalValueGauge = totalValueGauge
s.sessionValueMeter = sessionValueMeter s.sessionValueMeter = sessionValueMeter

@ -109,7 +109,6 @@ func (w *WrsIterator) chooseNode() *enode.Node {
return w.ns.GetNode(id) return w.ns.GetNode(id)
} }
} }
} }
// Close ends the iterator. // Close ends the iterator.

@ -410,7 +410,6 @@ func TestFreeClientKickedOut(t *testing.T) {
clock.Run(5 * time.Minute) clock.Run(5 * time.Minute)
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
connect(pool, newPoolTestPeer(i+10, kicked)) connect(pool, newPoolTestPeer(i+10, kicked))
} }
clock.Run(0) clock.Run(0)

@ -81,7 +81,6 @@ func (r *v2Reporter) run() {
} }
} }
} }
} }
func (r *v2Reporter) send() { func (r *v2Reporter) send() {
@ -90,7 +89,6 @@ func (r *v2Reporter) send() {
namespace := r.namespace namespace := r.namespace
switch metric := i.(type) { switch metric := i.(type) {
case metrics.Counter: case metrics.Counter:
v := metric.Count() v := metric.Count()
l := r.cache[name] l := r.cache[name]

@ -307,5 +307,4 @@ func TestWalkRegistries(t *testing.T) {
if prefix != "prefix.prefix2." { if prefix != "prefix.prefix2." {
t.Fatal(prefix) t.Fatal(prefix)
} }
} }

@ -188,7 +188,6 @@ func TestStartStopMiner(t *testing.T) {
waitForMiningState(t, miner, true) waitForMiningState(t, miner, true)
miner.Stop() miner.Stop()
waitForMiningState(t, miner, false) waitForMiningState(t, miner, false)
} }
func TestCloseMiner(t *testing.T) { func TestCloseMiner(t *testing.T) {

@ -94,7 +94,6 @@ func (ec *EthereumClient) GetTransactionCount(ctx *Context, hash *Hash) (count i
func (ec *EthereumClient) GetTransactionInBlock(ctx *Context, hash *Hash, index int) (tx *Transaction, _ error) { func (ec *EthereumClient) GetTransactionInBlock(ctx *Context, hash *Hash, index int) (tx *Transaction, _ error) {
rawTx, err := ec.client.TransactionInBlock(ctx.context, hash.hash, uint(index)) rawTx, err := ec.client.TransactionInBlock(ctx.context, hash.hash, uint(index))
return &Transaction{rawTx}, err return &Transaction{rawTx}, err
} }
// GetTransactionReceipt returns the receipt of a transaction by transaction hash. // GetTransactionReceipt returns the receipt of a transaction by transaction hash.

@ -581,7 +581,6 @@ func (test rpcPrefixTest) check(t *testing.T, node *Node) {
if err == nil { if err == nil {
t.Errorf("Error: %s: WebSocket connection succeeded for path in wantNoWS", path) t.Errorf("Error: %s: WebSocket connection succeeded for path in wantNoWS", path)
} }
} }
} }
@ -614,7 +613,6 @@ func doHTTPRequest(t *testing.T, req *http.Request) *http.Response {
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
t.Fatalf("could not issue a GET request to the given endpoint: %v", err) t.Fatalf("could not issue a GET request to the given endpoint: %v", err)
} }
return resp return resp
} }

@ -438,7 +438,6 @@ func (h *virtualHostHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// It's an IP address, we can serve that // It's an IP address, we can serve that
h.next.ServeHTTP(w, r) h.next.ServeHTTP(w, r)
return return
} }
// Not an IP address, but a hostname. Need to validate // Not an IP address, but a hostname. Need to validate
if _, exist := h.vhosts["*"]; exist { if _, exist := h.vhosts["*"]; exist {

@ -367,7 +367,6 @@ func (s *Server) StopMocker(w http.ResponseWriter, req *http.Request) {
// GetMockerList returns a list of available mockers // GetMockerList returns a list of available mockers
func (s *Server) GetMockers(w http.ResponseWriter, req *http.Request) { func (s *Server) GetMockers(w http.ResponseWriter, req *http.Request) {
list := GetMockerList() list := GetMockerList()
s.JSON(w, http.StatusOK, list) s.JSON(w, http.StatusOK, list)
} }

@ -489,7 +489,6 @@ func (t *expectEvents) expect(events ...*Event) {
} }
switch expected.Type { switch expected.Type {
case EventTypeNode: case EventTypeNode:
if event.Node == nil { if event.Node == nil {
t.Fatal("expected event.Node to be set") t.Fatal("expected event.Node to be set")
@ -514,7 +513,6 @@ func (t *expectEvents) expect(events ...*Event) {
if event.Conn.Up != expected.Conn.Up { if event.Conn.Up != expected.Conn.Up {
t.Fatalf("expected conn event %d to have up=%t, got up=%t", i, expected.Conn.Up, event.Conn.Up) t.Fatalf("expected conn event %d to have up=%t, got up=%t", i, expected.Conn.Up, event.Conn.Up)
} }
} }
i++ i++

@ -157,7 +157,6 @@ func probabilistic(net *Network, quit chan struct{}, nodeCount int) {
} }
wg.Wait() wg.Wait()
} }
} }
//connect nodeCount number of nodes in a ring //connect nodeCount number of nodes in a ring

@ -235,7 +235,6 @@ func (net *Network) watchPeerEvents(id enode.ID, events chan *p2p.PeerEvent, sub
} }
peer := event.Peer peer := event.Peer
switch event.Type { switch event.Type {
case p2p.PeerEventTypeAdd: case p2p.PeerEventTypeAdd:
net.DidConnect(id, peer) net.DidConnect(id, peer)
@ -247,7 +246,6 @@ func (net *Network) watchPeerEvents(id enode.ID, events chan *p2p.PeerEvent, sub
case p2p.PeerEventTypeMsgRecv: case p2p.PeerEventTypeMsgRecv:
net.DidReceive(peer, id, event.Protocol, *event.MsgCode) net.DidReceive(peer, id, event.Protocol, *event.MsgCode)
} }
case err := <-sub.Err(): case err := <-sub.Err():
@ -927,7 +925,6 @@ func (net *Network) snapshot(addServices []string, removeServices []string) (*Sn
if !haveSvc { if !haveSvc {
cleanedServices = append(cleanedServices, svc) cleanedServices = append(cleanedServices, svc)
} }
} }
snap.Nodes[i].Node.Config.Lifecycles = cleanedServices snap.Nodes[i].Node.Config.Lifecycles = cleanedServices
} }
@ -1021,7 +1018,6 @@ func (net *Network) Load(snap *Snapshot) error {
// Start connecting. // Start connecting.
for _, conn := range snap.Conns { for _, conn := range snap.Conns {
if !net.GetNode(conn.One).Up() || !net.GetNode(conn.Other).Up() { if !net.GetNode(conn.One).Up() || !net.GetNode(conn.Other).Up() {
//in this case, at least one of the nodes of a connection is not up, //in this case, at least one of the nodes of a connection is not up,
//so it would result in the snapshot `Load` to fail //so it would result in the snapshot `Load` to fail

@ -36,7 +36,6 @@ import (
// Tests that a created snapshot with a minimal service only contains the expected connections // Tests that a created snapshot with a minimal service only contains the expected connections
// and that a network when loaded with this snapshot only contains those same connections // and that a network when loaded with this snapshot only contains those same connections
func TestSnapshot(t *testing.T) { func TestSnapshot(t *testing.T) {
// PART I // PART I
// create snapshot from ring network // create snapshot from ring network
@ -204,7 +203,6 @@ OuterTwo:
t.Fatal(ctx.Err()) t.Fatal(ctx.Err())
case ev := <-evC: case ev := <-evC:
if ev.Type == EventTypeConn && !ev.Control { if ev.Type == EventTypeConn && !ev.Control {
// fail on any disconnect // fail on any disconnect
if !ev.Conn.Up { if !ev.Conn.Up {
t.Fatalf("unexpected disconnect: %v -> %v", ev.Conn.One, ev.Conn.Other) t.Fatalf("unexpected disconnect: %v -> %v", ev.Conn.One, ev.Conn.Other)
@ -693,7 +691,6 @@ func BenchmarkMinimalService(b *testing.B) {
} }
func benchmarkMinimalServiceTmp(b *testing.B) { func benchmarkMinimalServiceTmp(b *testing.B) {
// stop timer to discard setup time pollution // stop timer to discard setup time pollution
args := strings.Split(b.Name(), "/") args := strings.Split(b.Name(), "/")
nodeCount, err := strconv.ParseInt(args[2], 10, 16) nodeCount, err := strconv.ParseInt(args[2], 10, 16)

@ -1043,7 +1043,6 @@ func TestInvalidOptionalField(t *testing.T) {
t.Errorf("wrong error for %T: %v", test.v, err.Error()) t.Errorf("wrong error for %T: %v", test.v, err.Error())
} }
} }
} }
func ExampleDecode() { func ExampleDecode() {

@ -36,7 +36,6 @@ func NewListIterator(data RawValue) (*listIterator, error) {
data: data[t : t+c], data: data[t : t+c],
} }
return it, nil return it, nil
} }
// Next forwards the iterator one step, returns true if it was not at end yet // Next forwards the iterator one step, returns true if it was not at end yet

@ -319,7 +319,6 @@ func (api *SignerAPI) openTrezor(url accounts.URL) {
log.Warn("failed to open wallet", "wallet", url, "err", err) log.Warn("failed to open wallet", "wallet", url, "err", err)
return return
} }
} }
// startUSBListener starts a listener for USB events, for hardware wallet interaction // startUSBListener starts a listener for USB events, for hardware wallet interaction
@ -612,7 +611,6 @@ func (api *SignerAPI) SignTransaction(ctx context.Context, args apitypes.SendTxA
api.UI.OnApprovedTx(response) api.UI.OnApprovedTx(response)
// ...and to the external caller // ...and to the external caller
return &response, nil return &response, nil
} }
func (api *SignerAPI) SignGnosisSafeTx(ctx context.Context, signerAddress common.MixedcaseAddress, gnosisTx GnosisSafeTx, methodSelector *string) (*GnosisSafeTx, error) { func (api *SignerAPI) SignGnosisSafeTx(ctx context.Context, signerAddress common.MixedcaseAddress, gnosisTx GnosisSafeTx, methodSelector *string) (*GnosisSafeTx, error) {

@ -55,7 +55,6 @@ func (ui *headlessUi) RegisterUIServer(api *core.UIServerAPI) {}
func (ui *headlessUi) OnApprovedTx(tx ethapi.SignTransactionResult) {} func (ui *headlessUi) OnApprovedTx(tx ethapi.SignTransactionResult) {}
func (ui *headlessUi) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) { func (ui *headlessUi) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) {
switch <-ui.approveCh { switch <-ui.approveCh {
case "Y": case "Y":
return core.SignTxResponse{request.Transaction, true}, nil return core.SignTxResponse{request.Transaction, true}, nil
@ -125,7 +124,6 @@ func setup(t *testing.T) (*core.SignerAPI, *headlessUi) {
am := core.StartClefAccountManager(tmpDirName(t), true, true, "") am := core.StartClefAccountManager(tmpDirName(t), true, true, "")
api := core.NewSignerAPI(am, 1337, true, ui, db, true, &storage.NoStorage{}) api := core.NewSignerAPI(am, 1337, true, ui, db, true, &storage.NoStorage{})
return api, ui return api, ui
} }
func createAccount(ui *headlessUi, api *core.SignerAPI, t *testing.T) { func createAccount(ui *headlessUi, api *core.SignerAPI, t *testing.T) {
ui.approveCh <- "Y" ui.approveCh <- "Y"
@ -139,7 +137,6 @@ func createAccount(ui *headlessUi, api *core.SignerAPI, t *testing.T) {
} }
func failCreateAccountWithPassword(ui *headlessUi, api *core.SignerAPI, password string, t *testing.T) { func failCreateAccountWithPassword(ui *headlessUi, api *core.SignerAPI, password string, t *testing.T) {
ui.approveCh <- "Y" ui.approveCh <- "Y"
// We will be asked three times to provide a suitable password // We will be asked three times to provide a suitable password
ui.inputCh <- password ui.inputCh <- password
@ -169,7 +166,6 @@ func failCreateAccount(ui *headlessUi, api *core.SignerAPI, t *testing.T) {
func list(ui *headlessUi, api *core.SignerAPI, t *testing.T) ([]common.Address, error) { func list(ui *headlessUi, api *core.SignerAPI, t *testing.T) ([]common.Address, error) {
ui.approveCh <- "A" ui.approveCh <- "A"
return api.List(context.Background()) return api.List(context.Background())
} }
func TestNewAcc(t *testing.T) { func TestNewAcc(t *testing.T) {
@ -321,5 +317,4 @@ func TestSignTx(t *testing.T) {
if bytes.Equal(res.Raw, res2.Raw) { if bytes.Equal(res.Raw, res2.Raw) {
t.Error("Expected tx to be modified by UI") t.Error("Expected tx to be modified by UI")
} }
} }

@ -545,7 +545,6 @@ func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue interf
return math.U256Bytes(b), nil return math.U256Bytes(b), nil
} }
return nil, fmt.Errorf("unrecognized type '%s'", encType) return nil, fmt.Errorf("unrecognized type '%s'", encType)
} }
// dataMismatchError generates an error for a mismatch between // dataMismatchError generates an error for a mismatch between
@ -672,7 +671,6 @@ func formatPrimitiveValue(encType string, encValue interface{}) (string, error)
} }
if strings.HasPrefix(encType, "bytes") { if strings.HasPrefix(encType, "bytes") {
return fmt.Sprintf("%s", encValue), nil return fmt.Sprintf("%s", encValue), nil
} }
if strings.HasPrefix(encType, "uint") || strings.HasPrefix(encType, "int") { if strings.HasPrefix(encType, "uint") || strings.HasPrefix(encType, "int") {
if b, err := parseInteger(encType, encValue); err != nil { if b, err := parseInteger(encType, encValue); err != nil {

@ -110,7 +110,6 @@ func (l *AuditLogger) Version(ctx context.Context) (string, error) {
data, err := l.api.Version(ctx) data, err := l.api.Version(ctx)
l.log.Info("Version", "type", "response", "data", data, "error", err) l.log.Info("Version", "type", "response", "data", data, "error", err)
return data, err return data, err
} }
func NewAuditLogger(path string, api ExternalAPI) (*AuditLogger, error) { func NewAuditLogger(path string, api ExternalAPI) (*AuditLogger, error) {

@ -59,7 +59,6 @@ func (ui *CommandlineUI) readString() string {
} }
func (ui *CommandlineUI) OnInputRequired(info UserInputRequest) (UserInputResponse, error) { func (ui *CommandlineUI) OnInputRequired(info UserInputRequest) (UserInputResponse, error) {
fmt.Printf("## %s\n\n%s\n", info.Title, info.Prompt) fmt.Printf("## %s\n\n%s\n", info.Title, info.Prompt)
defer fmt.Println("-----------------------") defer fmt.Println("-----------------------")
if info.IsPassword { if info.IsPassword {
@ -147,7 +146,6 @@ func (ui *CommandlineUI) ApproveTx(request *SignTxRequest) (SignTxResponse, erro
fmt.Printf(" * %s : %s\n", m.Typ, m.Message) fmt.Printf(" * %s : %s\n", m.Typ, m.Message)
} }
fmt.Println() fmt.Println()
} }
fmt.Printf("\n") fmt.Printf("\n")
showMetadata(request.Meta) showMetadata(request.Meta)
@ -209,7 +207,6 @@ func (ui *CommandlineUI) ApproveListing(request *ListRequest) (ListResponse, err
// ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
func (ui *CommandlineUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) { func (ui *CommandlineUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
ui.mu.Lock() ui.mu.Lock()
defer ui.mu.Unlock() defer ui.mu.Unlock()
@ -245,7 +242,6 @@ func (ui *CommandlineUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
} }
func (ui *CommandlineUI) OnSignerStartup(info StartupInfo) { func (ui *CommandlineUI) OnSignerStartup(info StartupInfo) {
fmt.Printf("------- Signer info -------\n") fmt.Printf("------- Signer info -------\n")
for k, v := range info.Info { for k, v := range info.Info {
fmt.Printf("* %v : %v\n", k, v) fmt.Printf("* %v : %v\n", k, v)

@ -38,7 +38,6 @@ func TestPasswordValidation(t *testing.T) {
if err == nil && test.shouldFail { if err == nil && test.shouldFail {
t.Errorf("password '%v' should fail validation", test.pw) t.Errorf("password '%v' should fail validation", test.pw)
} else if err != nil && !test.shouldFail { } else if err != nil && !test.shouldFail {
t.Errorf("password '%v' shound not fail validation, but did: %v", test.pw, err) t.Errorf("password '%v' shound not fail validation, but did: %v", test.pw, err)
} }
} }

@ -53,7 +53,6 @@ func dummyTxArgs(t txtestcase) *apitypes.SendTxArgs {
if t.i != "" { if t.i != "" {
a := hexutil.Bytes(common.FromHex(t.i)) a := hexutil.Bytes(common.FromHex(t.i))
input = &a input = &a
} }
return &apitypes.SendTxArgs{ return &apitypes.SendTxArgs{
From: *from, From: *from,

@ -67,7 +67,6 @@ func (r *rulesetUI) Init(javascriptRules string) error {
return nil return nil
} }
func (r *rulesetUI) execute(jsfunc string, jsarg interface{}) (goja.Value, error) { func (r *rulesetUI) execute(jsfunc string, jsarg interface{}) (goja.Value, error) {
// Instantiate a fresh vm engine every time // Instantiate a fresh vm engine every time
vm := goja.New() vm := goja.New()

@ -152,7 +152,6 @@ func TestListRequest(t *testing.T) {
} }
func TestSignTxRequest(t *testing.T) { func TestSignTxRequest(t *testing.T) {
js := ` js := `
function ApproveTx(r){ function ApproveTx(r){
console.log("transaction.from", r.transaction.from); console.log("transaction.from", r.transaction.from);
@ -245,7 +244,6 @@ func (d *dummyUI) OnSignerStartup(info core.StartupInfo) {
//TestForwarding tests that the rule-engine correctly dispatches requests to the next caller //TestForwarding tests that the rule-engine correctly dispatches requests to the next caller
func TestForwarding(t *testing.T) { func TestForwarding(t *testing.T) {
js := "" js := ""
ui := &dummyUI{make([]string, 0)} ui := &dummyUI{make([]string, 0)}
jsBackend := storage.NewEphemeralStorage() jsBackend := storage.NewEphemeralStorage()
@ -268,11 +266,8 @@ func TestForwarding(t *testing.T) {
expCalls := 6 expCalls := 6
if len(ui.calls) != expCalls { if len(ui.calls) != expCalls {
t.Errorf("Expected %d forwarded calls, got %d: %s", expCalls, len(ui.calls), strings.Join(ui.calls, ",")) t.Errorf("Expected %d forwarded calls, got %d: %s", expCalls, len(ui.calls), strings.Join(ui.calls, ","))
} }
} }
func TestMissingFunc(t *testing.T) { func TestMissingFunc(t *testing.T) {
@ -296,10 +291,8 @@ func TestMissingFunc(t *testing.T) {
t.Errorf("Expected missing method to cause non-approval") t.Errorf("Expected missing method to cause non-approval")
} }
t.Logf("Err %v", err) t.Logf("Err %v", err)
} }
func TestStorage(t *testing.T) { func TestStorage(t *testing.T) {
js := ` js := `
function testStorage(){ function testStorage(){
storage.put("mykey", "myvalue") storage.put("mykey", "myvalue")
@ -348,7 +341,6 @@ func TestStorage(t *testing.T) {
t.Errorf("Unexpected data, expected '%v', got '%v'", exp, retval) t.Errorf("Unexpected data, expected '%v', got '%v'", exp, retval)
} }
t.Logf("Err %v", err) t.Logf("Err %v", err)
} }
const ExampleTxWindow = ` const ExampleTxWindow = `
@ -548,7 +540,6 @@ func (d *dontCallMe) OnApprovedTx(tx ethapi.SignTransactionResult) {
// if it does, that would be bad since developers may rely on that to store data, // if it does, that would be bad since developers may rely on that to store data,
// instead of using the disk-based data storage // instead of using the disk-based data storage
func TestContextIsCleared(t *testing.T) { func TestContextIsCleared(t *testing.T) {
js := ` js := `
function ApproveTx(){ function ApproveTx(){
if (typeof foobar == 'undefined') { if (typeof foobar == 'undefined') {
@ -580,7 +571,6 @@ func TestContextIsCleared(t *testing.T) {
} }
func TestSignData(t *testing.T) { func TestSignData(t *testing.T) {
js := `function ApproveListing(){ js := `function ApproveListing(){
return "Approve" return "Approve"
} }

@ -51,7 +51,6 @@ func TestEncryption(t *testing.T) {
} }
func TestFileStorage(t *testing.T) { func TestFileStorage(t *testing.T) {
a := map[string]storedCredential{ a := map[string]storedCredential{
"secret": { "secret": {
Iv: common.Hex2Bytes("cdb30036279601aeee60f16b"), Iv: common.Hex2Bytes("cdb30036279601aeee60f16b"),

@ -65,5 +65,4 @@ func (test *DifficultyTest) Run(config *params.ChainConfig) error {
test.CurrentTimestamp, test.CurrentBlockNumber, actual, exp) test.CurrentTimestamp, test.CurrentBlockNumber, actual, exp)
} }
return nil return nil
} }

@ -163,7 +163,6 @@ func (f *fuzzer) fuzz() int {
// Modify something in the proof db // Modify something in the proof db
// add stuff to proof db // add stuff to proof db
// drop stuff from proof db // drop stuff from proof db
} }
if f.exhausted { if f.exhausted {
break break

@ -138,7 +138,6 @@ func Debug(data []byte) int {
} }
func (f *fuzzer) fuzz() int { func (f *fuzzer) fuzz() int {
// This spongeDb is used to check the sequence of disk-db-writes // This spongeDb is used to check the sequence of disk-db-writes
var ( var (
spongeA = &spongeDb{sponge: sha3.NewLegacyKeccak256()} spongeA = &spongeDb{sponge: sha3.NewLegacyKeccak256()}

@ -84,11 +84,9 @@ func (ds *dataSource) Ended() bool {
} }
func Generate(input []byte) randTest { func Generate(input []byte) randTest {
var allKeys [][]byte var allKeys [][]byte
r := newDataSource(input) r := newDataSource(input)
genKey := func() []byte { genKey := func() []byte {
if len(allKeys) < 2 || r.readByte() < 0x0f { if len(allKeys) < 2 || r.readByte() < 0x0f {
// new key // new key
key := make([]byte, r.readByte()%50) key := make([]byte, r.readByte()%50)
@ -103,7 +101,6 @@ func Generate(input []byte) randTest {
var steps randTest var steps randTest
for i := 0; !r.Ended(); i++ { for i := 0; !r.Ended(); i++ {
step := randTestStep{op: int(r.readByte()) % opMax} step := randTestStep{op: int(r.readByte()) % opMax}
switch step.op { switch step.op {
case opUpdate: case opUpdate:
@ -141,7 +138,6 @@ func Fuzz(input []byte) int {
} }
func runRandTest(rt randTest) error { func runRandTest(rt randTest) error {
triedb := trie.NewDatabase(memorydb.New()) triedb := trie.NewDatabase(memorydb.New())
tr := trie.NewEmpty(triedb) tr := trie.NewEmpty(triedb)

@ -249,7 +249,6 @@ func runBenchmark(b *testing.B, t *StateTest) {
} }
statedb.RevertToSnapshot(snapshot) statedb.RevertToSnapshot(snapshot)
} }
}) })
} }
} }

@ -345,7 +345,6 @@ func TestStacktrieNotModifyValues(t *testing.T) {
if !bytes.Equal(have, want) { if !bytes.Equal(have, want) {
t.Fatalf("item %d, have %#x want %#x", i, have, want) t.Fatalf("item %d, have %#x want %#x", i, have, want)
} }
} }
} }

@ -352,7 +352,6 @@ func TestRandomCases(t *testing.T) {
{op: 1, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")}, // step 25 {op: 1, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")}, // step 25
} }
runRandTest(rt) runRandTest(rt)
} }
// randTest performs random trie operations. // randTest performs random trie operations.