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,6 +28,7 @@ linters:
- durationcheck
- exportloopref
- gosec
- whitespace
# - structcheck # lots of false positives
# - errcheck #lot of false positives

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

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

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

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

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

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

@ -138,7 +138,6 @@ func (ks keyStorePassphrase) JoinPath(filename string) string {
// Encryptdata encrypts the data given as 'data' with the password 'auth'.
func EncryptDataV3(data, auth []byte, scryptN, scryptP int) (CryptoJSON, error) {
salt := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, salt); err != nil {
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"])
p := ensureInt(cryptoJSON.KDFParams["p"])
return scrypt.Key(authArray, salt, n, r, p, dkLen)
} else if cryptoJSON.KDF == "pbkdf2" {
c := ensureInt(cryptoJSON.KDFParams["c"])
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
func (w *wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
// Unless we are doing 712 signing, simply dispatch to signHash
if !(mimeType == accounts.MimetypeTypedData && len(data) == 66 && data[0] == 0x19 && data[1] == 0x01) {
return w.signHash(account, crypto.Keccak256(data))

@ -759,7 +759,6 @@ func confirm(text string) bool {
}
func testExternalUI(api *core.SignerAPI) {
ctx := context.WithValue(context.Background(), "remote", "clef binary")
ctx = context.WithValue(ctx, "scheme", "in-proc")
ctx = context.WithValue(ctx, "local", "main")
@ -859,7 +858,6 @@ func testExternalUI(api *core.SignerAPI) {
expectDeny("signdata - text", err)
}
{ // Sign transaction
api.UI.ShowInfo("Please reject next transaction")
time.Sleep(delay)
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"))
api.UI.ShowInfo(result)
}
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
func GenDoc(ctx *cli.Context) error {
var (
a = common.HexToAddress("0xdeadbeef000000000000000000000000deadbeef")
b = common.HexToAddress("0x1111111122222222222233333333334444444444")
@ -1049,7 +1045,6 @@ func GenDoc(ctx *cli.Context) error {
var tx types.Transaction
tx.UnmarshalBinary(rlpdata)
add("OnApproved - SignTransactionResult", desc, &ethapi.SignTransactionResult{Raw: rlpdata, Tx: &tx})
}
{ // 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)",

@ -134,7 +134,6 @@ func (c *cloudflareClient) uploadRecords(name string, records map[string]string)
ttl := rootTTL
if path != name {
ttl = treeNodeTTLCloudflare // Max TTL permitted by Cloudflare
}
record := cloudflare.DNSRecord{Type: "TXT", Name: path, Content: val, TTL: ttl}
_, 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++ {
blockNumber -= (1 - req.Skip)
headers[i] = c.blocks[blockNumber].Header()
}
return headers, nil

@ -350,7 +350,6 @@ func hexToCompact(hex []byte) []byte {
// TestSnapTrieNodes various forms of GetTrieNodes requests.
func (s *Suite) TestSnapTrieNodes(t *utesting.T) {
key := common.FromHex("0x00bf49f440a1cd0527e4d06e2765654c0f56452257516d793a9b8d604dcfdf2a")
// helper function to iterate the key, and generate the compact-encoded
// 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 snpMsg.(Message), nil
}
return nil, fmt.Errorf("request timed out")
}

@ -100,7 +100,6 @@ type rejectedTx struct {
func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
txs types.Transactions, miningReward int64,
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
// required blockhashes
var hashError error

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

@ -171,7 +171,6 @@ func BenchmarkByteAt(b *testing.B) {
}
func BenchmarkByteAtOld(b *testing.B) {
bigint := MustParseBig256("0x18F8F8F1000111000110011100222004330052300000000000000000FEFCF3CC")
for i := 0; i < b.N; i++ {
PaddedBigBytes(bigint, 32)
@ -244,7 +243,6 @@ func TestBigEndianByteAt(t *testing.T) {
if actual != test.exp {
t.Fatalf("Expected [%v] %v:th byte to be %v, was %v.", test.x, test.y, test.exp, actual)
}
}
}
func TestLittleEndianByteAt(t *testing.T) {
@ -277,7 +275,6 @@ func TestLittleEndianByteAt(t *testing.T) {
if actual != test.exp {
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) {
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md
// 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 {
t.Errorf("Expected failure, input %v", r)
}
}
}
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) {
if i == 1 {
gen.OffsetTime(-9) // higher block difficulty
}
})
if _, err := blockchain.InsertChain(chain); err != nil {
@ -1364,7 +1363,6 @@ done:
t.Errorf("unexpected event fired: %v", e)
case <-time.After(250 * time.Millisecond):
}
}
// 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()
if got := chain.CurrentBlock().Transactions().Len(); got != numTxs*numBlocks {
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
if block.GasUsed() != expected {
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)
rand.Read(value)
accStorage[randomHash()] = value
}
storage[accountKey] = accStorage
}
@ -382,7 +381,6 @@ func BenchmarkJournal(b *testing.B) {
value := make([]byte, 32)
rand.Read(value)
accStorage[randomHash()] = value
}
storage[accountKey] = accStorage
}

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

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

@ -92,7 +92,6 @@ func BenchmarkBloom9Lookup(b *testing.B) {
}
func BenchmarkCreateBloom(b *testing.B) {
var txs = Transactions{
NewContractCreation(1, big.NewInt(1), 1, big.NewInt(1), 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 {
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.
func TestEIP2930Signer(t *testing.T) {
var (
key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
keyAddr = crypto.PubkeyToAddress(key.PublicKey)

@ -46,7 +46,6 @@ var commonParams []*twoOperandParams
var twoOpMethods map[string]executionFunc
func init() {
// Params is a list of common edgecases that should be used for some common tests
params := []string{
"0000000000000000000000000000000000000000000000000000000000000000", // 0
@ -92,7 +91,6 @@ func init() {
}
func testTwoOperandOp(t *testing.T, tests []TwoOperandTestcase, opFn executionFunc, name string) {
var (
env = NewEVM(BlockContext{}, TxContext{}, nil, params.TestChainConfig, Config{})
stack = newstack()
@ -641,7 +639,6 @@ func TestCreate2Addreses(t *testing.T) {
expected: "0xE33C0C7F7df4809055C3ebA6c09CFe4BaF1BD9e0",
},
} {
origin := common.BytesToAddress(common.FromHex(tt.origin))
salt := common.BytesToHash(common.FromHex(tt.salt))
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
// ErrExecutionReverted which means revert-and-keep-gas-left.
func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
// Increment the call depth which is restricted to 1024
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[EXP].dynamicGas = gasExpEIP158
return validate(instructionSet)
}
// 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
// 55 ms
func BenchmarkSimpleLoop(b *testing.B) {
staticCallIdentity := []byte{
byte(vm.JUMPDEST), // [ count ]
// push args for the call
@ -498,7 +497,6 @@ func TestEip2929Cases(t *testing.T) {
t.Skip("Test only useful for generating documentation")
id := 1
prettyPrint := func(comment string, code []byte) {
instrs := make([]string, 0)
it := asm.NewInstructionIterator(code)
for it.Next() {

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

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

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

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

@ -334,7 +334,6 @@ func testParamSelection(t *testing.T, c testCase) {
if err == nil {
t.Fatalf("ecies: encryption should not have succeeded (%s)\n", c.Name)
}
}
// 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,
results int, validate func(index int, header *types.Header) error,
reconstruct func(index int, result *fetchResult)) (int, error) {
// Short circuit if the data was never requested
request := pendPool[id]
if request == nil {

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

@ -790,7 +790,6 @@ func TestSkeletonSyncRetrievals(t *testing.T) {
check := func() error {
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))
}
for j := 0; j < len(progress.Subchains); j++ {
if progress.Subchains[j].Head != tt.midstate[j].Head {

@ -692,7 +692,6 @@ func (f *BlockFetcher) loop() {
} else {
f.forgetHash(hash)
}
}
if matched {
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() {
for {
select {
case logs := <-matchedLogs:

@ -72,7 +72,6 @@ func BenchmarkFilters(b *testing.B) {
receipt := makeReceipt(addr4)
gen.AddUncheckedReceipt(receipt)
gen.AddUncheckedTx(types.NewTransaction(999, common.HexToAddress("0x999"), big.NewInt(999), 999, gen.BaseFee(), nil))
}
})
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) {
// Reduce the checkpoint handshake challenge timeout
defer func(old time.Duration) { syncChallengeTimeout = old }(syncChallengeTimeout)
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)
}
}
}
// TestEth66Messages tests the encoding of all redefined eth66 messages
func TestEth66Messages(t *testing.T) {
// Some basic structs used during testing
var (
header *types.Header

@ -878,7 +878,6 @@ func (r *callframeResult) GetError() goja.Value {
return r.vm.ToValue(r.err.Error())
}
return goja.Undefined()
}
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.
// 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) {
type storageResult struct {
Key string `json:"key"`
Value *hexutil.Big `json:"value"`

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

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

@ -219,7 +219,6 @@ func (ctx ppctx) fields(obj *goja.Object) []string {
vals = append(vals, k)
}
}
}
iterOwnAndConstructorKeys(ctx.vm, obj, add)
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 {
t.Fatalf("Failed to freeze client: %v", err)
}
}
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),
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 {
// Create a ticker to detect expired retrieval tasks
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()

@ -621,7 +621,6 @@ func testThrottling(t *testing.T, protocol uint, mode SyncMode) {
t.Fatalf("block synchronization failed: %v", err)
}
tester.terminate()
}
// 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,
results int, validate func(index int, header *types.Header) error,
reconstruct func(index int, result *fetchResult)) (int, error) {
// Short circuit if the data was never requested
request := pendPool[id]
if request == nil {

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

@ -641,7 +641,6 @@ func (f *BlockFetcher) loop() {
} else {
f.forgetHash(hash)
}
}
if matched {
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 {
t.Errorf("totalCost/totalCapacity/testLength ratio incorrect (expected: 1, got: %f)", ratio)
}
}
func (n *testNode) send(t *testing.T, now mclock.AbsTime) bool {

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

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

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

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

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

@ -188,7 +188,6 @@ func TestStartStopMiner(t *testing.T) {
waitForMiningState(t, miner, true)
miner.Stop()
waitForMiningState(t, miner, false)
}
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) {
rawTx, err := ec.client.TransactionInBlock(ctx.context, hash.hash, uint(index))
return &Transaction{rawTx}, err
}
// 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 {
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)
if err != nil {
t.Fatalf("could not issue a GET request to the given endpoint: %v", err)
}
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
h.next.ServeHTTP(w, r)
return
}
// Not an IP address, but a hostname. Need to validate
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
func (s *Server) GetMockers(w http.ResponseWriter, req *http.Request) {
list := GetMockerList()
s.JSON(w, http.StatusOK, list)
}

@ -489,7 +489,6 @@ func (t *expectEvents) expect(events ...*Event) {
}
switch expected.Type {
case EventTypeNode:
if event.Node == nil {
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 {
t.Fatalf("expected conn event %d to have up=%t, got up=%t", i, expected.Conn.Up, event.Conn.Up)
}
}
i++

@ -157,7 +157,6 @@ func probabilistic(net *Network, quit chan struct{}, nodeCount int) {
}
wg.Wait()
}
}
//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
switch event.Type {
case p2p.PeerEventTypeAdd:
net.DidConnect(id, peer)
@ -247,7 +246,6 @@ func (net *Network) watchPeerEvents(id enode.ID, events chan *p2p.PeerEvent, sub
case p2p.PeerEventTypeMsgRecv:
net.DidReceive(peer, id, event.Protocol, *event.MsgCode)
}
case err := <-sub.Err():
@ -927,7 +925,6 @@ func (net *Network) snapshot(addServices []string, removeServices []string) (*Sn
if !haveSvc {
cleanedServices = append(cleanedServices, svc)
}
}
snap.Nodes[i].Node.Config.Lifecycles = cleanedServices
}
@ -1021,7 +1018,6 @@ func (net *Network) Load(snap *Snapshot) error {
// Start connecting.
for _, conn := range snap.Conns {
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,
//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
// and that a network when loaded with this snapshot only contains those same connections
func TestSnapshot(t *testing.T) {
// PART I
// create snapshot from ring network
@ -204,7 +203,6 @@ OuterTwo:
t.Fatal(ctx.Err())
case ev := <-evC:
if ev.Type == EventTypeConn && !ev.Control {
// fail on any disconnect
if !ev.Conn.Up {
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) {
// stop timer to discard setup time pollution
args := strings.Split(b.Name(), "/")
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())
}
}
}
func ExampleDecode() {

@ -36,7 +36,6 @@ func NewListIterator(data RawValue) (*listIterator, error) {
data: data[t : t+c],
}
return it, nil
}
// 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)
return
}
}
// 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)
// ...and to the external caller
return &response, nil
}
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) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) {
switch <-ui.approveCh {
case "Y":
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, "")
api := core.NewSignerAPI(am, 1337, true, ui, db, true, &storage.NoStorage{})
return api, ui
}
func createAccount(ui *headlessUi, api *core.SignerAPI, t *testing.T) {
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) {
ui.approveCh <- "Y"
// We will be asked three times to provide a suitable 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) {
ui.approveCh <- "A"
return api.List(context.Background())
}
func TestNewAcc(t *testing.T) {
@ -321,5 +317,4 @@ func TestSignTx(t *testing.T) {
if bytes.Equal(res.Raw, res2.Raw) {
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 nil, fmt.Errorf("unrecognized type '%s'", encType)
}
// 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") {
return fmt.Sprintf("%s", encValue), nil
}
if strings.HasPrefix(encType, "uint") || strings.HasPrefix(encType, "int") {
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)
l.log.Info("Version", "type", "response", "data", data, "error", err)
return data, err
}
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) {
fmt.Printf("## %s\n\n%s\n", info.Title, info.Prompt)
defer fmt.Println("-----------------------")
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.Println()
}
fmt.Printf("\n")
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
func (ui *CommandlineUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
ui.mu.Lock()
defer ui.mu.Unlock()
@ -245,7 +242,6 @@ func (ui *CommandlineUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
}
func (ui *CommandlineUI) OnSignerStartup(info StartupInfo) {
fmt.Printf("------- Signer info -------\n")
for k, v := range info.Info {
fmt.Printf("* %v : %v\n", k, v)

@ -38,7 +38,6 @@ func TestPasswordValidation(t *testing.T) {
if err == nil && test.shouldFail {
t.Errorf("password '%v' should fail validation", test.pw)
} else if err != nil && !test.shouldFail {
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 != "" {
a := hexutil.Bytes(common.FromHex(t.i))
input = &a
}
return &apitypes.SendTxArgs{
From: *from,

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

@ -152,7 +152,6 @@ func TestListRequest(t *testing.T) {
}
func TestSignTxRequest(t *testing.T) {
js := `
function ApproveTx(r){
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
func TestForwarding(t *testing.T) {
js := ""
ui := &dummyUI{make([]string, 0)}
jsBackend := storage.NewEphemeralStorage()
@ -268,11 +266,8 @@ func TestForwarding(t *testing.T) {
expCalls := 6
if len(ui.calls) != expCalls {
t.Errorf("Expected %d forwarded calls, got %d: %s", expCalls, len(ui.calls), strings.Join(ui.calls, ","))
}
}
func TestMissingFunc(t *testing.T) {
@ -296,10 +291,8 @@ func TestMissingFunc(t *testing.T) {
t.Errorf("Expected missing method to cause non-approval")
}
t.Logf("Err %v", err)
}
func TestStorage(t *testing.T) {
js := `
function testStorage(){
storage.put("mykey", "myvalue")
@ -348,7 +341,6 @@ func TestStorage(t *testing.T) {
t.Errorf("Unexpected data, expected '%v', got '%v'", exp, retval)
}
t.Logf("Err %v", err)
}
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,
// instead of using the disk-based data storage
func TestContextIsCleared(t *testing.T) {
js := `
function ApproveTx(){
if (typeof foobar == 'undefined') {
@ -580,7 +571,6 @@ func TestContextIsCleared(t *testing.T) {
}
func TestSignData(t *testing.T) {
js := `function ApproveListing(){
return "Approve"
}

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

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

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

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

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

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

@ -345,7 +345,6 @@ func TestStacktrieNotModifyValues(t *testing.T) {
if !bytes.Equal(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
}
runRandTest(rt)
}
// randTest performs random trie operations.