Skip to content

Commit

Permalink
all: fix ineffectual assignments and remove uses of crypto.Sha3
Browse files Browse the repository at this point in the history
go get github.com/gordonklaus/ineffassign
ineffassign .
  • Loading branch information
fjl committed Jan 9, 2017
1 parent 0f34d50 commit b9b3efb
Show file tree
Hide file tree
Showing 31 changed files with 108 additions and 103 deletions.
2 changes: 1 addition & 1 deletion accounts/abi/bind/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i
if value == nil {
value = new(big.Int)
}
nonce := uint64(0)
var nonce uint64
if opts.Nonce == nil {
nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
if err != nil {
Expand Down
6 changes: 6 additions & 0 deletions accounts/accounts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ func TestTimedUnlock(t *testing.T) {

pass := "foo"
a1, err := am.NewAccount(pass)
if err != nil {
t.Fatal(err)
}

// Signing without passphrase fails because account is locked
_, err = am.Sign(a1.Address, testSigData)
Expand Down Expand Up @@ -147,6 +150,9 @@ func TestOverrideUnlock(t *testing.T) {

pass := "foo"
a1, err := am.NewAccount(pass)
if err != nil {
t.Fatal(err)
}

// Unlock indefinitely.
if err = am.TimedUnlock(a1, pass, 5*time.Minute); err != nil {
Expand Down
4 changes: 4 additions & 0 deletions accounts/presale.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"

"github.com/ethereum/go-ethereum/crypto"
Expand Down Expand Up @@ -53,6 +54,9 @@ func decryptPreSaleKey(fileContent []byte, password string) (key *Key, err error
return nil, err
}
encSeedBytes, err := hex.DecodeString(preSaleKeyStruct.EncSeed)
if err != nil {
return nil, errors.New("invalid hex in encSeed")
}
iv := encSeedBytes[:16]
cipherText := encSeedBytes[16:]
/*
Expand Down
3 changes: 2 additions & 1 deletion cmd/geth/monitorcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,9 @@ func expandMetrics(metrics map[string]interface{}, path string) []string {

// fetchMetric iterates over the metrics map and retrieves a specific one.
func fetchMetric(metrics map[string]interface{}, metric string) float64 {
parts, found := strings.Split(metric, "/"), true
parts := strings.Split(metric, "/")
for _, part := range parts[:len(parts)-1] {
var found bool
metrics, found = metrics[part].(map[string]interface{})
if !found {
return 0
Expand Down
7 changes: 1 addition & 6 deletions cmd/utils/customflags.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,10 @@ type DirectoryFlag struct {
}

func (self DirectoryFlag) String() string {
var fmtString string
fmtString = "%s %v\t%v"

fmtString := "%s %v\t%v"
if len(self.Value.Value) > 0 {
fmtString = "%s \"%v\"\t%v"
} else {
fmtString = "%s %v\t%v"
}

return withEnvHint(self.EnvVar, fmt.Sprintf(fmtString, prefixedNames(self.Name), self.Value.Value, self.Usage))
}

Expand Down
4 changes: 2 additions & 2 deletions console/console.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,8 @@ func (c *Console) AutoCompleteInput(line string, pos int) (string, []string, str
}
// Chunck data to relevant part for autocompletion
// E.g. in case of nested lines eth.getBalance(eth.coinb<tab><tab>
start := 0
for start = pos - 1; start > 0; start-- {
start := pos - 1
for ; start > 0; start-- {
// Skip all methods and namespaces (i.e. including te dot)
if line[start] == '.' || (line[start] >= 'a' && line[start] <= 'z') || (line[start] >= 'A' && line[start] <= 'Z') {
continue
Expand Down
25 changes: 14 additions & 11 deletions contracts/chequebook/cheque_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ func TestIssueAndReceive(t *testing.T) {
}
chbook.sent[addr1] = new(big.Int).SetUint64(42)
amount := common.Big1
ch, err := chbook.Issue(addr1, amount)
if err == nil {

if _, err = chbook.Issue(addr1, amount); err == nil {
t.Fatalf("expected insufficient funds error, got none")
}

Expand All @@ -83,7 +83,7 @@ func TestIssueAndReceive(t *testing.T) {
t.Fatalf("expected: %v, got %v", "0", chbook.Balance())
}

ch, err = chbook.Issue(addr1, amount)
ch, err := chbook.Issue(addr1, amount)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
Expand Down Expand Up @@ -128,8 +128,8 @@ func TestCheckbookFile(t *testing.T) {
t.Errorf("expected: %v, got %v", "0", chbook.Balance())
}

ch, err := chbook.Issue(addr1, common.Big1)
if err != nil {
var ch *Cheque
if ch, err = chbook.Issue(addr1, common.Big1); err != nil {
t.Fatalf("expected no error, got %v", err)
}
if ch.Amount.Cmp(new(big.Int).SetUint64(43)) != 0 {
Expand All @@ -155,7 +155,7 @@ func TestVerifyErrors(t *testing.T) {
}

path1 := filepath.Join(os.TempDir(), "chequebook-test-1.json")
contr1, err := deploy(key1, common.Big2, backend)
contr1, _ := deploy(key1, common.Big2, backend)
chbook1, err := NewChequebook(path1, contr1, key1, backend)
if err != nil {
t.Errorf("expected no error, got %v", err)
Expand Down Expand Up @@ -223,7 +223,8 @@ func TestVerifyErrors(t *testing.T) {
func TestDeposit(t *testing.T) {
path0 := filepath.Join(os.TempDir(), "chequebook-test-0.json")
backend := newTestBackend()
contr0, err := deploy(key0, new(big.Int), backend)
contr0, _ := deploy(key0, new(big.Int), backend)

chbook, err := NewChequebook(path0, contr0, key0, backend)
if err != nil {
t.Errorf("expected no error, got %v", err)
Expand Down Expand Up @@ -361,7 +362,8 @@ func TestDeposit(t *testing.T) {
func TestCash(t *testing.T) {
path := filepath.Join(os.TempDir(), "chequebook-test.json")
backend := newTestBackend()
contr0, err := deploy(key0, common.Big2, backend)
contr0, _ := deploy(key0, common.Big2, backend)

chbook, err := NewChequebook(path, contr0, key0, backend)
if err != nil {
t.Errorf("expected no error, got %v", err)
Expand All @@ -380,11 +382,12 @@ func TestCash(t *testing.T) {
}

// cashing latest cheque
_, err = chbox.Receive(ch)
if err != nil {
if _, err = chbox.Receive(ch); err != nil {
t.Fatalf("expected no error, got %v", err)
}
_, err = ch.Cash(chbook.session)
if _, err = ch.Cash(chbook.session); err != nil {
t.Fatal("Cash failed:", err)
}
backend.Commit()

chbook.balance = new(big.Int).Set(common.Big3)
Expand Down
2 changes: 1 addition & 1 deletion contracts/ens/ens_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import (
var (
key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
name = "my name on ENS"
hash = crypto.Sha3Hash([]byte("my content"))
hash = crypto.Keccak256Hash([]byte("my content"))
addr = crypto.PubkeyToAddress(key.PublicKey)
)

Expand Down
3 changes: 1 addition & 2 deletions core/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -1054,11 +1054,10 @@ func (st *insertStats) report(chain []*types.Block, index int) {
start, end := chain[st.lastIndex], chain[index]
txcount := countTransactions(chain[st.lastIndex : index+1])

extra := ""
var hashes, extra string
if st.queued > 0 || st.ignored > 0 {
extra = fmt.Sprintf(" (%d queued %d ignored)", st.queued, st.ignored)
}
hashes := ""
if st.processed > 1 {
hashes = fmt.Sprintf("%x… / %x…", start.Hash().Bytes()[:4], end.Hash().Bytes()[:4])
} else {
Expand Down
8 changes: 4 additions & 4 deletions core/state/managed_state_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,20 +88,20 @@ func TestRemoteNonceChange(t *testing.T) {
nn[i] = true
}
account.nonces = append(account.nonces, nn...)
nonce := ms.NewNonce(addr)
ms.NewNonce(addr)

ms.StateDB.stateObjects[addr].data.Nonce = 200
nonce = ms.NewNonce(addr)
nonce := ms.NewNonce(addr)
if nonce != 200 {
t.Error("expected nonce after remote update to be", 201, "got", nonce)
t.Error("expected nonce after remote update to be", 200, "got", nonce)
}
ms.NewNonce(addr)
ms.NewNonce(addr)
ms.NewNonce(addr)
ms.StateDB.stateObjects[addr].data.Nonce = 200
nonce = ms.NewNonce(addr)
if nonce != 204 {
t.Error("expected nonce after remote update to be", 201, "got", nonce)
t.Error("expected nonce after remote update to be", 204, "got", nonce)
}
}

Expand Down
9 changes: 2 additions & 7 deletions crypto/secp256k1/secp256_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,17 +129,12 @@ func signAndRecoverWithRandomMessages(t *testing.T, keys func() ([]byte, []byte)
}

func TestRecoveryOfRandomSignature(t *testing.T) {
pubkey1, seckey := GenerateKeyPair()
pubkey1, _ := GenerateKeyPair()
msg := randentropy.GetEntropyCSPRNG(32)
sig, err := Sign(msg, seckey)
if err != nil {
t.Errorf("signature error: %s", err)
}

for i := 0; i < TestCount; i++ {
sig = randSig()
pubkey2, _ := RecoverPubkey(msg, sig)
// recovery can sometimes work, but if so should always give wrong pubkey
pubkey2, _ := RecoverPubkey(msg, randSig())
if bytes.Equal(pubkey1, pubkey2) {
t.Fatalf("iteration: %d: pubkey mismatch: do NOT want %x: ", i, pubkey2)
}
Expand Down
2 changes: 1 addition & 1 deletion eth/downloader/downloader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,7 @@ func assertOwnForkedChain(t *testing.T, tester *downloadTester, common int, leng
}
// Verify the state trie too for fast syncs
if tester.downloader.mode == FastSync {
index := 0
var index int
if pivot := int(tester.downloader.queue.fastSyncPivot); pivot < common {
index = pivot
} else {
Expand Down
3 changes: 1 addition & 2 deletions les/odr_requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,7 @@ func (self *CodeRequest) Valid(db ethdb.Database, msg *Msg) bool {
return false
}
data := reply[0]
hash := crypto.Sha3Hash(data)
if !bytes.Equal(self.Hash[:], hash[:]) {
if hash := crypto.Keccak256Hash(data); self.Hash != hash {
glog.V(logger.Debug).Infof("ODR: requested hash %08x does not match received data hash %08x", self.Hash[:4], hash[:4])
return false
}
Expand Down
15 changes: 8 additions & 7 deletions metrics/disk_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,16 @@ func ReadDiskStats(stats *DiskStats) error {
}
return err
}
key, value := "", int64(0)
if parts := strings.Split(line, ":"); len(parts) != 2 {
parts := strings.Split(line, ":")
if len(parts) != 2 {
continue
} else {
key = strings.TrimSpace(parts[0])
if value, err = strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 64); err != nil {
return err
}
}
key := strings.TrimSpace(parts[0])
value, err := strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 64)
if err != nil {
return err
}

// Update the counter based on the key
switch key {
case "syscr":
Expand Down
3 changes: 1 addition & 2 deletions node/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,7 @@ func TestNodeKeyPersistency(t *testing.T) {
if _, err := os.Stat(keyfile); err != nil {
t.Fatalf("node key not persisted to data directory: %v", err)
}
key, err = crypto.LoadECDSA(keyfile)
if err != nil {
if _, err = crypto.LoadECDSA(keyfile); err != nil {
t.Fatalf("failed to load freshly persisted node key: %v", err)
}
blob1, err := ioutil.ReadFile(keyfile)
Expand Down
6 changes: 3 additions & 3 deletions p2p/rlpx.go
Original file line number Diff line number Diff line change
Expand Up @@ -429,21 +429,21 @@ func (msg *authMsgV4) decodePlain(input []byte) {
n := copy(msg.Signature[:], input)
n += shaLen // skip sha3(initiator-ephemeral-pubk)
n += copy(msg.InitiatorPubkey[:], input[n:])
n += copy(msg.Nonce[:], input[n:])
copy(msg.Nonce[:], input[n:])
msg.Version = 4
msg.gotPlain = true
}

func (msg *authRespV4) sealPlain(hs *encHandshake) ([]byte, error) {
buf := make([]byte, authRespLen)
n := copy(buf, msg.RandomPubkey[:])
n += copy(buf[n:], msg.Nonce[:])
copy(buf[n:], msg.Nonce[:])
return ecies.Encrypt(rand.Reader, hs.remotePub, buf, nil, nil)
}

func (msg *authRespV4) decodePlain(input []byte) {
n := copy(msg.RandomPubkey[:], input)
n += copy(msg.Nonce[:], input[n:])
copy(msg.Nonce[:], input[n:])
msg.Version = 4
}

Expand Down
2 changes: 1 addition & 1 deletion rpc/subscription_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ func TestNotifications(t *testing.T) {
}

var ok bool
if subid, ok = response.Result.(string); !ok {
if _, ok = response.Result.(string); !ok {
t.Fatalf("expected subscription id, got %T", response.Result)
}

Expand Down
9 changes: 8 additions & 1 deletion swarm/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,11 @@ func (self *Api) Put(content, contentType string) (string, error) {
// to resolve path to content using dpa retrieve
// it returns a section reader, mimeType, status and an error
func (self *Api) Get(uri string, nameresolver bool) (reader storage.LazySectionReader, mimeType string, status int, err error) {

key, _, path, err := self.parseAndResolve(uri, nameresolver)
if err != nil {
return nil, "", 500, fmt.Errorf("can't resolve: %v", err)
}

quitC := make(chan bool)
trie, err := loadManifest(self.dpa, key, quitC)
if err != nil {
Expand All @@ -166,6 +169,10 @@ func (self *Api) Get(uri string, nameresolver bool) (reader storage.LazySectionR

func (self *Api) Modify(uri, contentHash, contentType string, nameresolver bool) (newRootHash string, err error) {
root, _, path, err := self.parseAndResolve(uri, nameresolver)
if err != nil {
return "", fmt.Errorf("can't resolve: %v", err)
}

quitC := make(chan bool)
trie, err := loadManifest(self.dpa, root, quitC)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion swarm/api/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func NewConfig(path string, contract common.Address, prvKey *ecdsa.PrivateKey, n
var data []byte
pubkey := crypto.FromECDSAPub(&prvKey.PublicKey)
pubkeyhex := common.ToHex(pubkey)
keyhex := crypto.Sha3Hash(pubkey).Hex()
keyhex := crypto.Keccak256Hash(pubkey).Hex()

self = &Config{
SyncParams: network.NewSyncParams(dirpath),
Expand Down
38 changes: 20 additions & 18 deletions swarm/api/filesystem.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,24 +241,7 @@ func (self *FileSystem) Download(bzzpath, localpath string) error {
}
go func(i int, entry *downloadListEntry) {
defer wg.Done()
f, err := os.Create(entry.path) // TODO: path separators
if err == nil {

reader := self.api.dpa.Retrieve(entry.key)
writer := bufio.NewWriter(f)
size, err := reader.Size(quitC)
if err == nil {
_, err = io.CopyN(writer, reader, size) // TODO: handle errors
err2 := writer.Flush()
if err == nil {
err = err2
}
err2 = f.Close()
if err == nil {
err = err2
}
}
}
err := retrieveToFile(quitC, self.api.dpa, entry.key, entry.path)
if err != nil {
select {
case errC <- err:
Expand All @@ -279,5 +262,24 @@ func (self *FileSystem) Download(bzzpath, localpath string) error {
case <-quitC:
return fmt.Errorf("aborted")
}
}

func retrieveToFile(quitC chan bool, dpa *storage.DPA, key storage.Key, path string) error {
f, err := os.Create(path) // TODO: path separators
if err != nil {
return err
}
reader := dpa.Retrieve(key)
writer := bufio.NewWriter(f)
size, err := reader.Size(quitC)
if err != nil {
return err
}
if _, err = io.CopyN(writer, reader, size); err != nil {
return err
}
if err := writer.Flush(); err != nil {
return err
}
return f.Close()
}
Loading

0 comments on commit b9b3efb

Please sign in to comment.