diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 6c1cb9f9ad..7d80659b0d 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,3 +1,9 @@ +Hi there, + +please note that this is an issue tracker reserved for bug reports and feature requests. + +For general questions please use the gitter channel or the Ethereum stack exchange at https://ethereum.stackexchange.com. + #### System information Geth version: `geth version` diff --git a/.travis.yml b/.travis.yml index 8a7f65e3d6..1bd69da347 100644 --- a/.travis.yml +++ b/.travis.yml @@ -38,7 +38,7 @@ matrix: - sudo chmod 666 /dev/fuse - sudo chown root:$USER /etc/fuse.conf - go run build/ci.go install - - go run build/ci.go test -coverage -misspell + - go run build/ci.go test -coverage - os: osx go: 1.9.x @@ -48,7 +48,21 @@ matrix: - brew install caskroom/cask/brew-cask - brew cask install osxfuse - go run build/ci.go install - - go run build/ci.go test -coverage -misspell + - go run build/ci.go test -coverage + + # This builder only tests code linters on latest version of Go + - os: linux + dist: trusty + sudo: required + go: 1.9.x + env: + - lint + script: + - sudo -E apt-get -yq --no-install-suggests --no-install-recommends --force-yes install fuse + - sudo modprobe fuse + - sudo chmod 666 /dev/fuse + - sudo chown root:$USER /etc/fuse.conf + - go run build/ci.go lint # This builder does the Ubuntu PPA and Linux Azure uploads - os: linux @@ -133,16 +147,16 @@ matrix: - azure-android - maven-android before_install: - - curl https://storage.googleapis.com/golang/go1.9.linux-amd64.tar.gz | tar -xz + - curl https://storage.googleapis.com/golang/go1.9.2.linux-amd64.tar.gz | tar -xz - export PATH=`pwd`/go/bin:$PATH - export GOROOT=`pwd`/go - export GOPATH=$HOME/go script: # Build the Android archive and upload it to Maven Central and Azure - - curl https://dl.google.com/android/repository/android-ndk-r14b-linux-x86_64.zip -o android-ndk-r14b.zip - - unzip -q android-ndk-r14b.zip && rm android-ndk-r14b.zip - - mv android-ndk-r14b $HOME - - export ANDROID_NDK=$HOME/android-ndk-r14b + - curl https://dl.google.com/android/repository/android-ndk-r15c-linux-x86_64.zip -o android-ndk-r15c.zip + - unzip -q android-ndk-r15c.zip && rm android-ndk-r15c.zip + - mv android-ndk-r15c $HOME + - export ANDROID_NDK=$HOME/android-ndk-r15c - mkdir -p $GOPATH/src/github.com/ethereum - ln -s `pwd` $GOPATH/src/github.com/ethereum diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go index 17b2216426..43ed53b922 100644 --- a/accounts/abi/bind/bind_test.go +++ b/accounts/abi/bind/bind_test.go @@ -472,7 +472,7 @@ func TestBindings(t *testing.T) { t.Fatalf("failed to create temporary workspace: %v", err) } defer os.RemoveAll(ws) - + pkg := filepath.Join(ws, "bindtest") if err = os.MkdirAll(pkg, 0700); err != nil { t.Fatalf("failed to create package: %v", err) diff --git a/accounts/abi/unpack.go b/accounts/abi/unpack.go index ffa14ccd3b..57732797b6 100644 --- a/accounts/abi/unpack.go +++ b/accounts/abi/unpack.go @@ -38,7 +38,7 @@ type unpacker interface { func readInteger(kind reflect.Kind, b []byte) interface{} { switch kind { case reflect.Uint8: - return uint8(b[len(b)-1]) + return b[len(b)-1] case reflect.Uint16: return binary.BigEndian.Uint16(b[len(b)-2:]) case reflect.Uint32: diff --git a/accounts/abi/unpack_test.go b/accounts/abi/unpack_test.go index 9c7c339f3f..2949083788 100644 --- a/accounts/abi/unpack_test.go +++ b/accounts/abi/unpack_test.go @@ -365,7 +365,7 @@ func TestUnmarshal(t *testing.T) { buff.Write(common.Hex2Bytes("0102000000000000000000000000000000000000000000000000000000000000")) err = abi.Unpack(&mixedBytes, "mixedBytes", buff.Bytes()) - if err !=nil { + if err != nil { t.Error(err) } else { if bytes.Compare(p0, p0Exp) != 0 { diff --git a/build/ci.go b/build/ci.go index a4f5616bc7..0c825ef31e 100644 --- a/build/ci.go +++ b/build/ci.go @@ -24,7 +24,8 @@ Usage: go run ci.go Available commands are: install [ -arch architecture ] [ packages... ] -- builds packages and executables - test [ -coverage ] [ -misspell ] [ packages... ] -- runs the tests + test [ -coverage ] [ packages... ] -- runs the tests + lint -- runs certain pre-selected linters archive [ -arch architecture ] [ -type zip|tar ] [ -signer key-envvar ] [ -upload dest ] -- archives build artefacts importkeys -- imports signing keys from env debsrc [ -signer key-id ] [ -upload dest ] -- creates a debian source package @@ -146,6 +147,8 @@ func main() { doInstall(os.Args[2:]) case "test": doTest(os.Args[2:]) + case "lint": + doLint(os.Args[2:]) case "archive": doArchive(os.Args[2:]) case "debsrc": @@ -280,7 +283,6 @@ func goToolArch(arch string, subcmd string, args ...string) *exec.Cmd { func doTest(cmdline []string) { var ( - misspell = flag.Bool("misspell", false, "Whether to run the spell checker") coverage = flag.Bool("coverage", false, "Whether to record code coverage") ) flag.CommandLine.Parse(cmdline) @@ -294,10 +296,7 @@ func doTest(cmdline []string) { // Run analysis tools before the tests. build.MustRun(goTool("vet", packages...)) - if *misspell { - // TODO(karalabe): Reenable after false detection is fixed: https://github.com/client9/misspell/issues/105 - // spellcheck(packages) - } + // Run the actual tests. gotest := goTool("test", buildFlags(env)...) // Test a single package at a time. CI builders are slow @@ -306,35 +305,31 @@ func doTest(cmdline []string) { if *coverage { gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover") } + gotest.Args = append(gotest.Args, packages...) build.MustRun(gotest) } -// spellcheck runs the client9/misspell spellchecker package on all Go, Cgo and -// test files in the requested packages. -func spellcheck(packages []string) { - // Ensure the spellchecker is available - build.MustRun(goTool("get", "github.com/client9/misspell/cmd/misspell")) +// runs gometalinter on requested packages +func doLint(cmdline []string) { + flag.CommandLine.Parse(cmdline) - // Windows chokes on long argument lists, check packages individually - for _, pkg := range packages { - // The spell checker doesn't work on packages, gather all .go files for it - out, err := goTool("list", "-f", "{{.Dir}}{{range .GoFiles}}\n{{.}}{{end}}{{range .CgoFiles}}\n{{.}}{{end}}{{range .TestGoFiles}}\n{{.}}{{end}}", pkg).CombinedOutput() - if err != nil { - log.Fatalf("source file listing failed: %v\n%s", err, string(out)) - } - // Retrieve the folder and assemble the source list - lines := strings.Split(string(out), "\n") - root := lines[0] + packages := []string{"./..."} + if len(flag.CommandLine.Args()) > 0 { + packages = flag.CommandLine.Args() + } + // Get metalinter and install all supported linters + build.MustRun(goTool("get", "gopkg.in/alecthomas/gometalinter.v1")) + build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v1"), "--install") - sources := make([]string, 0, len(lines)-1) - for _, line := range lines[1:] { - if line = strings.TrimSpace(line); line != "" { - sources = append(sources, filepath.Join(root, line)) - } - } - // Run the spell checker for this particular package - build.MustRunCommand(filepath.Join(GOBIN, "misspell"), append([]string{"-error"}, sources...)...) + // Run fast linters batched together + configs := []string{"--vendor", "--disable-all", "--enable=vet", "--enable=gofmt", "--enable=misspell"} + build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v1"), append(configs, packages...)...) + + // Run slow linters one by one + for _, linter := range []string{"unconvert"} { + configs = []string{"--vendor", "--deadline=10m", "--disable-all", "--enable=" + linter} + build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v1"), append(configs, packages...)...) } } diff --git a/cmd/faucet/website.go b/cmd/faucet/website.go index eeb8e410e4..6a99f8c6f8 100644 --- a/cmd/faucet/website.go +++ b/cmd/faucet/website.go @@ -182,8 +182,9 @@ type bintree struct { Func func() (*asset, error) Children map[string]*bintree } + var _bintree = &bintree{nil, map[string]*bintree{ - "faucet.html": &bintree{faucetHtml, map[string]*bintree{}}, + "faucet.html": {faucetHtml, map[string]*bintree{}}, }} // RestoreAsset restores an asset under the given directory @@ -232,4 +233,3 @@ func _filePath(dir, name string) string { cannonicalName := strings.Replace(name, "\\", "/", -1) return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...) } - diff --git a/cmd/puppeth/module_faucet.go b/cmd/puppeth/module_faucet.go index acf1e4324e..3c1296bddb 100644 --- a/cmd/puppeth/module_faucet.go +++ b/cmd/puppeth/module_faucet.go @@ -133,7 +133,7 @@ func deployFaucet(client *sshClient, network string, bootnodes []string, config }) files[filepath.Join(workdir, "docker-compose.yaml")] = composefile.Bytes() - files[filepath.Join(workdir, "genesis.json")] = []byte(config.node.genesis) + files[filepath.Join(workdir, "genesis.json")] = config.node.genesis files[filepath.Join(workdir, "account.json")] = []byte(config.node.keyJSON) files[filepath.Join(workdir, "account.pass")] = []byte(config.node.keyPass) diff --git a/cmd/puppeth/module_node.go b/cmd/puppeth/module_node.go index 8f912f9ebd..375e3e6463 100644 --- a/cmd/puppeth/module_node.go +++ b/cmd/puppeth/module_node.go @@ -128,7 +128,7 @@ func deployNode(client *sshClient, network string, bootv4, bootv5 []string, conf files[filepath.Join(workdir, "docker-compose.yaml")] = composefile.Bytes() //genesisfile, _ := json.MarshalIndent(config.genesis, "", " ") - files[filepath.Join(workdir, "genesis.json")] = []byte(config.genesis) + files[filepath.Join(workdir, "genesis.json")] = config.genesis if config.keyJSON != "" { files[filepath.Join(workdir, "signer.json")] = []byte(config.keyJSON) diff --git a/cmd/puppeth/ssh.go b/cmd/puppeth/ssh.go index 26f8466850..47378a6063 100644 --- a/cmd/puppeth/ssh.go +++ b/cmd/puppeth/ssh.go @@ -27,7 +27,6 @@ import ( "os/user" "path/filepath" "strings" - "syscall" "github.com/ethereum/go-ethereum/log" "golang.org/x/crypto/ssh" @@ -85,7 +84,7 @@ func dial(server string, pubkey []byte) (*sshClient, error) { } auths = append(auths, ssh.PasswordCallback(func() (string, error) { fmt.Printf("What's the login password for %s at %s? (won't be echoed)\n> ", login, server) - blob, err := terminal.ReadPassword(int(syscall.Stdin)) + blob, err := terminal.ReadPassword(int(os.Stdin.Fd())) fmt.Println() return string(blob), err diff --git a/cmd/puppeth/wizard.go b/cmd/puppeth/wizard.go index 5fbc11cb98..eb6d9e5aae 100644 --- a/cmd/puppeth/wizard.go +++ b/cmd/puppeth/wizard.go @@ -28,7 +28,6 @@ import ( "sort" "strconv" "strings" - "syscall" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core" @@ -231,7 +230,7 @@ func (w *wizard) readDefaultFloat(def float64) float64 { // line and returns it. The input will not be echoed. func (w *wizard) readPassword() string { fmt.Printf("> ") - text, err := terminal.ReadPassword(int(syscall.Stdin)) + text, err := terminal.ReadPassword(int(os.Stdin.Fd())) if err != nil { log.Crit("Failed to read password", "err", err) } diff --git a/common/hexutil/hexutil.go b/common/hexutil/hexutil.go index 582a67c22c..02c488a3f1 100644 --- a/common/hexutil/hexutil.go +++ b/common/hexutil/hexutil.go @@ -53,9 +53,7 @@ var ( type decError struct{ msg string } -func (err decError) Error() string { - return string(err.msg) -} +func (err decError) Error() string { return err.msg } // Decode decodes a hex string with 0x prefix. func Decode(input string) ([]byte, error) { diff --git a/common/hexutil/json.go b/common/hexutil/json.go index 11e14cae7f..fbc21241c8 100644 --- a/common/hexutil/json.go +++ b/common/hexutil/json.go @@ -223,7 +223,7 @@ func (b *Uint64) UnmarshalText(input []byte) error { return ErrSyntax } dec *= 16 - dec += uint64(nib) + dec += nib } *b = Uint64(dec) return nil diff --git a/consensus/ethash/algorithm_go1.8.go b/consensus/ethash/algorithm_go1.8.go index 62bf4dec1b..d691b758f0 100644 --- a/consensus/ethash/algorithm_go1.8.go +++ b/consensus/ethash/algorithm_go1.8.go @@ -31,7 +31,7 @@ func cacheSize(block uint64) uint64 { return cacheSizes[epoch] } // No known cache size, calculate manually (sanity branch only) - size := uint64(cacheInitBytes + cacheGrowthBytes*uint64(epoch) - hashBytes) + size := cacheInitBytes + cacheGrowthBytes*uint64(epoch) - hashBytes for !new(big.Int).SetUint64(size / hashBytes).ProbablyPrime(1) { // Always accurate for n < 2^64 size -= 2 * hashBytes } @@ -49,7 +49,7 @@ func datasetSize(block uint64) uint64 { return datasetSizes[epoch] } // No known dataset size, calculate manually (sanity branch only) - size := uint64(datasetInitBytes + datasetGrowthBytes*uint64(epoch) - mixBytes) + size := datasetInitBytes + datasetGrowthBytes*uint64(epoch) - mixBytes for !new(big.Int).SetUint64(size / mixBytes).ProbablyPrime(1) { // Always accurate for n < 2^64 size -= 2 * mixBytes } diff --git a/contracts/chequebook/contract/chequebook.sol b/contracts/chequebook/contract/chequebook.sol index 845ba464b3..8d6e85d119 100644 --- a/contracts/chequebook/contract/chequebook.sol +++ b/contracts/chequebook/contract/chequebook.sol @@ -1,7 +1,9 @@ -import "mortal"; +pragma solidity ^0.4.18; + +import "https://github.com/ethereum/solidity/std/mortal.sol"; /// @title Chequebook for Ethereum micropayments -/// @author Daniel A. Nagy +/// @author Daniel A. Nagy contract chequebook is mortal { // Cumulative paid amount in wei to each beneficiary mapping (address => uint256) public sent; @@ -21,26 +23,23 @@ contract chequebook is mortal { uint8 sig_v, bytes32 sig_r, bytes32 sig_s) { // Check if the cheque is old. // Only cheques that are more recent than the last cashed one are considered. - if(amount <= sent[beneficiary]) return; + require(amount > sent[beneficiary]); // Check the digital signature of the cheque. - bytes32 hash = sha3(address(this), beneficiary, amount); - if(owner != ecrecover(hash, sig_v, sig_r, sig_s)) return; + bytes32 hash = keccak256(address(this), beneficiary, amount); + require(owner == ecrecover(hash, sig_v, sig_r, sig_s)); // Attempt sending the difference between the cumulative amount on the cheque // and the cumulative amount on the last cashed cheque to beneficiary. uint256 diff = amount - sent[beneficiary]; if (diff <= this.balance) { // update the cumulative amount before sending sent[beneficiary] = amount; - if (!beneficiary.send(diff)) { - // Upon failure to execute send, revert everything - throw; - } + beneficiary.transfer(diff); } else { // Upon failure, punish owner for writing a bounced cheque. // owner.sendToDebtorsPrison(); Overdraft(owner); // Compensate beneficiary. - suicide(beneficiary); + selfdestruct(beneficiary); } } } diff --git a/core/bloombits/matcher_test.go b/core/bloombits/matcher_test.go index 0d8544136d..4a31854c58 100644 --- a/core/bloombits/matcher_test.go +++ b/core/bloombits/matcher_test.go @@ -31,14 +31,14 @@ const testSectionSize = 4096 // Tests that wildcard filter rules (nil) can be specified and are handled well. func TestMatcherWildcards(t *testing.T) { matcher := NewMatcher(testSectionSize, [][][]byte{ - [][]byte{common.Address{}.Bytes(), common.Address{0x01}.Bytes()}, // Default address is not a wildcard - [][]byte{common.Hash{}.Bytes(), common.Hash{0x01}.Bytes()}, // Default hash is not a wildcard - [][]byte{common.Hash{0x01}.Bytes()}, // Plain rule, sanity check - [][]byte{common.Hash{0x01}.Bytes(), nil}, // Wildcard suffix, drop rule - [][]byte{nil, common.Hash{0x01}.Bytes()}, // Wildcard prefix, drop rule - [][]byte{nil, nil}, // Wildcard combo, drop rule - [][]byte{}, // Inited wildcard rule, drop rule - nil, // Proper wildcard rule, drop rule + {common.Address{}.Bytes(), common.Address{0x01}.Bytes()}, // Default address is not a wildcard + {common.Hash{}.Bytes(), common.Hash{0x01}.Bytes()}, // Default hash is not a wildcard + {common.Hash{0x01}.Bytes()}, // Plain rule, sanity check + {common.Hash{0x01}.Bytes(), nil}, // Wildcard suffix, drop rule + {nil, common.Hash{0x01}.Bytes()}, // Wildcard prefix, drop rule + {nil, nil}, // Wildcard combo, drop rule + {}, // Inited wildcard rule, drop rule + nil, // Proper wildcard rule, drop rule }) if len(matcher.filters) != 3 { t.Fatalf("filter system size mismatch: have %d, want %d", len(matcher.filters), 3) diff --git a/core/bloombits/scheduler_test.go b/core/bloombits/scheduler_test.go index 8a159c2370..70772e4ab9 100644 --- a/core/bloombits/scheduler_test.go +++ b/core/bloombits/scheduler_test.go @@ -60,7 +60,7 @@ func testScheduler(t *testing.T, clients int, fetchers int, requests int) { req.section, // Requested data req.section, // Duplicated data (ensure it doesn't double close anything) }, [][]byte{ - []byte{}, + {}, new(big.Int).SetUint64(req.section).Bytes(), new(big.Int).SetUint64(req.section).Bytes(), }) diff --git a/core/genesis.go b/core/genesis.go index 26b1c9f63f..df491ce0f4 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -356,15 +356,15 @@ func DeveloperGenesisBlock(period uint64, faucet common.Address) *Genesis { GasLimit: 6283185, Difficulty: big.NewInt(1), Alloc: map[common.Address]GenesisAccount{ - common.BytesToAddress([]byte{1}): GenesisAccount{Balance: big.NewInt(1)}, // ECRecover - common.BytesToAddress([]byte{2}): GenesisAccount{Balance: big.NewInt(1)}, // SHA256 - common.BytesToAddress([]byte{3}): GenesisAccount{Balance: big.NewInt(1)}, // RIPEMD - common.BytesToAddress([]byte{4}): GenesisAccount{Balance: big.NewInt(1)}, // Identity - common.BytesToAddress([]byte{5}): GenesisAccount{Balance: big.NewInt(1)}, // ModExp - common.BytesToAddress([]byte{6}): GenesisAccount{Balance: big.NewInt(1)}, // ECAdd - common.BytesToAddress([]byte{7}): GenesisAccount{Balance: big.NewInt(1)}, // ECScalarMul - common.BytesToAddress([]byte{8}): GenesisAccount{Balance: big.NewInt(1)}, // ECPairing - faucet: GenesisAccount{Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))}, + common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover + common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256 + common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD + common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity + common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp + common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd + common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul + common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing + faucet: {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))}, }, } } diff --git a/core/tx_pool.go b/core/tx_pool.go index 0f008ddc0d..c3915575b0 100644 --- a/core/tx_pool.go +++ b/core/tx_pool.go @@ -820,7 +820,7 @@ func (pool *TxPool) addTxsLocked(txs []*types.Transaction, local bool) []error { // Only reprocess the internal state if something was actually added if len(dirty) > 0 { addrs := make([]common.Address, 0, len(dirty)) - for addr, _ := range dirty { + for addr := range dirty { addrs = append(addrs, addr) } pool.promoteExecutables(addrs) @@ -907,7 +907,7 @@ func (pool *TxPool) promoteExecutables(accounts []common.Address) { // Gather all the accounts potentially needing updates if accounts == nil { accounts = make([]common.Address, 0, len(pool.queue)) - for addr, _ := range pool.queue { + for addr := range pool.queue { accounts = append(accounts, addr) } } diff --git a/core/tx_pool_test.go b/core/tx_pool_test.go index 737ea4cd39..e9ecbb9338 100644 --- a/core/tx_pool_test.go +++ b/core/tx_pool_test.go @@ -105,7 +105,7 @@ func validateTxPoolInternals(pool *TxPool) error { for addr, txs := range pool.pending { // Find the last transaction var last uint64 - for nonce, _ := range txs.txs.items { + for nonce := range txs.txs.items { if last < nonce { last = nonce } diff --git a/core/vm/interpreter.go b/core/vm/interpreter.go index 516438509f..ea5468f901 100644 --- a/core/vm/interpreter.go +++ b/core/vm/interpreter.go @@ -161,8 +161,8 @@ func (in *Interpreter) Run(snapshot int, contract *Contract, input []byte) (ret if in.cfg.Debug { logged = false - pcCopy = uint64(pc) - gasCopy = uint64(contract.Gas) + pcCopy = pc + gasCopy = contract.Gas stackCopy = newstack() for _, val := range stack.data { stackCopy.push(val) diff --git a/eth/downloader/downloader.go b/eth/downloader/downloader.go index 5782d4cf53..cca4fe7a93 100644 --- a/eth/downloader/downloader.go +++ b/eth/downloader/downloader.go @@ -708,7 +708,7 @@ func (d *Downloader) findAncestor(p *peerConnection, height uint64) (uint64, err ttl := d.requestTTL() timeout := time.After(ttl) - go p.peer.RequestHeadersByNumber(uint64(check), 1, 0, false) + go p.peer.RequestHeadersByNumber(check, 1, 0, false) // Wait until a reply arrives to this request for arrived := false; !arrived; { @@ -1518,7 +1518,7 @@ func (d *Downloader) deliver(id string, destCh chan dataPack, packet dataPack, i func (d *Downloader) qosTuner() { for { // Retrieve the current median RTT and integrate into the previoust target RTT - rtt := time.Duration(float64(1-qosTuningImpact)*float64(atomic.LoadUint64(&d.rttEstimate)) + qosTuningImpact*float64(d.peers.medianRTT())) + rtt := time.Duration((1-qosTuningImpact)*float64(atomic.LoadUint64(&d.rttEstimate)) + qosTuningImpact*float64(d.peers.medianRTT())) atomic.StoreUint64(&d.rttEstimate, uint64(rtt)) // A new RTT cycle passed, increase our confidence in the estimated RTT diff --git a/eth/downloader/fakepeer.go b/eth/downloader/fakepeer.go index ebdb9c3342..b45acff7d0 100644 --- a/eth/downloader/fakepeer.go +++ b/eth/downloader/fakepeer.go @@ -62,7 +62,7 @@ func (p *FakePeer) RequestHeadersByHash(hash common.Hash, amount int, skip int, number := origin.Number.Uint64() headers = append(headers, origin) if reverse { - for i := 0; i < int(skip)+1; i++ { + for i := 0; i <= skip; i++ { if header := p.hc.GetHeader(hash, number); header != nil { hash = header.ParentHash number-- diff --git a/eth/filters/bench_test.go b/eth/filters/bench_test.go index abbf4593e9..0a0929bc10 100644 --- a/eth/filters/bench_test.go +++ b/eth/filters/bench_test.go @@ -192,7 +192,7 @@ func BenchmarkNoBloomBits(b *testing.B) { start := time.Now() mux := new(event.TypeMux) backend := &testBackend{mux, db, 0, new(event.Feed), new(event.Feed), new(event.Feed), new(event.Feed)} - filter := New(backend, 0, int64(headNum), []common.Address{common.Address{}}, nil) + filter := New(backend, 0, int64(headNum), []common.Address{{}}, nil) filter.Logs(context.Background()) d := time.Since(start) fmt.Println("Finished running filter benchmarks") diff --git a/eth/filters/filter.go b/eth/filters/filter.go index d16af84ee8..e208f8f38e 100644 --- a/eth/filters/filter.go +++ b/eth/filters/filter.go @@ -206,7 +206,7 @@ func (f *Filter) checkMatches(ctx context.Context, header *types.Header) (logs [ } var unfiltered []*types.Log for _, receipt := range receipts { - unfiltered = append(unfiltered, ([]*types.Log)(receipt.Logs)...) + unfiltered = append(unfiltered, receipt.Logs...) } logs = filterLogs(unfiltered, nil, nil, f.addresses, f.topics) if len(logs) > 0 { diff --git a/les/bloombits.go b/les/bloombits.go index dff83d3491..de233d7518 100644 --- a/les/bloombits.go +++ b/les/bloombits.go @@ -56,7 +56,7 @@ func (eth *LightEthereum) startBloomHandlers() { task.Bitsets = make([][]byte, len(task.Sections)) compVectors, err := light.GetBloomBits(task.Context, eth.odr, task.Bit, task.Sections) if err == nil { - for i, _ := range task.Sections { + for i := range task.Sections { if blob, err := bitutil.DecompressBytes(compVectors[i], int(light.BloomTrieFrequency/8)); err == nil { task.Bitsets[i] = blob } else { diff --git a/les/distributor.go b/les/distributor.go index e8ef5b02e2..159fa4c73f 100644 --- a/les/distributor.go +++ b/les/distributor.go @@ -191,7 +191,7 @@ func (d *requestDistributor) nextRequest() (distPeer, *distReq, time.Duration) { for (len(d.peers) > 0 || elem == d.reqQueue.Front()) && elem != nil { req := elem.Value.(*distReq) canSend := false - for peer, _ := range d.peers { + for peer := range d.peers { if _, ok := checkedPeers[peer]; !ok && peer.canQueue() && req.canSend(peer) { canSend = true cost := req.getCost(peer) diff --git a/les/distributor_test.go b/les/distributor_test.go index 4e7f8bd291..55defb69be 100644 --- a/les/distributor_test.go +++ b/les/distributor_test.go @@ -124,7 +124,7 @@ func testRequestDistributor(t *testing.T, resend bool) { dist := newRequestDistributor(nil, stop) var peers [testDistPeerCount]*testDistPeer - for i, _ := range peers { + for i := range peers { peers[i] = &testDistPeer{} go peers[i].worker(t, !resend, stop) dist.registerTestPeer(peers[i]) diff --git a/les/fetcher.go b/les/fetcher.go index 4fc142f0f4..3fc4df30b9 100644 --- a/les/fetcher.go +++ b/les/fetcher.go @@ -117,16 +117,16 @@ func newLightFetcher(pm *ProtocolManager) *lightFetcher { maxConfirmedTd: big.NewInt(0), } pm.peers.notify(f) + + f.pm.wg.Add(1) go f.syncLoop() return f } // syncLoop is the main event loop of the light fetcher func (f *lightFetcher) syncLoop() { - f.pm.wg.Add(1) - defer f.pm.wg.Done() - requesting := false + defer f.pm.wg.Done() for { select { case <-f.pm.quitSync: diff --git a/les/odr.go b/les/odr.go index 986630dbfd..f8412aaad7 100644 --- a/les/odr.go +++ b/les/odr.go @@ -27,20 +27,20 @@ import ( // LesOdr implements light.OdrBackend type LesOdr struct { - db ethdb.Database + db ethdb.Database chtIndexer, bloomTrieIndexer, bloomIndexer *core.ChainIndexer - retriever *retrieveManager - stop chan struct{} + retriever *retrieveManager + stop chan struct{} } func NewLesOdr(db ethdb.Database, chtIndexer, bloomTrieIndexer, bloomIndexer *core.ChainIndexer, retriever *retrieveManager) *LesOdr { return &LesOdr{ - db: db, - chtIndexer: chtIndexer, - bloomTrieIndexer: bloomTrieIndexer, - bloomIndexer: bloomIndexer, - retriever: retriever, - stop: make(chan struct{}), + db: db, + chtIndexer: chtIndexer, + bloomTrieIndexer: bloomTrieIndexer, + bloomIndexer: bloomIndexer, + retriever: retriever, + stop: make(chan struct{}), } } diff --git a/les/peer.go b/les/peer.go index 524690e2f5..04d747a6b3 100644 --- a/les/peer.go +++ b/les/peer.go @@ -400,7 +400,7 @@ func (p *peer) Handshake(td *big.Int, head common.Hash, headNum uint64, genesis var send keyValueList send = send.add("protocolVersion", uint64(p.version)) - send = send.add("networkId", uint64(p.network)) + send = send.add("networkId", p.network) send = send.add("headTd", td) send = send.add("headHash", head) send = send.add("headNum", headNum) diff --git a/les/serverpool.go b/les/serverpool.go index f4e4df2fbf..dc1ea6bf02 100644 --- a/les/serverpool.go +++ b/les/serverpool.go @@ -145,15 +145,15 @@ func (pool *serverPool) start(server *p2p.Server, topic discv5.Topic) { pool.wg.Add(1) pool.loadNodes() - go pool.eventLoop() - - pool.checkDial() if pool.server.DiscV5 != nil { pool.discSetPeriod = make(chan time.Duration, 1) pool.discNodes = make(chan *discv5.Node, 100) pool.discLookups = make(chan bool, 100) go pool.server.DiscV5.SearchTopic(pool.topic, pool.discSetPeriod, pool.discNodes, pool.discLookups) } + + go pool.eventLoop() + pool.checkDial() } // connect should be called upon any incoming connection. If the connection has been diff --git a/metrics/metrics.go b/metrics/metrics.go index da2cdbc53c..afdfd89fa7 100644 --- a/metrics/metrics.go +++ b/metrics/metrics.go @@ -112,10 +112,10 @@ func CollectProcessMetrics(refresh time.Duration) { memPauses.Mark(int64(memstats[i%2].PauseTotalNs - memstats[(i-1)%2].PauseTotalNs)) if ReadDiskStats(diskstats[i%2]) == nil { - diskReads.Mark(int64(diskstats[i%2].ReadCount - diskstats[(i-1)%2].ReadCount)) - diskReadBytes.Mark(int64(diskstats[i%2].ReadBytes - diskstats[(i-1)%2].ReadBytes)) - diskWrites.Mark(int64(diskstats[i%2].WriteCount - diskstats[(i-1)%2].WriteCount)) - diskWriteBytes.Mark(int64(diskstats[i%2].WriteBytes - diskstats[(i-1)%2].WriteBytes)) + diskReads.Mark(diskstats[i%2].ReadCount - diskstats[(i-1)%2].ReadCount) + diskReadBytes.Mark(diskstats[i%2].ReadBytes - diskstats[(i-1)%2].ReadBytes) + diskWrites.Mark(diskstats[i%2].WriteCount - diskstats[(i-1)%2].WriteCount) + diskWriteBytes.Mark(diskstats[i%2].WriteBytes - diskstats[(i-1)%2].WriteBytes) } time.Sleep(refresh) } diff --git a/mobile/interface.go b/mobile/interface.go index 72958e66a2..ac0c26088a 100644 --- a/mobile/interface.go +++ b/mobile/interface.go @@ -59,7 +59,7 @@ func (i *Interface) SetInt64(n int64) { i.object = &n } func (i *Interface) SetUint8(bigint *BigInt) { n := uint8(bigint.bigint.Uint64()); i.object = &n } func (i *Interface) SetUint16(bigint *BigInt) { n := uint16(bigint.bigint.Uint64()); i.object = &n } func (i *Interface) SetUint32(bigint *BigInt) { n := uint32(bigint.bigint.Uint64()); i.object = &n } -func (i *Interface) SetUint64(bigint *BigInt) { n := uint64(bigint.bigint.Uint64()); i.object = &n } +func (i *Interface) SetUint64(bigint *BigInt) { n := bigint.bigint.Uint64(); i.object = &n } func (i *Interface) SetBigInt(bigint *BigInt) { i.object = &bigint.bigint } func (i *Interface) SetBigInts(bigints *BigInts) { i.object = &bigints.bigints } diff --git a/p2p/discover/table.go b/p2p/discover/table.go index 2f5a26c34c..ec4eb94ad5 100644 --- a/p2p/discover/table.go +++ b/p2p/discover/table.go @@ -427,7 +427,7 @@ func (tab *Table) bondall(nodes []*Node) (result []*Node) { rc := make(chan *Node, len(nodes)) for i := range nodes { go func(n *Node) { - nn, _ := tab.bond(false, n.ID, n.addr(), uint16(n.TCP)) + nn, _ := tab.bond(false, n.ID, n.addr(), n.TCP) rc <- nn }(nodes[i]) } diff --git a/rpc/http.go b/rpc/http.go index 4143e2a8dc..3f572b34c0 100644 --- a/rpc/http.go +++ b/rpc/http.go @@ -23,6 +23,7 @@ import ( "fmt" "io" "io/ioutil" + "mime" "net" "net/http" "sync" @@ -151,6 +152,16 @@ func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { http.StatusRequestEntityTooLarge) return } + + ct := r.Header.Get("content-type") + mt, _, err := mime.ParseMediaType(ct) + if err != nil || mt != "application/json" { + http.Error(w, + "invalid content type, only application/json is supported", + http.StatusUnsupportedMediaType) + return + } + w.Header().Set("content-type", "application/json") // create a codec that reads direct from the request body until diff --git a/rpc/subscription_test.go b/rpc/subscription_test.go index 39f7596923..0ba177e63b 100644 --- a/rpc/subscription_test.go +++ b/rpc/subscription_test.go @@ -290,7 +290,7 @@ func TestSubscriptionMultipleNamespaces(t *testing.T) { for { done := true - for id, _ := range count { + for id := range count { if count, found := count[id]; !found || count < (2*n) { done = false } diff --git a/rpc/websocket.go b/rpc/websocket.go index 5f9593a43f..4214fc86a0 100644 --- a/rpc/websocket.go +++ b/rpc/websocket.go @@ -83,7 +83,7 @@ func wsHandshakeValidator(allowedOrigins []string) func(*websocket.Config, *http if allowAllOrigins || origins.Has(origin) { return nil } - log.Debug(fmt.Sprintf("origin '%s' not allowed on WS-RPC interface\n", origin)) + log.Warn(fmt.Sprintf("origin '%s' not allowed on WS-RPC interface\n", origin)) return fmt.Errorf("origin %s not allowed", origin) } diff --git a/swarm/api/client/client_test.go b/swarm/api/client/client_test.go index edf385dd08..c1d144e370 100644 --- a/swarm/api/client/client_test.go +++ b/swarm/api/client/client_test.go @@ -244,25 +244,25 @@ func TestClientFileList(t *testing.T) { } tests := map[string][]string{ - "": []string{"dir1/", "dir2/", "file1.txt", "file2.txt"}, - "file": []string{"file1.txt", "file2.txt"}, - "file1": []string{"file1.txt"}, - "file2.txt": []string{"file2.txt"}, - "file12": []string{}, - "dir": []string{"dir1/", "dir2/"}, - "dir1": []string{"dir1/"}, - "dir1/": []string{"dir1/file3.txt", "dir1/file4.txt"}, - "dir1/file": []string{"dir1/file3.txt", "dir1/file4.txt"}, - "dir1/file3.txt": []string{"dir1/file3.txt"}, - "dir1/file34": []string{}, - "dir2/": []string{"dir2/dir3/", "dir2/dir4/", "dir2/file5.txt"}, - "dir2/file": []string{"dir2/file5.txt"}, - "dir2/dir": []string{"dir2/dir3/", "dir2/dir4/"}, - "dir2/dir3/": []string{"dir2/dir3/file6.txt"}, - "dir2/dir4/": []string{"dir2/dir4/file7.txt", "dir2/dir4/file8.txt"}, - "dir2/dir4/file": []string{"dir2/dir4/file7.txt", "dir2/dir4/file8.txt"}, - "dir2/dir4/file7.txt": []string{"dir2/dir4/file7.txt"}, - "dir2/dir4/file78": []string{}, + "": {"dir1/", "dir2/", "file1.txt", "file2.txt"}, + "file": {"file1.txt", "file2.txt"}, + "file1": {"file1.txt"}, + "file2.txt": {"file2.txt"}, + "file12": {}, + "dir": {"dir1/", "dir2/"}, + "dir1": {"dir1/"}, + "dir1/": {"dir1/file3.txt", "dir1/file4.txt"}, + "dir1/file": {"dir1/file3.txt", "dir1/file4.txt"}, + "dir1/file3.txt": {"dir1/file3.txt"}, + "dir1/file34": {}, + "dir2/": {"dir2/dir3/", "dir2/dir4/", "dir2/file5.txt"}, + "dir2/file": {"dir2/file5.txt"}, + "dir2/dir": {"dir2/dir3/", "dir2/dir4/"}, + "dir2/dir3/": {"dir2/dir3/file6.txt"}, + "dir2/dir4/": {"dir2/dir4/file7.txt", "dir2/dir4/file8.txt"}, + "dir2/dir4/file": {"dir2/dir4/file7.txt", "dir2/dir4/file8.txt"}, + "dir2/dir4/file7.txt": {"dir2/dir4/file7.txt"}, + "dir2/dir4/file78": {}, } for prefix, expected := range tests { actual := ls(prefix) diff --git a/swarm/api/manifest.go b/swarm/api/manifest.go index d3eced1980..32b5f80a7c 100644 --- a/swarm/api/manifest.go +++ b/swarm/api/manifest.go @@ -238,7 +238,7 @@ func (self *manifestTrie) addEntry(entry *manifestTrieEntry, quitC chan bool) { return } - b := byte(entry.Path[0]) + b := entry.Path[0] oldentry := self.entries[b] if (oldentry == nil) || (oldentry.Path == entry.Path && oldentry.ContentType != ManifestType) { self.entries[b] = entry @@ -294,7 +294,7 @@ func (self *manifestTrie) deleteEntry(path string, quitC chan bool) { return } - b := byte(path[0]) + b := path[0] entry := self.entries[b] if entry == nil { return @@ -425,7 +425,7 @@ func (self *manifestTrie) findPrefixOf(path string, quitC chan bool) (entry *man } //see if first char is in manifest entries - b := byte(path[0]) + b := path[0] entry = self.entries[b] if entry == nil { return self.entries[256], 0 diff --git a/swarm/fuse/fuse_file.go b/swarm/fuse/fuse_file.go index 32c85d02f7..c94a0773f5 100644 --- a/swarm/fuse/fuse_file.go +++ b/swarm/fuse/fuse_file.go @@ -19,15 +19,16 @@ package fuse import ( - "bazil.org/fuse" - "bazil.org/fuse/fs" "errors" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/swarm/storage" - "golang.org/x/net/context" "io" "os" "sync" + + "bazil.org/fuse" + "bazil.org/fuse/fs" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/swarm/storage" + "golang.org/x/net/context" ) const ( @@ -87,7 +88,7 @@ func (file *SwarmFile) Attr(ctx context.Context, a *fuse.Attr) error { if err != nil { log.Warn("Couldnt get size of file %s : %v", file.path, err) } - file.fileSize = int64(size) + file.fileSize = size } a.Size = uint64(file.fileSize) return nil diff --git a/swarm/network/depo.go b/swarm/network/depo.go index 8695bf5d98..17540d2f9f 100644 --- a/swarm/network/depo.go +++ b/swarm/network/depo.go @@ -55,7 +55,7 @@ func (self *Depo) HandleUnsyncedKeysMsg(req *unsyncedKeysMsgData, p *peer) error var err error for _, req := range unsynced { // skip keys that are found, - chunk, err = self.localStore.Get(storage.Key(req.Key[:])) + chunk, err = self.localStore.Get(req.Key[:]) if err != nil || chunk.SData == nil { missing = append(missing, req) } diff --git a/swarm/network/kademlia/address.go b/swarm/network/kademlia/address.go index 16c5ce5322..4c38a846f9 100644 --- a/swarm/network/kademlia/address.go +++ b/swarm/network/kademlia/address.go @@ -67,7 +67,7 @@ func proximity(one, other Address) (ret int) { for i := 0; i < len(one); i++ { oxo := one[i] ^ other[i] for j := 0; j < 8; j++ { - if (uint8(oxo)>>uint8(7-j))&0x01 != 0 { + if (oxo>>uint8(7-j))&0x01 != 0 { return i*8 + j } } diff --git a/swarm/network/kademlia/kaddb.go b/swarm/network/kademlia/kaddb.go index 3e4b261fde..cb0869467e 100644 --- a/swarm/network/kademlia/kaddb.go +++ b/swarm/network/kademlia/kaddb.go @@ -211,12 +211,12 @@ func (self *KadDb) findBest(maxBinSize int, binSize func(int) int) (node *NodeRe } // if node is scheduled to connect - if time.Time(node.After).After(time.Now()) { + if node.After.After(time.Now()) { log.Debug(fmt.Sprintf("kaddb record %v (PO%03d:%d) skipped. seen at %v (%v ago), scheduled at %v", node.Addr, po, cursor, node.Seen, delta, node.After)) continue ROW } - delta = time.Since(time.Time(node.Seen)) + delta = time.Since(node.Seen) if delta < self.initialRetryInterval { delta = self.initialRetryInterval } @@ -230,7 +230,7 @@ func (self *KadDb) findBest(maxBinSize int, binSize func(int) int) (node *NodeRe log.Debug(fmt.Sprintf("kaddb record %v (PO%03d:%d) ready to be tried. seen at %v (%v ago), scheduled at %v", node.Addr, po, cursor, node.Seen, delta, node.After)) // scheduling next check - interval = time.Duration(delta * time.Duration(self.connRetryExp)) + interval = delta * time.Duration(self.connRetryExp) after = time.Now().Add(interval) log.Debug(fmt.Sprintf("kaddb record %v (PO%03d:%d) selected as candidate connection %v. seen at %v (%v ago), selectable since %v, retry after %v (in %v)", node.Addr, po, cursor, rounds, node.Seen, delta, node.After, after, interval)) diff --git a/swarm/network/protocol.go b/swarm/network/protocol.go index 2f880df570..a418c1dbbd 100644 --- a/swarm/network/protocol.go +++ b/swarm/network/protocol.go @@ -309,7 +309,7 @@ func (self *bzz) handleStatus() (err error) { Version: uint64(Version), ID: "honey", Addr: self.selfAddr(), - NetworkId: uint64(self.NetworkId), + NetworkId: self.NetworkId, Swap: &bzzswap.SwapProfile{ Profile: self.swapParams.Profile, PayProfile: self.swapParams.PayProfile, diff --git a/swarm/network/syncer.go b/swarm/network/syncer.go index a3814e4232..d76af022c1 100644 --- a/swarm/network/syncer.go +++ b/swarm/network/syncer.go @@ -378,7 +378,7 @@ func (self *syncer) syncHistory(state *syncState) chan interface{} { } select { // blocking until history channel is read from - case history <- storage.Key(key): + case history <- key: n++ log.Trace(fmt.Sprintf("syncer[%v]: history: %v (%v keys)", self.key.Log(), key.Log(), n)) state.Latest = key diff --git a/swarm/storage/chunker.go b/swarm/storage/chunker.go index 0454828b9c..98cd6e75ea 100644 --- a/swarm/storage/chunker.go +++ b/swarm/storage/chunker.go @@ -50,7 +50,6 @@ data_{i} := size(subtree_{i}) || key_{j} || key_{j+1} .... || key_{j+n-1} The underlying hash function is configurable */ - /* Tree chunker is a concrete implementation of data chunking. This chunker works in a simple way, it builds a tree out of the document so that each node either represents a chunk of real data or a chunk of data representing an branching non-leaf node of the tree. In particular each such non-leaf chunk will represent is a concatenation of the hash of its respective children. This scheme simultaneously guarantees data integrity as well as self addressing. Abstract nodes are transparent since their represented size component is strictly greater than their maximum data size, since they encode a subtree. @@ -61,17 +60,17 @@ The hashing itself does use extra copies and allocation though, since it does ne var ( errAppendOppNotSuported = errors.New("Append operation not supported") - errOperationTimedOut = errors.New("operation timed out") + errOperationTimedOut = errors.New("operation timed out") ) type TreeChunker struct { branches int64 hashFunc SwarmHasher // calculated - hashSize int64 // self.hashFunc.New().Size() - chunkSize int64 // hashSize* branches - workerCount int64 // the number of worker routines used - workerLock sync.RWMutex // lock for the worker count + hashSize int64 // self.hashFunc.New().Size() + chunkSize int64 // hashSize* branches + workerCount int64 // the number of worker routines used + workerLock sync.RWMutex // lock for the worker count } func NewTreeChunker(params *ChunkerParams) (self *TreeChunker) { @@ -124,7 +123,6 @@ func (self *TreeChunker) Split(data io.Reader, size int64, chunkC chan *Chunk, s panic("chunker must be initialised") } - jobC := make(chan *hashJob, 2*ChunkProcessors) wg := &sync.WaitGroup{} errC := make(chan error) @@ -164,7 +162,6 @@ func (self *TreeChunker) Split(data io.Reader, size int64, chunkC chan *Chunk, s close(errC) }() - defer close(quitC) select { case err := <-errC: @@ -172,7 +169,7 @@ func (self *TreeChunker) Split(data io.Reader, size int64, chunkC chan *Chunk, s return nil, err } case <-time.NewTimer(splitTimeout).C: - return nil,errOperationTimedOut + return nil, errOperationTimedOut } return key, nil @@ -208,9 +205,9 @@ func (self *TreeChunker) split(depth int, treeSize int64, key Key, data io.Reade } // dept > 0 // intermediate chunk containing child nodes hashes - branchCnt := int64((size + treeSize - 1) / treeSize) + branchCnt := (size + treeSize - 1) / treeSize - var chunk []byte = make([]byte, branchCnt*self.hashSize+8) + var chunk = make([]byte, branchCnt*self.hashSize+8) var pos, i int64 binary.LittleEndian.PutUint64(chunk[0:8], uint64(size)) diff --git a/swarm/storage/memstore.go b/swarm/storage/memstore.go index 155dd00882..3cb25ac625 100644 --- a/swarm/storage/memstore.go +++ b/swarm/storage/memstore.go @@ -78,7 +78,7 @@ type memTree struct { func newMemTree(b uint, parent *memTree, pidx uint) (node *memTree) { node = new(memTree) node.bits = b - node.width = 1 << uint(b) + node.width = 1 << b node.subtree = make([]*memTree, node.width) node.access = make([]uint64, node.width-1) node.parent = parent diff --git a/swarm/storage/pyramid.go b/swarm/storage/pyramid.go index 631ab52b86..5de385dcbe 100644 --- a/swarm/storage/pyramid.go +++ b/swarm/storage/pyramid.go @@ -123,7 +123,7 @@ type PyramidChunker struct { hashSize int64 branches int64 workerCount int64 - workerLock sync.RWMutex + workerLock sync.RWMutex } func NewPyramidChunker(params *ChunkerParams) (self *PyramidChunker) { @@ -327,7 +327,7 @@ func (self *PyramidChunker) loadTree(chunkLevel [][]*TreeEntry, key Key, chunkC // Add the root chunk entry branchCount := int64(len(chunk.SData)-8) / self.hashSize newEntry := &TreeEntry{ - level: int(depth - 1), + level: depth - 1, branchCount: branchCount, subtreeSize: uint64(chunk.Size), chunk: chunk.SData, @@ -352,7 +352,7 @@ func (self *PyramidChunker) loadTree(chunkLevel [][]*TreeEntry, key Key, chunkC } bewBranchCount := int64(len(newChunk.SData)-8) / self.hashSize newEntry := &TreeEntry{ - level: int(lvl - 1), + level: lvl - 1, branchCount: bewBranchCount, subtreeSize: uint64(newChunk.Size), chunk: newChunk.SData, @@ -634,4 +634,4 @@ func (self *PyramidChunker) enqueueDataChunk(chunkData []byte, size uint64, pare return pkey -} \ No newline at end of file +} diff --git a/tests/init.go b/tests/init.go index a2c633ad67..9e884efe39 100644 --- a/tests/init.go +++ b/tests/init.go @@ -25,26 +25,26 @@ import ( // This table defines supported forks and their chain config. var Forks = map[string]*params.ChainConfig{ - "Frontier": ¶ms.ChainConfig{ + "Frontier": { ChainId: big.NewInt(1), }, - "Homestead": ¶ms.ChainConfig{ + "Homestead": { ChainId: big.NewInt(1), HomesteadBlock: big.NewInt(0), }, - "EIP150": ¶ms.ChainConfig{ + "EIP150": { ChainId: big.NewInt(1), HomesteadBlock: big.NewInt(0), EIP150Block: big.NewInt(0), }, - "EIP158": ¶ms.ChainConfig{ + "EIP158": { ChainId: big.NewInt(1), HomesteadBlock: big.NewInt(0), EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), }, - "Byzantium": ¶ms.ChainConfig{ + "Byzantium": { ChainId: big.NewInt(1), HomesteadBlock: big.NewInt(0), EIP150Block: big.NewInt(0), @@ -53,22 +53,22 @@ var Forks = map[string]*params.ChainConfig{ DAOForkBlock: big.NewInt(0), ByzantiumBlock: big.NewInt(0), }, - "FrontierToHomesteadAt5": ¶ms.ChainConfig{ + "FrontierToHomesteadAt5": { ChainId: big.NewInt(1), HomesteadBlock: big.NewInt(5), }, - "HomesteadToEIP150At5": ¶ms.ChainConfig{ + "HomesteadToEIP150At5": { ChainId: big.NewInt(1), HomesteadBlock: big.NewInt(0), EIP150Block: big.NewInt(5), }, - "HomesteadToDaoAt5": ¶ms.ChainConfig{ + "HomesteadToDaoAt5": { ChainId: big.NewInt(1), HomesteadBlock: big.NewInt(0), DAOForkBlock: big.NewInt(5), DAOForkSupport: true, }, - "EIP158ToByzantiumAt5": ¶ms.ChainConfig{ + "EIP158ToByzantiumAt5": { ChainId: big.NewInt(1), HomesteadBlock: big.NewInt(0), EIP150Block: big.NewInt(0), diff --git a/tests/state_test_util.go b/tests/state_test_util.go index 64bf09cb42..352f840d9f 100644 --- a/tests/state_test_util.go +++ b/tests/state_test_util.go @@ -112,7 +112,7 @@ type stTransactionMarshaling struct { func (t *StateTest) Subtests() []StateSubtest { var sub []StateSubtest for fork, pss := range t.json.Post { - for i, _ := range pss { + for i := range pss { sub = append(sub, StateSubtest{fork, i}) } } diff --git a/whisper/whisperv5/topic.go b/whisper/whisperv5/topic.go index d1996c4604..c4ea67eefa 100644 --- a/whisper/whisperv5/topic.go +++ b/whisper/whisperv5/topic.go @@ -40,8 +40,8 @@ func BytesToTopic(b []byte) (t TopicType) { } // String converts a topic byte array to a string representation. -func (topic *TopicType) String() string { - return string(common.ToHex(topic[:])) +func (t *TopicType) String() string { + return common.ToHex(t[:]) } // MarshalText returns the hex representation of t. diff --git a/whisper/whisperv5/whisper.go b/whisper/whisperv5/whisper.go index d09246f699..85849ccce4 100644 --- a/whisper/whisperv5/whisper.go +++ b/whisper/whisperv5/whisper.go @@ -171,7 +171,7 @@ func (w *Whisper) SetMaxMessageSize(size uint32) error { if size > MaxMessageSize { return fmt.Errorf("message size too large [%d>%d]", size, MaxMessageSize) } - w.settings.Store(maxMsgSizeIdx, uint32(size)) + w.settings.Store(maxMsgSizeIdx, size) return nil } diff --git a/whisper/whisperv6/topic.go b/whisper/whisperv6/topic.go index 5ef7f69392..bf5da01e34 100644 --- a/whisper/whisperv6/topic.go +++ b/whisper/whisperv6/topic.go @@ -40,8 +40,8 @@ func BytesToTopic(b []byte) (t TopicType) { } // String converts a topic byte array to a string representation. -func (topic *TopicType) String() string { - return string(common.ToHex(topic[:])) +func (t *TopicType) String() string { + return common.ToHex(t[:]) } // MarshalText returns the hex representation of t. diff --git a/whisper/whisperv6/whisper.go b/whisper/whisperv6/whisper.go index 553ac3f000..e2b884f3d4 100644 --- a/whisper/whisperv6/whisper.go +++ b/whisper/whisperv6/whisper.go @@ -171,7 +171,7 @@ func (w *Whisper) SetMaxMessageSize(size uint32) error { if size > MaxMessageSize { return fmt.Errorf("message size too large [%d>%d]", size, MaxMessageSize) } - w.settings.Store(maxMsgSizeIdx, uint32(size)) + w.settings.Store(maxMsgSizeIdx, size) return nil }