From 915fa6639b092c3d92e351cde47769b5c85fbc1c Mon Sep 17 00:00:00 2001 From: Dave Collins Date: Wed, 2 Nov 2016 23:02:04 -0500 Subject: [PATCH] multi: Simplify code per gosimple linter. This simplifies the code based on the recommendations of the gosimple lint tool. --- addrmgr/addrmanager_test.go | 4 +- blockchain/chain.go | 11 ++-- blockchain/chain_test.go | 10 +--- blockchain/indexers/manager.go | 5 +- blockchain/reorganization_test.go | 4 +- blockchain/scriptval.go | 12 +---- btcjson/help.go | 4 +- database/cmd/dbtool/fetchblock.go | 2 +- database/cmd/dbtool/fetchblockregion.go | 2 +- database/cmd/dbtool/insecureimport.go | 10 +--- database/cmd/dbtool/loadheaders.go | 16 ++---- database/ffldb/bench_test.go | 10 +--- database/ffldb/dbcache.go | 8 +-- database/ffldb/interface_test.go | 42 ++++----------- database/internal/treap/immutable_test.go | 15 +++--- database/internal/treap/mutable_test.go | 15 +++--- mempool/mempool.go | 6 +-- peer/log.go | 2 +- peer/peer.go | 4 +- rpcserver.go | 19 +++---- rpctest/rpc_harness.go | 13 ++--- server.go | 2 +- service_windows.go | 14 +---- txscript/engine.go | 4 +- txscript/opcode.go | 12 ++--- txscript/stack_test.go | 64 ++++++----------------- upgrade.go | 7 +-- upnp.go | 2 +- wire/blockheader.go | 14 +---- wire/common.go | 12 ++--- wire/invvect.go | 12 +---- wire/message.go | 6 +-- wire/msgalert.go | 23 ++------ wire/msgfeefilter.go | 14 +---- wire/msgfilteradd.go | 13 +---- wire/msgfilterload.go | 7 +-- wire/msggetblocks.go | 14 +---- wire/msggetheaders.go | 14 +---- wire/msgmerkleblock.go | 13 +---- wire/msgpong.go | 14 +---- wire/msgtx.go | 45 +++------------- wire/msgversion_test.go | 2 +- wire/netaddress.go | 12 +---- 43 files changed, 122 insertions(+), 412 deletions(-) diff --git a/addrmgr/addrmanager_test.go b/addrmgr/addrmanager_test.go index 3442d360..c3e5d7b0 100644 --- a/addrmgr/addrmanager_test.go +++ b/addrmgr/addrmanager_test.go @@ -258,7 +258,7 @@ func TestNeedMoreAddresses(t *testing.T) { n := addrmgr.New("testneedmoreaddresses", lookupFunc) addrsToAdd := 1500 b := n.NeedMoreAddresses() - if b == false { + if !b { t.Errorf("Expected that we need more addresses") } addrs := make([]*wire.NetAddress, addrsToAdd) @@ -287,7 +287,7 @@ func TestNeedMoreAddresses(t *testing.T) { } b = n.NeedMoreAddresses() - if b == true { + if b { t.Errorf("Expected that we don't need more addresses") } } diff --git a/blockchain/chain.go b/blockchain/chain.go index 757188a1..be4d006d 100644 --- a/blockchain/chain.go +++ b/blockchain/chain.go @@ -1527,14 +1527,11 @@ func (b *BlockChain) IsCurrent() bool { // Not current if the latest best block has a timestamp before 24 hours // ago. - minus24Hours := b.timeSource.AdjustedTime().Add(-24 * time.Hour) - if b.bestNode.timestamp.Before(minus24Hours) { - return false - } - - // The chain appears to be current if the above checks did not report + // + // The chain appears to be current if none of the checks reported // otherwise. - return true + minus24Hours := b.timeSource.AdjustedTime().Add(-24 * time.Hour) + return !b.bestNode.timestamp.Before(minus24Hours) } // BestSnapshot returns information about the current best chain block and diff --git a/blockchain/chain_test.go b/blockchain/chain_test.go index e8ffa186..f92d3952 100644 --- a/blockchain/chain_test.go +++ b/blockchain/chain_test.go @@ -31,9 +31,7 @@ func TestHaveBlock(t *testing.T) { t.Errorf("Error loading file: %v\n", err) return } - for _, block := range blockTmp { - blocks = append(blocks, block) - } + blocks = append(blocks, blockTmp...) } // Create a new database and chain instance to run tests against. @@ -119,15 +117,11 @@ func TestHaveBlock(t *testing.T) { // the returned SequenceLocks are correct for each test instance. func TestCalcSequenceLock(t *testing.T) { fileName := "blk_0_to_4.dat.bz2" - blockTmp, err := loadBlocks(fileName) + blocks, err := loadBlocks(fileName) if err != nil { t.Errorf("Error loading file: %v\n", err) return } - var blocks []*btcutil.Block - for _, block := range blockTmp { - blocks = append(blocks, block) - } // Create a new database and chain instance to run tests against. chain, teardownFunc, err := chainSetup("haveblock", &chaincfg.MainNetParams) diff --git a/blockchain/indexers/manager.go b/blockchain/indexers/manager.go index 5662c30f..da0ef38f 100644 --- a/blockchain/indexers/manager.go +++ b/blockchain/indexers/manager.go @@ -271,10 +271,7 @@ func (m *Manager) Init(chain *blockchain.BlockChain) error { err := m.db.View(func(dbTx database.Tx) error { idxKey := indexer.Key() hash, height, err = dbFetchIndexerTip(dbTx, idxKey) - if err != nil { - return err - } - return nil + return err }) if err != nil { return err diff --git a/blockchain/reorganization_test.go b/blockchain/reorganization_test.go index b3f8c566..bb71fa5a 100644 --- a/blockchain/reorganization_test.go +++ b/blockchain/reorganization_test.go @@ -39,9 +39,7 @@ func TestReorganization(t *testing.T) { if err != nil { t.Errorf("Error loading file: %v\n", err) } - for _, block := range blockTmp { - blocks = append(blocks, block) - } + blocks = append(blocks, blockTmp...) } t.Logf("Number of blocks: %v\n", len(blocks)) diff --git a/blockchain/scriptval.go b/blockchain/scriptval.go index fc8b8bc2..3310646e 100644 --- a/blockchain/scriptval.go +++ b/blockchain/scriptval.go @@ -213,11 +213,7 @@ func ValidateTransactionScripts(tx *btcutil.Tx, utxoView *UtxoViewpoint, flags t // Validate all of the inputs. validator := newTxValidator(utxoView, flags, sigCache) - if err := validator.Validate(txValItems); err != nil { - return err - } - - return nil + return validator.Validate(txValItems) } // checkBlockScripts executes and validates the scripts for all transactions in @@ -248,9 +244,5 @@ func checkBlockScripts(block *btcutil.Block, utxoView *UtxoViewpoint, scriptFlag // Validate all of the inputs. validator := newTxValidator(utxoView, scriptFlags, sigCache) - if err := validator.Validate(txValItems); err != nil { - return err - } - - return nil + return validator.Validate(txValItems) } diff --git a/btcjson/help.go b/btcjson/help.go index 113960fd..c23e6b81 100644 --- a/btcjson/help.go +++ b/btcjson/help.go @@ -122,9 +122,7 @@ func resultStructHelp(xT descLookupFunc, rt reflect.Type, indentLevel int) []str result := fmt.Sprintf("%s\"%s\": %s\t(%s)\t%s", indent, fieldName, brace, fieldType, xT(fieldDescKey)) results = append(results, result) - for _, example := range fieldExamples { - results = append(results, example) - } + results = append(results, fieldExamples...) } else { result := fmt.Sprintf("%s\"%s\": %s,\t(%s)\t%s", indent, fieldName, fieldExamples[0], fieldType, diff --git a/database/cmd/dbtool/fetchblock.go b/database/cmd/dbtool/fetchblock.go index 8b9c0eee..75a3e31a 100644 --- a/database/cmd/dbtool/fetchblock.go +++ b/database/cmd/dbtool/fetchblock.go @@ -50,7 +50,7 @@ func (cmd *fetchBlockCmd) Execute(args []string) error { if err != nil { return err } - log.Infof("Loaded block in %v", time.Now().Sub(startTime)) + log.Infof("Loaded block in %v", time.Since(startTime)) log.Infof("Block Hex: %s", hex.EncodeToString(blockBytes)) return nil }) diff --git a/database/cmd/dbtool/fetchblockregion.go b/database/cmd/dbtool/fetchblockregion.go index 7a7e5923..9d63ed17 100644 --- a/database/cmd/dbtool/fetchblockregion.go +++ b/database/cmd/dbtool/fetchblockregion.go @@ -77,7 +77,7 @@ func (cmd *blockRegionCmd) Execute(args []string) error { if err != nil { return err } - log.Infof("Loaded block region in %v", time.Now().Sub(startTime)) + log.Infof("Loaded block region in %v", time.Since(startTime)) log.Infof("Double Hash: %s", chainhash.DoubleHashH(regionBytes)) log.Infof("Region Hex: %s", hex.EncodeToString(regionBytes)) return nil diff --git a/database/cmd/dbtool/insecureimport.go b/database/cmd/dbtool/insecureimport.go index a4866b9c..7564eb68 100644 --- a/database/cmd/dbtool/insecureimport.go +++ b/database/cmd/dbtool/insecureimport.go @@ -121,10 +121,7 @@ func (bi *blockImporter) processBlock(serializedBlock []byte) (bool, error) { var exists bool err = bi.db.View(func(tx database.Tx) error { exists, err = tx.HasBlock(block.Hash()) - if err != nil { - return err - } - return nil + return err }) if err != nil { return false, err @@ -139,10 +136,7 @@ func (bi *blockImporter) processBlock(serializedBlock []byte) (bool, error) { var exists bool err := bi.db.View(func(tx database.Tx) error { exists, err = tx.HasBlock(prevHash) - if err != nil { - return err - } - return nil + return err }) if err != nil { return false, err diff --git a/database/cmd/dbtool/loadheaders.go b/database/cmd/dbtool/loadheaders.go index 9246fff1..a3ee8c73 100644 --- a/database/cmd/dbtool/loadheaders.go +++ b/database/cmd/dbtool/loadheaders.go @@ -62,14 +62,10 @@ func (cmd *headersCmd) Execute(args []string) error { return nil }) log.Infof("Loaded %d headers in %v", numLoaded, - time.Now().Sub(startTime)) + time.Since(startTime)) return nil }) - if err != nil { - return err - } - - return nil + return err } // Bulk load headers. @@ -90,12 +86,8 @@ func (cmd *headersCmd) Execute(args []string) error { return err } log.Infof("Loaded %d headers in %v", len(hdrs), - time.Now().Sub(startTime)) + time.Since(startTime)) return nil }) - if err != nil { - return err - } - - return nil + return err } diff --git a/database/ffldb/bench_test.go b/database/ffldb/bench_test.go index deb7b700..8d020313 100644 --- a/database/ffldb/bench_test.go +++ b/database/ffldb/bench_test.go @@ -29,10 +29,7 @@ func BenchmarkBlockHeader(b *testing.B) { defer db.Close() err = db.Update(func(tx database.Tx) error { block := btcutil.NewBlock(chaincfg.MainNetParams.GenesisBlock) - if err := tx.StoreBlock(block); err != nil { - return err - } - return nil + return tx.StoreBlock(block) }) if err != nil { b.Fatal(err) @@ -73,10 +70,7 @@ func BenchmarkBlock(b *testing.B) { defer db.Close() err = db.Update(func(tx database.Tx) error { block := btcutil.NewBlock(chaincfg.MainNetParams.GenesisBlock) - if err := tx.StoreBlock(block); err != nil { - return err - } - return nil + return tx.StoreBlock(block) }) if err != nil { b.Fatal(err) diff --git a/database/ffldb/dbcache.go b/database/ffldb/dbcache.go index 7068434f..a2346b58 100644 --- a/database/ffldb/dbcache.go +++ b/database/ffldb/dbcache.go @@ -533,7 +533,7 @@ func (c *dbCache) flush() error { func (c *dbCache) needsFlush(tx *transaction) bool { // A flush is needed when more time has elapsed than the configured // flush interval. - if time.Now().Sub(c.lastFlush) > c.flushInterval { + if time.Since(c.lastFlush) > c.flushInterval { return true } @@ -545,11 +545,7 @@ func (c *dbCache) needsFlush(tx *transaction) bool { snap := tx.snapshot totalSize := snap.pendingKeys.Size() + snap.pendingRemove.Size() totalSize = uint64(float64(totalSize) * 1.5) - if totalSize > c.maxSize { - return true - } - - return false + return totalSize > c.maxSize } // commitTx atomically adds all of the pending keys to add and remove into the diff --git a/database/ffldb/interface_test.go b/database/ffldb/interface_test.go index ef1a7d16..4989913d 100644 --- a/database/ffldb/interface_test.go +++ b/database/ffldb/interface_test.go @@ -395,11 +395,7 @@ func testNestedBucket(tc *testContext, testBucket database.Bucket) bool { defer func() { tc.bucketDepth-- }() - if !testBucketInterface(tc, testBucket) { - return false - } - - return true + return testBucketInterface(tc, testBucket) } // testBucketInterface ensures the bucket interface is working properly by @@ -1504,11 +1500,7 @@ func testFetchBlockIO(tc *testContext, tx database.Tx) bool { } wantErrCode = database.ErrBlockRegionInvalid _, err = tx.FetchBlockRegions(badBlockRegions) - if !checkDbError(tc.t, testName, err, wantErrCode) { - return false - } - - return true + return checkDbError(tc.t, testName, err, wantErrCode) } // testBlockIOTxInterface ensures that the block IO interface works as expected @@ -1942,11 +1934,7 @@ func testClosedTxInterface(tc *testContext, tx database.Tx) bool { return false } err = tx.Commit() - if !checkDbError(tc.t, "closed tx commit", err, wantErrCode) { - return false - } - - return true + return checkDbError(tc.t, "closed tx commit", err, wantErrCode) } // testTxClosed ensures that both the metadata and block IO API functions behave @@ -2016,16 +2004,13 @@ func testConcurrecy(tc *testContext) bool { startTime := time.Now() err := tc.db.View(func(tx database.Tx) error { _, err := tx.FetchBlock(tc.blocks[0].Hash()) - if err != nil { - return err - } - return nil + return err }) if err != nil { tc.t.Errorf("Unexpected error in view: %v", err) return false } - elapsed := time.Now().Sub(startTime) + elapsed := time.Since(startTime) if sleepTime < elapsed { sleepTime = elapsed } @@ -2041,10 +2026,7 @@ func testConcurrecy(tc *testContext) bool { err := tc.db.View(func(tx database.Tx) error { time.Sleep(sleepTime) _, err := tx.FetchBlock(tc.blocks[blockNum].Hash()) - if err != nil { - return err - } - return nil + return err }) if err != nil { tc.t.Errorf("Unexpected error in concurrent view: %v", @@ -2065,7 +2047,7 @@ func testConcurrecy(tc *testContext) bool { return false } } - elapsed = time.Now().Sub(startTime) + elapsed = time.Since(startTime) tc.t.Logf("%d concurrent reads of same block elapsed: %v", numReaders, elapsed) @@ -2088,7 +2070,7 @@ func testConcurrecy(tc *testContext) bool { return false } } - elapsed = time.Now().Sub(startTime) + elapsed = time.Since(startTime) tc.t.Logf("%d concurrent reads of different blocks elapsed: %v", numReaders, elapsed) @@ -2142,11 +2124,7 @@ func testConcurrecy(tc *testContext) bool { // Set some data the readers are expecting to not find and signal the // readers the write is done by closing the writeComplete channel. err = tc.db.Update(func(tx database.Tx) error { - err := tx.Metadata().Put(concurrentKey, concurrentVal) - if err != nil { - return err - } - return nil + return tx.Metadata().Put(concurrentKey, concurrentVal) }) if err != nil { tc.t.Errorf("Unexpected error in update: %v", err) @@ -2187,7 +2165,7 @@ func testConcurrecy(tc *testContext) bool { return false } } - elapsed = time.Now().Sub(startTime) + elapsed = time.Since(startTime) tc.t.Logf("%d concurrent writers elapsed using sleep time %v: %v", numWriters, writeSleepTime, elapsed) diff --git a/database/internal/treap/immutable_test.go b/database/internal/treap/immutable_test.go index 176a2c46..e8952c38 100644 --- a/database/internal/treap/immutable_test.go +++ b/database/internal/treap/immutable_test.go @@ -29,7 +29,7 @@ func TestImmutableEmpty(t *testing.T) { // Ensure there are no errors with requesting keys from an empty treap. key := serializeUint32(0) - if gotVal := testTreap.Has(key); gotVal != false { + if gotVal := testTreap.Has(key); gotVal { t.Fatalf("Has: unexpected result - got %v, want false", gotVal) } if gotVal := testTreap.Get(key); gotVal != nil { @@ -348,8 +348,8 @@ func TestImmutableDuplicatePut(t *testing.T) { testTreap = testTreap.Put(key, expectedVal) // Ensure the key still exists and is the new value. - if gotVal := testTreap.Has(key); gotVal != true { - t.Fatalf("Has: unexpected result - got %v, want false", + if gotVal := testTreap.Has(key); !gotVal { + t.Fatalf("Has: unexpected result - got %v, want true", gotVal) } if gotVal := testTreap.Get(key); !bytes.Equal(gotVal, expectedVal) { @@ -379,8 +379,8 @@ func TestImmutableNilValue(t *testing.T) { testTreap = testTreap.Put(key, nil) // Ensure the key exists and is an empty byte slice. - if gotVal := testTreap.Has(key); gotVal != true { - t.Fatalf("Has: unexpected result - got %v, want false", gotVal) + if gotVal := testTreap.Has(key); !gotVal { + t.Fatalf("Has: unexpected result - got %v, want true", gotVal) } if gotVal := testTreap.Get(key); gotVal == nil { t.Fatalf("Get: unexpected result - got nil, want empty slice") @@ -408,10 +408,7 @@ func TestImmutableForEachStopIterator(t *testing.T) { var numIterated int testTreap.ForEach(func(k, v []byte) bool { numIterated++ - if numIterated == numItems/2 { - return false - } - return true + return numIterated != numItems/2 }) if numIterated != numItems/2 { t.Fatalf("ForEach: unexpected iterate count - got %d, want %d", diff --git a/database/internal/treap/mutable_test.go b/database/internal/treap/mutable_test.go index c22ced0e..ff479ec5 100644 --- a/database/internal/treap/mutable_test.go +++ b/database/internal/treap/mutable_test.go @@ -29,7 +29,7 @@ func TestMutableEmpty(t *testing.T) { // Ensure there are no errors with requesting keys from an empty treap. key := serializeUint32(0) - if gotVal := testTreap.Has(key); gotVal != false { + if gotVal := testTreap.Has(key); gotVal { t.Fatalf("Has: unexpected result - got %v, want false", gotVal) } if gotVal := testTreap.Get(key); gotVal != nil { @@ -400,8 +400,8 @@ func TestMutableDuplicatePut(t *testing.T) { testTreap.Put(key, val) // Ensure the key still exists and is the new value. - if gotVal := testTreap.Has(key); gotVal != true { - t.Fatalf("Has: unexpected result - got %v, want false", gotVal) + if gotVal := testTreap.Has(key); !gotVal { + t.Fatalf("Has: unexpected result - got %v, want true", gotVal) } if gotVal := testTreap.Get(key); !bytes.Equal(gotVal, val) { t.Fatalf("Get: unexpected result - got %x, want %x", gotVal, val) @@ -427,8 +427,8 @@ func TestMutableNilValue(t *testing.T) { testTreap.Put(key, nil) // Ensure the key exists and is an empty byte slice. - if gotVal := testTreap.Has(key); gotVal != true { - t.Fatalf("Has: unexpected result - got %v, want false", gotVal) + if gotVal := testTreap.Has(key); !gotVal { + t.Fatalf("Has: unexpected result - got %v, want true", gotVal) } if gotVal := testTreap.Get(key); gotVal == nil { t.Fatalf("Get: unexpected result - got nil, want empty slice") @@ -456,10 +456,7 @@ func TestMutableForEachStopIterator(t *testing.T) { var numIterated int testTreap.ForEach(func(k, v []byte) bool { numIterated++ - if numIterated == numItems/2 { - return false - } - return true + return numIterated != numItems/2 }) if numIterated != numItems/2 { t.Fatalf("ForEach: unexpected iterate count - got %d, want %d", diff --git a/mempool/mempool.go b/mempool/mempool.go index 7f47e0a2..c669cb35 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -1055,11 +1055,7 @@ func (mp *TxPool) ProcessTransaction(tx *btcutil.Tx, allowOrphan, rateLimit bool // Potentially add the orphan transaction to the orphan pool. err = mp.maybeAddOrphan(tx, tag) - if err != nil { - return nil, err - } - - return nil, nil + return nil, err } // Count returns the number of transactions in the main pool. It does not diff --git a/peer/log.go b/peer/log.go index a62dea01..e37a0bf1 100644 --- a/peer/log.go +++ b/peer/log.go @@ -151,7 +151,7 @@ func sanitizeString(str string, maxLength uint) string { // Strip any characters not in the safeChars string removed. str = strings.Map(func(r rune) rune { - if strings.IndexRune(safeChars, r) >= 0 { + if strings.ContainsRune(safeChars, r) { return r } return -1 diff --git a/peer/peer.go b/peer/peer.go index 2b08bcab..4beddf05 100644 --- a/peer/peer.go +++ b/peer/peer.go @@ -1073,7 +1073,7 @@ func (p *Peer) handlePongMsg(msg *wire.MsgPong) { if p.ProtocolVersion() > wire.BIP0031Version { p.statsMtx.Lock() if p.lastPingNonce != 0 && msg.Nonce == p.lastPingNonce { - p.lastPingMicros = time.Now().Sub(p.lastPingTime).Nanoseconds() + p.lastPingMicros = time.Since(p.lastPingTime).Nanoseconds() p.lastPingMicros /= 1000 // convert to usec. p.lastPingNonce = 0 } @@ -1322,7 +1322,7 @@ out: // Extend active deadlines by the time it took // to execute the callback. - duration := time.Now().Sub(handlersStartTime) + duration := time.Since(handlersStartTime) deadlineOffset += duration handlerActive = false diff --git a/rpcserver.go b/rpcserver.go index a14e595e..c039c7a8 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -2232,7 +2232,7 @@ func handleGetPeerInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) SyncNode: p == syncPeer, } if p.LastPingNonce() != 0 { - wait := float64(time.Now().Sub(statsSnap.LastPingTime).Nanoseconds()) + wait := float64(time.Since(statsSnap.LastPingTime).Nanoseconds()) // We actually want microseconds. info.PingWait = wait / 1000 } @@ -3740,11 +3740,7 @@ func (s *rpcServer) writeHTTPResponseHeaders(req *http.Request, headers http.Hea } _, err = io.WriteString(w, "\r\n") - if err != nil { - return err - } - - return nil + return err } // Stop is used by server.go to stop the rpc listener. @@ -3945,10 +3941,9 @@ func (s *rpcServer) jsonRPCRead(w http.ResponseWriter, r *http.Request, isAdmin body, err := ioutil.ReadAll(r.Body) r.Body.Close() if err != nil { - errMsg := fmt.Sprintf("error reading JSON message: %v", err) errCode := http.StatusBadRequest - http.Error(w, strconv.FormatInt(int64(errCode), 10)+" "+errMsg, - errCode) + http.Error(w, fmt.Sprintf("%d error reading JSON message: %v", + errCode, err), errCode) return } @@ -3963,16 +3958,14 @@ func (s *rpcServer) jsonRPCRead(w http.ResponseWriter, r *http.Request, isAdmin errMsg := "webserver doesn't support hijacking" rpcsLog.Warnf(errMsg) errCode := http.StatusInternalServerError - http.Error(w, strconv.FormatInt(int64(errCode), 10)+" "+errMsg, - errCode) + http.Error(w, strconv.Itoa(errCode)+" "+errMsg, errCode) return } conn, buf, err := hj.Hijack() if err != nil { rpcsLog.Warnf("Failed to hijack HTTP connection: %v", err) errCode := http.StatusInternalServerError - http.Error(w, strconv.FormatInt(int64(errCode), 10)+" "+ - err.Error(), errCode) + http.Error(w, strconv.Itoa(errCode)+" "+err.Error(), errCode) return } defer conn.Close() diff --git a/rpctest/rpc_harness.go b/rpctest/rpc_harness.go index b89e4351..26074da2 100644 --- a/rpctest/rpc_harness.go +++ b/rpctest/rpc_harness.go @@ -240,16 +240,13 @@ func (h *Harness) SetUp(createTestChain bool, numMatureOutputs uint32) error { return err } ticker := time.NewTicker(time.Millisecond * 100) -out: - for { - select { - case <-ticker.C: - walletHeight := h.wallet.SyncedHeight() - if walletHeight == height { - break out - } + for range ticker.C { + walletHeight := h.wallet.SyncedHeight() + if walletHeight == height { + break } } + ticker.Stop() return nil } diff --git a/server.go b/server.go index 951b473f..82c1ee0b 100644 --- a/server.go +++ b/server.go @@ -2424,7 +2424,7 @@ func newServer(listenAddrs []string, db database.DB, chainParams *chaincfg.Param // only allow recent nodes (10mins) after we failed 30 // times - if tries < 30 && time.Now().Sub(addr.LastAttempt()) < 10*time.Minute { + if tries < 30 && time.Since(addr.LastAttempt()) < 10*time.Minute { continue } diff --git a/service_windows.go b/service_windows.go index be642ad5..8101ae65 100644 --- a/service_windows.go +++ b/service_windows.go @@ -156,12 +156,7 @@ func installService() error { // messges instead of needing to create our own message catalog. eventlog.Remove(svcName) eventsSupported := uint32(eventlog.Error | eventlog.Warning | eventlog.Info) - err = eventlog.InstallAsEventCreate(svcName, eventsSupported) - if err != nil { - return err - } - - return nil + return eventlog.InstallAsEventCreate(svcName, eventsSupported) } // removeService attempts to uninstall the btcd service. Typically this should @@ -184,12 +179,7 @@ func removeService() error { defer service.Close() // Remove the service. - err = service.Delete() - if err != nil { - return err - } - - return nil + return service.Delete() } // startService attempts to start the btcd service. diff --git a/txscript/engine.go b/txscript/engine.go index fc9a8269..6c54ea9d 100644 --- a/txscript/engine.go +++ b/txscript/engine.go @@ -241,7 +241,7 @@ func (vm *Engine) CheckErrorCondition(finalScript bool) error { if err != nil { return err } - if v == false { + if !v { // Log interesting data. log.Tracef("%v", newLogClosure(func() string { dis0, _ := vm.DisasmScript(0) @@ -337,7 +337,7 @@ func (vm *Engine) Step() (done bool, err error) { // for successful validation or an error if one occurred. func (vm *Engine) Execute() (err error) { done := false - for done != true { + for !done { log.Tracef("%v", newLogClosure(func() string { dis, err := vm.DisasmPC() if err != nil { diff --git a/txscript/opcode.go b/txscript/opcode.go index 145e7b77..0d72b663 100644 --- a/txscript/opcode.go +++ b/txscript/opcode.go @@ -998,7 +998,7 @@ func opcodeVerify(op *parsedOpcode, vm *Engine) error { return err } - if verified != true { + if !verified { return ErrStackVerifyFailed } return nil @@ -1169,14 +1169,8 @@ func opcodeCheckSequenceVerify(op *parsedOpcode, vm *Engine) error { // Mask off non-consensus bits before doing comparisons. lockTimeMask := int64(wire.SequenceLockTimeIsSeconds | wire.SequenceLockTimeMask) - err = verifyLockTime(txSequence&lockTimeMask, - wire.SequenceLockTimeIsSeconds, - sequence&lockTimeMask) - if err != nil { - return err - } - - return nil + return verifyLockTime(txSequence&lockTimeMask, + wire.SequenceLockTimeIsSeconds, sequence&lockTimeMask) } // opcodeToAltStack removes the top item from the main data stack and pushes it diff --git a/txscript/stack_test.go b/txscript/stack_test.go index 03c65d02..80a02b21 100644 --- a/txscript/stack_test.go +++ b/txscript/stack_test.go @@ -116,7 +116,7 @@ func TestStack(t *testing.T) { return err } - if val != false { + if val { return errors.New("unexpected value") } return nil @@ -133,7 +133,7 @@ func TestStack(t *testing.T) { return err } - if val != true { + if !val { return errors.New("unexpected value") } return nil @@ -146,11 +146,7 @@ func TestStack(t *testing.T) { nil, func(s *stack) error { _, err := s.PopBool() - if err != nil { - return err - } - - return nil + return err }, ErrStackUnderflow, nil, @@ -345,12 +341,7 @@ func TestStack(t *testing.T) { "dup", [][]byte{{1}}, func(s *stack) error { - err := s.DupN(1) - if err != nil { - return err - } - - return nil + return s.DupN(1) }, nil, [][]byte{{1}, {1}}, @@ -359,12 +350,7 @@ func TestStack(t *testing.T) { "dup2", [][]byte{{1}, {2}}, func(s *stack) error { - err := s.DupN(2) - if err != nil { - return err - } - - return nil + return s.DupN(2) }, nil, [][]byte{{1}, {2}, {1}, {2}}, @@ -373,12 +359,7 @@ func TestStack(t *testing.T) { "dup3", [][]byte{{1}, {2}, {3}}, func(s *stack) error { - err := s.DupN(3) - if err != nil { - return err - } - - return nil + return s.DupN(3) }, nil, [][]byte{{1}, {2}, {3}, {1}, {2}, {3}}, @@ -387,12 +368,7 @@ func TestStack(t *testing.T) { "dup0", [][]byte{{1}}, func(s *stack) error { - err := s.DupN(0) - if err != nil { - return err - } - - return nil + return s.DupN(0) }, ErrStackInvalidArgs, nil, @@ -401,12 +377,7 @@ func TestStack(t *testing.T) { "dup-1", [][]byte{{1}}, func(s *stack) error { - err := s.DupN(-1) - if err != nil { - return err - } - - return nil + return s.DupN(-1) }, ErrStackInvalidArgs, nil, @@ -415,12 +386,7 @@ func TestStack(t *testing.T) { "dup too much", [][]byte{{1}}, func(s *stack) error { - err := s.DupN(2) - if err != nil { - return err - } - - return nil + return s.DupN(2) }, ErrStackUnderflow, nil, @@ -456,7 +422,7 @@ func TestStack(t *testing.T) { if err != nil { return err } - if val != true { + if !val { return errors.New("unexpected value") } @@ -474,7 +440,7 @@ func TestStack(t *testing.T) { if err != nil { return err } - if val != false { + if val { return errors.New("unexpected value") } @@ -492,7 +458,7 @@ func TestStack(t *testing.T) { if err != nil { return err } - if val != true { + if !val { return errors.New("unexpected value") } @@ -510,7 +476,7 @@ func TestStack(t *testing.T) { if err != nil { return err } - if val != false { + if val { return errors.New("unexpected value") } @@ -809,7 +775,7 @@ func TestStack(t *testing.T) { if err != nil { return err } - if val != true { + if !val { return errors.New("invalid result") } return nil @@ -827,7 +793,7 @@ func TestStack(t *testing.T) { if err != nil { return err } - if val != false { + if val { return errors.New("invalid result") } return nil diff --git a/upgrade.go b/upgrade.go index da9c27b7..5dec8d4c 100644 --- a/upgrade.go +++ b/upgrade.go @@ -101,12 +101,7 @@ func upgradeDBPaths() error { upgradeDBPathNet(filepath.Join(oldDbRoot, "btcd_regtest.db"), "regtest") // Remove the old db directory. - err := os.RemoveAll(oldDbRoot) - if err != nil { - return err - } - - return nil + return os.RemoveAll(oldDbRoot) } // upgradeDataPaths moves the application data from its location prior to btcd diff --git a/upnp.go b/upnp.go index 172d9eba..f91196a3 100644 --- a/upnp.go +++ b/upnp.go @@ -104,7 +104,7 @@ func Discover() (nat NAT, err error) { // return } answer := string(answerBytes[0:n]) - if strings.Index(answer, "\r\n"+st) < 0 { + if !strings.Contains(answer, "\r\n"+st) { continue } // HTTP header field names are case-insensitive. diff --git a/wire/blockheader.go b/wire/blockheader.go index cc0e63c0..39859cd7 100644 --- a/wire/blockheader.go +++ b/wire/blockheader.go @@ -117,13 +117,8 @@ func NewBlockHeader(prevHash *chainhash.Hash, merkleRootHash *chainhash.Hash, // decoding block headers stored to disk, such as in a database, as opposed to // decoding from the wire. func readBlockHeader(r io.Reader, pver uint32, bh *BlockHeader) error { - err := readElements(r, &bh.Version, &bh.PrevBlock, &bh.MerkleRoot, + return readElements(r, &bh.Version, &bh.PrevBlock, &bh.MerkleRoot, (*uint32Time)(&bh.Timestamp), &bh.Bits, &bh.Nonce) - if err != nil { - return err - } - - return nil } // writeBlockHeader writes a bitcoin block header to w. See Serialize for @@ -131,11 +126,6 @@ func readBlockHeader(r io.Reader, pver uint32, bh *BlockHeader) error { // opposed to encoding for the wire. func writeBlockHeader(w io.Writer, pver uint32, bh *BlockHeader) error { sec := uint32(bh.Timestamp.Unix()) - err := writeElements(w, bh.Version, &bh.PrevBlock, &bh.MerkleRoot, + return writeElements(w, bh.Version, &bh.PrevBlock, &bh.MerkleRoot, sec, bh.Bits, bh.Nonce) - if err != nil { - return err - } - - return nil } diff --git a/wire/common.go b/wire/common.go index 4b980a7f..85c9df83 100644 --- a/wire/common.go +++ b/wire/common.go @@ -378,7 +378,7 @@ func writeElement(w io.Writer, element interface{}) error { case bool: var err error - if e == true { + if e { err = binarySerializer.PutUint8(w, 0x01) } else { err = binarySerializer.PutUint8(w, 0x00) @@ -624,10 +624,7 @@ func WriteVarString(w io.Writer, pver uint32, str string) error { return err } _, err = w.Write([]byte(str)) - if err != nil { - return err - } - return nil + return err } // ReadVarBytes reads a variable length byte array. A byte array is encoded @@ -672,10 +669,7 @@ func WriteVarBytes(w io.Writer, pver uint32, bytes []byte) error { } _, err = w.Write(bytes) - if err != nil { - return err - } - return nil + return err } // randomUint64 returns a cryptographically random uint64 value. This diff --git a/wire/invvect.go b/wire/invvect.go index d6f04e26..3feddcb1 100644 --- a/wire/invvect.go +++ b/wire/invvect.go @@ -67,18 +67,10 @@ func NewInvVect(typ InvType, hash *chainhash.Hash) *InvVect { // readInvVect reads an encoded InvVect from r depending on the protocol // version. func readInvVect(r io.Reader, pver uint32, iv *InvVect) error { - err := readElements(r, &iv.Type, &iv.Hash) - if err != nil { - return err - } - return nil + return readElements(r, &iv.Type, &iv.Hash) } // writeInvVect serializes an InvVect to w depending on the protocol version. func writeInvVect(w io.Writer, pver uint32, iv *InvVect) error { - err := writeElements(w, iv.Type, &iv.Hash) - if err != nil { - return err - } - return nil + return writeElements(w, iv.Type, &iv.Hash) } diff --git a/wire/message.go b/wire/message.go index d1b684f7..c2edcdac 100644 --- a/wire/message.go +++ b/wire/message.go @@ -261,11 +261,7 @@ func WriteMessageN(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet) (in // Write payload. n, err = w.Write(payload) totalBytes += n - if err != nil { - return totalBytes, err - } - - return totalBytes, nil + return totalBytes, err } // WriteMessage writes a bitcoin Message to w including the necessary header diff --git a/wire/msgalert.go b/wire/msgalert.go index db87e2e3..8bddae19 100644 --- a/wire/msgalert.go +++ b/wire/msgalert.go @@ -206,11 +206,7 @@ func (alert *Alert) Serialize(w io.Writer, pver uint32) error { if err != nil { return err } - err = WriteVarString(w, pver, alert.Reserved) - if err != nil { - return err - } - return nil + return WriteVarString(w, pver, alert.Reserved) } // Deserialize decodes from r into the receiver using the alert protocol @@ -279,10 +275,7 @@ func (alert *Alert) Deserialize(r io.Reader, pver uint32) error { return err } alert.Reserved, err = ReadVarString(r, pver) - if err != nil { - return err - } - return nil + return err } // NewAlert returns an new Alert with values provided. @@ -356,11 +349,7 @@ func (msg *MsgAlert) BtcDecode(r io.Reader, pver uint32) error { msg.Signature, err = ReadVarBytes(r, pver, MaxMessagePayload, "alert signature") - if err != nil { - return err - } - - return nil + return err } // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. @@ -390,11 +379,7 @@ func (msg *MsgAlert) BtcEncode(w io.Writer, pver uint32) error { if err != nil { return err } - err = WriteVarBytes(w, pver, msg.Signature) - if err != nil { - return err - } - return nil + return WriteVarBytes(w, pver, msg.Signature) } // Command returns the protocol command string for the message. This is part diff --git a/wire/msgfeefilter.go b/wire/msgfeefilter.go index 198f9b03..0162f838 100644 --- a/wire/msgfeefilter.go +++ b/wire/msgfeefilter.go @@ -28,12 +28,7 @@ func (msg *MsgFeeFilter) BtcDecode(r io.Reader, pver uint32) error { return messageError("MsgFeeFilter.BtcDecode", str) } - err := readElement(r, &msg.MinFee) - if err != nil { - return err - } - - return nil + return readElement(r, &msg.MinFee) } // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. @@ -45,12 +40,7 @@ func (msg *MsgFeeFilter) BtcEncode(w io.Writer, pver uint32) error { return messageError("MsgFeeFilter.BtcEncode", str) } - err := writeElement(w, msg.MinFee) - if err != nil { - return err - } - - return nil + return writeElement(w, msg.MinFee) } // Command returns the protocol command string for the message. This is part diff --git a/wire/msgfilteradd.go b/wire/msgfilteradd.go index 244ae4d0..b9e8a869 100644 --- a/wire/msgfilteradd.go +++ b/wire/msgfilteradd.go @@ -37,11 +37,7 @@ func (msg *MsgFilterAdd) BtcDecode(r io.Reader, pver uint32) error { var err error msg.Data, err = ReadVarBytes(r, pver, MaxFilterAddDataSize, "filteradd data") - if err != nil { - return err - } - - return nil + return err } // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. @@ -60,12 +56,7 @@ func (msg *MsgFilterAdd) BtcEncode(w io.Writer, pver uint32) error { return messageError("MsgFilterAdd.BtcEncode", str) } - err := WriteVarBytes(w, pver, msg.Data) - if err != nil { - return err - } - - return nil + return WriteVarBytes(w, pver, msg.Data) } // Command returns the protocol command string for the message. This is part diff --git a/wire/msgfilterload.go b/wire/msgfilterload.go index b8bdd147..80374194 100644 --- a/wire/msgfilterload.go +++ b/wire/msgfilterload.go @@ -106,12 +106,7 @@ func (msg *MsgFilterLoad) BtcEncode(w io.Writer, pver uint32) error { return err } - err = writeElements(w, msg.HashFuncs, msg.Tweak, msg.Flags) - if err != nil { - return err - } - - return nil + return writeElements(w, msg.HashFuncs, msg.Tweak, msg.Flags) } // Command returns the protocol command string for the message. This is part diff --git a/wire/msggetblocks.go b/wire/msggetblocks.go index ffc4c2e6..8201ff41 100644 --- a/wire/msggetblocks.go +++ b/wire/msggetblocks.go @@ -80,12 +80,7 @@ func (msg *MsgGetBlocks) BtcDecode(r io.Reader, pver uint32) error { msg.AddBlockLocatorHash(hash) } - err = readElement(r, &msg.HashStop) - if err != nil { - return err - } - - return nil + return readElement(r, &msg.HashStop) } // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. @@ -115,12 +110,7 @@ func (msg *MsgGetBlocks) BtcEncode(w io.Writer, pver uint32) error { } } - err = writeElement(w, &msg.HashStop) - if err != nil { - return err - } - - return nil + return writeElement(w, &msg.HashStop) } // Command returns the protocol command string for the message. This is part diff --git a/wire/msggetheaders.go b/wire/msggetheaders.go index 46932de5..00755f3c 100644 --- a/wire/msggetheaders.go +++ b/wire/msggetheaders.go @@ -77,12 +77,7 @@ func (msg *MsgGetHeaders) BtcDecode(r io.Reader, pver uint32) error { msg.AddBlockLocatorHash(hash) } - err = readElement(r, &msg.HashStop) - if err != nil { - return err - } - - return nil + return readElement(r, &msg.HashStop) } // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. @@ -113,12 +108,7 @@ func (msg *MsgGetHeaders) BtcEncode(w io.Writer, pver uint32) error { } } - err = writeElement(w, &msg.HashStop) - if err != nil { - return err - } - - return nil + return writeElement(w, &msg.HashStop) } // Command returns the protocol command string for the message. This is part diff --git a/wire/msgmerkleblock.go b/wire/msgmerkleblock.go index 3cec9935..74707028 100644 --- a/wire/msgmerkleblock.go +++ b/wire/msgmerkleblock.go @@ -85,11 +85,7 @@ func (msg *MsgMerkleBlock) BtcDecode(r io.Reader, pver uint32) error { msg.Flags, err = ReadVarBytes(r, pver, maxFlagsPerMerkleBlock, "merkle block flags size") - if err != nil { - return err - } - - return nil + return err } // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. @@ -136,12 +132,7 @@ func (msg *MsgMerkleBlock) BtcEncode(w io.Writer, pver uint32) error { } } - err = WriteVarBytes(w, pver, msg.Flags) - if err != nil { - return err - } - - return nil + return WriteVarBytes(w, pver, msg.Flags) } // Command returns the protocol command string for the message. This is part diff --git a/wire/msgpong.go b/wire/msgpong.go index 4c89acc8..9fd02721 100644 --- a/wire/msgpong.go +++ b/wire/msgpong.go @@ -31,12 +31,7 @@ func (msg *MsgPong) BtcDecode(r io.Reader, pver uint32) error { return messageError("MsgPong.BtcDecode", str) } - err := readElement(r, &msg.Nonce) - if err != nil { - return err - } - - return nil + return readElement(r, &msg.Nonce) } // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. @@ -50,12 +45,7 @@ func (msg *MsgPong) BtcEncode(w io.Writer, pver uint32) error { return messageError("MsgPong.BtcEncode", str) } - err := writeElement(w, msg.Nonce) - if err != nil { - return err - } - - return nil + return writeElement(w, msg.Nonce) } // Command returns the protocol command string for the message. This is part diff --git a/wire/msgtx.go b/wire/msgtx.go index e87aab1d..899cf6a5 100644 --- a/wire/msgtx.go +++ b/wire/msgtx.go @@ -537,12 +537,7 @@ func (msg *MsgTx) BtcEncode(w io.Writer, pver uint32) error { } } - err = binarySerializer.PutUint32(w, littleEndian, msg.LockTime) - if err != nil { - return err - } - - return nil + return binarySerializer.PutUint32(w, littleEndian, msg.LockTime) } // Serialize encodes the transaction to w using a format that suitable for @@ -652,11 +647,7 @@ func readOutPoint(r io.Reader, pver uint32, version int32, op *OutPoint) error { } op.Index, err = binarySerializer.Uint32(r, littleEndian) - if err != nil { - return err - } - - return nil + return err } // writeOutPoint encodes op to the bitcoin protocol encoding for an OutPoint @@ -667,11 +658,7 @@ func writeOutPoint(w io.Writer, pver uint32, version int32, op *OutPoint) error return err } - err = binarySerializer.PutUint32(w, littleEndian, op.Index) - if err != nil { - return err - } - return nil + return binarySerializer.PutUint32(w, littleEndian, op.Index) } // readScript reads a variable length byte array that represents a transaction @@ -719,12 +706,7 @@ func readTxIn(r io.Reader, pver uint32, version int32, ti *TxIn) error { return err } - err = readElement(r, &ti.Sequence) - if err != nil { - return err - } - - return nil + return readElement(r, &ti.Sequence) } // writeTxIn encodes ti to the bitcoin protocol encoding for a transaction @@ -740,12 +722,7 @@ func writeTxIn(w io.Writer, pver uint32, version int32, ti *TxIn) error { return err } - err = binarySerializer.PutUint32(w, littleEndian, ti.Sequence) - if err != nil { - return err - } - - return nil + return binarySerializer.PutUint32(w, littleEndian, ti.Sequence) } // readTxOut reads the next sequence of bytes from r as a transaction output @@ -758,11 +735,7 @@ func readTxOut(r io.Reader, pver uint32, version int32, to *TxOut) error { to.PkScript, err = readScript(r, pver, MaxMessagePayload, "transaction output public key script") - if err != nil { - return err - } - - return nil + return err } // writeTxOut encodes to into the bitcoin protocol encoding for a transaction @@ -773,9 +746,5 @@ func writeTxOut(w io.Writer, pver uint32, version int32, to *TxOut) error { return err } - err = WriteVarBytes(w, pver, to.PkScript) - if err != nil { - return err - } - return nil + return WriteVarBytes(w, pver, to.PkScript) } diff --git a/wire/msgversion_test.go b/wire/msgversion_test.go index 7895e1cc..5d57b8b0 100644 --- a/wire/msgversion_test.go +++ b/wire/msgversion_test.go @@ -63,7 +63,7 @@ func TestVersion(t *testing.T) { t.Errorf("NewMsgVersion: wrong last block - got %v, want %v", msg.LastBlock, lastBlock) } - if msg.DisableRelayTx != false { + if msg.DisableRelayTx { t.Errorf("NewMsgVersion: disable relay tx is not false by "+ "default - got %v, want %v", msg.DisableRelayTx, false) } diff --git a/wire/netaddress.go b/wire/netaddress.go index 6c3e65a1..04fef9f4 100644 --- a/wire/netaddress.go +++ b/wire/netaddress.go @@ -53,10 +53,7 @@ type NetAddress struct { // HasService returns whether the specified service is supported by the address. func (na *NetAddress) HasService(service ServiceFlag) bool { - if na.Services&service == service { - return true - } - return false + return na.Services&service == service } // AddService adds service as a supported service by the peer generating the @@ -158,10 +155,5 @@ func writeNetAddress(w io.Writer, pver uint32, na *NetAddress, ts bool) error { } // Sigh. Bitcoin protocol mixes little and big endian. - err = binary.Write(w, bigEndian, na.Port) - if err != nil { - return err - } - - return nil + return binary.Write(w, bigEndian, na.Port) }