From caa57df4686675fc51add2d2c5e7a8de1d3beef3 Mon Sep 17 00:00:00 2001 From: David Hill Date: Wed, 8 Mar 2017 15:44:15 -0500 Subject: [PATCH] travis: enable gometalinter (#603) * Hook up gometalinter * travis: enable unconvert * travis: enable gosimple --- .travis.yml | 6 +- addrmgr/addrmanager_test.go | 4 +- addrmgr/network.go | 4 +- blockchain/chaingen/generator.go | 8 +- blockchain/common.go | 11 +- blockchain/difficulty.go | 4 +- blockchain/indexers/manager.go | 5 +- blockchain/scriptval.go | 14 +- blockchain/stake/internal/ticketdb/chainio.go | 6 +- .../stake/internal/ticketdb/chainio_test.go | 12 +- .../internal/tickettreap/immutable_test.go | 11 +- .../internal/tickettreap/mutable_test.go | 11 +- blockchain/stake/staketx.go | 12 +- blockchain/stake/staketx_test.go | 64 ++++----- blockchain/stake/tickets.go | 18 +-- blockchain/stake/tickets_test.go | 12 +- blockchain/upgrade.go | 7 +- blockchain/utxoviewpoint.go | 18 +-- blockchain/validate.go | 2 +- blockmanager.go | 31 ++-- cmd/addblock/import.go | 4 +- config.go | 6 +- database/cmd/dbtool/fetchblock.go | 2 +- database/cmd/dbtool/fetchblockregion.go | 2 +- database/cmd/dbtool/insecureimport.go | 10 +- database/cmd/dbtool/loadheaders.go | 18 +-- database/ffldb/bench_test.go | 10 +- database/ffldb/blockio.go | 2 +- database/ffldb/dbcache.go | 7 +- database/ffldb/interface_test.go | 41 ++---- database/internal/treap/immutable_test.go | 11 +- database/internal/treap/mutable_test.go | 11 +- dcrec/edwards/curve.go | 5 +- dcrec/edwards/ecdsa_test.go | 2 +- dcrec/edwards/primitives.go | 2 +- dcrec/edwards/threshold_test.go | 8 +- dcrec/secp256k1/schnorr/ecdsa_test.go | 2 +- dcrec/secp256k1/schnorr/threshold_test.go | 16 +-- dcrjson/help.go | 4 +- goclean.sh | 38 ++++- mempool/mempool.go | 8 +- mining.go | 35 ++--- peer/log.go | 2 +- peer/peer.go | 6 +- rpcserver.go | 44 +++--- server.go | 8 +- txscript/engine.go | 4 +- txscript/opcode.go | 2 +- txscript/scriptbuilder.go | 2 +- txscript/stack_test.go | 64 ++------- txscript/standard.go | 6 +- upnp.go | 2 +- wire/blockheader.go | 14 +- wire/common.go | 12 +- wire/invvect.go | 12 +- wire/message.go | 6 +- wire/msgalert.go | 27 +--- wire/msgfilteradd.go | 13 +- wire/msgfilterload.go | 7 +- wire/msggetblocks.go | 14 +- wire/msggetheaders.go | 14 +- wire/msgmerkleblock.go | 17 +-- wire/msgping.go | 12 +- wire/msgpong.go | 14 +- wire/msgtx.go | 133 +++--------------- wire/msgversion.go | 7 +- wire/msgversion_test.go | 2 +- wire/netaddress.go | 12 +- 68 files changed, 283 insertions(+), 677 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8cf21dd884..f271e50a80 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,10 +7,8 @@ install: - go get -v github.com/Masterminds/glide - glide install - go install -v . ./cmd/... - - go get -v golang.org/x/tools/cmd/cover - - go get -v github.com/bradfitz/goimports - - go get -v github.com/golang/lint/golint - - go get -v github.com/davecgh/go-spew/spew + - go get -v github.com/alecthomas/gometalinter + - gometalinter --install script: - export PATH=$PATH:$HOME/gopath/bin - ./goclean.sh diff --git a/addrmgr/addrmanager_test.go b/addrmgr/addrmanager_test.go index f53dfc74dc..bc1c022f79 100644 --- a/addrmgr/addrmanager_test.go +++ b/addrmgr/addrmanager_test.go @@ -259,7 +259,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) @@ -288,7 +288,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/addrmgr/network.go b/addrmgr/network.go index 4a1d798519..a662e4fdc5 100644 --- a/addrmgr/network.go +++ b/addrmgr/network.go @@ -247,12 +247,12 @@ func GroupKey(na *wire.NetAddress) string { } if IsRFC6145(na) || IsRFC6052(na) { // last four bytes are the ip address - ip := net.IP(na.IP[12:16]) + ip := na.IP[12:16] return ip.Mask(net.CIDRMask(16, 32)).String() } if IsRFC3964(na) { - ip := net.IP(na.IP[2:6]) + ip := na.IP[2:6] return ip.Mask(net.CIDRMask(16, 32)).String() } diff --git a/blockchain/chaingen/generator.go b/blockchain/chaingen/generator.go index 32dac52759..95cc9d7e22 100644 --- a/blockchain/chaingen/generator.go +++ b/blockchain/chaingen/generator.go @@ -427,7 +427,7 @@ func purchaseCommitmentScript(addr dcrutil.Address, amount, voteFeeLimit, revoca copy(data[:], addr.ScriptAddress()) binary.LittleEndian.PutUint64(data[20:], uint64(amount)) data[27] |= 1 << 7 - binary.LittleEndian.PutUint16(data[28:], uint16(limits)) + binary.LittleEndian.PutUint16(data[28:], limits) script, err := txscript.NewScriptBuilder().AddOp(txscript.OP_RETURN). AddData(data[:]).Script() if err != nil { @@ -1066,7 +1066,7 @@ func (hp *hash256prng) uniformRandom(upperBound uint32) uint32 { // (2^32 - (x*2)) % x == 2^32 % x when x <= 2^31 min := ((math.MaxUint32 - (upperBound * 2)) + 1) % upperBound if upperBound > 0x80000000 { - min = uint32(1 + ^upperBound) + min = 1 + ^upperBound } r := hp.Hash256Rand() @@ -1249,9 +1249,7 @@ func (g *Generator) ReplaceWithNVotes(numVotes uint16) func(*wire.MsgBlock) { // Add back the original stake transactions other than the // original stake votes that have been replaced. - for _, stakeTx := range b.STransactions[defaultNumVotes:] { - stakeTxns = append(stakeTxns, stakeTx) - } + stakeTxns = append(stakeTxns, b.STransactions[defaultNumVotes:]...) // Update the block with the new stake transactions and the // header with the new number of votes. diff --git a/blockchain/common.go b/blockchain/common.go index 9918d95d37..e64e60ac00 100644 --- a/blockchain/common.go +++ b/blockchain/common.go @@ -21,7 +21,7 @@ import ( // DoStxoTest does a test on a simulated blockchain to ensure that the data // stored in the STXO buckets is not corrupt. func (b *BlockChain) DoStxoTest() error { - err := b.db.View(func(dbTx database.Tx) error { + return b.db.View(func(dbTx database.Tx) error { for i := int64(2); i <= b.bestNode.height; i++ { block, err := dbFetchBlockByHeight(dbTx, i) if err != nil { @@ -39,20 +39,15 @@ func (b *BlockChain) DoStxoTest() error { return err } - if int(ntx) != len(stxos) { + if ntx != len(stxos) { return fmt.Errorf("bad number of stxos calculated at "+ "height %v, got %v expected %v", - i, len(stxos), int(ntx)) + i, len(stxos), ntx) } } return nil }) - if err != nil { - return err - } - - return nil } // DebugBlockHeaderString dumps a verbose message containing information about diff --git a/blockchain/difficulty.go b/blockchain/difficulty.go index fde8710072..cc5e6fd084 100644 --- a/blockchain/difficulty.go +++ b/blockchain/difficulty.go @@ -494,7 +494,7 @@ func (b *BlockChain) calcNextRequiredStakeDifficulty(curNode *blockNode) (int64, alpha := b.chainParams.StakeDiffAlpha stakeDiffStartHeight := int64(b.chainParams.CoinbaseMaturity) + 1 - maxRetarget := int64(b.chainParams.RetargetAdjustmentFactor) + maxRetarget := b.chainParams.RetargetAdjustmentFactor TicketPoolWeight := int64(b.chainParams.TicketPoolSizeWeight) // Number of nodes to traverse while calculating difficulty. @@ -759,7 +759,7 @@ func (b *BlockChain) estimateNextStakeDifficulty(curNode *blockNode, alpha := b.chainParams.StakeDiffAlpha stakeDiffStartHeight := int64(b.chainParams.CoinbaseMaturity) + 1 - maxRetarget := int64(b.chainParams.RetargetAdjustmentFactor) + maxRetarget := b.chainParams.RetargetAdjustmentFactor TicketPoolWeight := int64(b.chainParams.TicketPoolSizeWeight) // Number of nodes to traverse while calculating difficulty. diff --git a/blockchain/indexers/manager.go b/blockchain/indexers/manager.go index ee9afd2c46..d1283ceb04 100644 --- a/blockchain/indexers/manager.go +++ b/blockchain/indexers/manager.go @@ -278,10 +278,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/scriptval.go b/blockchain/scriptval.go index 342ea2140c..a5862cc1fd 100644 --- a/blockchain/scriptval.go +++ b/blockchain/scriptval.go @@ -215,12 +215,7 @@ func ValidateTransactionScripts(tx *dcrutil.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 newTxValidator(utxoView, flags, sigCache).Validate(txValItems) } @@ -263,10 +258,5 @@ func checkBlockScripts(block *dcrutil.Block, utxoView *UtxoViewpoint, txTree boo } // Validate all of the inputs. - validator := newTxValidator(utxoView, scriptFlags, sigCache) - if err := validator.Validate(txValItems); err != nil { - return err - } - - return nil + return newTxValidator(utxoView, scriptFlags, sigCache).Validate(txValItems) } diff --git a/blockchain/stake/internal/ticketdb/chainio.go b/blockchain/stake/internal/ticketdb/chainio.go index baa5b3a9c6..02d37027ff 100644 --- a/blockchain/stake/internal/ticketdb/chainio.go +++ b/blockchain/stake/internal/ticketdb/chainio.go @@ -712,9 +712,5 @@ func DbCreate(dbTx database.Tx) error { // Create the bucket that houses the tickets that were added with // this block into the main chain. _, err = meta.CreateBucket(dbnamespace.TicketsInBlockBucketName) - if err != nil { - return err - } - - return nil + return err } diff --git a/blockchain/stake/internal/ticketdb/chainio_test.go b/blockchain/stake/internal/ticketdb/chainio_test.go index 77aa916977..f9599b9049 100644 --- a/blockchain/stake/internal/ticketdb/chainio_test.go +++ b/blockchain/stake/internal/ticketdb/chainio_test.go @@ -446,11 +446,7 @@ func TestLiveDatabase(t *testing.T) { var dbi *DatabaseInfo err = testDb.View(func(dbTx database.Tx) error { dbi, err = DbFetchDatabaseInfo(dbTx) - if err != nil { - return err - } - - return nil + return err }) if err != nil { t.Fatalf("%v", err.Error()) @@ -495,11 +491,7 @@ func TestLiveDatabase(t *testing.T) { ticketMap2 := make(map[tickettreap.Key]*tickettreap.Value) err = testDb.View(func(dbTx database.Tx) error { treap, err = DbLoadAllTickets(dbTx, dbnamespace.LiveTicketsBucketName) - if err != nil { - return err - } - - return nil + return err }) if err != nil { t.Fatalf("%v", err.Error()) diff --git a/blockchain/stake/internal/tickettreap/immutable_test.go b/blockchain/stake/internal/tickettreap/immutable_test.go index 8dd9359f85..431b02ae83 100644 --- a/blockchain/stake/internal/tickettreap/immutable_test.go +++ b/blockchain/stake/internal/tickettreap/immutable_test.go @@ -36,7 +36,7 @@ func TestImmutableEmpty(t *testing.T) { // Ensure there are no errors with requesting keys from an empty treap. key := uint32ToKey(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 { @@ -357,7 +357,7 @@ 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 { + if gotVal := testTreap.Has(key); !gotVal { t.Fatalf("Has: unexpected result - got %v, want false", gotVal) } @@ -386,7 +386,7 @@ func TestImmutableNilValue(t *testing.T) { testTreap = testTreap.Put(key, nil) // Ensure the key does NOT exist. - if gotVal := testTreap.Has(key); gotVal == true { + if gotVal := testTreap.Has(key); gotVal { t.Fatalf("Has: unexpected result - got %v, want false", gotVal) } if gotVal := testTreap.Get(key); gotVal != nil { @@ -412,10 +412,7 @@ func TestImmutableForEachStopIterator(t *testing.T) { var numIterated int testTreap.ForEach(func(k Key, v *Value) 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/blockchain/stake/internal/tickettreap/mutable_test.go b/blockchain/stake/internal/tickettreap/mutable_test.go index faf252f452..680dac111f 100644 --- a/blockchain/stake/internal/tickettreap/mutable_test.go +++ b/blockchain/stake/internal/tickettreap/mutable_test.go @@ -31,7 +31,7 @@ func TestMutableEmpty(t *testing.T) { // Ensure there are no errors with requesting keys from an empty treap. key := uint32ToKey(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 { @@ -408,7 +408,7 @@ func TestMutableDuplicatePut(t *testing.T) { testTreap.Put(key, expectedVal) // Ensure the key still exists and is the new value. - if gotVal := testTreap.Has(key); gotVal != true { + if gotVal := testTreap.Has(key); !gotVal { t.Fatalf("Has: unexpected result - got %v, want false", gotVal) } @@ -437,7 +437,7 @@ func TestMutableNilValue(t *testing.T) { testTreap.Put(key, nil) // Ensure the key does NOT exist. - if gotVal := testTreap.Has(key); gotVal == true { + if gotVal := testTreap.Has(key); gotVal { t.Fatalf("Has: unexpected result - got %v, want false", gotVal) } if gotVal := testTreap.Get(key); gotVal != nil { @@ -463,10 +463,7 @@ func TestMutableForEachStopIterator(t *testing.T) { var numIterated int testTreap.ForEach(func(k Key, v *Value) 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/blockchain/stake/staketx.go b/blockchain/stake/staketx.go index 39bb2cf0aa..28df5eb47c 100644 --- a/blockchain/stake/staketx.go +++ b/blockchain/stake/staketx.go @@ -873,10 +873,10 @@ func IsSStx(tx *wire.MsgTx) (bool, error) { outputScriptBuffer := bytes.NewBuffer(rawScript) outputScriptPrefix := outputScriptBuffer.Next(2) - minPush := uint8(validSStxAddressOutMinPrefix[1]) - maxPush := uint8(validSStxAddressOutMinPrefix[1]) + + minPush := validSStxAddressOutMinPrefix[1] + maxPush := validSStxAddressOutMinPrefix[1] + (MaxSingleBytePushLength - minPush) - pushLen := uint8(outputScriptPrefix[1]) + pushLen := outputScriptPrefix[1] pushLengthValid := (pushLen >= minPush) && (pushLen <= maxPush) // The first byte should be OP_RETURN, while the second byte should be a // valid push length. @@ -1034,10 +1034,10 @@ func IsSSGen(tx *wire.MsgTx) (bool, error) { firstOutputScriptBuffer := bytes.NewBuffer(firstOutputScript) firstOutputScriptPrefix := firstOutputScriptBuffer.Next(2) - minPush := uint8(validSSGenVoteOutMinPrefix[1]) - maxPush := uint8(validSSGenVoteOutMinPrefix[1]) + + minPush := validSSGenVoteOutMinPrefix[1] + maxPush := validSSGenVoteOutMinPrefix[1] + (MaxSingleBytePushLength - minPush) - pushLen := uint8(firstOutputScriptPrefix[1]) + pushLen := firstOutputScriptPrefix[1] pushLengthValid := (pushLen >= minPush) && (pushLen <= maxPush) // The first byte should be OP_RETURN, while the second byte should be a // valid push length. diff --git a/blockchain/stake/staketx_test.go b/blockchain/stake/staketx_test.go index 544183daf3..1ae64fd8db 100644 --- a/blockchain/stake/staketx_test.go +++ b/blockchain/stake/staketx_test.go @@ -26,7 +26,7 @@ func TestIsSStx(t *testing.T) { sstx.SetIndex(0) test, err := stake.IsSStx(sstx.MsgTx()) - if test == false || err != nil { + if !test || err != nil { t.Errorf("IsSSTx should have returned true, but instead returned %v"+ ",%v", test, err) } @@ -53,7 +53,7 @@ func TestIsSStx(t *testing.T) { sstx.SetIndex(0) test, err = stake.IsSStx(sstx.MsgTx()) - if test == false || err != nil { + if !test || err != nil { t.Errorf("IsSSTx should have returned true, but instead returned %v"+ ",%v", test, err) } @@ -76,7 +76,7 @@ func TestIsSSTxErrors(t *testing.T) { sstxExtraInputs.SetIndex(0) test, err := stake.IsSStx(sstxExtraInputs.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSStxTooManyInputs { t.Errorf("IsSSTx should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSStxTooManyInputs, test, err) @@ -90,7 +90,7 @@ func TestIsSSTxErrors(t *testing.T) { sstxExtraOutputs.SetIndex(0) test, err = stake.IsSStx(sstxExtraOutputs.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSStxTooManyOutputs { t.Errorf("IsSSTx should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSStxTooManyOutputs, test, err) @@ -119,7 +119,7 @@ func TestIsSSTxErrors(t *testing.T) { sstxUntaggedOut.SetIndex(0) test, err = stake.IsSStx(sstxUntaggedOut.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSStxInvalidOutputs { t.Errorf("IsSSTx should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSStxInvalidOutputs, test, err) @@ -133,7 +133,7 @@ func TestIsSSTxErrors(t *testing.T) { sstxInsOutsMismatched.SetIndex(0) test, err = stake.IsSStx(sstxInsOutsMismatched.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSStxInOutProportions { t.Errorf("IsSSTx should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSStxInOutProportions, test, err) @@ -146,7 +146,7 @@ func TestIsSSTxErrors(t *testing.T) { sstxBadVerOut.SetIndex(0) test, err = stake.IsSStx(sstxBadVerOut.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSStxInvalidOutputs { t.Errorf("IsSSTx should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSStxInvalidOutputs, test, err) @@ -160,7 +160,7 @@ func TestIsSSTxErrors(t *testing.T) { sstxNoNullData.SetIndex(0) test, err = stake.IsSStx(sstxNoNullData.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSStxInvalidOutputs { t.Errorf("IsSSTx should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSStxInvalidOutputs, test, err) @@ -174,7 +174,7 @@ func TestIsSSTxErrors(t *testing.T) { sstxNullDataMis.SetIndex(0) test, err = stake.IsSStx(sstxNullDataMis.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSStxInvalidOutputs { t.Errorf("IsSSTx should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSStxInvalidOutputs, test, err) @@ -208,7 +208,7 @@ func TestIsSSTxErrors(t *testing.T) { sstxWrongPKHLength.SetIndex(0) test, err = stake.IsSStx(sstxWrongPKHLength.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSStxInvalidOutputs { t.Errorf("IsSSTx should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSStxInvalidOutputs, test, err) @@ -243,7 +243,7 @@ func TestIsSSTxErrors(t *testing.T) { sstxWrongPrefix.SetIndex(0) test, err = stake.IsSStx(sstxWrongPrefix.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSStxInvalidOutputs { t.Errorf("IsSSTx should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSStxInvalidOutputs, test, err) @@ -258,7 +258,7 @@ func TestIsSSGen(t *testing.T) { ssgen.SetIndex(0) test, err := stake.IsSSGen(ssgen.MsgTx()) - if test == false || err != nil { + if !test || err != nil { t.Errorf("IsSSGen should have returned true, but instead returned %v"+ ",%v", test, err) } @@ -284,7 +284,7 @@ func TestIsSSGen(t *testing.T) { ssgen.MsgTx().TxOut[1].PkScript = biggestPush test, err = stake.IsSSGen(ssgen.MsgTx()) - if test == false || err != nil { + if !test || err != nil { t.Errorf("IsSSGen should have returned true, but instead returned %v"+ ",%v", test, err) } @@ -308,7 +308,7 @@ func TestIsSSGenErrors(t *testing.T) { ssgenExtraInputs.SetIndex(0) test, err := stake.IsSSGen(ssgenExtraInputs.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSGenWrongNumInputs { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenWrongNumInputs, test, err) @@ -322,7 +322,7 @@ func TestIsSSGenErrors(t *testing.T) { ssgenExtraOutputs.SetIndex(0) test, err = stake.IsSSGen(ssgenExtraOutputs.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSGenTooManyOutputs { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenTooManyOutputs, test, err) @@ -336,7 +336,7 @@ func TestIsSSGenErrors(t *testing.T) { ssgenStakeBaseWrong.SetIndex(0) test, err = stake.IsSSGen(ssgenStakeBaseWrong.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSGenNoStakebase { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenNoStakebase, test, err) @@ -366,7 +366,7 @@ func TestIsSSGenErrors(t *testing.T) { ssgenWrongTreeIns.SetIndex(0) test, err = stake.IsSSGen(ssgenWrongTreeIns.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSGenWrongTxTree { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenWrongTxTree, test, err) @@ -379,7 +379,7 @@ func TestIsSSGenErrors(t *testing.T) { ssgenTxBadVerOut.SetIndex(0) test, err = stake.IsSSGen(ssgenTxBadVerOut.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSGenBadGenOuts { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenBadGenOuts, test, err) @@ -393,7 +393,7 @@ func TestIsSSGenErrors(t *testing.T) { ssgenWrongZeroethOut.SetIndex(0) test, err = stake.IsSSGen(ssgenWrongZeroethOut.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSGenNoReference { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenNoReference, test, err) @@ -432,7 +432,7 @@ func TestIsSSGenErrors(t *testing.T) { ssgenWrongDataPush0Length.SetIndex(0) test, err = stake.IsSSGen(ssgenWrongDataPush0Length.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSGenBadReference { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenBadReference, test, err) @@ -472,7 +472,7 @@ func TestIsSSGenErrors(t *testing.T) { ssgenWrongNullData0Prefix.SetIndex(0) test, err = stake.IsSSGen(ssgenWrongNullData0Prefix.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSGenBadReference { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenBadReference, test, err) @@ -486,7 +486,7 @@ func TestIsSSGenErrors(t *testing.T) { ssgenWrongFirstOut.SetIndex(0) test, err = stake.IsSSGen(ssgenWrongFirstOut.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSGenNoVotePush { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenNoVotePush, test, err) @@ -514,7 +514,7 @@ func TestIsSSGenErrors(t *testing.T) { ssgenWrongDataPush1Length.SetIndex(0) test, err = stake.IsSSGen(ssgenWrongDataPush1Length.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSGenBadVotePush { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenBadVotePush, test, err) @@ -543,7 +543,7 @@ func TestIsSSGenErrors(t *testing.T) { ssgenLongDataPush1Length.SetIndex(0) test, err = stake.IsSSGen(ssgenLongDataPush1Length.MsgTx()) - if test == false || err != nil { + if !test || err != nil { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenBadVotePush, test, err) } @@ -572,7 +572,7 @@ func TestIsSSGenErrors(t *testing.T) { ssgenWrongNullData1Prefix.SetIndex(0) test, err = stake.IsSSGen(ssgenWrongNullData1Prefix.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSGenBadVotePush { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenBadVotePush, test, err) @@ -602,7 +602,7 @@ func TestIsSSGenErrors(t *testing.T) { ssgentestGenOutputUntagged.SetIndex(0) test, err = stake.IsSSGen(ssgentestGenOutputUntagged.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSGenBadGenOuts { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenBadGenOuts, test, err) @@ -617,7 +617,7 @@ func TestIsSSRtx(t *testing.T) { ssrtx.SetIndex(0) test, err := stake.IsSSRtx(ssrtx.MsgTx()) - if test == false || err != nil { + if !test || err != nil { t.Errorf("IsSSRtx should have returned true, but instead returned %v"+ ",%v", test, err) } @@ -640,7 +640,7 @@ func TestIsSSRtxErrors(t *testing.T) { ssrtxTooManyInputs.SetIndex(0) test, err := stake.IsSSRtx(ssrtxTooManyInputs.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSRtxWrongNumInputs { t.Errorf("IsSSRtx should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSRtxWrongNumInputs, test, err) @@ -654,7 +654,7 @@ func TestIsSSRtxErrors(t *testing.T) { ssrtxTooManyOutputs.SetIndex(0) test, err = stake.IsSSRtx(ssrtxTooManyOutputs.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSRtxTooManyOutputs { t.Errorf("IsSSRtx should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSRtxTooManyOutputs, test, err) @@ -667,7 +667,7 @@ func TestIsSSRtxErrors(t *testing.T) { ssrtxTxBadVerOut.SetIndex(0) test, err = stake.IsSSRtx(ssrtxTxBadVerOut.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSRtxBadOuts { t.Errorf("IsSSRtx should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSRtxBadOuts, test, err) @@ -697,7 +697,7 @@ func TestIsSSRtxErrors(t *testing.T) { ssrtxTestRevocOutputUntagged.SetIndex(0) test, err = stake.IsSSRtx(ssrtxTestRevocOutputUntagged.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSRtxBadOuts { t.Errorf("IsSSGen should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSRtxBadOuts, test, err) @@ -726,7 +726,7 @@ func TestIsSSRtxErrors(t *testing.T) { ssrtxWrongTreeIns.SetIndex(0) test, err = stake.IsSSRtx(ssrtxWrongTreeIns.MsgTx()) - if test == true || err.(stake.RuleError).GetCode() != + if test || err.(stake.RuleError).GetCode() != stake.ErrSSRtxWrongTxTree { t.Errorf("IsSSRtx should have returned false,%v but instead returned %v"+ ",%v", stake.ErrSSGenWrongTxTree, test, err) diff --git a/blockchain/stake/tickets.go b/blockchain/stake/tickets.go index 9e4b837f62..5ed4bbe10c 100644 --- a/blockchain/stake/tickets.go +++ b/blockchain/stake/tickets.go @@ -501,9 +501,9 @@ func connectNode(node *Node, header wire.BlockHeader, ticketsSpentInBlock, revok // the winners are from the cached information in the previous block, so // no drop the results of that here. toExpireHeight := uint32(0) - if connectedNode.height > uint32(connectedNode.params.TicketExpiry) { + if connectedNode.height > connectedNode.params.TicketExpiry { toExpireHeight = connectedNode.height - - uint32(connectedNode.params.TicketExpiry) + connectedNode.params.TicketExpiry } expired := fetchExpired(toExpireHeight, connectedNode.liveTickets) for _, treapKey := range expired { @@ -894,7 +894,7 @@ func WriteConnectedBestNode(dbTx database.Tx, node *Node, hash chainhash.Hash) e } } - err = ticketdb.DbPutBestState(dbTx, ticketdb.BestChainState{ + return ticketdb.DbPutBestState(dbTx, ticketdb.BestChainState{ Hash: hash, Height: node.height, Live: uint32(node.liveTickets.Len()), @@ -903,11 +903,6 @@ func WriteConnectedBestNode(dbTx database.Tx, node *Node, hash chainhash.Hash) e PerBlock: node.params.TicketsPerBlock, NextWinners: nextWinners, }) - if err != nil { - return err - } - - return nil } // WriteDisconnectedBestNode writes the newly connected best node to the database @@ -1030,7 +1025,7 @@ func WriteDisconnectedBestNode(dbTx database.Tx, node *Node, hash chainhash.Hash } } - err = ticketdb.DbPutBestState(dbTx, ticketdb.BestChainState{ + return ticketdb.DbPutBestState(dbTx, ticketdb.BestChainState{ Hash: hash, Height: node.height, Live: uint32(node.liveTickets.Len()), @@ -1039,9 +1034,4 @@ func WriteDisconnectedBestNode(dbTx database.Tx, node *Node, hash chainhash.Hash PerBlock: node.params.TicketsPerBlock, NextWinners: nextWinners, }) - if err != nil { - return err - } - - return nil } diff --git a/blockchain/stake/tickets_test.go b/blockchain/stake/tickets_test.go index 098128b322..7dafce4b18 100644 --- a/blockchain/stake/tickets_test.go +++ b/blockchain/stake/tickets_test.go @@ -617,11 +617,7 @@ func TestTicketDBGeneral(t *testing.T) { err = testDb.Update(func(dbTx database.Tx) error { var errLocal error bestNode, errLocal = InitDatabaseState(dbTx, simNetParams) - if errLocal != nil { - return errLocal - } - - return nil + return errLocal }) if err != nil { t.Fatalf(err.Error()) @@ -729,11 +725,7 @@ func TestTicketDBGeneral(t *testing.T) { bestNodeUsingDB, err = formerBestNode.DisconnectNode(header, nil, nil, dbTx) - if err != nil { - return err - } - - return nil + return err }) if err != nil { t.Errorf("couldn't disconnect using the database: %v", diff --git a/blockchain/upgrade.go b/blockchain/upgrade.go index d7de41dbbf..1d4542a3c9 100644 --- a/blockchain/upgrade.go +++ b/blockchain/upgrade.go @@ -87,12 +87,7 @@ func (b *BlockChain) upgradeToVersion2() error { // Write the new database version. b.dbInfo.version = 2 - errLocal = dbPutDatabaseInfo(dbTx, b.dbInfo) - if errLocal != nil { - return errLocal - } - - return nil + return dbPutDatabaseInfo(dbTx, b.dbInfo) }) if err != nil { return err diff --git a/blockchain/utxoviewpoint.go b/blockchain/utxoviewpoint.go index 628bc7e8d6..4a09d892cf 100644 --- a/blockchain/utxoviewpoint.go +++ b/blockchain/utxoviewpoint.go @@ -314,7 +314,7 @@ func (view *UtxoViewpoint) AddTxOuts(tx *dcrutil.Tx, blockHeight int64, view.entries[*tx.Hash()] = entry } else { entry.height = uint32(blockHeight) - entry.index = uint32(blockIndex) + entry.index = blockIndex } entry.modified = true @@ -841,7 +841,7 @@ func (view *UtxoViewpoint) fetchUtxosMain(db database.DB, txSet map[chainhash.Ha // since other code uses the presence of an entry in the store as a way // to optimize spend and unspend updates to apply only to the specific // utxos that the caller needs access to. - err := db.View(func(dbTx database.Tx) error { + return db.View(func(dbTx database.Tx) error { for hash := range txSet { hashCopy := hash // If the UTX already exists in the view, skip adding it. @@ -858,11 +858,6 @@ func (view *UtxoViewpoint) fetchUtxosMain(db database.DB, txSet map[chainhash.Ha return nil }) - if err != nil { - return err - } - - return nil } // fetchUtxos loads utxo details about provided set of transaction hashes into @@ -886,14 +881,7 @@ func (view *UtxoViewpoint) fetchUtxos(db database.DB, txSet map[chainhash.Hash]s } // Request the input utxos from the database. - err := view.fetchUtxosMain(db, txNeededSet) - if err != nil { - return err - } - - // Connect up to the stake viewpoint that was requested - // if the flag to do so is given. - return nil + return view.fetchUtxosMain(db, txNeededSet) } // fetchInputUtxos loads utxo details about the input transactions referenced diff --git a/blockchain/validate.go b/blockchain/validate.go index 063f53b924..af274f6ee4 100644 --- a/blockchain/validate.go +++ b/blockchain/validate.go @@ -1597,7 +1597,7 @@ func CheckTransactionInputs(subsidyCache *SubsidyCache, tx *dcrutil.Tx, // Ensure the transaction is not spending coins which have not // yet reached the required coinbase maturity. coinbaseMaturity := int64(chainParams.CoinbaseMaturity) - originHeight := int64(utxoEntry.BlockHeight()) + originHeight := utxoEntry.BlockHeight() if utxoEntry.IsCoinBase() { blocksSincePrev := txHeight - originHeight if blocksSincePrev < coinbaseMaturity { diff --git a/blockmanager.go b/blockmanager.go index ab03666b80..091313a8b4 100644 --- a/blockmanager.go +++ b/blockmanager.go @@ -659,12 +659,7 @@ func (b *blockManager) startSync(peers *list.List) { // syncing from. func (b *blockManager) isSyncCandidate(sp *serverPeer) bool { // The peer is not a candidate for sync if it's not a full node. - if sp.Services()&wire.SFNodeNetwork != wire.SFNodeNetwork { - return false - } - - // Candidate if all checks passed. - return true + return sp.Services()&wire.SFNodeNetwork == wire.SFNodeNetwork } // syncMiningStateAfterSync polls the blockMananger for the current sync @@ -672,19 +667,15 @@ func (b *blockManager) isSyncCandidate(sp *serverPeer) bool { // sync the mining state to the network. func (b *blockManager) syncMiningStateAfterSync(sp *serverPeer) { go func() { - ticker := time.NewTicker(time.Second * 3) - defer ticker.Stop() for { - select { - case <-ticker.C: - if !sp.Connected() { - return - } - if b.IsCurrent() { - msg := wire.NewMsgGetMiningState() - sp.QueueMessage(msg, nil) - return - } + time.Sleep(3 * time.Second) + if !sp.Connected() { + return + } + if b.IsCurrent() { + msg := wire.NewMsgGetMiningState() + sp.QueueMessage(msg, nil) + return } } }() @@ -1312,7 +1303,7 @@ func (b *blockManager) handleBlockMsg(bmsg *blockMsg) { if blkHashUpdate != nil && heightUpdate != 0 { bmsg.peer.UpdateLastBlockHeight(heightUpdate) if isOrphan || b.current() { - go b.server.UpdatePeerHeights(blkHashUpdate, int64(heightUpdate), + go b.server.UpdatePeerHeights(blkHashUpdate, heightUpdate, bmsg.peer) } } @@ -1587,7 +1578,7 @@ func (b *blockManager) handleInvMsg(imsg *invMsg) { blkHeight, err := b.chain.BlockHeightByHash(&invVects[lastBlock].Hash) if err == nil { - imsg.peer.UpdateLastBlockHeight(int64(blkHeight)) + imsg.peer.UpdateLastBlockHeight(blkHeight) } } diff --git a/cmd/addblock/import.go b/cmd/addblock/import.go index 4004c804fe..5d8e8cfd81 100644 --- a/cmd/addblock/import.go +++ b/cmd/addblock/import.go @@ -257,7 +257,7 @@ func (bi *blockImporter) statusHandler(resultsChan chan *importResults) { resultsChan <- &importResults{ blocksProcessed: bi.blocksProcessed, blocksImported: bi.blocksImported, - duration: time.Now().Sub(bi.startTime), + duration: time.Since(bi.startTime), err: err, } close(bi.quit) @@ -267,7 +267,7 @@ func (bi *blockImporter) statusHandler(resultsChan chan *importResults) { resultsChan <- &importResults{ blocksProcessed: bi.blocksProcessed, blocksImported: bi.blocksImported, - duration: time.Now().Sub(bi.startTime), + duration: time.Since(bi.startTime), err: nil, } } diff --git a/config.go b/config.go index f250c21f11..50e1be04ec 100644 --- a/config.go +++ b/config.go @@ -583,7 +583,7 @@ func loadConfig() (*config, []string, error) { } // Don't allow ban durations that are too short. - if cfg.BanDuration < time.Duration(time.Second) { + if cfg.BanDuration < time.Second { str := "%s: The banduration option may not be less than 1s -- parsed [%v]" err := fmt.Errorf(str, funcName, cfg.BanDuration) fmt.Fprintln(os.Stderr, err) @@ -1004,9 +1004,9 @@ func createDefaultConfigFile(destinationPath string) error { } if strings.Contains(line, "rpcuser=") { - line = "rpcuser=" + string(generatedRPCUser) + "\n" + line = "rpcuser=" + generatedRPCUser + "\n" } else if strings.Contains(line, "rpcpass=") { - line = "rpcpass=" + string(generatedRPCPass) + "\n" + line = "rpcpass=" + generatedRPCPass + "\n" } if _, err := dest.WriteString(line); err != nil { diff --git a/database/cmd/dbtool/fetchblock.go b/database/cmd/dbtool/fetchblock.go index 8efea69114..d24b8b791c 100644 --- a/database/cmd/dbtool/fetchblock.go +++ b/database/cmd/dbtool/fetchblock.go @@ -51,7 +51,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 afcb2f0b3b..3d16d223e8 100644 --- a/database/cmd/dbtool/fetchblockregion.go +++ b/database/cmd/dbtool/fetchblockregion.go @@ -78,7 +78,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("Region Hex: %s", hex.EncodeToString(regionBytes)) return nil }) diff --git a/database/cmd/dbtool/insecureimport.go b/database/cmd/dbtool/insecureimport.go index 53a91f2417..402bf2c02f 100644 --- a/database/cmd/dbtool/insecureimport.go +++ b/database/cmd/dbtool/insecureimport.go @@ -122,10 +122,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 @@ -140,10 +137,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 12b40b981e..1ba7a6f772 100644 --- a/database/cmd/dbtool/loadheaders.go +++ b/database/cmd/dbtool/loadheaders.go @@ -42,7 +42,7 @@ func (cmd *headersCmd) Execute(args []string) error { // the database would keep a metadata index of its own. blockIdxName := []byte("ffldb-blockidx") if !headersCfg.Bulk { - err = db.View(func(tx database.Tx) error { + return db.View(func(tx database.Tx) error { totalHdrs := 0 blockIdxBucket := tx.Metadata().Bucket(blockIdxName) blockIdxBucket.ForEach(func(k, v []byte) error { @@ -63,18 +63,13 @@ 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 } // Bulk load headers. - err = db.View(func(tx database.Tx) error { + return db.View(func(tx database.Tx) error { blockIdxBucket := tx.Metadata().Bucket(blockIdxName) hashes := make([]chainhash.Hash, 0, 500000) blockIdxBucket.ForEach(func(k, v []byte) error { @@ -91,12 +86,7 @@ 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 } diff --git a/database/ffldb/bench_test.go b/database/ffldb/bench_test.go index 30e4f2b513..be1a0cf510 100644 --- a/database/ffldb/bench_test.go +++ b/database/ffldb/bench_test.go @@ -30,10 +30,7 @@ func BenchmarkBlockHeader(b *testing.B) { defer db.Close() err = db.Update(func(tx database.Tx) error { block := dcrutil.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) @@ -74,10 +71,7 @@ func BenchmarkBlock(b *testing.B) { defer db.Close() err = db.Update(func(tx database.Tx) error { block := dcrutil.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/blockio.go b/database/ffldb/blockio.go index b8bbe0efab..d7c7471fce 100644 --- a/database/ffldb/blockio.go +++ b/database/ffldb/blockio.go @@ -764,7 +764,7 @@ func newBlockStore(basePath string, network wire.CurrencyNet) *blockStore { writeCursor: &writeCursor{ curFile: &lockableFile{}, curFileNum: uint32(fileNum), - curOffset: uint32(fileOff), + curOffset: fileOff, }, } store.openFileFunc = store.openFile diff --git a/database/ffldb/dbcache.go b/database/ffldb/dbcache.go index 8124bf1ab1..40a7a86e2b 100644 --- a/database/ffldb/dbcache.go +++ b/database/ffldb/dbcache.go @@ -534,7 +534,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 } @@ -546,11 +546,8 @@ 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 e644300e99..4e893e2211 100644 --- a/database/ffldb/interface_test.go +++ b/database/ffldb/interface_test.go @@ -371,11 +371,8 @@ 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 @@ -1480,11 +1477,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 @@ -1918,11 +1911,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 @@ -1992,16 +1981,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 } @@ -2017,10 +2003,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", @@ -2041,7 +2024,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) @@ -2064,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 different blocks elapsed: %v", numReaders, elapsed) @@ -2118,11 +2101,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) @@ -2163,7 +2142,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 71a7e4a9af..66bbd3dff7 100644 --- a/database/internal/treap/immutable_test.go +++ b/database/internal/treap/immutable_test.go @@ -30,7 +30,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 { @@ -349,7 +349,7 @@ 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 { + if gotVal := testTreap.Has(key); !gotVal { t.Fatalf("Has: unexpected result - got %v, want false", gotVal) } @@ -380,7 +380,7 @@ 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 { + if gotVal := testTreap.Has(key); !gotVal { t.Fatalf("Has: unexpected result - got %v, want false", gotVal) } if gotVal := testTreap.Get(key); gotVal == nil { @@ -409,10 +409,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 6623177437..4cf07575e2 100644 --- a/database/internal/treap/mutable_test.go +++ b/database/internal/treap/mutable_test.go @@ -30,7 +30,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 { @@ -401,7 +401,7 @@ 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 { + if gotVal := testTreap.Has(key); !gotVal { t.Fatalf("Has: unexpected result - got %v, want false", gotVal) } if gotVal := testTreap.Get(key); !bytes.Equal(gotVal, val) { @@ -428,7 +428,7 @@ 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 { + if gotVal := testTreap.Has(key); !gotVal { t.Fatalf("Has: unexpected result - got %v, want false", gotVal) } if gotVal := testTreap.Get(key); gotVal == nil { @@ -457,10 +457,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/dcrec/edwards/curve.go b/dcrec/edwards/curve.go index d80840f695..19dd2b9f95 100644 --- a/dcrec/edwards/curve.go +++ b/dcrec/edwards/curve.go @@ -194,11 +194,8 @@ func (curve *TwistedEdwardsCurve) IsOnCurve(x *big.Int, y *big.Int) bool { // Check if we're in the cofactor of the curve (8). modEight := new(big.Int) modEight.Mod(enumBig, eight) - if modEight.Cmp(zero) != 0 { - return false - } - return true + return modEight.Cmp(zero) == 0 } // cachedGroupElement is a cached extended group element derived from diff --git a/dcrec/edwards/ecdsa_test.go b/dcrec/edwards/ecdsa_test.go index 357606e24e..6ad2a515b6 100644 --- a/dcrec/edwards/ecdsa_test.go +++ b/dcrec/edwards/ecdsa_test.go @@ -392,7 +392,7 @@ func benchmarkVerification(b *testing.B) { sigList[randIndex].msg, sigList[randIndex].sig.R, sigList[randIndex].sig.S) - if ver != true { + if !ver { panic("made invalid sig") } } diff --git a/dcrec/edwards/primitives.go b/dcrec/edwards/primitives.go index 819e3e4838..e341420ba7 100644 --- a/dcrec/edwards/primitives.go +++ b/dcrec/edwards/primitives.go @@ -248,7 +248,7 @@ func (curve *TwistedEdwardsCurve) EncodedBytesToBigIntPoint(s *[32]byte) (*big.I xIsNegBytes := sCopy[31]>>7 == 1 p := new(edwards25519.ExtendedGroupElement) - if p.FromBytes(sCopy) == false { + if !p.FromBytes(sCopy) { return nil, nil, fmt.Errorf("point not on curve") } diff --git a/dcrec/edwards/threshold_test.go b/dcrec/edwards/threshold_test.go index 16ed1dd04c..be8165c597 100644 --- a/dcrec/edwards/threshold_test.go +++ b/dcrec/edwards/threshold_test.go @@ -72,11 +72,9 @@ func TestSchnorrThreshold(t *testing.T) { } // Combine pubkeys. - allPubkeys := make([]*PublicKey, numKeysForTest, - numKeysForTest) - for j, pubkey := range pubKeysToUse { - allPubkeys[j] = pubkey - } + allPubkeys := make([]*PublicKey, numKeysForTest) + copy(allPubkeys, pubKeysToUse) + allPksSum := CombinePubkeys(curve, allPubkeys) privNoncesToUse := make([]*PrivateKey, numKeysForTest, diff --git a/dcrec/secp256k1/schnorr/ecdsa_test.go b/dcrec/secp256k1/schnorr/ecdsa_test.go index 2738e985d2..2eb5aa8f55 100644 --- a/dcrec/secp256k1/schnorr/ecdsa_test.go +++ b/dcrec/secp256k1/schnorr/ecdsa_test.go @@ -362,7 +362,7 @@ func benchmarkVerification(b *testing.B) { sigList[randIndex].msg, sigList[randIndex].sig.R, sigList[randIndex].sig.S) - if ver != true { + if !ver { panic("made invalid sig") } } diff --git a/dcrec/secp256k1/schnorr/threshold_test.go b/dcrec/secp256k1/schnorr/threshold_test.go index bab758ac0f..9bc041bd40 100644 --- a/dcrec/secp256k1/schnorr/threshold_test.go +++ b/dcrec/secp256k1/schnorr/threshold_test.go @@ -345,11 +345,9 @@ func TestSchnorrThreshold(t *testing.T) { assert.NoError(t, err) // Combine pubkeys. - allPubkeys := make([]*secp256k1.PublicKey, numKeysForTest, - numKeysForTest) - for j, pubkey := range pubKeysToUse { - allPubkeys[j] = pubkey - } + allPubkeys := make([]*secp256k1.PublicKey, numKeysForTest) + copy(allPubkeys, pubKeysToUse) + allPksSum := CombinePubkeys(curve, allPubkeys) // Verify the combined signature and public keys. @@ -420,11 +418,9 @@ func TestSchnorrThreshold(t *testing.T) { combinedSignature, _ = CombineSigs(curve, partialSignatures) // Combine pubkeys. - allPubkeys = make([]*secp256k1.PublicKey, numKeysForTest, - numKeysForTest) - for j, pubkey := range pubKeysToUse { - allPubkeys[j] = pubkey - } + allPubkeys = make([]*secp256k1.PublicKey, numKeysForTest) + copy(allPubkeys, pubKeysToUse) + allPksSum = CombinePubkeys(curve, allPubkeys) // Nothing that makes it here should be valid. diff --git a/dcrjson/help.go b/dcrjson/help.go index 0f1a6a55f7..8dd50a17b6 100644 --- a/dcrjson/help.go +++ b/dcrjson/help.go @@ -123,9 +123,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/goclean.sh b/goclean.sh index 3371f4da32..168aa8dd58 100755 --- a/goclean.sh +++ b/goclean.sh @@ -1,14 +1,38 @@ #!/bin/bash # The script does automatic checking on a Go package and its sub-packages, including: # 1. gofmt (http://golang.org/cmd/gofmt/) -# 2. golint (https://github.com/golang/lint) -# 3. go vet (http://golang.org/cmd/vet) -# 4. race detector (http://blog.golang.org/race-detector) -# 5. test coverage (http://blog.golang.org/cover) +# 2. go vet (http://golang.org/cmd/vet) +# 3. gosimple (https://github.com/dominikh/go-simple) +# 4. unconvert (https://github.com/mdempsky/unconvert) +# 5. race detector (http://blog.golang.org/race-detector) +# 6. test coverage (http://blog.golang.org/cover) +# gometalinter (github.com/alecthomas/gometalinter) is used to run each each +# static checker. set -ex +# Make sure glide is installed and $GOPATH/bin is in your path. +# $ go get -u github.com/Masterminds/glide +# $ glide install +if [ ! -x "$(type -p glide)" ]; then + exit 1 +fi + +# Make sure gometalinter is installed and $GOPATH/bin is in your path. +# $ go get -v github.com/alecthomas/gometalinter" +# $ gometalinter --install" +if [ ! -x "$(type -p gometalinter)" ]; then + exit 1 +fi + +linter_targets=$(glide novendor) + # Automatic checks -test -z "$(go fmt $(glide novendor) | tee /dev/stderr)" -test -z "$(go vet $(glide novendor) 2>&1 | tee /dev/stderr)" -env GORACE="halt_on_error=1" go test -short -race $(glide novendor) +test -z "$(gometalinter --disable-all \ +--enable=gofmt \ +--enable=vet \ +--enable=gosimple \ +--enable=unconvert \ +--deadline=4m $linter_targets 2>&1 | tee /dev/stderr)" + +env GORACE="halt_on_error=1" go test -short -race $linter_targets diff --git a/mempool/mempool.go b/mempool/mempool.go index f4eafbcd52..5852b728d4 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -1395,11 +1395,7 @@ func (mp *TxPool) ProcessTransaction(tx *dcrutil.Tx, allowOrphan, rateLimit, all // Potentially add the orphan transaction to the orphan pool. err = mp.maybeAddOrphan(tx) - 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 @@ -1504,7 +1500,7 @@ func (mp *TxPool) RawMempoolVerbose(filterType *stake.TxType) map[string]*dcrjso Size: int32(tx.MsgTx().SerializeSize()), Fee: dcrutil.Amount(desc.Fee).ToCoin(), Time: desc.Added.Unix(), - Height: int64(desc.Height), + Height: desc.Height, StartingPriority: desc.StartingPriority, CurrentPriority: currentPriority, Depends: make([]string, 0), diff --git a/mining.go b/mining.go index 5d8b407b66..c22df1e251 100644 --- a/mining.go +++ b/mining.go @@ -833,12 +833,8 @@ func deepCopyBlockTemplate(blockTemplate *BlockTemplate) *BlockTemplate { } } - sTransactionsCopy := make([]*wire.MsgTx, - len(blockTemplate.Block.STransactions), - len(blockTemplate.Block.STransactions)) - for i, mtx := range blockTemplate.Block.STransactions { - sTransactionsCopy[i] = mtx - } + sTransactionsCopy := make([]*wire.MsgTx, len(blockTemplate.Block.STransactions)) + copy(sTransactionsCopy, blockTemplate.Block.STransactions) msgBlockCopy := &wire.MsgBlock{ Header: headerCopy, @@ -846,16 +842,11 @@ func deepCopyBlockTemplate(blockTemplate *BlockTemplate) *BlockTemplate { STransactions: sTransactionsCopy, } - fees := make([]int64, len(blockTemplate.Fees), len(blockTemplate.Fees)) - for i, f := range blockTemplate.Fees { - fees[i] = f - } + fees := make([]int64, len(blockTemplate.Fees)) + copy(fees, blockTemplate.Fees) - sigOps := make([]int64, len(blockTemplate.SigOpCounts), - len(blockTemplate.SigOpCounts)) - for i, s := range blockTemplate.SigOpCounts { - sigOps[i] = s - } + sigOps := make([]int64, len(blockTemplate.SigOpCounts)) + copy(sigOps, blockTemplate.SigOpCounts) return &BlockTemplate{ Block: msgBlockCopy, @@ -1243,16 +1234,10 @@ func NewBlockTemplate(policy *mining.Policy, server *server, poolSize := chainState.nextPoolSize reqStakeDifficulty := chainState.nextStakeDifficulty finalState := chainState.nextFinalState - winningTickets := make([]chainhash.Hash, len(chainState.winningTickets), - len(chainState.winningTickets)) - for i, h := range chainState.winningTickets { - winningTickets[i] = h - } - missedTickets := make([]chainhash.Hash, len(chainState.missedTickets), - len(chainState.missedTickets)) - for i := range chainState.missedTickets { - missedTickets[i] = chainState.missedTickets[i] - } + winningTickets := make([]chainhash.Hash, len(chainState.winningTickets)) + copy(winningTickets, chainState.winningTickets) + missedTickets := make([]chainhash.Hash, len(chainState.missedTickets)) + copy(missedTickets, chainState.missedTickets) chainState.Unlock() chainBest := blockManager.chain.BestSnapshot() diff --git a/peer/log.go b/peer/log.go index cd2fa374da..99cc44fd95 100644 --- a/peer/log.go +++ b/peer/log.go @@ -152,7 +152,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 3367ffeb3f..65de915b0e 100644 --- a/peer/peer.go +++ b/peer/peer.go @@ -1077,7 +1077,7 @@ func (p *Peer) handlePongMsg(msg *wire.MsgPong) { // without large usage of the ping rpc call since we ping infrequently // enough that if they overlap we would have timed out the peer. 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 } @@ -1300,7 +1300,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 @@ -2022,7 +2022,7 @@ func (p *Peer) negotiateOutboundProtocol() error { func newPeerBase(cfg *Config, inbound bool) *Peer { // Default to the max supported protocol version. Override to the // version specified by the caller if configured. - protocolVersion := uint32(MaxProtocolVersion) + protocolVersion := MaxProtocolVersion if cfg.ProtocolVersion != 0 { protocolVersion = cfg.ProtocolVersion } diff --git a/rpcserver.go b/rpcserver.go index 48fb367398..66b4481b28 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -618,15 +618,15 @@ func handleCreateRawTransaction(s *rpcServer, cmd interface{}, closeChan <-chan return nil, rpcDecodeHexError(input.Txid) } - if !(int8(input.Tree) == wire.TxTreeRegular || - int8(input.Tree) == wire.TxTreeStake) { + if !(input.Tree == wire.TxTreeRegular || + input.Tree == wire.TxTreeStake) { return nil, dcrjson.RPCError{ Code: dcrjson.ErrRPCInvalidParams.Code, Message: "Invalid parameter, tx tree must be regular or stake", } } - prevOut := wire.NewOutPoint(txHash, uint32(input.Vout), int8(input.Tree)) + prevOut := wire.NewOutPoint(txHash, input.Vout, input.Tree) txIn := wire.NewTxIn(prevOut, []byte{}) if c.LockTime != nil && *c.LockTime != 0 { txIn.Sequence = wire.MaxTxInSequenceNum - 1 @@ -748,15 +748,15 @@ func handleCreateRawSStx(s *rpcServer, } } - if !(int8(input.Tree) == wire.TxTreeRegular || - int8(input.Tree) == wire.TxTreeStake) { + if !(input.Tree == wire.TxTreeRegular || + input.Tree == wire.TxTreeStake) { return nil, dcrjson.RPCError{ Code: dcrjson.ErrRPCInvalidParameter, Message: "Invalid parameter, tx tree must be regular or stake", } } - prevOut := wire.NewOutPoint(txHash, uint32(input.Vout), int8(input.Tree)) + prevOut := wire.NewOutPoint(txHash, input.Vout, input.Tree) txIn := wire.NewTxIn(prevOut, []byte{}) mtx.AddTxIn(txIn) } @@ -1053,14 +1053,14 @@ func handleCreateRawSSGenTx(s *rpcServer, } } - if !(int8(input.Tree) == wire.TxTreeStake) { + if !(input.Tree == wire.TxTreeStake) { return nil, dcrjson.RPCError{ Code: dcrjson.ErrRPCInvalidParameter, Message: "Invalid parameter, tx tree of sstx input must be stake", } } - prevOut := wire.NewOutPoint(txHash, uint32(input.Vout), int8(input.Tree)) + prevOut := wire.NewOutPoint(txHash, input.Vout, input.Tree) txIn := wire.NewTxIn(prevOut, []byte{}) mtx.AddTxIn(txIn) } @@ -1233,14 +1233,14 @@ func handleCreateRawSSRtx(s *rpcServer, } } - if !(int8(input.Tree) == wire.TxTreeStake) { + if !(input.Tree == wire.TxTreeStake) { return nil, dcrjson.RPCError{ Code: dcrjson.ErrRPCInvalidParameter, Message: "Invalid parameter, tx tree of sstx input must be stake", } } - prevOut := wire.NewOutPoint(txHash, uint32(input.Vout), int8(input.Tree)) + prevOut := wire.NewOutPoint(txHash, input.Vout, input.Tree) txIn := wire.NewTxIn(prevOut, []byte{}) mtx.AddTxIn(txIn) } @@ -2194,7 +2194,7 @@ func handleGetBlock(s *rpcServer, cmd interface{}, // handleGetBlockCount implements the getblockcount command. func handleGetBlockCount(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { best := s.chain.BestSnapshot() - return int64(best.Height), nil + return best.Height, nil } // handleGetBlockHash implements the getblockhash command. @@ -3466,7 +3466,7 @@ func handleGetMiningInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{ } result := dcrjson.GetMiningInfoResult{ - Blocks: int64(best.Height), + Blocks: best.Height, CurrentBlockSize: best.BlockSize, CurrentBlockTx: best.NumTxns, Difficulty: getDifficultyRatio(best.Bits), @@ -3628,7 +3628,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 } @@ -3880,7 +3880,7 @@ func handleGetStakeVersionInfo(s *rpcServer, cmd interface{}, closeChan <-chan s snapshot := s.chain.BestSnapshot() - interval := int64(s.server.chainParams.StakeVersionInterval) + interval := s.server.chainParams.StakeVersionInterval // Assemble JSON result. result := dcrjson.GetStakeVersionInfoResult{ CurrentHeight: snapshot.Height, @@ -5742,7 +5742,7 @@ func handleTicketVWAP(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) } ticketNum += int64(blockHeader.FreshStake) - totalValue += int64(blockHeader.SBits) * int64(blockHeader.FreshStake) + totalValue += blockHeader.SBits * int64(blockHeader.FreshStake) } vwap := int64(0) if ticketNum > 0 { @@ -5959,7 +5959,7 @@ func handleVerifyMessage(s *rpcServer, cmd interface{}, closeChan <-chan struct{ } // Reconstruct the pubkey hash. - dcrPK := (chainec.PublicKey)(pk) + dcrPK := pk var serializedPK []byte if wasCompressed { serializedPK = dcrPK.SerializeCompressed() @@ -6072,11 +6072,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. @@ -6279,7 +6275,7 @@ func (s *rpcServer) jsonRPCRead(w http.ResponseWriter, r *http.Request, isAdmin if err != nil { errMsg := fmt.Sprintf("error reading JSON message: %v", err) errCode := http.StatusBadRequest - http.Error(w, strconv.FormatInt(int64(errCode), 10)+" "+errMsg, + http.Error(w, strconv.Itoa(errCode)+" "+errMsg, errCode) return } @@ -6295,7 +6291,7 @@ 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, + http.Error(w, strconv.Itoa(errCode)+" "+errMsg, errCode) return } @@ -6303,7 +6299,7 @@ func (s *rpcServer) jsonRPCRead(w http.ResponseWriter, r *http.Request, isAdmin if err != nil { rpcsLog.Warnf("Failed to hijack HTTP connection: %v", err) errCode := http.StatusInternalServerError - http.Error(w, strconv.FormatInt(int64(errCode), 10)+" "+ + http.Error(w, strconv.Itoa(errCode)+" "+ err.Error(), errCode) return } diff --git a/server.go b/server.go index 6d0eecec29..26eb2ca140 100644 --- a/server.go +++ b/server.go @@ -528,9 +528,7 @@ func (sp *serverPeer) OnGetMiningState(p *peer.Peer, msg *wire.MsgGetMiningState "metadata for block", bh) return } - for _, vh := range vhsForBlock { - voteHashes = append(voteHashes, vh) - } + voteHashes = append(voteHashes, vhsForBlock...) } err = sp.pushMiningStateMsg(uint32(height), blockHashes, voteHashes) @@ -1230,7 +1228,7 @@ func (s *server) handleUpdatePeerHeights(state *peerState, umsg updatePeerHeight // matches our newly accepted block, then update their block // height. if *latestBlkHash == *umsg.newHash { - sp.UpdateLastBlockHeight(int64(umsg.newHeight)) + sp.UpdateLastBlockHeight(umsg.newHeight) sp.UpdateLastAnnouncedBlock(nil) } }) @@ -1919,7 +1917,7 @@ out: // 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/txscript/engine.go b/txscript/engine.go index e21d0a2321..f23eab37af 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) @@ -345,7 +345,7 @@ 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 7d65670d89..0d2d4faf83 100644 --- a/txscript/opcode.go +++ b/txscript/opcode.go @@ -1010,7 +1010,7 @@ func opcodeVerify(op *parsedOpcode, vm *Engine) error { return err } - if verified != true { + if !verified { return ErrStackVerifyFailed } return nil diff --git a/txscript/scriptbuilder.go b/txscript/scriptbuilder.go index f0cdd0f08a..d5132755b8 100644 --- a/txscript/scriptbuilder.go +++ b/txscript/scriptbuilder.go @@ -136,7 +136,7 @@ func (b *ScriptBuilder) addData(data []byte) *ScriptBuilder { b.script = append(b.script, OP_0) return b } else if dataLen == 1 && data[0] <= 16 { - b.script = append(b.script, byte((OP_1-1)+data[0])) + b.script = append(b.script, OP_1-1+data[0]) return b } else if dataLen == 1 && data[0] == 0x81 { b.script = append(b.script, byte(OP_1NEGATE)) diff --git a/txscript/stack_test.go b/txscript/stack_test.go index e5b1fbf4c5..29377bba57 100644 --- a/txscript/stack_test.go +++ b/txscript/stack_test.go @@ -117,7 +117,7 @@ func TestStack(t *testing.T) { return err } - if val != false { + if val { return errors.New("unexpected value") } return nil @@ -134,7 +134,7 @@ func TestStack(t *testing.T) { return err } - if val != true { + if !val { return errors.New("unexpected value") } return nil @@ -147,11 +147,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, @@ -346,12 +342,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}}, @@ -360,12 +351,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}}, @@ -374,12 +360,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}}, @@ -388,12 +369,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, @@ -402,12 +378,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, @@ -416,12 +387,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, @@ -457,7 +423,7 @@ func TestStack(t *testing.T) { if err != nil { return err } - if val != true { + if !val { return errors.New("unexpected value") } @@ -475,7 +441,7 @@ func TestStack(t *testing.T) { if err != nil { return err } - if val != false { + if val { return errors.New("unexpected value") } @@ -493,7 +459,7 @@ func TestStack(t *testing.T) { if err != nil { return err } - if val != true { + if !val { return errors.New("unexpected value") } @@ -511,7 +477,7 @@ func TestStack(t *testing.T) { if err != nil { return err } - if val != false { + if val { return errors.New("unexpected value") } @@ -810,7 +776,7 @@ func TestStack(t *testing.T) { if err != nil { return err } - if val != true { + if !val { return errors.New("invalid result") } return nil @@ -828,7 +794,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/txscript/standard.go b/txscript/standard.go index 71a8cd4cee..ecf6dd7ad2 100644 --- a/txscript/standard.go +++ b/txscript/standard.go @@ -171,15 +171,11 @@ func isAnyKindOfScriptHash(pops []parsedOpcode) bool { return true } - stakeP2SH := len(pops) == 4 && + return len(pops) == 4 && (pops[0].opcode.value >= 186 && pops[0].opcode.value <= 189) && pops[1].opcode.value == OP_HASH160 && pops[2].opcode.value == OP_DATA_20 && pops[3].opcode.value == OP_EQUAL - if stakeP2SH { - return true - } - return false } // isMultiSig returns true if the passed script is a multisig transaction, false diff --git a/upnp.go b/upnp.go index 172d9eba90..f91196a329 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 98d700d7f9..f0f55ca4e6 100644 --- a/wire/blockheader.go +++ b/wire/blockheader.go @@ -192,7 +192,7 @@ func NewBlockHeader(version int32, prevHash *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( + return readElements( r, &bh.Version, &bh.PrevBlock, @@ -212,11 +212,6 @@ func readBlockHeader(r io.Reader, pver uint32, bh *BlockHeader) error { &bh.Nonce, &bh.ExtraData, &bh.StakeVersion) - if err != nil { - return err - } - - return nil } // writeBlockHeader writes a decred block header to w. See Serialize for @@ -225,7 +220,7 @@ func readBlockHeader(r io.Reader, pver uint32, bh *BlockHeader) error { // TODO: make sure serializing/writing is actually correct w/r/t dereferencing func writeBlockHeader(w io.Writer, pver uint32, bh *BlockHeader) error { sec := uint32(bh.Timestamp.Unix()) - err := writeElements( + return writeElements( w, bh.Version, &bh.PrevBlock, @@ -245,9 +240,4 @@ func writeBlockHeader(w io.Writer, pver uint32, bh *BlockHeader) error { bh.Nonce, bh.ExtraData, bh.StakeVersion) - if err != nil { - return err - } - - return nil } diff --git a/wire/common.go b/wire/common.go index 93cfb272ff..387a61b0f2 100644 --- a/wire/common.go +++ b/wire/common.go @@ -379,7 +379,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) @@ -625,10 +625,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 @@ -673,10 +670,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 c06f5cf7cb..16e072a781 100644 --- a/wire/invvect.go +++ b/wire/invvect.go @@ -68,18 +68,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 b93c233ec8..eeef3012de 100644 --- a/wire/message.go +++ b/wire/message.go @@ -266,11 +266,7 @@ func WriteMessageN(w io.Writer, msg Message, pver uint32, dcrnet CurrencyNet) (i // Write payload. n, err = w.Write(payload) totalBytes += n - if err != nil { - return totalBytes, err - } - - return totalBytes, nil + return totalBytes, err } // WriteMessage writes a decred Message to w including the necessary header diff --git a/wire/msgalert.go b/wire/msgalert.go index 10a5012b95..d25067cdd4 100644 --- a/wire/msgalert.go +++ b/wire/msgalert.go @@ -166,7 +166,7 @@ func (alert *Alert) Serialize(w io.Writer, pver uint32) error { if err != nil { return err } - for i := 0; i < int(count); i++ { + for i := 0; i < count; i++ { err = writeElement(w, alert.SetCancel[i]) if err != nil { return err @@ -188,7 +188,7 @@ func (alert *Alert) Serialize(w io.Writer, pver uint32) error { if err != nil { return err } - for i := 0; i < int(count); i++ { + for i := 0; i < count; i++ { err = WriteVarString(w, pver, alert.SetSubVer[i]) if err != nil { return err @@ -207,11 +207,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 @@ -280,10 +276,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. @@ -357,11 +350,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 decred protocol encoding. @@ -391,11 +380,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/msgfilteradd.go b/wire/msgfilteradd.go index c0bc4523c0..861116fb20 100644 --- a/wire/msgfilteradd.go +++ b/wire/msgfilteradd.go @@ -32,11 +32,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 decred protocol encoding. @@ -49,12 +45,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 571bf4fae6..0ac4db9df6 100644 --- a/wire/msgfilterload.go +++ b/wire/msgfilterload.go @@ -95,12 +95,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 579f55e15e..2c3d267dba 100644 --- a/wire/msggetblocks.go +++ b/wire/msggetblocks.go @@ -81,12 +81,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 decred protocol encoding. @@ -116,12 +111,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 25707874f5..a09a41a9bb 100644 --- a/wire/msggetheaders.go +++ b/wire/msggetheaders.go @@ -78,12 +78,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 decred protocol encoding. @@ -114,12 +109,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 bc415581e5..cb6fa648fc 100644 --- a/wire/msgmerkleblock.go +++ b/wire/msgmerkleblock.go @@ -127,11 +127,7 @@ func (msg *MsgMerkleBlock) BtcDecode(r io.Reader, pver uint32) error { msg.Flags, err = ReadVarBytes(r, pver, maxFlagsPerMerkleBlock(pver), "merkle block flags size") - if err != nil { - return err - } - - return nil + return err } // BtcEncode encodes the receiver to w using the decred protocol encoding. @@ -171,7 +167,7 @@ func (msg *MsgMerkleBlock) BtcEncode(w io.Writer, pver uint32) error { return err } - err = WriteVarInt(w, pver, uint64(numHashes)) + err = WriteVarInt(w, pver, numHashes) if err != nil { return err } @@ -187,7 +183,7 @@ func (msg *MsgMerkleBlock) BtcEncode(w io.Writer, pver uint32) error { return err } - err = WriteVarInt(w, pver, uint64(numSHashes)) + err = WriteVarInt(w, pver, numSHashes) if err != nil { return err } @@ -198,12 +194,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/msgping.go b/wire/msgping.go index cda1e2670e..5e178eae9c 100644 --- a/wire/msgping.go +++ b/wire/msgping.go @@ -30,22 +30,14 @@ type MsgPing struct { // This is part of the Message interface implementation. func (msg *MsgPing) BtcDecode(r io.Reader, pver uint32) error { err := readElement(r, &msg.Nonce) - if err != nil { - return err - } - - return nil + return err } // BtcEncode encodes the receiver to w using the decred protocol encoding. // This is part of the Message interface implementation. func (msg *MsgPing) BtcEncode(w io.Writer, pver uint32) error { err := writeElement(w, msg.Nonce) - if err != nil { - return err - } - - return nil + return err } // Command returns the protocol command string for the message. This is part diff --git a/wire/msgpong.go b/wire/msgpong.go index 9826279e2d..fd145f59d1 100644 --- a/wire/msgpong.go +++ b/wire/msgpong.go @@ -23,23 +23,13 @@ type MsgPong struct { // BtcDecode decodes r using the decred protocol encoding into the receiver. // This is part of the Message interface implementation. func (msg *MsgPong) BtcDecode(r io.Reader, pver uint32) error { - 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 decred protocol encoding. // This is part of the Message interface implementation. func (msg *MsgPong) BtcEncode(w io.Writer, pver uint32) error { - 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 c49130dddf..48d51db179 100644 --- a/wire/msgtx.go +++ b/wire/msgtx.go @@ -1219,12 +1219,7 @@ func (msg *MsgTx) encodePrefix(w io.Writer, pver uint32) error { return err } - err = binarySerializer.PutUint32(w, littleEndian, msg.Expiry) - if err != nil { - return err - } - - return nil + return binarySerializer.PutUint32(w, littleEndian, msg.Expiry) } // encodeWitness encodes a transaction witness into a writer. @@ -1369,12 +1364,7 @@ func (msg *MsgTx) LegacyBtcEncode(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 @@ -1670,12 +1660,7 @@ func WriteOutPoint(w io.Writer, pver uint32, version int32, op *OutPoint) error return err } - err = binarySerializer.PutUint8(w, uint8(op.Tree)) - if err != nil { - return err - } - - return nil + return binarySerializer.PutUint8(w, uint8(op.Tree)) } // legacyReadOutPoint reads the next sequence of bytes from r as a legacy @@ -1688,11 +1673,7 @@ func legacyReadOutPoint(r io.Reader, pver uint32, version int32, } op.Index, err = binarySerializer.Uint32(r, littleEndian) - if err != nil { - return err - } - - return nil + return err } // legacyWriteOutPoint encodes op to the decred protocol encoding for a legacy @@ -1704,12 +1685,7 @@ func legacyWriteOutPoint(w io.Writer, pver uint32, version int32, return err } - err = binarySerializer.PutUint32(w, littleEndian, op.Index) - if err != nil { - return err - } - - return nil + return binarySerializer.PutUint32(w, littleEndian, op.Index) } // readTxInPrefix reads the next sequence of bytes from r as a transaction input @@ -1728,11 +1704,7 @@ func readTxInPrefix(r io.Reader, pver uint32, version int32, ti *TxIn) error { // Sequence. ti.Sequence, err = binarySerializer.Uint32(r, littleEndian) - if err != nil { - return err - } - - return nil + return err } // readTxInWitness reads the next sequence of bytes from r as a transaction input @@ -1760,11 +1732,7 @@ func readTxInWitness(r io.Reader, pver uint32, version int32, ti *TxIn) error { // Signature script. ti.SignatureScript, err = readScript(r, pver, MaxMessagePayload, "transaction input signature script") - if err != nil { - return err - } - - return nil + return err } // readTxInWitnessSigning reads a TxIn witness for signing. @@ -1775,11 +1743,7 @@ func readTxInWitnessSigning(r io.Reader, pver uint32, version int32, // Signature script. ti.SignatureScript, err = readScript(r, pver, MaxMessagePayload, "transaction input signature script") - if err != nil { - return err - } - - return nil + return err } // readTxInWitnessValueSigning reads a TxIn witness for signing with value @@ -1796,11 +1760,7 @@ func readTxInWitnessValueSigning(r io.Reader, pver uint32, version int32, // Signature script. ti.SignatureScript, err = readScript(r, pver, MaxMessagePayload, "transaction input signature script") - if err != nil { - return err - } - - return nil + return err } // readTxInPrefix reads the next sequence of bytes from r as a transaction input @@ -1818,11 +1778,7 @@ func legacyReadTxIn(r io.Reader, pver uint32, version int32, ti *TxIn) error { } ti.Sequence, err = binarySerializer.Uint32(r, littleEndian) - if err != nil { - return err - } - - return nil + return err } // legacyWriteTxIn encodes ti to the decred protocol encoding for a transaction @@ -1838,12 +1794,7 @@ func legacyWriteTxIn(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) } // writeTxInPrefixs encodes ti to the decred protocol encoding for a transaction @@ -1854,12 +1805,7 @@ func writeTxInPrefix(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) } // writeTxWitness encodes ti to the decred protocol encoding for a transaction @@ -1884,27 +1830,14 @@ func writeTxInWitness(w io.Writer, pver uint32, version int32, ti *TxIn) error { } // Write the signature script. - err = WriteVarBytes(w, pver, ti.SignatureScript) - if err != nil { - return err - } - - return nil + return WriteVarBytes(w, pver, ti.SignatureScript) } // writeTxInWitnessSigning encodes ti to the decred protocol encoding for a // transaction input (TxIn) witness to w for signing. -func writeTxInWitnessSigning(w io.Writer, pver uint32, version int32, - ti *TxIn) error { - var err error - +func writeTxInWitnessSigning(w io.Writer, pver uint32, version int32, ti *TxIn) error { // Only write the signature script. - err = WriteVarBytes(w, pver, ti.SignatureScript) - if err != nil { - return err - } - - return nil + return WriteVarBytes(w, pver, ti.SignatureScript) } // writeTxInWitnessValueSigning encodes ti to the decred protocol encoding for a @@ -1920,12 +1853,7 @@ func writeTxInWitnessValueSigning(w io.Writer, pver uint32, version int32, } // Signature script. - err = WriteVarBytes(w, pver, ti.SignatureScript) - if err != nil { - return err - } - - return nil + return WriteVarBytes(w, pver, ti.SignatureScript) } // readTxOut reads the next sequence of bytes from r as a transaction output @@ -1944,11 +1872,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 decred protocol encoding for a transaction @@ -1964,11 +1888,7 @@ 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) } // legacyReadTxOut reads the next sequence of bytes from r as a transaction output @@ -1982,11 +1902,7 @@ func legacyReadTxOut(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 } // legacyWriteTxOut encodes to into the decred protocol encoding for a transaction @@ -1997,19 +1913,12 @@ func legacyWriteTxOut(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) } // IsSupportedMsgTxVersion returns if a transaction version is supported or not. // Currently, inclusion into the memory pool (and thus blocks) only supports // the DefaultMsgTxVersion. func IsSupportedMsgTxVersion(msgTx *MsgTx) bool { - if msgTx.Version == DefaultMsgTxVersion() { - return true - } - return false + return msgTx.Version == DefaultMsgTxVersion() } diff --git a/wire/msgversion.go b/wire/msgversion.go index bae53bdb1e..ab6480f25f 100644 --- a/wire/msgversion.go +++ b/wire/msgversion.go @@ -188,12 +188,7 @@ func (msg *MsgVersion) BtcEncode(w io.Writer, pver uint32) error { return err } - err = writeElement(w, !msg.DisableRelayTx) - if err != nil { - return err - } - - return nil + return writeElement(w, !msg.DisableRelayTx) } // Command returns the protocol command string for the message. This is part diff --git a/wire/msgversion_test.go b/wire/msgversion_test.go index f125cb2123..ca193958b2 100644 --- a/wire/msgversion_test.go +++ b/wire/msgversion_test.go @@ -64,7 +64,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 d08e199c39..c80eacb305 100644 --- a/wire/netaddress.go +++ b/wire/netaddress.go @@ -51,10 +51,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 @@ -156,10 +153,5 @@ func writeNetAddress(w io.Writer, pver uint32, na *NetAddress, ts bool) error { } // Sigh. Decred 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) }