multi: Simplify code per gosimple linter.

This simplifies the code based on the recommendations of the gosimple
lint tool.
This commit is contained in:
Dave Collins 2016-11-02 23:02:04 -05:00
parent af524fb3e7
commit 915fa6639b
No known key found for this signature in database
GPG Key ID: B8904D9D9C93D1F2
43 changed files with 122 additions and 412 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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