From 8f847fcafa96296597d5f1b5e07a459f3131c0a4 Mon Sep 17 00:00:00 2001 From: Zach Ramsay Date: Sat, 10 Jun 2017 22:27:01 -0400 Subject: [PATCH] all: apply megacheck --- Makefile | 5 +++ accounts/keystore/key.go | 8 ----- accounts/keystore/keystore_passphrase.go | 2 -- accounts/usbwallet/ledger_hub.go | 2 +- accounts/usbwallet/ledger_wallet.go | 2 -- cmd/evm/disasm.go | 6 ++-- cmd/puppeth/ssh.go | 2 +- common/bitutil/compress_test.go | 2 +- common/hexutil/json.go | 5 +-- consensus/clique/snapshot.go | 4 +-- console/console_test.go | 2 -- contracts/chequebook/cheque.go | 3 -- core/asm/asm.go | 5 +-- core/asm/compiler.go | 11 +------ core/asm/lexer.go | 6 ++-- core/blockchain.go | 1 - core/blockchain_test.go | 26 ++++++--------- core/database_util.go | 1 - core/genesis.go | 16 ---------- core/helper_test.go | 18 ----------- core/types/block.go | 11 ------- core/types/log.go | 8 ----- core/types/receipt.go | 7 ----- core/types/transaction.go | 17 +--------- core/types/transaction_signing.go | 7 +---- core/vm/contracts.go | 3 -- core/vm/interpreter.go | 2 -- core/vm/jump_table.go | 2 -- core/vm/logger.go | 11 ------- core/vm/memory_table.go | 6 ---- crypto/ecies/ecies.go | 1 - crypto/ecies/ecies_test.go | 13 -------- crypto/sha3/sha3.go | 5 ++- crypto/sha3/sha3_test.go | 40 ------------------------ eth/config.go | 5 --- eth/filters/api.go | 1 - eth/filters/filter.go | 3 -- ethdb/database_test.go | 34 -------------------- ethstats/ethstats.go | 3 -- event/feed.go | 7 ++--- internal/ethapi/api.go | 9 ++---- internal/jsre/pretty.go | 8 ----- les/handler.go | 6 ---- les/handler_test.go | 37 ---------------------- les/helper_test.go | 9 ------ les/odr.go | 14 ++++----- les/odr_test.go | 2 +- les/peer.go | 5 +-- les/protocol.go | 27 ---------------- les/server.go | 11 ------- les/serverpool.go | 4 --- les/sync.go | 5 --- light/lightchain.go | 1 - light/lightchain_test.go | 8 ----- log/format.go | 2 +- miner/worker.go | 8 ++--- node/config.go | 1 - node/utils_test.go | 2 -- p2p/discover/udp.go | 2 -- p2p/discv5/net.go | 28 ++++++----------- p2p/discv5/table.go | 1 - p2p/discv5/table_test.go | 19 ++--------- p2p/discv5/udp.go | 25 +++------------ p2p/discv5/udp_test.go | 28 ++++++++--------- p2p/peer.go | 2 -- p2p/server.go | 4 +-- rpc/server.go | 22 ++----------- rpc/subscription.go | 1 - rpc/types.go | 7 ++--- rpc/utils.go | 15 --------- swarm/api/api.go | 8 ++--- swarm/api/client/client_test.go | 7 +---- swarm/api/http/server.go | 2 +- swarm/api/http/server_test.go | 8 +++-- swarm/fuse/swarmfs_test.go | 17 +++++----- swarm/fuse/swarmfs_unix.go | 12 ++----- swarm/network/kademlia/kademlia.go | 4 +-- swarm/storage/chunker.go | 13 ++++---- swarm/storage/chunker_test.go | 14 --------- swarm/storage/dbstore.go | 4 +-- swarm/storage/dpa.go | 2 -- swarm/storage/localstore.go | 1 - swarm/storage/memstore.go | 3 -- swarm/storage/netstore.go | 8 ----- swarm/swarm.go | 1 - tests/init.go | 11 ------- whisper/mailserver/mailserver.go | 2 +- whisper/mailserver/server_test.go | 2 +- whisper/whisperv2/whisper.go | 4 +-- whisper/whisperv5/api.go | 4 +-- whisper/whisperv5/api_test.go | 5 ++- whisper/whisperv5/message_test.go | 7 +---- 92 files changed, 126 insertions(+), 639 deletions(-) delete mode 100644 ethdb/database_test.go diff --git a/Makefile b/Makefile index 2b5d84f286..16139c88a8 100644 --- a/Makefile +++ b/Makefile @@ -8,6 +8,11 @@ .PHONY: geth-darwin geth-darwin-386 geth-darwin-amd64 .PHONY: geth-windows geth-windows-386 geth-windows-amd64 +PACKAGES=$(shell go list ./... | grep -v '/vendor/') + +megacheck: + @for pkg in ${PACKAGES}; do megacheck "$$pkg"; done + GOBIN = build/bin GO ?= latest diff --git a/accounts/keystore/key.go b/accounts/keystore/key.go index ecc955d74d..211fa863d7 100644 --- a/accounts/keystore/key.go +++ b/accounts/keystore/key.go @@ -91,14 +91,6 @@ type cipherparamsJSON struct { IV string `json:"iv"` } -type scryptParamsJSON struct { - N int `json:"n"` - R int `json:"r"` - P int `json:"p"` - DkLen int `json:"dklen"` - Salt string `json:"salt"` -} - func (k *Key) MarshalJSON() (j []byte, err error) { jStruct := plainKeyJSON{ hex.EncodeToString(k.Address[:]), diff --git a/accounts/keystore/keystore_passphrase.go b/accounts/keystore/keystore_passphrase.go index 679fc15d69..e03ca61fa5 100644 --- a/accounts/keystore/keystore_passphrase.go +++ b/accounts/keystore/keystore_passphrase.go @@ -45,8 +45,6 @@ import ( ) const ( - keyHeaderKDF = "scrypt" - // StandardScryptN is the N parameter of Scrypt encryption algorithm, using 256MB // memory and taking approximately 1s CPU time on a modern processor. StandardScryptN = 1 << 18 diff --git a/accounts/usbwallet/ledger_hub.go b/accounts/usbwallet/ledger_hub.go index fcbc24c0f5..a3588ddae7 100644 --- a/accounts/usbwallet/ledger_hub.go +++ b/accounts/usbwallet/ledger_hub.go @@ -199,7 +199,7 @@ func (hub *LedgerHub) updater() { for { // Wait for a USB hotplug event (not supported yet) or a refresh timeout select { - //case <-hub.changes: // reenable on hutplug implementation + // case <-hub.changes: // re-enable on hutplug implementation case <-time.After(ledgerRefreshCycle): } // Run the wallet refresher diff --git a/accounts/usbwallet/ledger_wallet.go b/accounts/usbwallet/ledger_wallet.go index f1beebb2c9..b6a34040fb 100644 --- a/accounts/usbwallet/ledger_wallet.go +++ b/accounts/usbwallet/ledger_wallet.go @@ -65,11 +65,9 @@ const ( ledgerOpGetConfiguration ledgerOpcode = 0x06 // Returns specific wallet application configuration ledgerP1DirectlyFetchAddress ledgerParam1 = 0x00 // Return address directly from the wallet - ledgerP1ConfirmFetchAddress ledgerParam1 = 0x01 // Require a user confirmation before returning the address ledgerP1InitTransactionData ledgerParam1 = 0x00 // First transaction data block for signing ledgerP1ContTransactionData ledgerParam1 = 0x80 // Subsequent transaction data block for signing ledgerP2DiscardAddressChainCode ledgerParam2 = 0x00 // Do not return the chain code along with the address - ledgerP2ReturnAddressChainCode ledgerParam2 = 0x01 // Require a user confirmation before returning the address ) // errReplyInvalidHeader is the error message returned by a Ledger data exchange diff --git a/cmd/evm/disasm.go b/cmd/evm/disasm.go index a78b2a8e18..b3becfcf23 100644 --- a/cmd/evm/disasm.go +++ b/cmd/evm/disasm.go @@ -46,8 +46,6 @@ func disasmCmd(ctx *cli.Context) error { code := strings.TrimSpace(string(in[:])) fmt.Printf("%v\n", code) - if err = asm.PrintDisassembled(code); err != nil { - return err - } - return nil + + return asm.PrintDisassembled(code) } diff --git a/cmd/puppeth/ssh.go b/cmd/puppeth/ssh.go index 93668945c0..26f8466850 100644 --- a/cmd/puppeth/ssh.go +++ b/cmd/puppeth/ssh.go @@ -122,7 +122,7 @@ func dial(server string, pubkey []byte) (*sshClient, error) { } } // If a public key exists for this SSH server, check that it matches - if bytes.Compare(pubkey, key.Marshal()) == 0 { + if bytes.Equal(pubkey, key.Marshal()) { return nil } // We have a mismatch, forbid connecting diff --git a/common/bitutil/compress_test.go b/common/bitutil/compress_test.go index 805ab0369d..bcee7459f8 100644 --- a/common/bitutil/compress_test.go +++ b/common/bitutil/compress_test.go @@ -121,7 +121,7 @@ func TestCompression(t *testing.T) { in := hexutil.MustDecode("0x4912385c0e7b64000000") out := hexutil.MustDecode("0x80fe4912385c0e7b64") - if data := CompressBytes(in); bytes.Compare(data, out) != 0 { + if data := CompressBytes(in); !bytes.Equal(data, out) { t.Errorf("encoding mismatch for sparse data: have %x, want %x", data, out) } if data, err := DecompressBytes(out, len(in)); err != nil || bytes.Compare(data, in) != 0 { diff --git a/common/hexutil/json.go b/common/hexutil/json.go index 1bc1d014c7..554b397b26 100644 --- a/common/hexutil/json.go +++ b/common/hexutil/json.go @@ -24,10 +24,7 @@ import ( "strconv" ) -var ( - textZero = []byte(`0x0`) - errNonString = errors.New("cannot unmarshal non-string as hex data") -) +var errNonString = errors.New("cannot unmarshal non-string as hex data") // Bytes marshals/unmarshals as a JSON string with 0x prefix. // The empty slice marshals as "0x". diff --git a/consensus/clique/snapshot.go b/consensus/clique/snapshot.go index 8eaf3b62e4..da7a4c85f4 100644 --- a/consensus/clique/snapshot.go +++ b/consensus/clique/snapshot.go @@ -223,9 +223,9 @@ func (s *Snapshot) apply(headers []*types.Header) (*Snapshot, error) { // Tally up the new vote from the signer var authorize bool switch { - case bytes.Compare(header.Nonce[:], nonceAuthVote) == 0: + case bytes.Equal(header.Nonce[:], nonceAuthVote): authorize = true - case bytes.Compare(header.Nonce[:], nonceDropVote) == 0: + case bytes.Equal(header.Nonce[:], nonceDropVote): authorize = false default: return nil, errInvalidVote diff --git a/console/console_test.go b/console/console_test.go index 0fc0e70513..8ac499bd12 100644 --- a/console/console_test.go +++ b/console/console_test.go @@ -77,8 +77,6 @@ type tester struct { console *Console input *hookedPrompter output *bytes.Buffer - - lastConfirm string } // newTester creates a test environment based on which the console can operate. diff --git a/contracts/chequebook/cheque.go b/contracts/chequebook/cheque.go index bd635705e1..66a6c5c4ea 100644 --- a/contracts/chequebook/cheque.go +++ b/contracts/chequebook/cheque.go @@ -395,7 +395,6 @@ func (self *Chequebook) autoDeposit(interval time.Duration) { } } }() - return } // Outbox can issue cheques from a single contract to a single beneficiary. @@ -436,7 +435,6 @@ type Inbox struct { sender common.Address // local peer's address to send cashing tx from signer *ecdsa.PublicKey // peer's public key txhash string // tx hash of last cashing tx - abigen bind.ContractBackend // blockchain API session *contract.ChequebookSession // abi contract backend with tx opts quit chan bool // when closed causes autocash to stop maxUncashed *big.Int // threshold that triggers autocashing @@ -543,7 +541,6 @@ func (self *Inbox) autoCash(cashInterval time.Duration) { } } }() - return } // Receive is called to deposit the latest cheque to the incoming Inbox. diff --git a/core/asm/asm.go b/core/asm/asm.go index 5fe827e7c1..ce22f93f92 100644 --- a/core/asm/asm.go +++ b/core/asm/asm.go @@ -114,10 +114,7 @@ func PrintDisassembled(code string) error { fmt.Printf("%06v: %v\n", it.PC(), it.Op()) } } - if err := it.Error(); err != nil { - return err - } - return nil + return it.Error() } // Return all disassembled EVM instructions in human-readable format. diff --git a/core/asm/compiler.go b/core/asm/compiler.go index b2c85375cc..a6fecf99e0 100644 --- a/core/asm/compiler.go +++ b/core/asm/compiler.go @@ -17,7 +17,6 @@ package asm import ( - "errors" "fmt" "math/big" "os" @@ -237,10 +236,7 @@ func (c *Compiler) pushBin(v interface{}) { // isPush returns whether the string op is either any of // push(N). func isPush(op string) bool { - if op == "push" { - return true - } - return false + return op == "push" } // isJump returns whether the string op is jump(i) @@ -267,11 +263,6 @@ func (err compileError) Error() string { return fmt.Sprintf("%d syntax error: unexpected %v, expected %v", err.lineno, err.got, err.want) } -var ( - errExpBol = errors.New("expected beginning of line") - errExpElementOrLabel = errors.New("expected beginning of line") -) - func compileErr(c token, got, want string) error { return compileError{ got: got, diff --git a/core/asm/lexer.go b/core/asm/lexer.go index 2770bd35fc..9f1f10341d 100644 --- a/core/asm/lexer.go +++ b/core/asm/lexer.go @@ -145,7 +145,7 @@ func (l *lexer) ignore() { // Accepts checks whether the given input matches the next rune func (l *lexer) accept(valid string) bool { - if strings.IndexRune(valid, l.next()) >= 0 { + if strings.ContainsRune(valid, l.next()) { return true } @@ -157,7 +157,7 @@ func (l *lexer) accept(valid string) bool { // acceptRun will continue to advance the seeker until valid // can no longer be met. func (l *lexer) acceptRun(valid string) { - for strings.IndexRune(valid, l.next()) >= 0 { + for strings.ContainsRune(valid, l.next()) { } l.backup() } @@ -166,7 +166,7 @@ func (l *lexer) acceptRun(valid string) { // to advance the seeker until the rune has been found. func (l *lexer) acceptRunUntil(until rune) bool { // Continues running until a rune is found - for i := l.next(); strings.IndexRune(string(until), i) == -1; i = l.next() { + for i := l.next(); !strings.ContainsRune(string(until), i); i = l.next() { if i == 0 { return false } diff --git a/core/blockchain.go b/core/blockchain.go index 073b91bab4..ba214d7165 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -88,7 +88,6 @@ type BlockChain struct { chainmu sync.RWMutex // blockchain insertion lock procmu sync.RWMutex // block processor lock - checkpoint int // checkpoint counts towards the new checkpoint currentBlock *types.Block // Current head of the block chain currentFastBlock *types.Block // Current head of the fast-sync chain (may be above the block chain!) diff --git a/core/blockchain_test.go b/core/blockchain_test.go index 7505208e18..3b8f828bcd 100644 --- a/core/blockchain_test.go +++ b/core/blockchain_test.go @@ -17,7 +17,6 @@ package core import ( - "fmt" "math/big" "math/rand" "testing" @@ -109,13 +108,6 @@ func testFork(t *testing.T, blockchain *BlockChain, i, n int, full bool, compara comparator(tdPre, tdPost) } -func printChain(bc *BlockChain) { - for i := bc.CurrentBlock().Number().Uint64(); i > 0; i-- { - b := bc.GetBlockByNumber(uint64(i)) - fmt.Printf("\t%x %v\n", b.Hash(), b.Difficulty()) - } -} - // testBlockChainImport tries to process a chain of blocks, writing them into // the database if successful. func testBlockChainImport(chain types.Blocks, blockchain *BlockChain) error { @@ -171,15 +163,6 @@ func testHeaderChainImport(chain []*types.Header, blockchain *BlockChain) error return nil } -func insertChain(done chan bool, blockchain *BlockChain, chain types.Blocks, t *testing.T) { - _, err := blockchain.InsertChain(chain) - if err != nil { - fmt.Println(err) - t.FailNow() - } - done <- true -} - func TestLastBlock(t *testing.T) { bchain := newTestBlockChain(false) block := makeBlockChain(bchain.CurrentBlock(), 1, bchain.chainDb, 0)[0] @@ -522,6 +505,11 @@ func testInsertNonceError(t *testing.T, full bool) { blockchain.engine = ethash.NewFakeFailer(failNum) failRes, err = blockchain.InsertChain(blocks) + // catching this error fails the test + //if err != nil { + // t.Fatalf("failed to insert chain: %v", err) + //} + } else { headers := makeHeaderChain(blockchain.CurrentHeader(), i, db, 0) @@ -531,6 +519,10 @@ func testInsertNonceError(t *testing.T, full bool) { blockchain.engine = ethash.NewFakeFailer(failNum) blockchain.hc.engine = blockchain.engine failRes, err = blockchain.InsertHeaderChain(headers, 1) + // catching this error fails the test + //if err != nil { + // t.Fatalf("failed to insert header chain: %v", err) + //} } // Check that the returned error indicates the failure. if failRes != failAt { diff --git a/core/database_util.go b/core/database_util.go index b4a230c9c9..138d9a3478 100644 --- a/core/database_util.go +++ b/core/database_util.go @@ -62,7 +62,6 @@ var ( oldBodySuffix = []byte("-body") oldBlockNumPrefix = []byte("block-num-") oldBlockReceiptsPrefix = []byte("receipts-block-") - oldBlockHashPrefix = []byte("block-hash-") // [deprecated by the header/block split, remove eventually] ErrChainConfigNotFound = errors.New("ChainConfig not found") // general config not found error diff --git a/core/genesis.go b/core/genesis.go index 947a53c700..c17d7cb9e9 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -24,7 +24,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethdb" @@ -64,21 +63,6 @@ type GenesisAccount struct { Nonce uint64 `json:"nonce,omitempty"` } -// field type overrides for gencodec -type genesisSpecMarshaling struct { - Nonce math.HexOrDecimal64 - Timestamp math.HexOrDecimal64 - ExtraData hexutil.Bytes - GasLimit math.HexOrDecimal64 - Difficulty *math.HexOrDecimal256 - Alloc map[common.UnprefixedAddress]GenesisAccount -} -type genesisAccountMarshaling struct { - Code hexutil.Bytes - Balance *math.HexOrDecimal256 - Nonce math.HexOrDecimal64 -} - // GenesisMismatchError is raised when trying to overwrite an existing // genesis block with an incompatible one. type GenesisMismatchError struct { diff --git a/core/helper_test.go b/core/helper_test.go index 698a2924cb..1bde5723fe 100644 --- a/core/helper_test.go +++ b/core/helper_test.go @@ -18,7 +18,6 @@ package core import ( "container/list" - "fmt" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethdb" @@ -75,20 +74,3 @@ func (tm *TestManager) EventMux() *event.TypeMux { func (tm *TestManager) Db() ethdb.Database { return tm.db } - -func NewTestManager() *TestManager { - db, err := ethdb.NewMemDatabase() - if err != nil { - fmt.Println("Could not create mem-db, failing") - return nil - } - - testManager := &TestManager{} - testManager.eventMux = new(event.TypeMux) - testManager.db = db - // testManager.txPool = NewTxPool(testManager) - // testManager.blockChain = NewBlockChain(testManager) - // testManager.stateManager = NewStateManager(testManager) - - return testManager -} diff --git a/core/types/block.go b/core/types/block.go index 1d00d9f930..3a40e88f53 100644 --- a/core/types/block.go +++ b/core/types/block.go @@ -85,17 +85,6 @@ type Header struct { Nonce BlockNonce `json:"nonce" gencodec:"required"` } -// field type overrides for gencodec -type headerMarshaling struct { - Difficulty *hexutil.Big - Number *hexutil.Big - GasLimit *hexutil.Big - GasUsed *hexutil.Big - Time *hexutil.Big - Extra hexutil.Bytes - Hash common.Hash `json:"hash"` // adds call to Hash() in MarshalJSON -} - // Hash returns the block hash of the header, which is simply the keccak256 hash of its // RLP encoding. func (h *Header) Hash() common.Hash { diff --git a/core/types/log.go b/core/types/log.go index be5de38da7..7caea98626 100644 --- a/core/types/log.go +++ b/core/types/log.go @@ -21,7 +21,6 @@ import ( "io" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/rlp" ) @@ -56,13 +55,6 @@ type Log struct { Removed bool `json:"removed"` } -type logMarshaling struct { - Data hexutil.Bytes - BlockNumber hexutil.Uint64 - TxIndex hexutil.Uint - Index hexutil.Uint -} - type rlpLog struct { Address common.Address Topics []common.Hash diff --git a/core/types/receipt.go b/core/types/receipt.go index ef6f6a2bb2..0a70a97c33 100644 --- a/core/types/receipt.go +++ b/core/types/receipt.go @@ -22,7 +22,6 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/rlp" ) @@ -42,12 +41,6 @@ type Receipt struct { GasUsed *big.Int `json:"gasUsed" gencodec:"required"` } -type receiptMarshaling struct { - PostState hexutil.Bytes - CumulativeGasUsed *hexutil.Big - GasUsed *hexutil.Big -} - // NewReceipt creates a barebone transaction receipt, copying the init fields. func NewReceipt(root []byte, cumulativeGasUsed *big.Int) *Receipt { return &Receipt{PostState: common.CopyBytes(root), CumulativeGasUsed: new(big.Int).Set(cumulativeGasUsed)} diff --git a/core/types/transaction.go b/core/types/transaction.go index 8e108b2a33..ce336fcf65 100644 --- a/core/types/transaction.go +++ b/core/types/transaction.go @@ -25,17 +25,13 @@ import ( "sync/atomic" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/rlp" ) //go:generate gencodec -type txdata -field-override txdataMarshaling -out gen_tx_json.go -var ( - ErrInvalidSig = errors.New("invalid transaction v, r, s values") - errNoSigner = errors.New("missing signing methods") -) +var ErrInvalidSig = errors.New("invalid transaction v, r, s values") // deriveSigner makes a *best* guess about which signer to use. func deriveSigner(V *big.Int) Signer { @@ -71,17 +67,6 @@ type txdata struct { Hash *common.Hash `json:"hash" rlp:"-"` } -type txdataMarshaling struct { - AccountNonce hexutil.Uint64 - Price *hexutil.Big - GasLimit *hexutil.Big - Amount *hexutil.Big - Payload hexutil.Bytes - V *hexutil.Big - R *hexutil.Big - S *hexutil.Big -} - func NewTransaction(nonce uint64, to common.Address, amount, gasLimit, gasPrice *big.Int, data []byte) *Transaction { return newTransaction(nonce, &to, amount, gasLimit, gasPrice, data) } diff --git a/core/types/transaction_signing.go b/core/types/transaction_signing.go index b0f3275b2a..b4bab0aad7 100644 --- a/core/types/transaction_signing.go +++ b/core/types/transaction_signing.go @@ -27,12 +27,7 @@ import ( "github.com/ethereum/go-ethereum/params" ) -var ( - ErrInvalidChainId = errors.New("invalid chaid id for signer") - - errAbstractSigner = errors.New("abstract signer") - abstractSignerAddress = common.HexToAddress("ffffffffffffffffffffffffffffffffffffffff") -) +var ErrInvalidChainId = errors.New("invalid chaid id for signer") // sigCache is used to cache the derived sender and contains // the signer used to derive it. diff --git a/core/vm/contracts.go b/core/vm/contracts.go index 90b2f913e6..3340b615e2 100644 --- a/core/vm/contracts.go +++ b/core/vm/contracts.go @@ -18,7 +18,6 @@ package vm import ( "crypto/sha256" - "errors" "math/big" "github.com/ethereum/go-ethereum/common" @@ -28,8 +27,6 @@ import ( "golang.org/x/crypto/ripemd160" ) -var errBadPrecompileInput = errors.New("bad pre compile input") - // Precompiled contract is the basic interface for native Go contracts. The implementation // requires a deterministic gas count based on the input size of the Run method of the // contract. diff --git a/core/vm/interpreter.go b/core/vm/interpreter.go index 545f7d6502..8ddf842fc7 100644 --- a/core/vm/interpreter.go +++ b/core/vm/interpreter.go @@ -60,8 +60,6 @@ type Interpreter struct { cfg Config gasTable params.GasTable intPool *intPool - - readonly bool } // NewInterpreter returns a new instance of the Interpreter. diff --git a/core/vm/jump_table.go b/core/vm/jump_table.go index 0034eacb7d..90c166418b 100644 --- a/core/vm/jump_table.go +++ b/core/vm/jump_table.go @@ -51,8 +51,6 @@ type operation struct { writes bool // valid is used to check whether the retrieved operation is valid and known valid bool - // reverts determined whether the operation reverts state - reverts bool } var ( diff --git a/core/vm/logger.go b/core/vm/logger.go index 405ab169cf..6deb130357 100644 --- a/core/vm/logger.go +++ b/core/vm/logger.go @@ -24,7 +24,6 @@ import ( "time" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/core/types" ) @@ -65,16 +64,6 @@ type StructLog struct { Err error `json:"error"` } -// overrides for gencodec -type structLogMarshaling struct { - Stack []*math.HexOrDecimal256 - Gas math.HexOrDecimal64 - GasCost math.HexOrDecimal64 - Memory hexutil.Bytes - OpName string `json:"opName"` - MemorySize int `json:"memSize"` -} - func (s *StructLog) OpName() string { return s.Op.String() } diff --git a/core/vm/memory_table.go b/core/vm/memory_table.go index 654137c70b..59482122e6 100644 --- a/core/vm/memory_table.go +++ b/core/vm/memory_table.go @@ -61,12 +61,6 @@ func memoryCall(stack *Stack) *big.Int { return math.BigMax(x, y) } -func memoryCallCode(stack *Stack) *big.Int { - x := calcMemSize(stack.Back(5), stack.Back(6)) - y := calcMemSize(stack.Back(3), stack.Back(4)) - - return math.BigMax(x, y) -} func memoryDelegateCall(stack *Stack) *big.Int { x := calcMemSize(stack.Back(4), stack.Back(5)) y := calcMemSize(stack.Back(2), stack.Back(3)) diff --git a/crypto/ecies/ecies.go b/crypto/ecies/ecies.go index 2a16f20a2e..5a8a4a01fc 100644 --- a/crypto/ecies/ecies.go +++ b/crypto/ecies/ecies.go @@ -158,7 +158,6 @@ func incCounter(ctr []byte) { } else if ctr[0]++; ctr[0] != 0 { return } - return } // NIST SP 800-56 Concatenation Key Derivation Function (see section 5.8.1). diff --git a/crypto/ecies/ecies_test.go b/crypto/ecies/ecies_test.go index 7c454aa730..4c68592038 100644 --- a/crypto/ecies/ecies_test.go +++ b/crypto/ecies/ecies_test.go @@ -71,19 +71,6 @@ func TestKDF(t *testing.T) { var ErrBadSharedKeys = fmt.Errorf("ecies: shared keys don't match") -// cmpParams compares a set of ECIES parameters. We assume, as per the -// docs, that AES is the only supported symmetric encryption algorithm. -func cmpParams(p1, p2 *ECIESParams) bool { - if p1.hashAlgo != p2.hashAlgo { - return false - } else if p1.KeyLen != p2.KeyLen { - return false - } else if p1.BlockSize != p2.BlockSize { - return false - } - return true -} - // cmpPublic returns true if the two public keys represent the same pojnt. func cmpPublic(pub1, pub2 PublicKey) bool { if pub1.X == nil || pub1.Y == nil { diff --git a/crypto/sha3/sha3.go b/crypto/sha3/sha3.go index c86167c0b4..b12a35c87f 100644 --- a/crypto/sha3/sha3.go +++ b/crypto/sha3/sha3.go @@ -42,9 +42,8 @@ type state struct { storage [maxRate]byte // Specific to SHA-3 and SHAKE. - fixedOutput bool // whether this is a fixed-output-length instance - outputLen int // the default output size in bytes - state spongeDirection // whether the sponge is absorbing or squeezing + outputLen int // the default output size in bytes + state spongeDirection // whether the sponge is absorbing or squeezing } // BlockSize returns the rate of sponge underlying this hash function. diff --git a/crypto/sha3/sha3_test.go b/crypto/sha3/sha3_test.go index c433761a8a..19722d6c02 100644 --- a/crypto/sha3/sha3_test.go +++ b/crypto/sha3/sha3_test.go @@ -53,15 +53,6 @@ var testShakes = map[string]func() ShakeHash{ "SHAKE256": NewShake256, } -// decodeHex converts a hex-encoded string into a raw byte string. -func decodeHex(s string) []byte { - b, err := hex.DecodeString(s) - if err != nil { - panic(err) - } - return b -} - // structs used to marshal JSON test-cases. type KeccakKats struct { Kats map[string][]struct { @@ -123,37 +114,6 @@ func TestKeccakKats(t *testing.T) { }) } -// TestUnalignedWrite tests that writing data in an arbitrary pattern with -// small input buffers. -func testUnalignedWrite(t *testing.T) { - testUnalignedAndGeneric(t, func(impl string) { - buf := sequentialBytes(0x10000) - for alg, df := range testDigests { - d := df() - d.Reset() - d.Write(buf) - want := d.Sum(nil) - d.Reset() - for i := 0; i < len(buf); { - // Cycle through offsets which make a 137 byte sequence. - // Because 137 is prime this sequence should exercise all corner cases. - offsets := [17]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1} - for _, j := range offsets { - if v := len(buf) - i; v < j { - j = v - } - d.Write(buf[i : i+j]) - i += j - } - } - got := d.Sum(nil) - if !bytes.Equal(got, want) { - t.Errorf("Unaligned writes, implementation=%s, alg=%s\ngot %q, want %q", impl, alg, got, want) - } - } - }) -} - // TestAppend checks that appending works when reallocation is necessary. func TestAppend(t *testing.T) { testUnalignedAndGeneric(t, func(impl string) { diff --git a/eth/config.go b/eth/config.go index 4109cff8b7..e5714341fe 100644 --- a/eth/config.go +++ b/eth/config.go @@ -24,7 +24,6 @@ import ( "runtime" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/eth/downloader" "github.com/ethereum/go-ethereum/eth/gasprice" @@ -115,7 +114,3 @@ type Config struct { PowTest bool `toml:"-"` PowShared bool `toml:"-"` } - -type configMarshaling struct { - ExtraData hexutil.Bytes -} diff --git a/eth/filters/api.go b/eth/filters/api.go index 61647a5d07..fff58a268e 100644 --- a/eth/filters/api.go +++ b/eth/filters/api.go @@ -54,7 +54,6 @@ type PublicFilterAPI struct { backend Backend useMipMap bool mux *event.TypeMux - quit chan struct{} chainDb ethdb.Database events *EventSystem filtersMu sync.Mutex diff --git a/eth/filters/filter.go b/eth/filters/filter.go index 0a0b81224e..f27b76929e 100644 --- a/eth/filters/filter.go +++ b/eth/filters/filter.go @@ -20,7 +20,6 @@ import ( "context" "math" "math/big" - "time" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core" @@ -42,8 +41,6 @@ type Filter struct { backend Backend useMipMap bool - created time.Time - db ethdb.Database begin, end int64 addresses []common.Address diff --git a/ethdb/database_test.go b/ethdb/database_test.go deleted file mode 100644 index 0e69a1218c..0000000000 --- a/ethdb/database_test.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2014 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package ethdb - -import ( - "os" - "path/filepath" - - "github.com/ethereum/go-ethereum/common" -) - -func newDb() *LDBDatabase { - file := filepath.Join("/", "tmp", "ldbtesttmpfile") - if common.FileExist(file) { - os.RemoveAll(file) - } - db, _ := NewLDBDatabase(file, 0, 0) - - return db -} diff --git a/ethstats/ethstats.go b/ethstats/ethstats.go index 333c975c9a..b75c5e6da4 100644 --- a/ethstats/ethstats.go +++ b/ethstats/ethstats.go @@ -39,7 +39,6 @@ import ( "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/les" "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/rpc" "golang.org/x/net/websocket" @@ -52,8 +51,6 @@ const historyUpdateRange = 50 // Service implements an Ethereum netstats reporting daemon that pushes local // chain statistics up to a monitoring server. type Service struct { - stack *node.Node // Temporary workaround, remove when API finalized - server *p2p.Server // Peer-to-peer server to retrieve networking infos eth *eth.Ethereum // Full Ethereum service if monitoring a full node les *les.LightEthereum // Light Ethereum service if monitoring a light node diff --git a/event/feed.go b/event/feed.go index b1b597f17b..db49e894a8 100644 --- a/event/feed.go +++ b/event/feed.go @@ -39,10 +39,9 @@ type Feed struct { sendCases caseList // the active set of select cases used by Send // The inbox holds newly subscribed channels until they are added to sendCases. - mu sync.Mutex - inbox caseList - etype reflect.Type - closed bool + mu sync.Mutex + inbox caseList + etype reflect.Type } // This is the index of the first actual subscription channel in sendCases. diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index da5dc5d583..0d2f2a3cdd 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -48,7 +48,6 @@ import ( const ( defaultGas = 90000 defaultGasPrice = 50 * params.Shannon - emptyHex = "0x" ) // PublicEthereumAPI provides an API to access Ethereum related information. @@ -634,10 +633,8 @@ func (s *PublicBlockChainAPI) doCall(ctx context.Context, args CallArgs, blockNr // Wait for the context to be done and cancel the evm. Even if the // EVM has finished, cancelling may be done (repeatedly) go func() { - select { - case <-ctx.Done(): - evm.Cancel() - } + <-ctx.Done() + evm.Cancel() }() // Setup the gas pool (also for unmetered requests) @@ -1393,7 +1390,7 @@ func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (strin if block == nil { return "", fmt.Errorf("block #%d not found", number) } - return fmt.Sprintf("%s", block), nil + return block.String(), nil } // SeedHash retrieves the seed hash of a block. diff --git a/internal/jsre/pretty.go b/internal/jsre/pretty.go index e096eec236..16fa91b67d 100644 --- a/internal/jsre/pretty.go +++ b/internal/jsre/pretty.go @@ -65,14 +65,6 @@ func prettyError(vm *otto.Otto, err error, w io.Writer) { fmt.Fprint(w, ErrorColor("%s", failure)) } -// jsErrorString adds a backtrace to errors generated by otto. -func jsErrorString(err error) string { - if ottoErr, ok := err.(*otto.Error); ok { - return ottoErr.String() - } - return err.Error() -} - func (re *JSRE) prettyPrintJS(call otto.FunctionCall) otto.Value { for _, v := range call.ArgumentList { prettyPrint(call.Otto, v, re.output) diff --git a/les/handler.go b/les/handler.go index 64023af0f5..581b62bcc6 100644 --- a/les/handler.go +++ b/les/handler.go @@ -69,8 +69,6 @@ func errResp(code errCode, format string, v ...interface{}) error { return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...)) } -type hashFetcherFn func(common.Hash) error - type BlockChain interface { HasHeader(hash common.Hash) bool GetHeader(hash common.Hash, number uint64) *types.Header @@ -117,10 +115,6 @@ type ProtocolManager struct { quitSync chan struct{} noMorePeers chan struct{} - syncMu sync.Mutex - syncing bool - syncDone chan struct{} - // wait group is used for graceful shutdowns during downloading // and processing wg sync.WaitGroup diff --git a/les/handler_test.go b/les/handler_test.go index 0b94d0d30b..616b9aaab8 100644 --- a/les/handler_test.go +++ b/les/handler_test.go @@ -26,8 +26,6 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth/downloader" "github.com/ethereum/go-ethereum/p2p" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie" ) func expectResponse(r p2p.MsgReader, msgcode, reqID, bv uint64, data interface{}) error { @@ -301,38 +299,3 @@ func testGetReceipt(t *testing.T, protocol int) { // Tests that trie merkle proofs can be retrieved func TestGetProofsLes1(t *testing.T) { testGetReceipt(t, 1) } - -func testGetProofs(t *testing.T, protocol int) { - // Assemble the test environment - pm, db, _ := newTestProtocolManagerMust(t, false, 4, testChainGen) - bc := pm.blockchain.(*core.BlockChain) - peer, _ := newTestPeer(t, "peer", protocol, pm, true) - defer peer.close() - - var proofreqs []ProofReq - var proofs [][]rlp.RawValue - - accounts := []common.Address{testBankAddress, acc1Addr, acc2Addr, {}} - for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ { - header := bc.GetHeaderByNumber(i) - root := header.Root - trie, _ := trie.New(root, db) - - for _, acc := range accounts { - req := ProofReq{ - BHash: header.Hash(), - Key: acc[:], - } - proofreqs = append(proofreqs, req) - - proof := trie.Prove(crypto.Keccak256(acc[:])) - proofs = append(proofs, proof) - } - } - // Send the proof request and verify the response - cost := peer.GetRequestCost(GetProofsMsg, len(proofreqs)) - sendRequest(peer.app, GetProofsMsg, 42, cost, proofreqs) - if err := expectResponse(peer.app, ProofsMsg, 42, testBufLimit, proofs); err != nil { - t.Errorf("proofs mismatch: %v", err) - } -} diff --git a/les/helper_test.go b/les/helper_test.go index 7e442c131b..64f996263c 100644 --- a/les/helper_test.go +++ b/les/helper_test.go @@ -20,7 +20,6 @@ package les import ( - "crypto/ecdsa" "crypto/rand" "math/big" "sync" @@ -221,14 +220,6 @@ func (p *testTxPool) GetTransactions() types.Transactions { return txs } -// newTestTransaction create a new dummy transaction. -func newTestTransaction(from *ecdsa.PrivateKey, nonce uint64, datasize int) *types.Transaction { - tx := types.NewTransaction(nonce, common.Address{}, big.NewInt(0), big.NewInt(100000), big.NewInt(0), make([]byte, datasize)) - tx, _ = types.SignTx(tx, types.HomesteadSigner{}, from) - - return tx -} - // testPeer is a simulated peer to allow testing direct network calls. type testPeer struct { net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging diff --git a/les/odr.go b/les/odr.go index 684f36c761..de9a2e92f7 100644 --- a/les/odr.go +++ b/les/odr.go @@ -43,13 +43,13 @@ type odrPeerSelector interface { type LesOdr struct { light.OdrBackend - db ethdb.Database - stop chan struct{} - removePeer peerDropFn - mlock, clock sync.Mutex - sentReqs map[uint64]*sentReq - serverPool odrPeerSelector - reqDist *requestDistributor + db ethdb.Database + stop chan struct{} + removePeer peerDropFn + mlock sync.Mutex + sentReqs map[uint64]*sentReq + serverPool odrPeerSelector + reqDist *requestDistributor } func NewLesOdr(db ethdb.Database) *LesOdr { diff --git a/les/odr_test.go b/les/odr_test.go index 532de4d80b..6c2dc0989a 100644 --- a/les/odr_test.go +++ b/les/odr_test.go @@ -158,7 +158,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, config *params.Chai func testOdr(t *testing.T, protocol int, expFail uint64, fn odrTestFn) { // Assemble the test environment - pm, db, odr := newTestProtocolManagerMust(t, false, 4, testChainGen) + pm, db, _ := newTestProtocolManagerMust(t, false, 4, testChainGen) lpm, ldb, odr := newTestProtocolManagerMust(t, true, 0, nil) _, err1, lpeer, err2 := newTestPeerPair("peer", protocol, pm, lpm) pool := &testServerPool{} diff --git a/les/peer.go b/les/peer.go index ab55bafe3e..97a29fe7cc 100644 --- a/les/peer.go +++ b/les/peer.go @@ -38,10 +38,7 @@ var ( errNotRegistered = errors.New("peer is not registered") ) -const ( - maxHeadInfoLen = 20 - maxResponseErrors = 50 // number of invalid responses tolerated (makes the protocol less brittle but still avoids spam) -) +const maxResponseErrors = 50 // number of invalid responses tolerated (makes the protocol less brittle but still avoids spam) type peer struct { *p2p.Peer diff --git a/les/protocol.go b/les/protocol.go index 46da2b8c8b..33d930ee0c 100644 --- a/les/protocol.go +++ b/les/protocol.go @@ -23,7 +23,6 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rlp" ) @@ -105,12 +104,6 @@ var errorToString = map[int]string{ ErrHandshakeMissingKey: "Key missing from handshake message", } -type chainManager interface { - GetBlockHashesFromHash(hash common.Hash, amount uint64) (hashes []common.Hash) - GetBlock(hash common.Hash) (block *types.Block) - Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) -} - // announceData is the network packet for the block announcements. type announceData struct { Hash common.Hash // Hash of one particular block being announced @@ -118,11 +111,6 @@ type announceData struct { Td *big.Int // Total difficulty of one particular block being announced ReorgDepth uint64 Update keyValueList - - haveHeaders uint64 // we have the headers of the remote peer's chain up to this number - headKnown bool - requested bool - next *announceData } type blockInfo struct { @@ -131,12 +119,6 @@ type blockInfo struct { Td *big.Int // Total difficulty of one particular block being announced } -// getBlockHashesData is the network packet for the hash based hash retrieval. -type getBlockHashesData struct { - Hash common.Hash - Amount uint64 -} - // getBlockHeadersData represents a block header query. type getBlockHeadersData struct { Origin hashOrNumber // Block from which to retrieve headers @@ -181,15 +163,6 @@ func (hn *hashOrNumber) DecodeRLP(s *rlp.Stream) error { return err } -// newBlockData is the network packet for the block propagation message. -type newBlockData struct { - Block *types.Block - TD *big.Int -} - -// blockBodiesData is the network packet for block content distribution. -type blockBodiesData []*types.Body - // CodeData is the network response packet for a node data retrieval. type CodeData []struct { Value []byte diff --git a/les/server.go b/les/server.go index 22fe59b7ac..4c0b067023 100644 --- a/les/server.go +++ b/les/server.go @@ -41,7 +41,6 @@ type LesServer struct { fcManager *flowcontrol.ClientManager // nil if our node is client only fcCostStats *requestCostStats defParams *flowcontrol.ServerParams - stopped bool } func NewLesServer(eth *eth.Ethereum, config *eth.Config) (*LesServer, error) { @@ -103,16 +102,6 @@ func (list RequestCostList) decode() requestCostTable { return table } -func (table requestCostTable) encode() RequestCostList { - list := make(RequestCostList, len(table)) - for idx, code := range reqList { - list[idx].MsgCode = code - list[idx].BaseCost = table[code].baseCost - list[idx].ReqCost = table[code].reqCost - } - return list -} - type linReg struct { sumX, sumY, sumXX, sumXY float64 cnt uint64 diff --git a/les/serverpool.go b/les/serverpool.go index 64fe991c63..0697267bb5 100644 --- a/les/serverpool.go +++ b/les/serverpool.go @@ -73,7 +73,6 @@ const ( // and a short term value which is adjusted exponentially with a factor of // pstatRecentAdjust with each dial/connection and also returned exponentially // to the average with the time constant pstatReturnToMeanTC - pstatRecentAdjust = 0.1 pstatReturnToMeanTC = time.Hour // node address selection weight is dropped by a factor of exp(-addrFailDropLn) after // each unsuccessful connection (restored after a successful one) @@ -83,9 +82,6 @@ const ( responseScoreTC = time.Millisecond * 100 delayScoreTC = time.Second * 5 timeoutPow = 10 - // peerSelectMinWeight is added to calculated weights at request peer selection - // to give poorly performing peers a little chance of coming back - peerSelectMinWeight = 0.005 // initStatsWeight is used to initialize previously unknown peers with good // statistics to give a chance to prove themselves initStatsWeight = 1 diff --git a/les/sync.go b/les/sync.go index c0e17f97d9..c3d37e2f3f 100644 --- a/les/sync.go +++ b/les/sync.go @@ -25,11 +25,6 @@ import ( "github.com/ethereum/go-ethereum/light" ) -const ( - //forceSyncCycle = 10 * time.Second // Time interval to force syncs, even if few peers are available - minDesiredPeerCount = 5 // Amount of peers desired to start syncing -) - // syncer is responsible for periodically synchronising with the network, both // downloading hashes and blocks as well as handling the announcement handler. func (pm *ProtocolManager) syncer() { diff --git a/light/lightchain.go b/light/lightchain.go index 5b7e570417..6029de29c5 100644 --- a/light/lightchain.go +++ b/light/lightchain.go @@ -52,7 +52,6 @@ type LightChain struct { mu sync.RWMutex chainmu sync.RWMutex - procmu sync.RWMutex bodyCache *lru.Cache // Cache for the most recent block bodies bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format diff --git a/light/lightchain_test.go b/light/lightchain_test.go index 21b6210462..f475bc1cf3 100644 --- a/light/lightchain_test.go +++ b/light/lightchain_test.go @@ -18,7 +18,6 @@ package light import ( "context" - "fmt" "math/big" "testing" @@ -117,13 +116,6 @@ func testFork(t *testing.T, LightChain *LightChain, i, n int, comparator func(td comparator(tdPre, tdPost) } -func printChain(bc *LightChain) { - for i := bc.CurrentHeader().Number.Uint64(); i > 0; i-- { - b := bc.GetHeaderByNumber(uint64(i)) - fmt.Printf("\t%x %v\n", b.Hash(), b.Difficulty) - } -} - // testHeaderChainImport tries to process a chain of header, writing them into // the database if successful. func testHeaderChainImport(chain []*types.Header, lightchain *LightChain) error { diff --git a/log/format.go b/log/format.go index 6c19c7a552..0b07abb2ac 100644 --- a/log/format.go +++ b/log/format.go @@ -330,7 +330,7 @@ func escapeString(s string) string { needsEscape = true } } - if needsEscape == false && needsQuotes == false { + if !needsEscape && !needsQuotes { return s } e := stringBufPool.Get().(*bytes.Buffer) diff --git a/miner/worker.go b/miner/worker.go index 8030153904..e39c2cce5c 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -39,10 +39,7 @@ import ( "gopkg.in/fatih/set.v0" ) -const ( - resultQueueSize = 10 - miningLogAtDepth = 5 -) +const resultQueueSize = 10 // Agent can register themself with the worker type Agent interface { @@ -109,8 +106,7 @@ type worker struct { uncleMu sync.Mutex possibleUncles map[common.Hash]*types.Block - txQueueMu sync.Mutex - txQueue map[common.Hash]*types.Transaction + txQueue map[common.Hash]*types.Transaction unconfirmed *unconfirmedBlocks // set of locally mined blocks pending canonicalness confirmations diff --git a/node/config.go b/node/config.go index 61e0008ef9..caa14ae081 100644 --- a/node/config.go +++ b/node/config.go @@ -40,7 +40,6 @@ var ( datadirDefaultKeyStore = "keystore" // Path within the datadir to the keystore datadirStaticNodes = "static-nodes.json" // Path within the datadir to the static node list datadirTrustedNodes = "trusted-nodes.json" // Path within the datadir to the trusted node list - datadirNodeDatabase = "nodes" // Path within the datadir to store the node infos ) // Config represents a small collection of configuration values to fine tune the diff --git a/node/utils_test.go b/node/utils_test.go index 7cdfc2b3aa..8eddce3ed7 100644 --- a/node/utils_test.go +++ b/node/utils_test.go @@ -41,12 +41,10 @@ func NewNoopService(*ServiceContext) (Service, error) { return new(NoopService), type NoopServiceA struct{ NoopService } type NoopServiceB struct{ NoopService } type NoopServiceC struct{ NoopService } -type NoopServiceD struct{ NoopService } func NewNoopServiceA(*ServiceContext) (Service, error) { return new(NoopServiceA), nil } func NewNoopServiceB(*ServiceContext) (Service, error) { return new(NoopServiceB), nil } func NewNoopServiceC(*ServiceContext) (Service, error) { return new(NoopServiceC), nil } -func NewNoopServiceD(*ServiceContext) (Service, error) { return new(NoopServiceD), nil } // InstrumentedService is an implementation of Service for which all interface // methods can be instrumented both return value as well as event hook wise. diff --git a/p2p/discover/udp.go b/p2p/discover/udp.go index f9eb99ee36..8efad9d93d 100644 --- a/p2p/discover/udp.go +++ b/p2p/discover/udp.go @@ -49,7 +49,6 @@ var ( // Timeouts const ( respTimeout = 500 * time.Millisecond - sendTimeout = 500 * time.Millisecond expiration = 20 * time.Second ntpFailureThreshold = 32 // Continuous timeouts after which to check NTP @@ -168,7 +167,6 @@ type udp struct { gotreply chan reply closing chan struct{} - nat nat.Interface *Table } diff --git a/p2p/discv5/net.go b/p2p/discv5/net.go index a39cfcc645..147436a4f2 100644 --- a/p2p/discv5/net.go +++ b/p2p/discv5/net.go @@ -37,7 +37,6 @@ import ( var ( errInvalidEvent = errors.New("invalid in current state") errNoQuery = errors.New("no pending query") - errWrongAddress = errors.New("unknown sender address") ) const ( @@ -86,14 +85,6 @@ type Network struct { nursery []*Node nodes map[NodeID]*Node // tracks active nodes with state != known timeoutTimers map[timeoutEvent]*time.Timer - - // Revalidation queues. - // Nodes put on these queues will be pinged eventually. - slowRevalidateQueue []*Node - fastRevalidateQueue []*Node - - // Buffers for state transition. - sendBuf []*ingressPacket } // transport is implemented by the UDP transport. @@ -113,10 +104,9 @@ type transport interface { } type findnodeQuery struct { - remote *Node - target common.Hash - reply chan<- []*Node - nresults int // counter for received nodes + remote *Node + target common.Hash + reply chan<- []*Node } type topicRegisterReq struct { @@ -658,11 +648,13 @@ loop: if net.conn != nil { net.conn.Close() } - if refreshDone != nil { - // TODO: wait for pending refresh. - //<-refreshResults - } + // TODO : issue # + //if refreshDone != nil { + // TODO: wait for pending refresh. + //<-refreshResults + //} // Cancel all pending timeouts. + for _, timer := range net.timeoutTimers { timer.Stop() } @@ -684,7 +676,7 @@ func (net *Network) refresh(done chan<- struct{}) { seeds = net.nursery } if len(seeds) == 0 { - log.Trace(fmt.Sprint("no seed nodes found")) + log.Trace("no seed nodes found") close(done) return } diff --git a/p2p/discv5/table.go b/p2p/discv5/table.go index 2cf05009cb..c8d234b936 100644 --- a/p2p/discv5/table.go +++ b/p2p/discv5/table.go @@ -38,7 +38,6 @@ const ( hashBits = len(common.Hash{}) * 8 nBuckets = hashBits + 1 // Number of buckets - maxBondingPingPongs = 16 maxFindnodeFailures = 5 ) diff --git a/p2p/discv5/table_test.go b/p2p/discv5/table_test.go index a29943dab9..a002ac2a5b 100644 --- a/p2p/discv5/table_test.go +++ b/p2p/discv5/table_test.go @@ -18,9 +18,9 @@ package discv5 import ( "crypto/ecdsa" + "errors" "fmt" "math/rand" - "net" "reflect" "testing" @@ -31,6 +31,8 @@ import ( "github.com/ethereum/go-ethereum/crypto" ) +var errTimeout = errors.New("RPC timeout") + type nullTransport struct{} func (nullTransport) sendPing(remote *Node, remoteAddr *net.UDPAddr) []byte { return []byte{1} } @@ -139,17 +141,6 @@ func TestBucket_bumpNoDuplicates(t *testing.T) { } } -// fillBucket inserts nodes into the given bucket until -// it is full. The node's IDs dont correspond to their -// hashes. -func fillBucket(tab *Table, ld int) (last *Node) { - b := tab.buckets[ld] - for len(b.entries) < bucketSize { - b.entries = append(b.entries, nodeAtDistance(tab.self.sha, ld)) - } - return b.entries[bucketSize-1] -} - // nodeAtDistance creates a node for which logdist(base, n.sha) == ld. // The node's ID does not correspond to n.sha. func nodeAtDistance(base common.Hash, ld int) (n *Node) { @@ -161,10 +152,6 @@ func nodeAtDistance(base common.Hash, ld int) (n *Node) { type pingRecorder struct{ responding, pinged map[NodeID]bool } -func newPingRecorder() *pingRecorder { - return &pingRecorder{make(map[NodeID]bool), make(map[NodeID]bool)} -} - func (t *pingRecorder) findnode(toid NodeID, toaddr *net.UDPAddr, target NodeID) ([]*Node, error) { panic("findnode called on pingRecorder") } diff --git a/p2p/discv5/udp.go b/p2p/discv5/udp.go index 26087cd8e5..b8d41fb947 100644 --- a/p2p/discv5/udp.go +++ b/p2p/discv5/udp.go @@ -36,25 +36,15 @@ const Version = 4 // Errors var ( - errPacketTooSmall = errors.New("too small") - errBadHash = errors.New("bad hash") - errExpired = errors.New("expired") - errUnsolicitedReply = errors.New("unsolicited reply") - errUnknownNode = errors.New("unknown node") - errTimeout = errors.New("RPC timeout") - errClockWarp = errors.New("reply deadline too far in the future") - errClosed = errors.New("socket closed") + errPacketTooSmall = errors.New("too small") + errBadHash = errors.New("bad hash") ) // Timeouts const ( - respTimeout = 500 * time.Millisecond - sendTimeout = 500 * time.Millisecond - expiration = 20 * time.Second - - ntpFailureThreshold = 32 // Continuous timeouts after which to check NTP - ntpWarningCooldown = 10 * time.Minute // Minimum amount of time to pass before repeating NTP warning - driftThreshold = 10 * time.Second // Allowed clock drift before warning user + respTimeout = 500 * time.Millisecond + expiration = 20 * time.Second + driftThreshold = 10 * time.Second // Allowed clock drift before warning user ) // RPC request structures @@ -194,10 +184,6 @@ func makeEndpoint(addr *net.UDPAddr, tcpPort uint16) rpcEndpoint { return rpcEndpoint{IP: ip, UDP: uint16(addr.Port), TCP: tcpPort} } -func (e1 rpcEndpoint) equal(e2 rpcEndpoint) bool { - return e1.UDP == e2.UDP && e1.TCP == e2.TCP && e1.IP.Equal(e2.IP) -} - func nodeFromRPC(sender *net.UDPAddr, rn rpcNode) (*Node, error) { if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil { return nil, err @@ -232,7 +218,6 @@ type udp struct { conn conn priv *ecdsa.PrivateKey ourEndpoint rpcEndpoint - nat nat.Interface net *Network } diff --git a/p2p/discv5/udp_test.go b/p2p/discv5/udp_test.go index 7d31815947..c5b6077b63 100644 --- a/p2p/discv5/udp_test.go +++ b/p2p/discv5/udp_test.go @@ -390,6 +390,20 @@ func TestForwardCompatibility(t *testing.T) { } } +// WriteToUDP queues a datagram. +func (c *dgramPipe) WriteToUDP(b []byte, to *net.UDPAddr) (n int, err error) { + msg := make([]byte, len(b)) + copy(msg, b) + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return 0, errors.New("closed") + } + c.queue = append(c.queue, msg) + c.cond.Signal() + return len(b), nil +} + // dgramPipe is a fake UDP socket. It queues all sent datagrams. type dgramPipe struct { mu *sync.Mutex @@ -408,20 +422,6 @@ func newpipe() *dgramPipe { } } -// WriteToUDP queues a datagram. -func (c *dgramPipe) WriteToUDP(b []byte, to *net.UDPAddr) (n int, err error) { - msg := make([]byte, len(b)) - copy(msg, b) - c.mu.Lock() - defer c.mu.Unlock() - if c.closed { - return 0, errors.New("closed") - } - c.queue = append(c.queue, msg) - c.cond.Signal() - return len(b), nil -} - // ReadFromUDP just hangs until the pipe is closed. func (c *dgramPipe) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) { <-c.closing diff --git a/p2p/peer.go b/p2p/peer.go index a9c20189a4..a9ef65c8ec 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -44,8 +44,6 @@ const ( discMsg = 0x01 pingMsg = 0x02 pongMsg = 0x03 - getPeersMsg = 0x04 - peersMsg = 0x05 ) // protoHandshake is the RLP structure of the protocol handshake. diff --git a/p2p/server.go b/p2p/server.go index d7909d53a9..6d64658fc5 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -35,9 +35,7 @@ import ( ) const ( - defaultDialTimeout = 15 * time.Second - refreshPeersInterval = 30 * time.Second - staticPeerCheckInterval = 15 * time.Second + defaultDialTimeout = 15 * time.Second // Maximum number of concurrently handshaking inbound connections. maxAcceptConns = 50 diff --git a/rpc/server.go b/rpc/server.go index 62b84af34e..dbbc85cb51 100644 --- a/rpc/server.go +++ b/rpc/server.go @@ -29,11 +29,7 @@ import ( "gopkg.in/fatih/set.v0" ) -const ( - notificationBufferSize = 10000 // max buffered notifications before codec is closed - - MetadataApi = "rpc" -) +const MetadataApi = "rpc" // CodecOption specifies which type of messages this codec supports type CodecOption int @@ -124,16 +120,6 @@ func (s *Server) RegisterName(name string, rcvr interface{}) error { return nil } -// hasOption returns true if option is included in options, otherwise false -func hasOption(option CodecOption, options []CodecOption) bool { - for _, o := range options { - if option == o { - return true - } - } - return false -} - // serveRequest will reads requests from the codec, calls the RPC callback and // writes the response to the given codec. // @@ -148,13 +134,11 @@ func (s *Server) serveRequest(codec ServerCodec, singleShot bool, options CodecO const size = 64 << 10 buf := make([]byte, size) buf = buf[:runtime.Stack(buf, false)] - log.Error(fmt.Sprint(string(buf))) + log.Error(string(buf)) } s.codecsMu.Lock() s.codecs.Remove(codec) s.codecsMu.Unlock() - - return }() ctx, cancel := context.WithCancel(context.Background()) @@ -246,7 +230,7 @@ func (s *Server) ServeSingleRequest(codec ServerCodec, options CodecOption) { // close all codecs which will cancel pending requests/subscriptions. func (s *Server) Stop() { if atomic.CompareAndSwapInt32(&s.run, 1, 0) { - log.Debug(fmt.Sprint("RPC Server shutdown initiatied")) + log.Debug("RPC Server shutdown initiatied") s.codecsMu.Lock() defer s.codecsMu.Unlock() s.codecs.Each(func(c interface{}) bool { diff --git a/rpc/subscription.go b/rpc/subscription.go index 720e4dd06b..6ce7befa1d 100644 --- a/rpc/subscription.go +++ b/rpc/subscription.go @@ -53,7 +53,6 @@ type notifierKey struct{} type Notifier struct { codec ServerCodec subMu sync.RWMutex // guards active and inactive maps - stopped bool active map[ID]*Subscription inactive map[ID]*Subscription } diff --git a/rpc/types.go b/rpc/types.go index a7b8c9788c..6d5912a30d 100644 --- a/rpc/types.go +++ b/rpc/types.go @@ -48,7 +48,6 @@ type callback struct { // service represents a registered object type service struct { name string // name for service - rcvr reflect.Value // receiver of methods for the service typ reflect.Type // receiver type callbacks callbacks // registered handlers subscriptions subscriptions // available subscriptions/notifications @@ -58,7 +57,6 @@ type service struct { type serverRequest struct { id interface{} svcname string - rcvr reflect.Value callb *callback args []reflect.Value isUnsubscribe bool @@ -72,9 +70,8 @@ type subscriptionRegistry map[string]*callback // collection of subscription cal // Server represents a RPC server type Server struct { - services serviceRegistry - muSubcriptions sync.Mutex // protects subscriptions - subscriptions subscriptionRegistry + services serviceRegistry + subscriptions subscriptionRegistry run int32 codecsMu sync.Mutex diff --git a/rpc/utils.go b/rpc/utils.go index 2506c48331..74c0a11a4e 100644 --- a/rpc/utils.go +++ b/rpc/utils.go @@ -119,21 +119,6 @@ func isHexNum(t reflect.Type) bool { return t == bigIntType } -var blockNumberType = reflect.TypeOf((*BlockNumber)(nil)).Elem() - -// Indication if the given block is a BlockNumber -func isBlockNumber(t reflect.Type) bool { - if t == nil { - return false - } - - for t.Kind() == reflect.Ptr { - t = t.Elem() - } - - return t == blockNumberType -} - // suitableCallbacks iterates over the methods of the given type. It will determine if a method satisfies the criteria // for a RPC callback or a subscription callback and adds it to the collection of callbacks or subscriptions. See server // documentation for a summary of these criteria. diff --git a/swarm/api/api.go b/swarm/api/api.go index 803265a3e7..be2363e258 100644 --- a/swarm/api/api.go +++ b/swarm/api/api.go @@ -34,11 +34,7 @@ import ( "github.com/ethereum/go-ethereum/swarm/storage" ) -var ( - hashMatcher = regexp.MustCompile("^[0-9A-Fa-f]{64}") - slashes = regexp.MustCompile("/+") - domainAndVersion = regexp.MustCompile("[@:;,]+") -) +var hashMatcher = regexp.MustCompile("^[0-9A-Fa-f]{64}") type Resolver interface { Resolve(string) (common.Hash, error) @@ -356,5 +352,5 @@ func (self *Api) BuildDirectoryTree(mhash string, nameresolver bool) (key storag manifestEntryMap[suffix] = entry }) - return key, manifestEntryMap, nil + return key, manifestEntryMap, err } diff --git a/swarm/api/client/client_test.go b/swarm/api/client/client_test.go index 03d25049d4..44468dd69b 100644 --- a/swarm/api/client/client_test.go +++ b/swarm/api/client/client_test.go @@ -89,9 +89,6 @@ func TestClientUploadDownloadFiles(t *testing.T) { if file.Size != int64(len(expected)) { t.Fatalf("expected downloaded file to be %d bytes, got %d", len(expected), file.Size) } - if file.ContentType != file.ContentType { - t.Fatalf("expected downloaded file to have type %q, got %q", file.ContentType, file.ContentType) - } data, err := ioutil.ReadAll(file) if err != nil { t.Fatal(err) @@ -235,9 +232,7 @@ func TestClientFileList(t *testing.T) { t.Fatal(err) } paths := make([]string, 0, len(list.CommonPrefixes)+len(list.Entries)) - for _, prefix := range list.CommonPrefixes { - paths = append(paths, prefix) - } + paths = append(paths, list.CommonPrefixes...) for _, entry := range list.Entries { paths = append(paths, entry.Path) } diff --git a/swarm/api/http/server.go b/swarm/api/http/server.go index 5f64f971bb..e49844e192 100644 --- a/swarm/api/http/server.go +++ b/swarm/api/http/server.go @@ -224,7 +224,7 @@ func (s *Server) handleMultipartUpload(req *Request, boundary string, mw *api.Ma if err != nil { return fmt.Errorf("error copying multipart content: %s", err) } - if _, err := tmp.Seek(0, os.SEEK_SET); err != nil { + if _, err := tmp.Seek(0, io.SeekStart); err != nil { return fmt.Errorf("error copying multipart content: %s", err) } reader = tmp diff --git a/swarm/api/http/server_test.go b/swarm/api/http/server_test.go index 0b124a19a9..b0c3350ac2 100644 --- a/swarm/api/http/server_test.go +++ b/swarm/api/http/server_test.go @@ -93,7 +93,7 @@ func TestBzzrGetPath(t *testing.T) { isexpectedfailrequest = true } } - if isexpectedfailrequest == false { + if !isexpectedfailrequest { t.Fatalf("Response body does not match, expected: %v, got %v", testmanifest[v], string(respbody)) } } @@ -116,12 +116,16 @@ func TestBzzrGetPath(t *testing.T) { var respbody []byte resp, err = http.Get(url) - if err != nil { t.Fatalf("Request failed: %v", err) } defer resp.Body.Close() + respbody, err = ioutil.ReadAll(resp.Body) + if err != nil { + t.Fatalf("Reading body failed: %v", err) + } + if string(respbody) != nonhashresponses[i] { t.Fatalf("Non-Hash response body does not match, expected: %v, got: %v", nonhashresponses[i], string(respbody)) } diff --git a/swarm/fuse/swarmfs_test.go b/swarm/fuse/swarmfs_test.go index f307b38ead..71727c6a11 100644 --- a/swarm/fuse/swarmfs_test.go +++ b/swarm/fuse/swarmfs_test.go @@ -115,7 +115,7 @@ func mountDir(t *testing.T, api *api.Api, files map[string]fileInfo, bzzHash str } // Test listMounts - if found == false { + if !found { t.Fatalf("Error getting mounts information for %v: %v", mountDir, err) } @@ -164,7 +164,7 @@ func compareGeneratedFileWithFileInMount(t *testing.T, files map[string]fileInfo t.Fatalf("Could not readfile %v : %v", fname, err) } - if bytes.Compare(fileContents, finfo.contents) != 0 { + if !bytes.Equal(fileContents, finfo.contents) { t.Fatalf("File %v contents mismatch: %v , %v", fname, fileContents, finfo.contents) } @@ -212,10 +212,7 @@ func IsDirEmpty(name string) bool { defer f.Close() _, err = f.Readdirnames(1) - if err == io.EOF { - return true - } - return false + return err == io.EOF } func testMountListAndUnmount(api *api.Api, t *testing.T) { @@ -381,11 +378,15 @@ func testUnmountWhenResourceBusy(api *api.Api, t *testing.T) { actualPath := filepath.Join(testMountDir, "2.txt") d, err := os.OpenFile(actualPath, os.O_RDWR, os.FileMode(0700)) + // catching this error fails the test + //if err != nil { + // t.Fatalf("could not open file %v", bzzHash) + //} d.Write(getRandomBtes(10)) _, err = swarmfs.Unmount(testMountDir) if err != nil { - t.Fatalf("could not unmount %v", bzzHash) + t.Fatalf("could not unmount %v", bzzHash) } d.Close() @@ -419,7 +420,7 @@ func testSeekInMultiChunkFile(api *api.Api, t *testing.T) { d.Read(contents) finfo := files["1.txt"] - if bytes.Compare(finfo.contents[:6024][5000:], contents) != 0 { + if !bytes.Equal(finfo.contents[:6024][5000:], contents) { t.Fatalf("File seek contents mismatch") } d.Close() diff --git a/swarm/fuse/swarmfs_unix.go b/swarm/fuse/swarmfs_unix.go index f4eecef245..c7d9f41cfe 100644 --- a/swarm/fuse/swarmfs_unix.go +++ b/swarm/fuse/swarmfs_unix.go @@ -58,14 +58,6 @@ type MountInfo struct { lock *sync.RWMutex } -// Inode numbers need to be unique, they are used for caching inside fuse -func newInode() uint64 { - inodeLock.Lock() - defer inodeLock.Unlock() - inode += 1 - return inode -} - func NewMountInfo(mhash, mpoint string, sapi *api.Api) *MountInfo { newMountInfo := &MountInfo{ MountPoint: mpoint, @@ -102,7 +94,7 @@ func (self *SwarmFS) Mount(mhash, mountpoint string) (*MountInfo, error) { } log.Info(fmt.Sprintf("Attempting to mount %s ", cleanedMountPoint)) - key, manifestEntryMap, err := self.swarmApi.BuildDirectoryTree(mhash, true) + _, manifestEntryMap, err := self.swarmApi.BuildDirectoryTree(mhash, true) if err != nil { return nil, err } @@ -116,7 +108,7 @@ func (self *SwarmFS) Mount(mhash, mountpoint string) (*MountInfo, error) { for suffix, entry := range manifestEntryMap { - key = common.Hex2Bytes(entry.Hash) + key := common.Hex2Bytes(entry.Hash) fullpath := "/" + suffix basepath := filepath.Dir(fullpath) diff --git a/swarm/network/kademlia/kademlia.go b/swarm/network/kademlia/kademlia.go index bf976a3e1d..b97accc1bb 100644 --- a/swarm/network/kademlia/kademlia.go +++ b/swarm/network/kademlia/kademlia.go @@ -420,8 +420,8 @@ func (self *Kademlia) String() string { } } rows = append(rows, strings.Join(row, " ")) - if i == self.MaxProx { - } + //if i == self.MaxProx { + //} } rows = append(rows, "=========================================================================") return strings.Join(rows, "\n") diff --git a/swarm/storage/chunker.go b/swarm/storage/chunker.go index d55875369d..f39c91fe70 100644 --- a/swarm/storage/chunker.go +++ b/swarm/storage/chunker.go @@ -156,14 +156,13 @@ func (self *TreeChunker) Split(data io.Reader, size int64, chunkC chan *Chunk, s close(errC) }() - select { - case err := <-errC: - if err != nil { - close(quitC) - return nil, err - } - //TODO: add a timeout + err := <-errC + if err != nil { + close(quitC) + return nil, err } + //TODO: add a timeout + return key, nil } diff --git a/swarm/storage/chunker_test.go b/swarm/storage/chunker_test.go index 40f870246f..412b850fca 100644 --- a/swarm/storage/chunker_test.go +++ b/swarm/storage/chunker_test.go @@ -209,20 +209,6 @@ func TestRandomBrokenData(t *testing.T) { } } -func readAll(reader LazySectionReader, result []byte) { - size := int64(len(result)) - - var end int64 - for pos := int64(0); pos < size; pos += 1000 { - if pos+1000 > size { - end = size - } else { - end = pos + 1000 - } - reader.ReadAt(result[pos:end], pos) - } -} - func benchReadAll(reader LazySectionReader) { size, _ := reader.Size(nil) output := make([]byte, 1000) diff --git a/swarm/storage/dbstore.go b/swarm/storage/dbstore.go index 30925a919f..e17ddf35a7 100644 --- a/swarm/storage/dbstore.go +++ b/swarm/storage/dbstore.go @@ -43,7 +43,6 @@ const ( // key prefixes for leveldb storage kpIndex = 0 - kpData = 1 ) var ( @@ -432,8 +431,7 @@ func (s *DbStore) setCapacity(c uint64) { s.capacity = c if s.entryCnt > c { - var ratio float32 - ratio = float32(1.01) - float32(c)/float32(s.entryCnt) + ratio := float32(1.01) - float32(c)/float32(s.entryCnt) if ratio < gcArrayFreeRatio { ratio = gcArrayFreeRatio } diff --git a/swarm/storage/dpa.go b/swarm/storage/dpa.go index e16e4aacb4..647f8998ba 100644 --- a/swarm/storage/dpa.go +++ b/swarm/storage/dpa.go @@ -59,7 +59,6 @@ type DPA struct { lock sync.Mutex running bool - wg *sync.WaitGroup quitC chan bool } @@ -240,5 +239,4 @@ func (self *dpaChunkStore) Put(entry *Chunk) { // Close chunk store func (self *dpaChunkStore) Close() { - return } diff --git a/swarm/storage/localstore.go b/swarm/storage/localstore.go index 14827e3618..5929dc36cb 100644 --- a/swarm/storage/localstore.go +++ b/swarm/storage/localstore.go @@ -75,5 +75,4 @@ func (self *LocalStore) Get(key Key) (chunk *Chunk, err error) { // Close local store func (self *LocalStore) Close() { - return } diff --git a/swarm/storage/memstore.go b/swarm/storage/memstore.go index f96792c6ea..5a072f3cbd 100644 --- a/swarm/storage/memstore.go +++ b/swarm/storage/memstore.go @@ -206,8 +206,6 @@ func (s *MemStore) Put(entry *Chunk) { node.lastDBaccess = s.dbAccessCnt node.updateAccess(s.accessCnt) s.entryCnt++ - - return } func (s *MemStore) Get(hash Key) (chunk *Chunk, err error) { @@ -324,5 +322,4 @@ func (s *MemStore) removeOldest() { // Close memstore func (s *MemStore) Close() { - return } diff --git a/swarm/storage/netstore.go b/swarm/storage/netstore.go index 7c0436c3fd..cf77c2447a 100644 --- a/swarm/storage/netstore.go +++ b/swarm/storage/netstore.go @@ -19,7 +19,6 @@ package storage import ( "fmt" "path/filepath" - "sync" "time" "github.com/ethereum/go-ethereum/log" @@ -40,7 +39,6 @@ type NetStore struct { hashfunc Hasher localStore *LocalStore cloud CloudStore - lock sync.Mutex } // backend engine for cloud store @@ -79,11 +77,6 @@ func NewNetStore(hash Hasher, lstore *LocalStore, cloud CloudStore, params *Stor } } -const ( - // maximum number of peers that a retrieved message is delivered to - requesterCount = 3 -) - var ( // timeout interval before retrieval is timed out searchTimeout = 3 * time.Second @@ -135,5 +128,4 @@ func (self *NetStore) Get(key Key) (*Chunk, error) { // Close netstore func (self *NetStore) Close() { - return } diff --git a/swarm/swarm.go b/swarm/swarm.go index 4f93a30b79..81c9260374 100644 --- a/swarm/swarm.go +++ b/swarm/swarm.go @@ -50,7 +50,6 @@ type Swarm struct { storage storage.ChunkStore // internal access to storage, common interface to cloud storage backends dpa *storage.DPA // distributed preimage archive, the local API to the storage with document level storage/retrieval support depo network.StorageHandler // remote request handler, interface between bzz protocol and the storage - cloud storage.CloudStore // procurement, cloud storage backend (can multi-cloud) hive *network.Hive // the logistic manager backend chequebook.Backend // simple blockchain Backend privateKey *ecdsa.PrivateKey diff --git a/tests/init.go b/tests/init.go index 7b0924bc38..15f53bab7b 100644 --- a/tests/init.go +++ b/tests/init.go @@ -22,7 +22,6 @@ import ( "fmt" "io" "io/ioutil" - "net/http" "os" "path/filepath" ) @@ -80,16 +79,6 @@ func readJson(reader io.Reader, value interface{}) error { return nil } -func readJsonHttp(uri string, value interface{}) error { - resp, err := http.Get(uri) - if err != nil { - return err - } - defer resp.Body.Close() - - return readJson(resp.Body, value) -} - func readJsonFile(fn string, value interface{}) error { file, err := os.Open(fn) if err != nil { diff --git a/whisper/mailserver/mailserver.go b/whisper/mailserver/mailserver.go index 42a0671a37..0ec6ec570c 100644 --- a/whisper/mailserver/mailserver.go +++ b/whisper/mailserver/mailserver.go @@ -104,7 +104,7 @@ func (s *WMailServer) Archive(env *whisper.Envelope) { func (s *WMailServer) DeliverMail(peer *whisper.Peer, request *whisper.Envelope) { if peer == nil { - log.Error(fmt.Sprint("Whisper peer is nil")) + log.Error("Whisper peer is nil") return } diff --git a/whisper/mailserver/server_test.go b/whisper/mailserver/server_test.go index 64dbcd7838..373d91cc4d 100644 --- a/whisper/mailserver/server_test.go +++ b/whisper/mailserver/server_test.go @@ -166,7 +166,7 @@ func singleRequest(t *testing.T, server *WMailServer, env *whisper.Envelope, p * } src[0]++ - ok, lower, upper, topic = server.validateRequest(src, request) + ok, _, _, topic = server.validateRequest(src, request) if ok { t.Fatalf("request validation false positive, seed: %d.", seed) } diff --git a/whisper/whisperv2/whisper.go b/whisper/whisperv2/whisper.go index 1d7c21bd12..61c36918d4 100644 --- a/whisper/whisperv2/whisper.go +++ b/whisper/whisperv2/whisper.go @@ -173,7 +173,7 @@ func (self *Whisper) Send(envelope *Envelope) error { // Start implements node.Service, starting the background data propagation thread // of the Whisper protocol. func (self *Whisper) Start(*p2p.Server) error { - log.Info(fmt.Sprint("Whisper started")) + log.Info("Whisper started") go self.update() return nil } @@ -182,7 +182,7 @@ func (self *Whisper) Start(*p2p.Server) error { // of the Whisper protocol. func (self *Whisper) Stop() error { close(self.quit) - log.Info(fmt.Sprint("Whisper stopped")) + log.Info("Whisper stopped") return nil } diff --git a/whisper/whisperv5/api.go b/whisper/whisperv5/api.go index 1a4e4d8799..8978825a0f 100644 --- a/whisper/whisperv5/api.go +++ b/whisper/whisperv5/api.go @@ -222,7 +222,7 @@ func (api *PublicWhisperAPI) Subscribe(args WhisperFilterArgs) (string, error) { var err error for i, bt := range args.Topics { if len(bt) == 0 || len(bt) > 4 { - return "", errors.New(fmt.Sprintf("subscribe: topic %d has wrong size: %d", i, len(bt))) + return "", fmt.Errorf("subscribe: topic %d has wrong size: %d", i, len(bt)) } filter.Topics = append(filter.Topics, bt) } @@ -332,7 +332,7 @@ func (api *PublicWhisperAPI) Post(args PostArgs) error { if len(args.Topic) == TopicLength { params.Topic = BytesToTopic(args.Topic) } else if len(args.Topic) != 0 { - return errors.New(fmt.Sprintf("post: wrong topic size %d", len(args.Topic))) + return fmt.Errorf("post: wrong topic size %d", len(args.Topic)) } if args.Type == "sym" { diff --git a/whisper/whisperv5/api_test.go b/whisper/whisperv5/api_test.go index a6d82d8505..b2f96cbb2c 100644 --- a/whisper/whisperv5/api_test.go +++ b/whisper/whisperv5/api_test.go @@ -284,9 +284,8 @@ func waitForMessages(api *PublicWhisperAPI, id string, target int) []*WhisperMes for i := 0; i < 100; i++ { mail := api.GetNewSubscriptionMessages(id) if len(mail) > 0 { - for _, m := range mail { - result = append(result, m) - } + result = append(result, mail...) + if len(result) >= target { break } diff --git a/whisper/whisperv5/message_test.go b/whisper/whisperv5/message_test.go index aa82a02f36..2edf945df0 100644 --- a/whisper/whisperv5/message_test.go +++ b/whisper/whisperv5/message_test.go @@ -25,11 +25,6 @@ import ( "github.com/ethereum/go-ethereum/rlp" ) -func copyFromBuf(dst []byte, src []byte, beg int) int { - copy(dst, src[beg:]) - return beg + len(dst) -} - func generateMessageParams() (*MessageParams, error) { // set all the parameters except p.Dst and p.Padding @@ -158,7 +153,7 @@ func TestMessageWrap(t *testing.T) { params.TTL = 1000000 params.WorkTime = 1 params.PoW = 10000000.0 - env, err = msg2.Wrap(params) + _, err = msg2.Wrap(params) if err == nil { t.Fatalf("unexpectedly reached the PoW target with seed %d.", seed) }