diff --git a/autopilot/graph.go b/autopilot/graph.go index 7b97b7c6f0..b4e415077f 100644 --- a/autopilot/graph.go +++ b/autopilot/graph.go @@ -3,6 +3,7 @@ package autopilot import ( "bytes" "encoding/hex" + "errors" "net" "sort" "sync/atomic" @@ -134,7 +135,9 @@ func (d *dbNode) ForEachChannel(cb func(ChannelEdge) error) error { // // NOTE: Part of the autopilot.ChannelGraph interface. func (d *databaseChannelGraph) ForEachNode(cb func(Node) error) error { - return d.db.ForEachNode(func(tx kvdb.RTx, n *models.LightningNode) error { + return d.db.ForEachNode(func(tx kvdb.RTx, + n *models.LightningNode) error { + // We'll skip over any node that doesn't have any advertised // addresses. As we won't be able to reach them to actually // open any channels. @@ -168,9 +171,9 @@ func (d *databaseChannelGraph) addRandChannel(node1, node2 *btcec.PublicKey, dbNode, err := d.db.FetchLightningNode(vertex) switch { - case err == graphdb.ErrGraphNodeNotFound: + case errors.Is(err, graphdb.ErrGraphNodeNotFound): fallthrough - case err == graphdb.ErrGraphNotFound: + case errors.Is(err, graphdb.ErrGraphNotFound): graphNode := &models.LightningNode{ HaveNodeAnnouncement: true, Addresses: []net.Addr{ diff --git a/channeldb/db_test.go b/channeldb/db_test.go index f5b525a5bb..1ae170f5c3 100644 --- a/channeldb/db_test.go +++ b/channeldb/db_test.go @@ -734,7 +734,7 @@ func createLightningNode(priv *btcec.PrivateKey) *models.LightningNode { AuthSigBytes: testSig.Serialize(), LastUpdate: time.Unix(updateTime, 0), Color: color.RGBA{1, 2, 3, 0}, - Alias: "kek" + string(pub[:]), + Alias: "kek" + string(pub), Features: testFeatures, Addresses: testAddrs, } diff --git a/discovery/gossiper.go b/discovery/gossiper.go index 951c4a98d9..41e58c404e 100644 --- a/discovery/gossiper.go +++ b/discovery/gossiper.go @@ -1685,7 +1685,7 @@ func (d *AuthenticatedGossiper) retransmitStaleAnns(now time.Time) error { return nil }) - if err != nil && err != graphdb.ErrGraphNoEdgesFound { + if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) { return fmt.Errorf("unable to retrieve outgoing channels: %w", err) } diff --git a/discovery/gossiper_test.go b/discovery/gossiper_test.go index 8a75c3239a..9e9e3162b7 100644 --- a/discovery/gossiper_test.go +++ b/discovery/gossiper_test.go @@ -202,7 +202,9 @@ func (r *mockGraphSource) AddProof(chanID lnwire.ShortChannelID, return nil } -func (r *mockGraphSource) ForEachNode(func(node *models.LightningNode) error) error { +func (r *mockGraphSource) ForEachNode( + func(node *models.LightningNode) error) error { + return nil } @@ -2318,9 +2320,7 @@ func TestProcessZombieEdgeNowLive(t *testing.T) { // At this point, the channel should still be considered a zombie. _, _, _, err = ctx.router.GetChannelByID(chanID) - if err != graphdb.ErrZombieEdge { - t.Fatalf("channel should still be a zombie") - } + require.ErrorIs(t, err, graphdb.ErrZombieEdge) // Attempting to process the current channel update should fail due to // its edge being considered a zombie and its timestamp not being within @@ -2441,7 +2441,7 @@ func TestReceiveRemoteChannelUpdateFirst(t *testing.T) { // to the map of premature ChannelUpdates. Check that nothing // was added to the graph. chanInfo, e1, e2, err := ctx.router.GetChannelByID(batch.chanUpdAnn1.ShortChannelID) - if err != graphdb.ErrEdgeNotFound { + if !errors.Is(err, graphdb.ErrEdgeNotFound) { t.Fatalf("Expected ErrEdgeNotFound, got: %v", err) } if chanInfo != nil { diff --git a/graph/db/graph.go b/graph/db/graph.go index 6b32a7bd62..434bd4279e 100644 --- a/graph/db/graph.go +++ b/graph/db/graph.go @@ -123,9 +123,9 @@ var ( // edge's participants. zombieBucket = []byte("zombie-index") - // disabledEdgePolicyBucket is a sub-bucket of the main edgeBucket bucket - // responsible for maintaining an index of disabled edge policies. Each - // entry exists within the bucket as follows: + // disabledEdgePolicyBucket is a sub-bucket of the main edgeBucket + // bucket responsible for maintaining an index of disabled edge + // policies. Each entry exists within the bucket as follows: // // maps: -> []byte{} // @@ -471,28 +471,31 @@ func (c *ChannelGraph) ForEachChannel(cb func(*models.ChannelEdgeInfo, // Load edge index, recombine each channel with the policies // loaded above and invoke the callback. - return kvdb.ForAll(edgeIndex, func(k, edgeInfoBytes []byte) error { - var chanID [8]byte - copy(chanID[:], k) - - edgeInfoReader := bytes.NewReader(edgeInfoBytes) - info, err := deserializeChanEdgeInfo(edgeInfoReader) - if err != nil { - return err - } + return kvdb.ForAll(edgeIndex, + func(k, edgeInfoBytes []byte) error { + var chanID [8]byte + copy(chanID[:], k) + + edgeInfoReader := bytes.NewReader(edgeInfoBytes) + info, err := deserializeChanEdgeInfo( + edgeInfoReader, + ) + if err != nil { + return err + } - policy1 := channelMap[channelMapKey{ - nodeKey: info.NodeKey1Bytes, - chanID: chanID, - }] + policy1 := channelMap[channelMapKey{ + nodeKey: info.NodeKey1Bytes, + chanID: chanID, + }] - policy2 := channelMap[channelMapKey{ - nodeKey: info.NodeKey2Bytes, - chanID: chanID, - }] + policy2 := channelMap[channelMapKey{ + nodeKey: info.NodeKey2Bytes, + chanID: chanID, + }] - return cb(&info, policy1, policy2) - }) + return cb(&info, policy1, policy2) + }) }, func() {}) } @@ -600,7 +603,9 @@ func (c *ChannelGraph) ForEachNodeCached(cb func(node route.Vertex, // We'll iterate over each node, then the set of channels for each // node, and construct a similar callback functiopn signature as the // main funcotin expects. - return c.ForEachNode(func(tx kvdb.RTx, node *models.LightningNode) error { + return c.ForEachNode(func(tx kvdb.RTx, + node *models.LightningNode) error { + channels := make(map[uint64]*DirectedChannel) err := c.ForEachNodeChannelTx(tx, node.PubKeyBytes, @@ -675,20 +680,27 @@ func (c *ChannelGraph) DisabledChannelIDs() ([]uint64, error) { return nil } - // We iterate over all disabled policies and we add each channel that - // has more than one disabled policy to disabledChanIDs array. - return disabledEdgePolicyIndex.ForEach(func(k, v []byte) error { - chanID := byteOrder.Uint64(k[:8]) - _, edgeFound := chanEdgeFound[chanID] - if edgeFound { - delete(chanEdgeFound, chanID) - disabledChanIDs = append(disabledChanIDs, chanID) - return nil - } + // We iterate over all disabled policies and we add each channel + // that has more than one disabled policy to disabledChanIDs + // array. + return disabledEdgePolicyIndex.ForEach( + func(k, v []byte) error { + chanID := byteOrder.Uint64(k[:8]) + _, edgeFound := chanEdgeFound[chanID] + if edgeFound { + delete(chanEdgeFound, chanID) + disabledChanIDs = append( + disabledChanIDs, chanID, + ) + + return nil + } - chanEdgeFound[chanID] = struct{}{} - return nil - }) + chanEdgeFound[chanID] = struct{}{} + + return nil + }, + ) }, func() { disabledChanIDs = nil chanEdgeFound = make(map[uint64]struct{}) @@ -816,7 +828,9 @@ func (c *ChannelGraph) SourceNode() (*models.LightningNode, error) { // of the graph. The source node is treated as the center node within a // star-graph. This method may be used to kick off a path finding algorithm in // order to explore the reachability of another node based off the source node. -func (c *ChannelGraph) sourceNode(nodes kvdb.RBucket) (*models.LightningNode, error) { +func (c *ChannelGraph) sourceNode(nodes kvdb.RBucket) (*models.LightningNode, + error) { + selfPub := nodes.Get(sourceKey) if selfPub == nil { return nil, ErrSourceNodeNotSet @@ -1334,12 +1348,15 @@ func (c *ChannelGraph) PruneGraph(spentOutputs []*wire.OutPoint, return err } - // Next grab the two edge indexes which will also need to be updated. + // Next grab the two edge indexes which will also need to be + // updated. edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket) if err != nil { return err } - chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket) + chanIndex, err := edges.CreateBucketIfNotExists( + channelPointBucket, + ) if err != nil { return err } @@ -1360,7 +1377,8 @@ func (c *ChannelGraph) PruneGraph(spentOutputs []*wire.OutPoint, // if NOT if filter var opBytes bytes.Buffer - if err := WriteOutpoint(&opBytes, chanPoint); err != nil { + err := WriteOutpoint(&opBytes, chanPoint) + if err != nil { return err } @@ -1399,7 +1417,9 @@ func (c *ChannelGraph) PruneGraph(spentOutputs []*wire.OutPoint, return err } - pruneBucket, err := metaBucket.CreateBucketIfNotExists(pruneLogBucket) + pruneBucket, err := metaBucket.CreateBucketIfNotExists( + pruneLogBucket, + ) if err != nil { return err } @@ -1545,7 +1565,8 @@ func (c *ChannelGraph) pruneGraphNodes(nodes kvdb.RwBucket, // If we reach this point, then there are no longer any edges // that connect this node, so we can delete it. - if err := c.deleteLightningNode(nodes, nodePubKey[:]); err != nil { + err := c.deleteLightningNode(nodes, nodePubKey[:]) + if err != nil { if errors.Is(err, ErrGraphNodeNotFound) || errors.Is(err, ErrGraphNodesNotFound) { @@ -1612,7 +1633,9 @@ func (c *ChannelGraph) DisconnectBlockAtHeight(height uint32) ( if err != nil { return err } - chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket) + chanIndex, err := edges.CreateBucketIfNotExists( + channelPointBucket, + ) if err != nil { return err } @@ -1632,7 +1655,7 @@ func (c *ChannelGraph) DisconnectBlockAtHeight(height uint32) ( //nolint:lll for k, v := cursor.Seek(chanIDStart[:]); k != nil && - bytes.Compare(k, chanIDEnd[:]) < 0; k, v = cursor.Next() { + bytes.Compare(k, chanIDEnd[:]) < 0; k, v = cursor.Next() { //nolint:lll edgeInfoReader := bytes.NewReader(v) edgeInfo, err := deserializeChanEdgeInfo(edgeInfoReader) if err != nil { @@ -1660,7 +1683,9 @@ func (c *ChannelGraph) DisconnectBlockAtHeight(height uint32) ( return err } - pruneBucket, err := metaBucket.CreateBucketIfNotExists(pruneLogBucket) + pruneBucket, err := metaBucket.CreateBucketIfNotExists( + pruneLogBucket, + ) if err != nil { return err } @@ -1676,8 +1701,7 @@ func (c *ChannelGraph) DisconnectBlockAtHeight(height uint32) ( var pruneKeys [][]byte pruneCursor := pruneBucket.ReadWriteCursor() for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil && - bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() { - + bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() { //nolint:lll pruneKeys = append(pruneKeys, k) } @@ -1973,6 +1997,8 @@ func (c *ChannelGraph) ChanUpdatesInHorizon(startTime, // With our start and end times constructed, we'll step through // the index collecting the info and policy of each update of // each channel that has a last update within the time range. + // + //nolint:lll for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil && bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() { @@ -2106,6 +2132,8 @@ func (c *ChannelGraph) NodeUpdatesInHorizon(startTime, // With our start and end times constructed, we'll step through // the index collecting info for each node within the time // range. + // + //nolint:lll for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil && bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() { @@ -2343,7 +2371,7 @@ func (c *ChannelGraph) FilterChannelRange(startHeight, // We'll now iterate through the database, and find each // channel ID that resides within the specified range. for k, v := cursor.Seek(chanIDStart[:]); k != nil && - bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() { + bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() { //nolint:lll // Don't send alias SCIDs during gossip sync. edgeReader := bytes.NewReader(v) edgeInfo, err := deserializeChanEdgeInfo(edgeReader) @@ -2574,7 +2602,9 @@ func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64, // would have been created by both edges: we'll alternate the update // times, as one may had overridden the other. if edge1 != nil { - byteOrder.PutUint64(indexKey[:8], uint64(edge1.LastUpdate.Unix())) + byteOrder.PutUint64( + indexKey[:8], uint64(edge1.LastUpdate.Unix()), + ) if err := updateIndex.Delete(indexKey[:]); err != nil { return err } @@ -2583,7 +2613,9 @@ func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64, // We'll also attempt to delete the entry that may have been created by // the second edge. if edge2 != nil { - byteOrder.PutUint64(indexKey[:8], uint64(edge2.LastUpdate.Unix())) + byteOrder.PutUint64( + indexKey[:8], uint64(edge2.LastUpdate.Unix()), + ) if err := updateIndex.Delete(indexKey[:]); err != nil { return err } @@ -2650,7 +2682,8 @@ func (c *ChannelGraph) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex, } // As part of deleting the edge we also remove all disabled entries - // from the edgePolicyDisabledIndex bucket. We do that for both directions. + // from the edgePolicyDisabledIndex bucket. We do that for both + // directions. updateEdgePolicyDisabledIndex(edges, cid, false, false) updateEdgePolicyDisabledIndex(edges, cid, true, false) @@ -2931,8 +2964,8 @@ func (c *ChannelGraph) FetchLightningNodeTx(tx kvdb.RTx, nodePub route.Vertex) ( // FetchLightningNode attempts to look up a target node by its identity public // key. If the node isn't found in the database, then ErrGraphNodeNotFound is // returned. -func (c *ChannelGraph) FetchLightningNode(nodePub route.Vertex) (*models.LightningNode, - error) { +func (c *ChannelGraph) FetchLightningNode(nodePub route.Vertex) ( + *models.LightningNode, error) { return c.fetchLightningNode(nil, nodePub) } @@ -3043,7 +3076,9 @@ var _ GraphCacheNode = (*graphCacheNode)(nil) // timestamp of when the data for the node was lasted updated is returned along // with a true boolean. Otherwise, an empty time.Time is returned with a false // boolean. -func (c *ChannelGraph) HasLightningNode(nodePub [33]byte) (time.Time, bool, error) { +func (c *ChannelGraph) HasLightningNode(nodePub [33]byte) (time.Time, bool, + error) { + var ( updateTime time.Time exists bool @@ -3120,7 +3155,7 @@ func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend, // as its prefix. This indicates that we've stepped over into // another node's edges, so we can terminate our scan. edgeCursor := edges.ReadCursor() - for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { + for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:lll // If the prefix still matches, the channel id is // returned in nodeEdge. Channel id is used to lookup // the node at the other end of the channel and both @@ -3212,8 +3247,8 @@ func (c *ChannelGraph) ForEachNodeChannelTx(tx kvdb.RTx, // one of the nodes, and wishes to obtain the full LightningNode for the other // end of the channel. func (c *ChannelGraph) FetchOtherNode(tx kvdb.RTx, - channel *models.ChannelEdgeInfo, thisNodeKey []byte) (*models.LightningNode, - error) { + channel *models.ChannelEdgeInfo, thisNodeKey []byte) ( + *models.LightningNode, error) { // Ensure that the node passed in is actually a member of the channel. var targetNodeBytes [33]byte @@ -3249,7 +3284,9 @@ func (c *ChannelGraph) FetchOtherNode(tx kvdb.RTx, // otherwise we can use the existing db transaction. var err error if tx == nil { - err = kvdb.View(c.db, fetchNodeFunc, func() { targetNode = nil }) + err = kvdb.View(c.db, fetchNodeFunc, func() { + targetNode = nil + }) } else { err = fetchNodeFunc(tx) } @@ -3559,37 +3596,41 @@ func (c *ChannelGraph) ChannelView() ([]EdgePoint, error) { // Once we have the proper bucket, we'll range over each key // (which is the channel point for the channel) and decode it, // accumulating each entry. - return chanIndex.ForEach(func(chanPointBytes, chanID []byte) error { - chanPointReader := bytes.NewReader(chanPointBytes) + return chanIndex.ForEach( + func(chanPointBytes, chanID []byte) error { + chanPointReader := bytes.NewReader( + chanPointBytes, + ) - var chanPoint wire.OutPoint - err := ReadOutpoint(chanPointReader, &chanPoint) - if err != nil { - return err - } + var chanPoint wire.OutPoint + err := ReadOutpoint(chanPointReader, &chanPoint) + if err != nil { + return err + } - edgeInfo, err := fetchChanEdgeInfo( - edgeIndex, chanID, - ) - if err != nil { - return err - } + edgeInfo, err := fetchChanEdgeInfo( + edgeIndex, chanID, + ) + if err != nil { + return err + } - pkScript, err := genMultiSigP2WSH( - edgeInfo.BitcoinKey1Bytes[:], - edgeInfo.BitcoinKey2Bytes[:], - ) - if err != nil { - return err - } + pkScript, err := genMultiSigP2WSH( + edgeInfo.BitcoinKey1Bytes[:], + edgeInfo.BitcoinKey2Bytes[:], + ) + if err != nil { + return err + } - edgePoints = append(edgePoints, EdgePoint{ - FundingPkScript: pkScript, - OutPoint: chanPoint, - }) + edgePoints = append(edgePoints, EdgePoint{ + FundingPkScript: pkScript, + OutPoint: chanPoint, + }) - return nil - }) + return nil + }, + ) }, func() { edgePoints = nil }); err != nil { @@ -4078,8 +4119,8 @@ func deserializeLightningNode(r io.Reader) (models.LightningNode, error) { node.HaveNodeAnnouncement = false } - // The rest of the data is optional, and will only be there if we got a node - // announcement for this node. + // The rest of the data is optional, and will only be there if we got a + // node announcement for this node. if !node.HaveNodeAnnouncement { return node, nil } @@ -4188,7 +4229,8 @@ func putChanEdgeInfo(edgeIndex kvdb.RwBucket, if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil { return err } - if err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity)); err != nil { + err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity)) + if err != nil { return err } if _, err := b.Write(chanID[:]); err != nil { @@ -4201,7 +4243,7 @@ func putChanEdgeInfo(edgeIndex kvdb.RwBucket, if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes { return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData)) } - err := wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData) + err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData) if err != nil { return err } @@ -4514,10 +4556,14 @@ func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy, if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil { return err } - if err := binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat)); err != nil { + err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat)) + if err != nil { return err } - if err := binary.Write(w, byteOrder, uint64(edge.FeeProportionalMillionths)); err != nil { + err = binary.Write( + w, byteOrder, uint64(edge.FeeProportionalMillionths), + ) + if err != nil { return err } @@ -4650,8 +4696,11 @@ func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy, return edge, nil } -// MakeTestGraph creates a new instance of the ChannelGraph for testing purposes. -func MakeTestGraph(t testing.TB, modifiers ...OptionModifier) (*ChannelGraph, error) { +// MakeTestGraph creates a new instance of the ChannelGraph for testing +// purposes. +func MakeTestGraph(t testing.TB, modifiers ...OptionModifier) (*ChannelGraph, + error) { + opts := DefaultOptions() for _, modifier := range modifiers { modifier(opts) diff --git a/graph/db/graph_test.go b/graph/db/graph_test.go index 2f88dc22a1..34e20cea03 100644 --- a/graph/db/graph_test.go +++ b/graph/db/graph_test.go @@ -21,7 +21,6 @@ import ( "github.com/btcsuite/btcd/btcutil" "github.com/btcsuite/btcd/chaincfg/chainhash" "github.com/btcsuite/btcd/wire" - "github.com/davecgh/go-spew/spew" "github.com/lightningnetwork/lnd/graph/db/models" "github.com/lightningnetwork/lnd/kvdb" "github.com/lightningnetwork/lnd/lnwire" @@ -37,13 +36,15 @@ var ( "[2001:db8:85a3:0:0:8a2e:370:7334]:80") testAddrs = []net.Addr{testAddr, anotherAddr} - testRBytes, _ = hex.DecodeString("8ce2bc69281ce27da07e6683571319d18e949ddfa2965fb6caa1bf0314f882d7") - testSBytes, _ = hex.DecodeString("299105481d63e0f4bc2a88121167221b6700d72a0ead154c03be696a292d24ae") - testRScalar = new(btcec.ModNScalar) - testSScalar = new(btcec.ModNScalar) - _ = testRScalar.SetByteSlice(testRBytes) - _ = testSScalar.SetByteSlice(testSBytes) - testSig = ecdsa.NewSignature(testRScalar, testSScalar) + testRBytes, _ = hex.DecodeString("8ce2bc69281ce27da07e6683571319d18" + + "e949ddfa2965fb6caa1bf0314f882d7") + testSBytes, _ = hex.DecodeString("299105481d63e0f4bc2a88121167221b6" + + "700d72a0ead154c03be696a292d24ae") + testRScalar = new(btcec.ModNScalar) + testSScalar = new(btcec.ModNScalar) + _ = testRScalar.SetByteSlice(testRBytes) + _ = testSScalar.SetByteSlice(testSBytes) + testSig = ecdsa.NewSignature(testRScalar, testSScalar) testFeatures = lnwire.NewFeatureVector( lnwire.NewRawFeatureVector(lnwire.GossipQueriesRequired), @@ -65,7 +66,9 @@ var ( } ) -func createLightningNode(db kvdb.Backend, priv *btcec.PrivateKey) (*models.LightningNode, error) { +func createLightningNode(_ kvdb.Backend, priv *btcec.PrivateKey) ( + *models.LightningNode, error) { + updateTime := prand.Int63() pub := priv.PubKey().SerializeCompressed() @@ -124,7 +127,8 @@ func TestNodeInsertionAndDeletion(t *testing.T) { dbNode, err := graph.FetchLightningNode(testPub) require.NoError(t, err, "unable to locate node") - if _, exists, err := graph.HasLightningNode(dbNode.PubKeyBytes); err != nil { + _, exists, err := graph.HasLightningNode(dbNode.PubKeyBytes) + if err != nil { t.Fatalf("unable to query for node: %v", err) } else if !exists { t.Fatalf("node should be found but wasn't") @@ -175,7 +179,8 @@ func TestPartialNode(t *testing.T) { dbNode, err := graph.FetchLightningNode(testPub) require.NoError(t, err, "unable to locate node") - if _, exists, err := graph.HasLightningNode(dbNode.PubKeyBytes); err != nil { + _, exists, err := graph.HasLightningNode(dbNode.PubKeyBytes) + if err != nil { t.Fatalf("unable to query for node: %v", err) } else if !exists { t.Fatalf("node should be found but wasn't") @@ -346,7 +351,8 @@ func TestEdgeInsertionDeletion(t *testing.T) { // Ensure that any query attempts to lookup the delete channel edge are // properly deleted. - if _, _, _, err := graph.FetchChannelEdgesByOutpoint(&outpoint); err == nil { + _, _, _, err = graph.FetchChannelEdgesByOutpoint(&outpoint) + if err == nil { t.Fatalf("channel edge not deleted") } if _, _, _, err := graph.FetchChannelEdgesByID(chanID); err == nil { @@ -528,12 +534,8 @@ func TestDisconnectBlockAtHeight(t *testing.T) { // at height 155. hash, h, err := graph.PruneTip() require.NoError(t, err, "unable to get prune tip") - if !blockHash.IsEqual(hash) { - t.Fatalf("expected best block to be %x, was %x", blockHash, hash) - } - if h != height-1 { - t.Fatalf("expected best block height to be %d, was %d", height-1, h) - } + require.True(t, blockHash.IsEqual(hash)) + require.Equal(t, h, height-1) } func assertEdgeInfoEqual(t *testing.T, e1 *models.ChannelEdgeInfo, @@ -567,20 +569,26 @@ func assertEdgeInfoEqual(t *testing.T, e1 *models.ChannelEdgeInfo, e2.Features) } - if !bytes.Equal(e1.AuthProof.NodeSig1Bytes, e2.AuthProof.NodeSig1Bytes) { - t.Fatalf("nodesig1 doesn't match: %v vs %v", - spew.Sdump(e1.AuthProof.NodeSig1Bytes), - spew.Sdump(e2.AuthProof.NodeSig1Bytes)) - } - if !bytes.Equal(e1.AuthProof.NodeSig2Bytes, e2.AuthProof.NodeSig2Bytes) { - t.Fatalf("nodesig2 doesn't match") - } - if !bytes.Equal(e1.AuthProof.BitcoinSig1Bytes, e2.AuthProof.BitcoinSig1Bytes) { - t.Fatalf("bitcoinsig1 doesn't match") - } - if !bytes.Equal(e1.AuthProof.BitcoinSig2Bytes, e2.AuthProof.BitcoinSig2Bytes) { - t.Fatalf("bitcoinsig2 doesn't match") - } + require.True( + t, bytes.Equal( + e1.AuthProof.NodeSig1Bytes, e2.AuthProof.NodeSig1Bytes, + ), + ) + require.True( + t, bytes.Equal( + e1.AuthProof.NodeSig2Bytes, e2.AuthProof.NodeSig2Bytes, + ), + ) + require.True( + t, + bytes.Equal( + e1.AuthProof.BitcoinSig1Bytes, + e2.AuthProof.BitcoinSig1Bytes, + ), + ) + require.True(t, bytes.Equal( + e1.AuthProof.BitcoinSig2Bytes, e2.AuthProof.BitcoinSig2Bytes, + )) if e1.ChannelPoint != e2.ChannelPoint { t.Fatalf("channel point match: %v vs %v", e1.ChannelPoint, @@ -759,7 +767,9 @@ func TestEdgeInfoUpdates(t *testing.T) { // Next, attempt to query the channel edges according to the outpoint // of the channel. - dbEdgeInfo, dbEdge1, dbEdge2, err = graph.FetchChannelEdgesByOutpoint(&outpoint) + dbEdgeInfo, dbEdge1, dbEdge2, err = graph.FetchChannelEdgesByOutpoint( + &outpoint, + ) require.NoError(t, err, "unable to fetch channel by ID") if err := compareEdgePolicies(dbEdge1, edge1); err != nil { t.Fatalf("edge doesn't match: %v", err) @@ -1089,11 +1099,13 @@ func TestGraphTraversalCacheable(t *testing.T) { // Create a map of all nodes with the iteration we know works (because // it is tested in another test). nodeMap := make(map[route.Vertex]struct{}) - err = graph.ForEachNode(func(tx kvdb.RTx, n *models.LightningNode) error { - nodeMap[n.PubKeyBytes] = struct{}{} + err = graph.ForEachNode( + func(tx kvdb.RTx, n *models.LightningNode) error { + nodeMap[n.PubKeyBytes] = struct{}{} - return nil - }) + return nil + }, + ) require.NoError(t, err) require.Len(t, nodeMap, numNodes) @@ -1162,8 +1174,8 @@ func TestGraphCacheTraversal(t *testing.T) { delete(chanIndex, d.ChannelID) if !d.OutPolicySet || d.InPolicy == nil { - return fmt.Errorf("channel policy not " + - "present") + return fmt.Errorf("channel policy " + + "not present") } // The incoming edge should also indicate that @@ -1212,10 +1224,12 @@ func fillTestGraph(t require.TestingT, graph *ChannelGraph, numNodes, // Iterate over each node as returned by the graph, if all nodes are // reached, then the map created above should be empty. - err := graph.ForEachNode(func(_ kvdb.RTx, node *models.LightningNode) error { - delete(nodeIndex, node.Alias) - return nil - }) + err := graph.ForEachNode( + func(_ kvdb.RTx, node *models.LightningNode) error { + delete(nodeIndex, node.Alias) + return nil + }, + ) require.NoError(t, err) require.Len(t, nodeIndex, 0) @@ -1225,7 +1239,9 @@ func fillTestGraph(t require.TestingT, graph *ChannelGraph, numNodes, for n := 0; n < numNodes-1; n++ { node1 := nodes[n] node2 := nodes[n+1] - if bytes.Compare(node1.PubKeyBytes[:], node2.PubKeyBytes[:]) == -1 { + if bytes.Compare( + node1.PubKeyBytes[:], node2.PubKeyBytes[:], + ) == -1 { node1, node2 = node2, node1 } @@ -1279,8 +1295,8 @@ func fillTestGraph(t require.TestingT, graph *ChannelGraph, numNodes, return chanIndex, nodes } -func assertPruneTip(t *testing.T, graph *ChannelGraph, blockHash *chainhash.Hash, - blockHeight uint32) { +func assertPruneTip(t *testing.T, graph *ChannelGraph, + blockHash *chainhash.Hash, blockHeight uint32) { pruneHash, pruneHeight, err := graph.PruneTip() if err != nil { @@ -1320,10 +1336,12 @@ func assertNumChans(t *testing.T, graph *ChannelGraph, n int) { func assertNumNodes(t *testing.T, graph *ChannelGraph, n int) { numNodes := 0 - err := graph.ForEachNode(func(_ kvdb.RTx, _ *models.LightningNode) error { - numNodes++ - return nil - }) + err := graph.ForEachNode( + func(_ kvdb.RTx, _ *models.LightningNode) error { + numNodes++ + return nil + }, + ) if err != nil { _, _, line, _ := runtime.Caller(1) t.Fatalf("line %v: unable to scan nodes: %v", line, err) @@ -1331,7 +1349,8 @@ func assertNumNodes(t *testing.T, graph *ChannelGraph, n int) { if numNodes != n { _, _, line, _ := runtime.Caller(1) - t.Fatalf("line %v: expected %v nodes, got %v", line, n, numNodes) + t.Fatalf("line %v: expected %v nodes, got %v", line, n, + numNodes) } } @@ -1355,7 +1374,9 @@ func assertChanViewEqual(t *testing.T, a []EdgePoint, b []EdgePoint) { } } -func assertChanViewEqualChanPoints(t *testing.T, a []EdgePoint, b []*wire.OutPoint) { +func assertChanViewEqualChanPoints(t *testing.T, a []EdgePoint, + b []*wire.OutPoint) { + if len(a) != len(b) { _, _, line, _ := runtime.Caller(1) t.Fatalf("line %v: chan views don't match", line) @@ -1434,13 +1455,17 @@ func TestGraphPruning(t *testing.T) { copy(edgeInfo.NodeKey1Bytes[:], graphNodes[i].PubKeyBytes[:]) copy(edgeInfo.NodeKey2Bytes[:], graphNodes[i+1].PubKeyBytes[:]) copy(edgeInfo.BitcoinKey1Bytes[:], graphNodes[i].PubKeyBytes[:]) - copy(edgeInfo.BitcoinKey2Bytes[:], graphNodes[i+1].PubKeyBytes[:]) + copy( + edgeInfo.BitcoinKey2Bytes[:], + graphNodes[i+1].PubKeyBytes[:], + ) if err := graph.AddChannelEdge(&edgeInfo); err != nil { t.Fatalf("unable to add node: %v", err) } pkScript, err := genMultiSigP2WSH( - edgeInfo.BitcoinKey1Bytes[:], edgeInfo.BitcoinKey2Bytes[:], + edgeInfo.BitcoinKey1Bytes[:], + edgeInfo.BitcoinKey2Bytes[:], ) if err != nil { t.Fatalf("unable to gen multi-sig p2wsh: %v", err) @@ -1772,7 +1797,9 @@ func TestChanUpdatesInHorizon(t *testing.T) { assertEdgeInfoEqual(t, chanExp.Info, chanRet.Info) - err := compareEdgePolicies(chanExp.Policy1, chanRet.Policy1) + err := compareEdgePolicies( + chanExp.Policy1, chanRet.Policy1, + ) if err != nil { t.Fatal(err) } @@ -1879,7 +1906,9 @@ func TestNodeUpdatesInHorizon(t *testing.T) { }, } for _, queryCase := range queryCases { - resp, err := graph.NodeUpdatesInHorizon(queryCase.start, queryCase.end) + resp, err := graph.NodeUpdatesInHorizon( + queryCase.start, queryCase.end, + ) if err != nil { t.Fatalf("unable to query for nodes: %v", err) } @@ -2725,7 +2754,9 @@ func TestIncompleteChannelPolicies(t *testing.T) { } // Ensure that channel is reported with unknown policies. - checkPolicies := func(node *models.LightningNode, expectedIn, expectedOut bool) { + checkPolicies := func(node *models.LightningNode, expectedIn, + expectedOut bool) { + calls := 0 err := graph.ForEachNodeChannel(node.PubKeyBytes, func(_ kvdb.RTx, _ *models.ChannelEdgeInfo, outEdge, @@ -3046,9 +3077,7 @@ func TestAddChannelEdgeShellNodes(t *testing.T) { node2, err = graph.FetchLightningNode(node2.PubKeyBytes) require.NoError(t, err, "unable to fetch node2") - if node2.HaveNodeAnnouncement { - t.Fatalf("should have shell announcement for node2, but is full") - } + require.False(t, node2.HaveNodeAnnouncement) } // TestNodePruningUpdateIndexDeletion tests that once a node has been removed @@ -3163,17 +3192,19 @@ func TestNodeIsPublic(t *testing.T) { // checkNodes is a helper closure that will be used to assert that the // given nodes are seen as public/private within the given graphs. - checkNodes := func(nodes []*models.LightningNode, graphs []*ChannelGraph, - public bool) { + checkNodes := func(nodes []*models.LightningNode, + graphs []*ChannelGraph, public bool) { t.Helper() for _, node := range nodes { for _, graph := range graphs { - isPublic, err := graph.IsPublicNode(node.PubKeyBytes) + isPublic, err := graph.IsPublicNode( + node.PubKeyBytes, + ) if err != nil { - t.Fatalf("unable to determine if pivot "+ - "is public: %v", err) + t.Fatalf("unable to determine if "+ + "pivot is public: %v", err) } switch { @@ -3278,8 +3309,8 @@ func TestDisabledChannelIDs(t *testing.T) { disabledChanIds, err := graph.DisabledChannelIDs() require.NoError(t, err, "unable to get disabled channel ids") if len(disabledChanIds) > 0 { - t.Fatalf("expected empty disabled channels, got %v disabled channels", - len(disabledChanIds)) + t.Fatalf("expected empty disabled channels, got %v disabled "+ + "channels", len(disabledChanIds)) } // Add one disabled policy and ensure the channel is still not in the @@ -3291,8 +3322,8 @@ func TestDisabledChannelIDs(t *testing.T) { disabledChanIds, err = graph.DisabledChannelIDs() require.NoError(t, err, "unable to get disabled channel ids") if len(disabledChanIds) > 0 { - t.Fatalf("expected empty disabled channels, got %v disabled channels", - len(disabledChanIds)) + t.Fatalf("expected empty disabled channels, got %v disabled "+ + "channels", len(disabledChanIds)) } // Add second disabled policy and ensure the channel is now in the @@ -3303,12 +3334,15 @@ func TestDisabledChannelIDs(t *testing.T) { } disabledChanIds, err = graph.DisabledChannelIDs() require.NoError(t, err, "unable to get disabled channel ids") - if len(disabledChanIds) != 1 || disabledChanIds[0] != edgeInfo.ChannelID { + if len(disabledChanIds) != 1 || + disabledChanIds[0] != edgeInfo.ChannelID { + t.Fatalf("expected disabled channel with id %v, "+ "got %v", edgeInfo.ChannelID, disabledChanIds) } - // Delete the channel edge and ensure it is removed from the disabled list. + // Delete the channel edge and ensure it is removed from the disabled + // list. if err = graph.DeleteChannelEdges( false, true, edgeInfo.ChannelID, ); err != nil { @@ -3317,8 +3351,8 @@ func TestDisabledChannelIDs(t *testing.T) { disabledChanIds, err = graph.DisabledChannelIDs() require.NoError(t, err, "unable to get disabled channel ids") if len(disabledChanIds) > 0 { - t.Fatalf("expected empty disabled channels, got %v disabled channels", - len(disabledChanIds)) + t.Fatalf("expected empty disabled channels, got %v disabled "+ + "channels", len(disabledChanIds)) } } @@ -3421,7 +3455,9 @@ func TestEdgePolicyMissingMaxHtcl(t *testing.T) { copy(indexKey[:], scratch[:]) byteOrder.PutUint64(indexKey[8:], edge1.ChannelID) - updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket) + updateIndex, err := edges.CreateBucketIfNotExists( + edgeUpdateIndexBucket, + ) if err != nil { return err } @@ -3556,8 +3592,8 @@ func TestGraphZombieIndex(t *testing.T) { // the featuresMap have not been defined. func compareNodes(a, b *models.LightningNode) error { if a.LastUpdate != b.LastUpdate { - return fmt.Errorf("node LastUpdate doesn't match: expected %v, \n"+ - "got %v", a.LastUpdate, b.LastUpdate) + return fmt.Errorf("node LastUpdate doesn't match: expected "+ + "%v, got %v", a.LastUpdate, b.LastUpdate) } if !reflect.DeepEqual(a.Addresses, b.Addresses) { return fmt.Errorf("Addresses doesn't match: expected %#v, \n "+ @@ -3576,8 +3612,9 @@ func compareNodes(a, b *models.LightningNode) error { "got %#v", a.Alias, b.Alias) } if !reflect.DeepEqual(a.HaveNodeAnnouncement, b.HaveNodeAnnouncement) { - return fmt.Errorf("HaveNodeAnnouncement doesn't match: expected %#v, \n "+ - "got %#v", a.HaveNodeAnnouncement, b.HaveNodeAnnouncement) + return fmt.Errorf("HaveNodeAnnouncement doesn't match: "+ + "expected %#v, got %#v", a.HaveNodeAnnouncement, + b.HaveNodeAnnouncement) } if !bytes.Equal(a.ExtraOpaqueData, b.ExtraOpaqueData) { return fmt.Errorf("extra data doesn't match: %v vs %v", @@ -3595,8 +3632,8 @@ func compareEdgePolicies(a, b *models.ChannelEdgePolicy) error { "got %v", a.ChannelID, b.ChannelID) } if !reflect.DeepEqual(a.LastUpdate, b.LastUpdate) { - return fmt.Errorf("edge LastUpdate doesn't match: expected %#v, \n "+ - "got %#v", a.LastUpdate, b.LastUpdate) + return fmt.Errorf("edge LastUpdate doesn't match: "+ + "expected %#v, got %#v", a.LastUpdate, b.LastUpdate) } if a.MessageFlags != b.MessageFlags { return fmt.Errorf("MessageFlags doesn't match: expected %v, "+ diff --git a/graph/notifications_test.go b/graph/notifications_test.go index cbcc7e8c98..39278bf13a 100644 --- a/graph/notifications_test.go +++ b/graph/notifications_test.go @@ -315,7 +315,7 @@ func (m *mockChainView) Reset() { m.staleBlocks = make(chan *chainview.FilteredBlock, 10) } -func (m *mockChainView) UpdateFilter(ops []graphdb.EdgePoint, updateHeight uint32) error { +func (m *mockChainView) UpdateFilter(ops []graphdb.EdgePoint, _ uint32) error { m.Lock() defer m.Unlock() diff --git a/netann/chan_status_manager_test.go b/netann/chan_status_manager_test.go index 470b79555f..320981d630 100644 --- a/netann/chan_status_manager_test.go +++ b/netann/chan_status_manager_test.go @@ -748,7 +748,9 @@ var stateMachineTests = []stateMachineTest{ // Check that trying to enable the channel with unknown // edges results in a failure. - h.assertEnables(newChans, graphdb.ErrEdgeNotFound, false) + h.assertEnables( + newChans, graphdb.ErrEdgeNotFound, false, + ) // Now, insert edge policies for the channel into the // graph, starting with the channel enabled, and mark diff --git a/routing/pathfind_test.go b/routing/pathfind_test.go index 6cd7d13c0e..81708d3930 100644 --- a/routing/pathfind_test.go +++ b/routing/pathfind_test.go @@ -354,7 +354,7 @@ func parseTestGraph(t *testing.T, useCache bool, path string) ( } err = graph.AddChannelEdge(&edgeInfo) - if err != nil && err != graphdb.ErrEdgeAlreadyExist { + if err != nil && !errors.Is(err, graphdb.ErrEdgeAlreadyExist) { return nil, err } @@ -662,7 +662,7 @@ func createTestGraphFromChannels(t *testing.T, useCache bool, } err = graph.AddChannelEdge(&edgeInfo) - if err != nil && err != graphdb.ErrEdgeAlreadyExist { + if err != nil && !errors.Is(err, graphdb.ErrEdgeAlreadyExist) { return nil, err } diff --git a/rpcserver.go b/rpcserver.go index f6720cd5f9..fe354529ac 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -6508,7 +6508,9 @@ func (r *rpcServer) DescribeGraph(ctx context.Context, // First iterate through all the known nodes (connected or unconnected // within the graph), collating their current state into the RPC // response. - err := graph.ForEachNode(func(_ kvdb.RTx, node *models.LightningNode) error { + err := graph.ForEachNode(func(_ kvdb.RTx, + node *models.LightningNode) error { + lnNode := marshalNode(node) resp.Nodes = append(resp.Nodes, lnNode) @@ -6538,7 +6540,7 @@ func (r *rpcServer) DescribeGraph(ctx context.Context, return nil }) - if err != nil && err != graphdb.ErrGraphNoEdgesFound { + if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) { return nil, err } @@ -6784,7 +6786,7 @@ func (r *rpcServer) GetNodeInfo(ctx context.Context, // be returned. node, err := graph.FetchLightningNode(pubKey) switch { - case err == graphdb.ErrGraphNodeNotFound: + case errors.Is(err, graphdb.ErrGraphNodeNotFound): return nil, status.Error(codes.NotFound, err.Error()) case err != nil: return nil, err diff --git a/server.go b/server.go index be3b506a3e..629a591376 100644 --- a/server.go +++ b/server.go @@ -3409,7 +3409,7 @@ func (s *server) establishPersistentConnections() error { nodeAddrsMap[pubStr] = n return nil }) - if err != nil && err != graphdb.ErrGraphNoEdgesFound { + if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) { return err }