Merge pull request #688 from gzliudan/fix-nil-deref

fix nil issues reported by nilness and staticcheck
This commit is contained in:
Daniel Liu 2024-10-31 09:31:14 +08:00 committed by GitHub
commit f81cb2bf55
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 30 additions and 40 deletions

View file

@ -280,7 +280,7 @@ func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]int
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
sub, err := event.NewSubscription(func(quit <-chan struct{}) error { sub := event.NewSubscription(func(quit <-chan struct{}) error {
for _, log := range buff { for _, log := range buff {
select { select {
case logs <- log: case logs <- log:
@ -289,11 +289,8 @@ func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]int
} }
} }
return nil return nil
}), nil })
if err != nil {
return nil, nil, err
}
return logs, sub, nil return logs, sub, nil
} }

View file

@ -12,6 +12,7 @@ import (
"github.com/XinFinOrg/XDPoSChain/cmd/utils" "github.com/XinFinOrg/XDPoSChain/cmd/utils"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/common/lru"
"github.com/XinFinOrg/XDPoSChain/core" "github.com/XinFinOrg/XDPoSChain/core"
"github.com/XinFinOrg/XDPoSChain/core/rawdb" "github.com/XinFinOrg/XDPoSChain/core/rawdb"
"github.com/XinFinOrg/XDPoSChain/core/state" "github.com/XinFinOrg/XDPoSChain/core/state"
@ -20,7 +21,6 @@ import (
"github.com/XinFinOrg/XDPoSChain/ethdb/leveldb" "github.com/XinFinOrg/XDPoSChain/ethdb/leveldb"
"github.com/XinFinOrg/XDPoSChain/rlp" "github.com/XinFinOrg/XDPoSChain/rlp"
"github.com/XinFinOrg/XDPoSChain/trie" "github.com/XinFinOrg/XDPoSChain/trie"
"github.com/XinFinOrg/XDPoSChain/common/lru"
) )
var ( var (
@ -170,7 +170,7 @@ func getAllChilds(n StateNode, db *leveldb.Database) ([17]*StateNode, error) {
} }
if err == nil { if err == nil {
childs[i] = &StateNode{node: childNode, path: append(n.path, byte(i))} childs[i] = &StateNode{node: childNode, path: append(n.path, byte(i))}
} else if err != nil { } else {
_, ok := err.(*trie.MissingNodeError) _, ok := err.(*trie.MissingNodeError)
if !ok { if !ok {
return childs, err return childs, err
@ -187,7 +187,7 @@ func getAllChilds(n StateNode, db *leveldb.Database) ([17]*StateNode, error) {
} }
if err == nil { if err == nil {
childs[0] = &StateNode{node: childNode, path: append(n.path, node.Key...)} childs[0] = &StateNode{node: childNode, path: append(n.path, node.Key...)}
} else if err != nil { } else {
_, ok := err.(*trie.MissingNodeError) _, ok := err.(*trie.MissingNodeError)
if !ok { if !ok {
return childs, err return childs, err

View file

@ -82,7 +82,6 @@ func (w *wizard) gatherStats(server string, pubkey []byte, client *sshClient) *s
logger.Info("Starting remote server health-check") logger.Info("Starting remote server health-check")
stat := &serverStat{ stat := &serverStat{
address: client.address,
services: make(map[string]map[string]string), services: make(map[string]map[string]string),
} }
if client == nil { if client == nil {
@ -94,6 +93,8 @@ func (w *wizard) gatherStats(server string, pubkey []byte, client *sshClient) *s
} }
client = conn client = conn
} }
stat.address = client.address
// Client connected one way or another, run health-checks // Client connected one way or another, run health-checks
logger.Debug("Checking for nginx availability") logger.Debug("Checking for nginx availability")
if infos, err := checkNginx(client, w.network); err != nil { if infos, err := checkNginx(client, w.network); err != nil {

View file

@ -476,7 +476,7 @@ func (x *XDPoS_v1) snapshot(chain consensus.ChainReader, number uint64, hash com
headers []*types.Header headers []*types.Header
snap *SnapshotV1 snap *SnapshotV1
) )
for snap == nil { for {
// If an in-memory SnapshotV1 was found, use that // If an in-memory SnapshotV1 was found, use that
if s, ok := x.recents.Get(hash); ok { if s, ok := x.recents.Get(hash); ok {
snap = s.(*SnapshotV1) snap = s.(*SnapshotV1)

View file

@ -210,7 +210,7 @@ func (f *Forensics) findAncestorQCs(chain consensus.ChainReader, currentQc types
parentHash := quorumCertificate.ProposedBlockInfo.Hash parentHash := quorumCertificate.ProposedBlockInfo.Hash
parentHeader := chain.GetHeaderByHash(parentHash) parentHeader := chain.GetHeaderByHash(parentHash)
if parentHeader == nil { if parentHeader == nil {
log.Error("[findAncestorQCs] Forensics findAncestorQCs unable to find its parent block header", "BlockNum", parentHeader.Number.Int64(), "ParentHash", parentHash.Hex()) log.Error("[findAncestorQCs] Forensics findAncestorQCs unable to find its parent block header", "ParentHash", parentHash.Hex())
return nil, errors.New("unable to find parent block header in forensics") return nil, errors.New("unable to find parent block header in forensics")
} }
var decodedExtraField types.ExtraFields_v2 var decodedExtraField types.ExtraFields_v2

View file

@ -390,7 +390,7 @@ func (c *Clique) snapshot(chain consensus.ChainReader, number uint64, hash commo
headers []*types.Header headers []*types.Header
snap *Snapshot snap *Snapshot
) )
for snap == nil { for {
// If an in-memory snapshot was found, use that // If an in-memory snapshot was found, use that
if s, ok := c.recents.Get(hash); ok { if s, ok := c.recents.Get(hash); ok {
snap = s.(*Snapshot) snap = s.(*Snapshot)

View file

@ -1659,7 +1659,7 @@ func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []
} }
} }
//check //check
if tradingState != nil && tradingService != nil { if tradingState != nil {
gotRoot := tradingState.IntermediateRoot() gotRoot := tradingState.IntermediateRoot()
expectRoot, _ := tradingService.GetTradingStateRoot(block, author) expectRoot, _ := tradingService.GetTradingStateRoot(block, author)
parentRoot, _ := tradingService.GetTradingStateRoot(parent, parentAuthor) parentRoot, _ := tradingService.GetTradingStateRoot(parent, parentAuthor)
@ -1938,7 +1938,7 @@ func (bc *BlockChain) getResultBlock(block *types.Block, verifiedM2 bool) (*Resu
} }
} }
} }
if tradingState != nil && tradingService != nil { if tradingState != nil {
gotRoot := tradingState.IntermediateRoot() gotRoot := tradingState.IntermediateRoot()
expectRoot, _ := tradingService.GetTradingStateRoot(block, author) expectRoot, _ := tradingService.GetTradingStateRoot(block, author)
parentRoot, _ := tradingService.GetTradingStateRoot(parent, parentAuthor) parentRoot, _ := tradingService.GetTradingStateRoot(parent, parentAuthor)

View file

@ -60,10 +60,6 @@ func getNonce(t *testing.T, userAddress common.Address) (uint64, error) {
return 0, err return 0, err
} }
var result interface{} var result interface{}
if err != nil {
return 0, err
}
err = rpcClient.Call(&result, "XDCx_getOrderCount", userAddress) err = rpcClient.Call(&result, "XDCx_getOrderCount", userAddress)
if err != nil { if err != nil {
return 0, err return 0, err

View file

@ -285,9 +285,7 @@ func (pm *ProtocolManager) removePeer(id string) {
log.Debug("Peer removal failed", "peer", id, "err", err) log.Debug("Peer removal failed", "peer", id, "err", err)
} }
// Hard disconnect at the networking layer // Hard disconnect at the networking layer
if peer != nil { peer.Peer.Disconnect(p2p.DiscUselessPeer)
peer.Peer.Disconnect(p2p.DiscUselessPeer)
}
} }
func (pm *ProtocolManager) Start(maxPeers int) { func (pm *ProtocolManager) Start(maxPeers int) {

View file

@ -147,7 +147,7 @@ func lesTopic(genesisHash common.Hash, protocolVersion uint) discv5.Topic {
case lpv2: case lpv2:
name = "LES2" name = "LES2"
default: default:
panic(nil) panic("lesTopic")
} }
return discv5.Topic(name + "@" + common.Bytes2Hex(genesisHash.Bytes()[0:8])) return discv5.Topic(name + "@" + common.Bytes2Hex(genesisHash.Bytes()[0:8]))
} }

View file

@ -196,7 +196,7 @@ func (r *TrieRequest) GetCost(peer *peer) uint64 {
case lpv2: case lpv2:
return peer.GetRequestCost(GetProofsV2Msg, 1) return peer.GetRequestCost(GetProofsV2Msg, 1)
default: default:
panic(nil) panic("TrieRequest GetCost")
} }
} }
@ -356,7 +356,7 @@ func (r *ChtRequest) GetCost(peer *peer) uint64 {
case lpv2: case lpv2:
return peer.GetRequestCost(GetHelperTrieProofsMsg, 1) return peer.GetRequestCost(GetHelperTrieProofsMsg, 1)
default: default:
panic(nil) panic("ChtRequest GetCost")
} }
} }

View file

@ -279,7 +279,7 @@ func (p *peer) RequestProofs(reqID, cost uint64, reqs []ProofReq) error {
case lpv2: case lpv2:
return sendRequest(p.rw, GetProofsV2Msg, reqID, cost, reqs) return sendRequest(p.rw, GetProofsV2Msg, reqID, cost, reqs)
default: default:
panic(nil) panic("peer RequestProofs")
} }
} }
@ -301,7 +301,7 @@ func (p *peer) RequestHelperTrieProofs(reqID, cost uint64, reqs []HelperTrieReq)
case lpv2: case lpv2:
return sendRequest(p.rw, GetHelperTrieProofsMsg, reqID, cost, reqs) return sendRequest(p.rw, GetHelperTrieProofsMsg, reqID, cost, reqs)
default: default:
panic(nil) panic("peer RequestHelperTrieProofs")
} }
} }
@ -320,7 +320,7 @@ func (p *peer) SendTxs(reqID, cost uint64, txs types.Transactions) error {
case lpv2: case lpv2:
return sendRequest(p.rw, SendTxV2Msg, reqID, cost, txs) return sendRequest(p.rw, SendTxV2Msg, reqID, cost, txs)
default: default:
panic(nil) panic("peer SendTxs")
} }
} }

View file

@ -109,7 +109,7 @@ func (n *wrsNode) insert(item wrsItem, weight int64) int {
for n.items[branch] != nil && (n.level == 0 || n.items[branch].(*wrsNode).itemCnt == n.items[branch].(*wrsNode).maxItems) { for n.items[branch] != nil && (n.level == 0 || n.items[branch].(*wrsNode).itemCnt == n.items[branch].(*wrsNode).maxItems) {
branch++ branch++
if branch == wrsBranches { if branch == wrsBranches {
panic(nil) panic("wrsNode insert: branch == wrsBranches")
} }
} }
n.itemCnt++ n.itemCnt++
@ -169,5 +169,5 @@ func (n *wrsNode) choose(val int64) (wrsItem, int64) {
val -= w val -= w
} }
} }
panic(nil) panic("wrsNode choose")
} }

View file

@ -306,7 +306,7 @@ func (r *sentReq) tryRequest() {
s, ok := r.sentTo[p] s, ok := r.sentTo[p]
r.lock.RUnlock() r.lock.RUnlock()
if !ok { if !ok {
panic(nil) panic("sentReq tryRequest: !ok")
} }
defer func() { defer func() {

View file

@ -22,11 +22,10 @@ import (
"math/big" "math/big"
"time" "time"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/common/bitutil" "github.com/XinFinOrg/XDPoSChain/common/bitutil"
"github.com/XinFinOrg/XDPoSChain/core" "github.com/XinFinOrg/XDPoSChain/core"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/core/types"
"github.com/XinFinOrg/XDPoSChain/ethdb" "github.com/XinFinOrg/XDPoSChain/ethdb"
"github.com/XinFinOrg/XDPoSChain/log" "github.com/XinFinOrg/XDPoSChain/log"
@ -165,7 +164,7 @@ func (c *ChtIndexerBackend) Process(header *types.Header) {
td := core.GetTd(c.diskdb, hash, num) td := core.GetTd(c.diskdb, hash, num)
if td == nil { if td == nil {
panic(nil) panic("ChtIndexerBackend Process: td == nil")
} }
var encNumber [8]byte var encNumber [8]byte
binary.BigEndian.PutUint64(encNumber[:], num) binary.BigEndian.PutUint64(encNumber[:], num)

View file

@ -64,11 +64,13 @@ func (msg *CallMsg) SetGas(gas int64) { msg.msg.Gas = uint64(gas) }
func (msg *CallMsg) SetGasPrice(price *BigInt) { msg.msg.GasPrice = price.bigint } func (msg *CallMsg) SetGasPrice(price *BigInt) { msg.msg.GasPrice = price.bigint }
func (msg *CallMsg) SetValue(value *BigInt) { msg.msg.Value = value.bigint } func (msg *CallMsg) SetValue(value *BigInt) { msg.msg.Value = value.bigint }
func (msg *CallMsg) SetData(data []byte) { msg.msg.Data = common.CopyBytes(data) } func (msg *CallMsg) SetData(data []byte) { msg.msg.Data = common.CopyBytes(data) }
func (msg *CallMsg) SetTo(address *Address) { func (msg *CallMsg) SetTo(address *Address) {
if address == nil { if address == nil {
msg.msg.To = nil msg.msg.To = nil
} else {
msg.msg.To = &address.address
} }
msg.msg.To = &address.address
} }
// SyncProgress gives progress indications when the node is synchronising with // SyncProgress gives progress indications when the node is synchronising with

View file

@ -441,7 +441,7 @@ func (s *ticketStore) removeTicketRef(ref ticketRef) {
} }
} }
if idx == -1 { if idx == -1 {
panic(nil) panic("ticketStore removeTicketRef: idx == -1")
} }
list = append(list[:idx], list[idx+1:]...) list = append(list[:idx], list[idx+1:]...)
if len(list) != 0 { if len(list) != 0 {
@ -802,7 +802,7 @@ func (r *topicRadius) chooseLookupBucket(a, b int) int {
rnd-- rnd--
} }
} }
panic(nil) // should never happen panic("topicRadius chooseLookupBucket") // should never happen
} }
func (r *topicRadius) needMoreLookups(a, b int, maxValue float64) bool { func (r *topicRadius) needMoreLookups(a, b int, maxValue float64) bool {

View file

@ -243,7 +243,7 @@ func (t *Trie) tryGetAllLeftKeyAndValue(origNode Node, prefix []byte, limit []by
if err != nil { if err != nil {
return nil, nil, n, false, err return nil, nil, n, false, err
} }
if err == nil && didResolve { if didResolve {
n = n.copy() n = n.copy()
n.Children[i] = newnode n.Children[i] = newnode
} }

View file

@ -501,9 +501,6 @@ func (whisper *Whisper) AddSymKeyFromPassword(password string) (string, error) {
// kdf should run no less than 0.1 seconds on an average computer, // kdf should run no less than 0.1 seconds on an average computer,
// because it's an once in a session experience // because it's an once in a session experience
derived := pbkdf2.Key([]byte(password), nil, 65356, aesKeyLength, sha256.New) derived := pbkdf2.Key([]byte(password), nil, 65356, aesKeyLength, sha256.New)
if err != nil {
return "", err
}
whisper.keyMu.Lock() whisper.keyMu.Lock()
defer whisper.keyMu.Unlock() defer whisper.keyMu.Unlock()