all: fix ineffectual assignments and remove uses of crypto.Sha3

go get github.com/gordonklaus/ineffassign
ineffassign .
This commit is contained in:
Felix Lange 2017-01-09 11:16:06 +01:00
parent 0f34d506b5
commit b9b3efb09f
31 changed files with 109 additions and 104 deletions

View File

@ -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 {

View File

@ -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)
@ -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 {

View File

@ -22,6 +22,7 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/ethereum/go-ethereum/crypto"
@ -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:]
/*

View File

@ -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

View File

@ -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))
}

View File

@ -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

View File

@ -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")
}
@ -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)
}
@ -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 {
@ -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)
@ -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)
@ -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)
@ -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)

View File

@ -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)
)

View File

@ -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 {

View File

@ -88,12 +88,12 @@ 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)
@ -101,7 +101,7 @@ func TestRemoteNonceChange(t *testing.T) {
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)
}
}

View File

@ -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)
}

View File

@ -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 {

View File

@ -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
}

View File

@ -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 {
}
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":

View File

@ -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)

View File

@ -429,7 +429,7 @@ 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
}
@ -437,13 +437,13 @@ func (msg *authMsgV4) decodePlain(input []byte) {
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
}

View File

@ -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)
}

View File

@ -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 {
@ -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 {

View File

@ -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),

View File

@ -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:
@ -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()
}

View File

@ -130,6 +130,7 @@ func TestApiDirUploadModify(t *testing.T) {
content = readPath(t, "testdata", "test0", "index.css")
resp = testGet(t, api, bzzhash+"/index.css")
exp = expResponse(content, "text/css", 0)
checkResponse(t, resp, exp)
_, _, _, err = api.Get(bzzhash, true)
if err == nil {

View File

@ -58,9 +58,9 @@ func (n *testNode) LastActive() time.Time {
}
func TestOn(t *testing.T) {
addr, ok := gen(Address{}, quickrand).(Address)
other, ok := gen(Address{}, quickrand).(Address)
if !ok {
addr, ok1 := gen(Address{}, quickrand).(Address)
other, ok2 := gen(Address{}, quickrand).(Address)
if !ok1 || !ok2 {
t.Errorf("oops")
}
kad := New(addr, NewKadParams())

View File

@ -63,7 +63,7 @@ func newTestSyncDb(priority, bufferSize, batchSize int, dbdir string, t *testing
dbdir: dbdir,
t: t,
}
h := crypto.Sha3Hash([]byte{0})
h := crypto.Keccak256Hash([]byte{0})
key := storage.Key(h[:])
self.syncDb = newSyncDb(db, key, uint(priority), uint(bufferSize), uint(batchSize), self.deliver)
// kick off db iterator right away, if no items on db this will allow
@ -79,7 +79,7 @@ func (self *testSyncDb) close() {
func (self *testSyncDb) push(n int) {
for i := 0; i < n; i++ {
self.buffer <- storage.Key(crypto.Sha3([]byte{byte(self.c)}))
self.buffer <- storage.Key(crypto.Keccak256([]byte{byte(self.c)}))
self.sent = append(self.sent, self.c)
self.c++
}
@ -126,7 +126,7 @@ func (self *testSyncDb) expect(n int, db bool) {
if self.at+1 > len(self.delivered) {
self.t.Fatalf("expected %v, got %v", self.at+1, len(self.delivered))
}
if len(self.sent) > self.at && !bytes.Equal(crypto.Sha3([]byte{byte(self.sent[self.at])}), self.delivered[self.at]) {
if len(self.sent) > self.at && !bytes.Equal(crypto.Keccak256([]byte{byte(self.sent[self.at])}), self.delivered[self.at]) {
self.t.Fatalf("expected delivery %v/%v/%v to be hash of %v, from db: %v = %v", i, n, self.at, self.sent[self.at], ok, db)
glog.V(logger.Debug).Infof("%v/%v/%v to be hash of %v, from db: %v = %v", i, n, self.at, self.sent[self.at], ok, db)
}
@ -195,7 +195,7 @@ func TestSaveSyncDb(t *testing.T) {
go s.dbRead(false, 0, s.deliver)
s.expect(amount, true)
for i, key := range s.delivered {
expKey := crypto.Sha3([]byte{byte(i)})
expKey := crypto.Keccak256([]byte{byte(i)})
if !bytes.Equal(key, expKey) {
t.Fatalf("delivery %v expected to be key %x, got %x", i, expKey, key)
}
@ -204,7 +204,7 @@ func TestSaveSyncDb(t *testing.T) {
s.expect(amount, false)
for i := amount; i < 2*amount; i++ {
key := s.delivered[i]
expKey := crypto.Sha3([]byte{byte(i - amount)})
expKey := crypto.Keccak256([]byte{byte(i - amount)})
if !bytes.Equal(key, expKey) {
t.Fatalf("delivery %v expected to be key %x, got %x", i, expKey, key)
}

View File

@ -80,7 +80,7 @@ func testStore(m ChunkStore, l int64, branches int64, t *testing.T) {
Hash: defaultHash,
})
swg := &sync.WaitGroup{}
key, err := chunker.Split(rand.Reader, l, chunkC, swg, nil)
key, _ := chunker.Split(rand.Reader, l, chunkC, swg, nil)
swg.Wait()
close(chunkC)
chunkC = make(chan *Chunk)

View File

@ -144,7 +144,7 @@ func TestDbStoreSyncIterator(t *testing.T) {
t.Fatalf("unexpected error creating NewSyncIterator")
}
it, err = m.NewSyncIterator(DbSyncState{
it, _ = m.NewSyncIterator(DbSyncState{
Start: Key(common.Hex2Bytes("1000000000000000000000000000000000000000000000000000000000000000")),
Stop: Key(common.Hex2Bytes("4000000000000000000000000000000000000000000000000000000000000000")),
First: 2,
@ -168,7 +168,7 @@ func TestDbStoreSyncIterator(t *testing.T) {
t.Fatalf("Expected %v chunk, got %v", keys[3], res[1])
}
it, err = m.NewSyncIterator(DbSyncState{
it, _ = m.NewSyncIterator(DbSyncState{
Start: Key(common.Hex2Bytes("2000000000000000000000000000000000000000000000000000000000000000")),
Stop: Key(common.Hex2Bytes("4000000000000000000000000000000000000000000000000000000000000000")),
First: 2,

View File

@ -120,8 +120,7 @@ func TestDPA_capacity(t *testing.T) {
// check whether it is, indeed, empty
dpa.ChunkStore = memStore
resultReader = dpa.Retrieve(key)
n, err = resultReader.ReadAt(resultSlice, 0)
if err == nil {
if _, err = resultReader.ReadAt(resultSlice, 0); err == nil {
t.Errorf("Was able to read %d bytes from an empty memStore.", len(slice))
}
// check how it works with localStore

View File

@ -56,9 +56,11 @@ func TestEmptyTrie(t *testing.T) {
func TestNull(t *testing.T) {
var trie Trie
key := make([]byte, 32)
value := common.FromHex("0x823140710bf13990e4500136726d8b55")
value := []byte("test")
trie.Update(key, value)
value = trie.Get(key)
if !bytes.Equal(trie.Get(key), value) {
t.Fatal("wrong value")
}
}
func TestMissingRoot(t *testing.T) {

View File

@ -47,7 +47,7 @@ func TestEnvelopeOpen(t *testing.T) {
t.Fatalf("payload mismatch: have 0x%x, want 0x%x", opened.Payload, message.Payload)
}
if opened.Sent.Unix() != message.Sent.Unix() {
t.Fatalf("send time mismatch: have %d, want %d", opened.Sent, message.Sent)
t.Fatalf("send time mismatch: have %v, want %v", opened.Sent, message.Sent)
}
if opened.TTL/time.Second != DefaultTTL/time.Second {
t.Fatalf("message TTL mismatch: have %v, want %v", opened.TTL, DefaultTTL)

View File

@ -86,7 +86,7 @@ func (fs *Filters) NotifyWatchers(env *Envelope, p2pMessage bool) {
continue
}
match := false
var match bool
if msg != nil {
match = watcher.MatchMessage(msg)
} else {

View File

@ -77,10 +77,8 @@ func singleMessageTest(t *testing.T, symmetric bool) {
text := make([]byte, 0, 512)
steg := make([]byte, 0, 512)
raw := make([]byte, 0, 1024)
text = append(text, params.Payload...)
steg = append(steg, params.Padding...)
raw = append(raw, params.Padding...)
msg := NewSentMessage(params)
env, err := msg.Wrap(params)
@ -238,10 +236,8 @@ func singleEnvelopeOpenTest(t *testing.T, symmetric bool) {
text := make([]byte, 0, 512)
steg := make([]byte, 0, 512)
raw := make([]byte, 0, 1024)
text = append(text, params.Payload...)
steg = append(steg, params.Padding...)
raw = append(raw, params.Padding...)
msg := NewSentMessage(params)
env, err := msg.Wrap(params)

View File

@ -50,20 +50,17 @@ func TestWhisperBasic(t *testing.T) {
peerID := make([]byte, 64)
randomize(peerID)
peer, err := w.getPeer(peerID)
peer, _ := w.getPeer(peerID)
if peer != nil {
t.Fatalf("failed GetPeer.")
t.Fatal("found peer for random key.")
}
err = w.MarkPeerTrusted(peerID)
if err == nil {
if err := w.MarkPeerTrusted(peerID); err == nil {
t.Fatalf("failed MarkPeerTrusted.")
}
err = w.RequestHistoricMessages(peerID, peerID)
if err == nil {
if err := w.RequestHistoricMessages(peerID, peerID); err == nil {
t.Fatalf("failed RequestHistoricMessages.")
}
err = w.SendP2PMessage(peerID, nil)
if err == nil {
if err := w.SendP2PMessage(peerID, nil); err == nil {
t.Fatalf("failed SendP2PMessage.")
}
exist := w.HasSymKey("non-existing")
@ -85,11 +82,10 @@ func TestWhisperBasic(t *testing.T) {
var derived []byte
ver := uint64(0xDEADBEEF)
derived, err = deriveKeyMaterial(peerID, ver)
if err != unknownVersionError(ver) {
if _, err := deriveKeyMaterial(peerID, ver); err != unknownVersionError(ver) {
t.Fatalf("failed deriveKeyMaterial with param = %v: %s.", peerID, err)
}
derived, err = deriveKeyMaterial(peerID, 0)
derived, err := deriveKeyMaterial(peerID, 0)
if err != nil {
t.Fatalf("failed second deriveKeyMaterial with param = %v: %s.", peerID, err)
}