Merge pull request #10609 from ellemouton/graph-unit-test-cleanup

graph: replace fatal assertions and simplify test helpers
This commit is contained in:
Elle authored and GitHub committed 2026-02-25 14:11:13 +02:00
commit 13a8356558
6 files changed
+334 -862

No files matched your search

+132 -243
View File
@@ -54,11 +54,10 @@ func TestAddProof(t *testing.T) {
// In order to be able to add the edge we should have a valid funding
// UTXO within the blockchain.
script, fundingTx, _, chanID, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
script, fundingTx, _, chanID := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(), 100, 0,
)
require.NoError(t, err, "unable create channel edge")
fundingBlock := &wire.MsgBlock{
Transactions: []*wire.MsgTx{fundingTx},
}
@@ -109,9 +108,10 @@ func TestIgnoreNodeAnnouncement(t *testing.T) {
)
err := ctx.builder.AddNode(t.Context(), node)
if !IsError(err, ErrIgnored) {
t.Fatalf("expected to get ErrIgnore, instead got: %v", err)
}
require.Truef(
t, IsError(err, ErrIgnored),
"expected to get ErrIgnore, instead got: %v", err,
)
}
// TestIgnoreChannelEdgePolicyForUnknownChannel checks that a router will
@@ -141,11 +141,10 @@ func TestIgnoreChannelEdgePolicyForUnknownChannel(t *testing.T) {
// Add the edge between the two unknown nodes to the graph, and check
// that the nodes are found after the fact.
script, fundingTx, _, chanID, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
script, fundingTx, _, chanID := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(), 10000, 500,
)
require.NoError(t, err, "unable to create channel edge")
fundingBlock := &wire.MsgBlock{
Transactions: []*wire.MsgTx{fundingTx},
}
@@ -179,14 +178,17 @@ func TestIgnoreChannelEdgePolicyForUnknownChannel(t *testing.T) {
// Attempt to update the edge. This should be ignored, since the edge
// is not yet added to the router.
err = ctx.builder.UpdateEdge(ctxb, edgePolicy)
if !IsError(err, ErrIgnored) {
t.Fatalf("expected to get ErrIgnore, instead got: %v", err)
}
require.Truef(
t, IsError(err, ErrIgnored),
"expected to get ErrIgnore, instead got: %v", err,
)
// Add the edge.
require.NoErrorf(t, ctx.builder.AddEdge(ctxb, edge),
require.NoErrorf(
t, ctx.builder.AddEdge(ctxb, edge),
"expected to be able to add edge to the channel graph, even "+
"though the vertexes were unknown: %v.", err)
"though the vertexes were unknown: %v.", err,
)
// Now updating the edge policy should succeed.
require.NoError(t, ctx.builder.UpdateEdge(ctxb, edgePolicy))
@@ -219,14 +221,11 @@ func TestWakeUpOnStaleBranch(t *testing.T) {
}
height := startingBlockHeight + i
if i == 5 {
script, fundingTx, _, chanID, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
script, fundingTx, _, chanID := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(),
chanValue, height,
)
if err != nil {
t.Fatalf("unable create channel edge: %v", err)
}
block.Transactions = append(block.Transactions,
fundingTx)
chanID1 = chanID.ToUint64()
@@ -252,13 +251,10 @@ func TestWakeUpOnStaleBranch(t *testing.T) {
}
height := uint32(forkHeight) + i
if i == 5 {
script, fundingTx, _, chanID, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
script, fundingTx, _, chanID := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(),
chanValue, height)
if err != nil {
t.Fatalf("unable create channel edge: %v", err)
}
block.Transactions = append(block.Transactions,
fundingTx)
chanID2 = chanID.ToUint64()
@@ -298,9 +294,7 @@ func TestWakeUpOnStaleBranch(t *testing.T) {
)
require.NoError(t, err)
if err := ctx.builder.AddEdge(ctxb, edge1); err != nil {
t.Fatalf("unable to add edge: %v", err)
}
require.NoError(t, ctx.builder.AddEdge(ctxb, edge1))
edge2, err := models.NewV1Channel(
chanID2, *chaincfg.SimNetParams.GenesisHash, node1.PubKeyBytes,
@@ -314,37 +308,21 @@ func TestWakeUpOnStaleBranch(t *testing.T) {
)
require.NoError(t, err)
if err := ctx.builder.AddEdge(ctxb, edge2); err != nil {
t.Fatalf("unable to add edge: %v", err)
}
require.NoError(t, ctx.builder.AddEdge(ctxb, edge2))
// Check that the fundingTxs are in the graph db.
has, isZombie, err := ctx.graph.HasChannelEdge(chanID1)
if err != nil {
t.Fatalf("error looking for edge: %v", chanID1)
}
if !has {
t.Fatalf("could not find edge in graph")
}
if isZombie {
t.Fatal("edge was marked as zombie")
}
require.NoError(t, err)
require.True(t, has)
require.False(t, isZombie)
has, isZombie, err = ctx.graph.HasChannelEdge(chanID2)
if err != nil {
t.Fatalf("error looking for edge: %v", chanID2)
}
if !has {
t.Fatalf("could not find edge in graph")
}
if isZombie {
t.Fatal("edge was marked as zombie")
}
require.NoError(t, err)
require.True(t, has)
require.False(t, isZombie)
// Stop the router, so we can reorg the chain while its offline.
if err := ctx.builder.Stop(); err != nil {
t.Fatalf("unable to stop router: %v", err)
}
require.NoError(t, ctx.builder.Stop())
// Create a 15 block fork.
for i := uint32(1); i <= 15; i++ {
@@ -380,33 +358,20 @@ func TestWakeUpOnStaleBranch(t *testing.T) {
require.NoError(t, err)
// It should resync to the longer chain on startup.
if err := router.Start(); err != nil {
t.Fatalf("unable to start router: %v", err)
}
require.NoError(t, router.Start())
// The channel with chanID2 should not be in the database anymore,
// since it is not confirmed on the longest chain. chanID1 should
// still be.
has, isZombie, err = ctx.graph.HasChannelEdge(chanID1)
require.NoError(t, err)
if !has {
t.Fatalf("did not find edge in graph")
}
if isZombie {
t.Fatal("edge was marked as zombie")
}
require.True(t, has)
require.False(t, isZombie)
has, isZombie, err = ctx.graph.HasChannelEdge(chanID2)
if err != nil {
t.Fatalf("error looking for edge: %v", chanID2)
}
if has {
t.Fatalf("found edge in graph")
}
if isZombie {
t.Fatal("reorged edge should not be marked as zombie")
}
require.NoError(t, err)
require.False(t, has)
require.False(t, isZombie)
}
// TestDisconnectedBlocks checks that the router handles a reorg happening when
@@ -430,14 +395,11 @@ func TestDisconnectedBlocks(t *testing.T) {
}
height := startingBlockHeight + i
if i == 5 {
_, fundingTx, _, chanID, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
_, fundingTx, _, chanID := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(),
chanValue, height,
)
if err != nil {
t.Fatalf("unable create channel edge: %v", err)
}
block.Transactions = append(block.Transactions,
fundingTx)
chanID1 = chanID.ToUint64()
@@ -462,14 +424,11 @@ func TestDisconnectedBlocks(t *testing.T) {
}
height := uint32(forkHeight) + i
if i == 5 {
_, fundingTx, _, chanID, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
_, fundingTx, _, chanID := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(),
chanValue, height,
)
if err != nil {
t.Fatalf("unable create channel edge: %v", err)
}
block.Transactions = append(block.Transactions,
fundingTx)
chanID2 = chanID.ToUint64()
@@ -508,9 +467,7 @@ func TestDisconnectedBlocks(t *testing.T) {
)
require.NoError(t, err)
if err := ctx.builder.AddEdge(ctxb, edge1); err != nil {
t.Fatalf("unable to add edge: %v", err)
}
require.NoError(t, ctx.builder.AddEdge(ctxb, edge1))
edge2, err := models.NewV1Channel(
chanID2, *chaincfg.SimNetParams.GenesisHash, node1.PubKeyBytes,
@@ -522,32 +479,18 @@ func TestDisconnectedBlocks(t *testing.T) {
)
require.NoError(t, err)
if err := ctx.builder.AddEdge(ctxb, edge2); err != nil {
t.Fatalf("unable to add edge: %v", err)
}
require.NoError(t, ctx.builder.AddEdge(ctxb, edge2))
// Check that the fundingTxs are in the graph db.
has, isZombie, err := ctx.graph.HasChannelEdge(chanID1)
if err != nil {
t.Fatalf("error looking for edge: %v", chanID1)
}
if !has {
t.Fatalf("could not find edge in graph")
}
if isZombie {
t.Fatal("edge was marked as zombie")
}
require.NoError(t, err)
require.True(t, has)
require.False(t, isZombie)
has, isZombie, err = ctx.graph.HasChannelEdge(chanID2)
if err != nil {
t.Fatalf("error looking for edge: %v", chanID2)
}
if !has {
t.Fatalf("could not find edge in graph")
}
if isZombie {
t.Fatal("edge was marked as zombie")
}
require.NoError(t, err)
require.True(t, has)
require.False(t, isZombie)
// Create a 15 block fork. We first let the chainView notify the router
// about stale blocks, before sending the now connected blocks. We do
@@ -581,26 +524,14 @@ func TestDisconnectedBlocks(t *testing.T) {
// chanID2 should not be in the database anymore, since it is not
// confirmed on the longest chain. chanID1 should still be.
has, isZombie, err = ctx.graph.HasChannelEdge(chanID1)
if err != nil {
t.Fatalf("error looking for edge: %v", chanID1)
}
if !has {
t.Fatalf("did not find edge in graph")
}
if isZombie {
t.Fatal("edge was marked as zombie")
}
require.NoError(t, err)
require.True(t, has)
require.False(t, isZombie)
has, isZombie, err = ctx.graph.HasChannelEdge(chanID2)
if err != nil {
t.Fatalf("error looking for edge: %v", chanID2)
}
if has {
t.Fatalf("found edge in graph")
}
if isZombie {
t.Fatal("reorged edge should not be marked as zombie")
}
require.NoError(t, err)
require.False(t, has)
require.False(t, isZombie)
}
// TestChansClosedOfflinePruneGraph tests that if channels we know of are
@@ -620,12 +551,11 @@ func TestChansClosedOfflinePruneGraph(t *testing.T) {
Transactions: []*wire.MsgTx{},
}
nextHeight := startingBlockHeight + 1
script, fundingTx1, chanUTXO, chanID1, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
script, fundingTx1, chanUTXO, chanID1 := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(),
chanValue, uint32(nextHeight),
)
require.NoError(t, err, "unable create channel edge")
block102.Transactions = append(block102.Transactions, fundingTx1)
ctx.chain.addBlock(block102, uint32(nextHeight), rand.Uint32())
ctx.chain.setBestBlock(int32(nextHeight))
@@ -660,23 +590,15 @@ func TestChansClosedOfflinePruneGraph(t *testing.T) {
)
require.NoError(t, err)
if err := ctx.builder.AddEdge(ctxb, edge1); err != nil {
t.Fatalf("unable to add edge: %v", err)
}
require.NoError(t, ctx.builder.AddEdge(ctxb, edge1))
// The router should now be aware of the channel we created above.
hasChan, isZombie, err := ctx.graph.HasChannelEdge(
chanID1.ToUint64(),
)
if err != nil {
t.Fatalf("error looking for edge: %v", chanID1)
}
if !hasChan {
t.Fatalf("could not find edge in graph")
}
if isZombie {
t.Fatal("edge was marked as zombie")
}
require.NoError(t, err)
require.True(t, hasChan)
require.False(t, isZombie)
// With the transaction included, and the router's database state
// updated, we'll now mine 5 additional blocks on top of it.
@@ -695,15 +617,10 @@ func TestChansClosedOfflinePruneGraph(t *testing.T) {
// At this point, our starting height should be 107.
_, chainHeight, err := ctx.chain.GetBestBlock()
require.NoError(t, err, "unable to get best block")
if chainHeight != 107 {
t.Fatalf("incorrect chain height: expected %v, got %v",
107, chainHeight)
}
require.EqualValues(t, 107, chainHeight)
// Next, we'll "shut down" the router in order to simulate downtime.
if err := ctx.builder.Stop(); err != nil {
t.Fatalf("unable to shutdown router: %v", err)
}
require.NoError(t, ctx.builder.Stop())
// While the router is "offline" we'll mine 5 additional blocks, with
// the second block closing the channel we created above.
@@ -735,10 +652,7 @@ func TestChansClosedOfflinePruneGraph(t *testing.T) {
// At this point, our starting height should be 112.
_, chainHeight, err = ctx.chain.GetBestBlock()
require.NoError(t, err, "unable to get best block")
if chainHeight != 112 {
t.Fatalf("incorrect chain height: expected %v, got %v",
112, chainHeight)
}
require.EqualValues(t, 112, chainHeight)
// Now we'll re-start the ChannelRouter. It should recognize that it's
// behind the main chain and prune all the blocks that it missed while
@@ -750,15 +664,9 @@ func TestChansClosedOfflinePruneGraph(t *testing.T) {
hasChan, isZombie, err = ctx.graph.HasChannelEdge(
chanID1.ToUint64(),
)
if err != nil {
t.Fatalf("error looking for edge: %v", chanID1)
}
if hasChan {
t.Fatalf("channel was found in graph but shouldn't have been")
}
if isZombie {
t.Fatal("closed channel should not be marked as zombie")
}
require.NoError(t, err)
require.False(t, hasChan)
require.False(t, isZombie)
}
// TestPruneChannelGraphStaleEdges ensures that we properly prune stale edges
@@ -857,9 +765,7 @@ func TestPruneChannelGraphStaleEdges(t *testing.T) {
testGraph, err := createTestGraphFromChannels(
t, true, testChannels, "a",
)
if err != nil {
t.Fatalf("unable to create test graph: %v", err)
}
require.NoError(t, err)
const startingHeight = 100
ctx := createTestCtxFromGraphInstance(
@@ -871,9 +777,7 @@ func TestPruneChannelGraphStaleEdges(t *testing.T) {
// Proceed to prune the channels - only the last one should be
// pruned.
if err := ctx.builder.pruneZombieChans(); err != nil {
t.Fatalf("unable to prune zombie channels: %v", err)
}
require.NoError(t, ctx.builder.pruneZombieChans())
// We expect channels that have either both edges stale, or one
// edge stale with both known.
@@ -1022,9 +926,7 @@ func testPruneChannelGraphDoubleDisabled(t *testing.T, assumeValid bool) {
assertChannelsPruned(t, ctx.graph, testChannels, prunedChannel)
}
if err := ctx.builder.pruneZombieChans(); err != nil {
t.Fatalf("unable to prune zombie channels: %v", err)
}
require.NoError(t, ctx.builder.pruneZombieChans())
// If we attempted to prune them without AssumeChannelValid being set,
// none should be pruned. Otherwise the last channel should still be
@@ -1055,12 +957,11 @@ func TestIsStaleNode(t *testing.T) {
copy(pub1[:], priv1.PubKey().SerializeCompressed())
copy(pub2[:], priv2.PubKey().SerializeCompressed())
script, fundingTx, _, chanID, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
script, fundingTx, _, chanID := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(),
10000, 500,
)
require.NoError(t, err, "unable to create channel edge")
fundingBlock := &wire.MsgBlock{
Transactions: []*wire.MsgTx{fundingTx},
}
@@ -1075,16 +976,12 @@ func TestIsStaleNode(t *testing.T) {
)
require.NoError(t, err)
if err := ctx.builder.AddEdge(ctxb, edge); err != nil {
t.Fatalf("unable to add edge: %v", err)
}
require.NoError(t, ctx.builder.AddEdge(ctxb, edge))
// Before we add the node, if we query for staleness, we should get
// false, as we haven't added the full node.
updateTimeStamp := time.Unix(123, 0)
if ctx.builder.IsStaleNode(ctxb, pub1, updateTimeStamp) {
t.Fatalf("incorrectly detected node as stale")
}
require.False(t, ctx.builder.IsStaleNode(ctxb, pub1, updateTimeStamp))
// With the node stub in the database, we'll add the fully node
// announcement to the database.
@@ -1098,22 +995,16 @@ func TestIsStaleNode(t *testing.T) {
Features: testFeatures.RawFeatureVector,
},
)
if err := ctx.builder.AddNode(t.Context(), n1); err != nil {
t.Fatalf("could not add node: %v", err)
}
require.NoError(t, ctx.builder.AddNode(t.Context(), n1))
// If we use the same timestamp and query for staleness, we should get
// true.
if !ctx.builder.IsStaleNode(ctxb, pub1, updateTimeStamp) {
t.Fatalf("failure to detect stale node update")
}
require.True(t, ctx.builder.IsStaleNode(ctxb, pub1, updateTimeStamp))
// If we update the timestamp and once again query for staleness, it
// should report false.
newTimeStamp := time.Unix(1234, 0)
if ctx.builder.IsStaleNode(ctxb, pub1, newTimeStamp) {
t.Fatalf("incorrectly detected node as stale")
}
require.False(t, ctx.builder.IsStaleNode(ctxb, pub1, newTimeStamp))
}
// TestIsKnownEdge tests that the IsKnownEdge method properly detects stale
@@ -1134,12 +1025,11 @@ func TestIsKnownEdge(t *testing.T) {
copy(pub1[:], priv1.PubKey().SerializeCompressed())
copy(pub2[:], priv2.PubKey().SerializeCompressed())
script, fundingTx, _, chanID, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
script, fundingTx, _, chanID := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(),
10000, 500,
)
require.NoError(t, err, "unable to create channel edge")
fundingBlock := &wire.MsgBlock{
Transactions: []*wire.MsgTx{fundingTx},
}
@@ -1155,15 +1045,11 @@ func TestIsKnownEdge(t *testing.T) {
)
require.NoError(t, err)
if err := ctx.builder.AddEdge(ctxb, edge); err != nil {
t.Fatalf("unable to add edge: %v", err)
}
require.NoError(t, ctx.builder.AddEdge(ctxb, edge))
// Now that the edge has been inserted, query is the router already
// knows of the edge should return true.
if !ctx.builder.IsKnownEdge(*chanID) {
t.Fatalf("router should detect edge as known")
}
require.True(t, ctx.builder.IsKnownEdge(*chanID))
}
// TestIsStaleEdgePolicy tests that the IsStaleEdgePolicy properly detects
@@ -1184,12 +1070,11 @@ func TestIsStaleEdgePolicy(t *testing.T) {
copy(pub1[:], priv1.PubKey().SerializeCompressed())
copy(pub2[:], priv2.PubKey().SerializeCompressed())
script, fundingTx, _, chanID, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
script, fundingTx, _, chanID := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(),
10000, 500,
)
require.NoError(t, err, "unable to create channel edge")
fundingBlock := &wire.MsgBlock{
Transactions: []*wire.MsgTx{fundingTx},
}
@@ -1198,12 +1083,16 @@ func TestIsStaleEdgePolicy(t *testing.T) {
// If we query for staleness before adding the edge, we should get
// false.
updateTimeStamp := time.Unix(123, 0)
if ctx.builder.IsStaleEdgePolicy(*chanID, updateTimeStamp, 0) {
t.Fatalf("router failed to detect fresh edge policy")
}
if ctx.builder.IsStaleEdgePolicy(*chanID, updateTimeStamp, 1) {
t.Fatalf("router failed to detect fresh edge policy")
}
require.False(
t, ctx.builder.IsStaleEdgePolicy(
*chanID, updateTimeStamp, 0,
),
)
require.False(
t, ctx.builder.IsStaleEdgePolicy(
*chanID, updateTimeStamp, 1,
),
)
edge, err := models.NewV1Channel(
chanID.ToUint64(), *chaincfg.SimNetParams.GenesisHash, pub1,
@@ -1214,9 +1103,7 @@ func TestIsStaleEdgePolicy(t *testing.T) {
)
require.NoError(t, err)
if err := ctx.builder.AddEdge(ctxb, edge); err != nil {
t.Fatalf("unable to add edge: %v", err)
}
require.NoError(t, ctx.builder.AddEdge(ctxb, edge))
// We'll also add two edge policies, one for each direction.
edgePolicy := &models.ChannelEdgePolicy{
@@ -1230,9 +1117,7 @@ func TestIsStaleEdgePolicy(t *testing.T) {
FeeProportionalMillionths: 10000,
}
edgePolicy.ChannelFlags = 0
if err := ctx.builder.UpdateEdge(ctxb, edgePolicy); err != nil {
t.Fatalf("unable to update edge policy: %v", err)
}
require.NoError(t, ctx.builder.UpdateEdge(ctxb, edgePolicy))
edgePolicy = &models.ChannelEdgePolicy{
Version: lnwire.GossipVersion1,
@@ -1245,28 +1130,34 @@ func TestIsStaleEdgePolicy(t *testing.T) {
FeeProportionalMillionths: 10000,
}
edgePolicy.ChannelFlags = 1
if err := ctx.builder.UpdateEdge(ctxb, edgePolicy); err != nil {
t.Fatalf("unable to update edge policy: %v", err)
}
require.NoError(t, ctx.builder.UpdateEdge(ctxb, edgePolicy))
// Now that the edges have been added, an identical (chanID, flag,
// timestamp) tuple for each edge should be detected as a stale edge.
if !ctx.builder.IsStaleEdgePolicy(*chanID, updateTimeStamp, 0) {
t.Fatalf("router failed to detect stale edge policy")
}
if !ctx.builder.IsStaleEdgePolicy(*chanID, updateTimeStamp, 1) {
t.Fatalf("router failed to detect stale edge policy")
}
require.True(
t, ctx.builder.IsStaleEdgePolicy(
*chanID, updateTimeStamp, 0,
),
)
require.True(
t, ctx.builder.IsStaleEdgePolicy(
*chanID, updateTimeStamp, 1,
),
)
// If we now update the timestamp for both edges, the router should
// detect that this tuple represents a fresh edge.
updateTimeStamp = time.Unix(9999, 0)
if ctx.builder.IsStaleEdgePolicy(*chanID, updateTimeStamp, 0) {
t.Fatalf("router failed to detect fresh edge policy")
}
if ctx.builder.IsStaleEdgePolicy(*chanID, updateTimeStamp, 1) {
t.Fatalf("router failed to detect fresh edge policy")
}
require.False(
t, ctx.builder.IsStaleEdgePolicy(
*chanID, updateTimeStamp, 0,
),
)
require.False(
t, ctx.builder.IsStaleEdgePolicy(
*chanID, updateTimeStamp, 1,
),
)
}
// TestBlockDifferenceFix tests if when the router is behind on blocks, the
@@ -1722,27 +1613,25 @@ func assertChannelsPruned(t *testing.T, graph *graphdb.VersionedGraph,
exists, isZombie, err := graph.HasChannelEdge(
channel.ChannelID,
)
if err != nil {
t.Fatalf("unable to determine existence of "+
"channel=%v in the graph: %v",
channel.ChannelID, err)
}
if !shouldPrune && !exists {
t.Fatalf("expected channel=%v to exist within "+
"the graph", channel.ChannelID)
}
if shouldPrune && exists {
t.Fatalf("expected channel=%v to not exist "+
"within the graph", channel.ChannelID)
}
if !shouldPrune && isZombie {
t.Fatalf("expected channel=%v to not be marked "+
"as zombie", channel.ChannelID)
}
if shouldPrune && !isZombie {
t.Fatalf("expected channel=%v to be marked as "+
"zombie", channel.ChannelID)
require.NoError(t, err)
if shouldPrune {
require.Falsef(t, exists,
"expected channel=%v to not exist within "+
"the graph",
channel.ChannelID)
require.Truef(t, isZombie,
"expected channel=%v to be marked as zombie",
channel.ChannelID)
continue
}
require.Truef(t, exists,
"expected channel=%v to exist within the graph",
channel.ChannelID)
require.Falsef(t, isZombie,
"expected channel=%v to not be marked as zombie",
channel.ChannelID)
}
}
+5 -20
View File
@@ -3,7 +3,6 @@ package graphdb
import (
"bytes"
"net"
"strings"
"testing"
"github.com/lightningnetwork/lnd/lnwire"
@@ -148,29 +147,15 @@ func TestAddrSerialization(t *testing.T) {
var b bytes.Buffer
for _, test := range addrTests {
err := SerializeAddr(&b, test.expAddr)
switch {
case err == nil && test.serErr != "":
t.Fatalf("expected serialization err for addr %v",
test.expAddr)
case err != nil && test.serErr == "":
t.Fatalf("unexpected serialization err for addr %v: %v",
test.expAddr, err)
case err != nil && !strings.Contains(err.Error(), test.serErr):
t.Fatalf("unexpected serialization err for addr %v, "+
"want: %v, got %v", test.expAddr, test.serErr,
err)
case err != nil:
if test.serErr != "" {
require.Error(t, err)
require.ErrorContains(t, err, test.serErr)
continue
}
require.NoError(t, err)
addr, err := DeserializeAddr(&b)
if err != nil {
t.Fatalf("unable to deserialize address: %v", err)
}
require.NoError(t, err)
require.Equal(t, test.expAddr, addr)
}
}
+5 -14
View File
@@ -1,13 +1,13 @@
package graphdb
import (
"reflect"
"testing"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/lightningnetwork/lnd/graph/db/models"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/routing/route"
"github.com/stretchr/testify/require"
)
// TestChannelCache checks the behavior of the channelCache with respect to
@@ -23,9 +23,7 @@ func TestChannelCache(t *testing.T) {
// As a sanity check, assert that querying the empty cache does not
// return an entry.
_, ok := c.get(v, 0)
if ok {
t.Fatalf("channel cache should be empty")
}
require.False(t, ok)
// Now, fill up the cache entirely.
for i := uint64(0); i < cacheSize; i++ {
@@ -55,9 +53,7 @@ func TestChannelCache(t *testing.T) {
// Assert that exactly one element has been evicted.
numEvicted := len(evicted)
if numEvicted != 1 {
t.Fatalf("expected one evicted entry, got: %d", numEvicted)
}
require.Equal(t, 1, numEvicted)
// Remove the highest item which initially caused the eviction and
// reinsert the element that was evicted prior.
@@ -92,15 +88,10 @@ func assertHasChanEntries(t *testing.T, c *channelCache,
for i := start; i < end; i++ {
entry, ok := c.get(v, i)
if !ok {
t.Fatalf("channel cache should contain chan %d", i)
}
require.True(t, ok)
expEntry := channelForInt(i)
if !reflect.DeepEqual(entry, expEntry) {
t.Fatalf("entry mismatch, want: %v, got: %v",
expEntry, entry)
}
require.Equal(t, expEntry, entry)
}
}
+130 -430
View File
File diff suppressed because it is too large. Load diff
+5 -14
View File
@@ -1,10 +1,10 @@
package graphdb
import (
"reflect"
"testing"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/stretchr/testify/require"
)
// TestRejectCache checks the behavior of the rejectCache with respect to insertion,
@@ -18,9 +18,7 @@ func TestRejectCache(t *testing.T) {
// As a sanity check, assert that querying the empty cache does not
// return an entry.
_, ok := c.get(lnwire.GossipVersion1, 0)
if ok {
t.Fatalf("reject cache should be empty")
}
require.False(t, ok)
// Now, fill up the cache entirely.
for i := uint64(0); i < cacheSize; i++ {
@@ -53,9 +51,7 @@ func TestRejectCache(t *testing.T) {
// Assert that exactly one element has been evicted.
numEvicted := len(evicted)
if numEvicted != 1 {
t.Fatalf("expected one evicted entry, got: %d", numEvicted)
}
require.Equal(t, 1, numEvicted)
// Remove the highest item which initially caused the eviction and
// reinsert the element that was evicted prior.
@@ -88,15 +84,10 @@ func assertHasEntries(t *testing.T, c *rejectCache, start, end uint64) {
for i := start; i < end; i++ {
entry, ok := c.get(lnwire.GossipVersion1, i)
if !ok {
t.Fatalf("reject cache should contain chan %d", i)
}
require.True(t, ok)
expEntry := entryForInt(i)
if !reflect.DeepEqual(entry, expEntry) {
t.Fatalf("entry mismatch, want: %v, got: %v",
expEntry, entry)
}
require.Equal(t, expEntry, entry)
}
}
+57 -141
View File
@@ -98,8 +98,10 @@ func createTestNode(t *testing.T) *models.Node {
return n
}
func randEdgePolicy(chanID *lnwire.ShortChannelID,
node *models.Node) (*models.ChannelEdgePolicy, error) {
func randEdgePolicy(t testing.TB, chanID *lnwire.ShortChannelID,
node *models.Node) *models.ChannelEdgePolicy {
t.Helper()
InboundFee := models.InboundFee{
Base: prand.Int31() * -1,
@@ -108,9 +110,7 @@ func randEdgePolicy(chanID *lnwire.ShortChannelID,
inboundFee := InboundFee.ToWire()
var extraOpaqueData lnwire.ExtraOpaqueData
if err := extraOpaqueData.PackRecords(&inboundFee); err != nil {
return nil, err
}
require.NoError(t, extraOpaqueData.PackRecords(&inboundFee))
return &models.ChannelEdgePolicy{
Version: lnwire.GossipVersion1,
@@ -125,12 +125,14 @@ func randEdgePolicy(chanID *lnwire.ShortChannelID,
ToNode: node.PubKeyBytes,
InboundFee: fn.Some(inboundFee),
ExtraOpaqueData: extraOpaqueData,
}, nil
}
}
func createChannelEdge(bitcoinKey1, bitcoinKey2 []byte,
func createChannelEdge(t testing.TB, bitcoinKey1, bitcoinKey2 []byte,
chanValue btcutil.Amount, fundingHeight uint32) ([]byte, *wire.MsgTx,
*wire.OutPoint, *lnwire.ShortChannelID, error) {
*wire.OutPoint, *lnwire.ShortChannelID) {
t.Helper()
fundingTx := wire.NewMsgTx(2)
script, tx, err := input.GenFundingPkScript(
@@ -138,9 +140,7 @@ func createChannelEdge(bitcoinKey1, bitcoinKey2 []byte,
bitcoinKey2,
int64(chanValue),
)
if err != nil {
return nil, nil, nil, nil, err
}
require.NoError(t, err)
fundingTx.TxOut = append(fundingTx.TxOut, tx)
chanUtxo := wire.OutPoint{
@@ -155,7 +155,7 @@ func createChannelEdge(bitcoinKey1, bitcoinKey2 []byte,
TxPosition: 0,
}
return script, fundingTx, &chanUtxo, chanID, nil
return script, fundingTx, &chanUtxo, chanID
}
type mockChain struct {
@@ -429,11 +429,10 @@ func TestEdgeUpdateNotification(t *testing.T) {
// First we'll create the utxo for the channel to be "closed"
const chanValue = 10000
script, fundingTx, chanPoint, chanID, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
script, fundingTx, chanPoint, chanID := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(), chanValue, 0,
)
require.NoError(t, err, "unable create channel edge")
// We'll also add a record for the block that included our funding
// transaction.
@@ -471,9 +470,7 @@ func TestEdgeUpdateNotification(t *testing.T) {
)
require.NoError(t, err)
if err := ctx.builder.AddEdge(ctxb, edge); err != nil {
t.Fatalf("unable to add edge: %v", err)
}
require.NoError(t, ctx.builder.AddEdge(ctxb, edge))
// With the channel edge now in place, we'll subscribe for topology
// notifications.
@@ -482,64 +479,34 @@ func TestEdgeUpdateNotification(t *testing.T) {
// Create random policy edges that are stemmed to the channel id
// created above.
edge1, err := randEdgePolicy(chanID, node1)
require.NoError(t, err, "unable to create a random chan policy")
edge1 := randEdgePolicy(t, chanID, node1)
edge1.ChannelFlags = 0
edge2, err := randEdgePolicy(chanID, node2)
require.NoError(t, err, "unable to create a random chan policy")
edge2 := randEdgePolicy(t, chanID, node2)
edge2.ChannelFlags = 1
if err := ctx.builder.UpdateEdge(ctxb, edge1); err != nil {
t.Fatalf("unable to add edge update: %v", err)
}
if err := ctx.builder.UpdateEdge(ctxb, edge2); err != nil {
t.Fatalf("unable to add edge update: %v", err)
}
require.NoError(t, ctx.builder.UpdateEdge(ctxb, edge1))
require.NoError(t, ctx.builder.UpdateEdge(ctxb, edge2))
assertEdgeCorrect := func(t *testing.T,
edgeUpdate *graphdb.ChannelEdgeUpdate,
edgeAnn *models.ChannelEdgePolicy) {
if edgeUpdate.ChanID != edgeAnn.ChannelID {
t.Fatalf("channel ID of edge doesn't match: "+
"expected %v, got %v", chanID.ToUint64(), edgeUpdate.ChanID)
}
if edgeUpdate.ChanPoint != *chanPoint {
t.Fatalf("channel don't match: expected %v, got %v",
chanPoint, edgeUpdate.ChanPoint)
}
require.Equal(t, edgeAnn.ChannelID, edgeUpdate.ChanID)
require.Equal(t, *chanPoint, edgeUpdate.ChanPoint)
// TODO(roasbeef): this is a hack, needs to be removed
// after commitment fees are dynamic.
if edgeUpdate.Capacity != chanValue {
t.Fatalf("capacity of edge doesn't match: "+
"expected %v, got %v", chanValue, edgeUpdate.Capacity)
}
if edgeUpdate.MinHTLC != edgeAnn.MinHTLC {
t.Fatalf("min HTLC of edge doesn't match: "+
"expected %v, got %v", edgeAnn.MinHTLC,
edgeUpdate.MinHTLC)
}
if edgeUpdate.MaxHTLC != edgeAnn.MaxHTLC {
t.Fatalf("max HTLC of edge doesn't match: "+
"expected %v, got %v", edgeAnn.MaxHTLC,
edgeUpdate.MaxHTLC)
}
if edgeUpdate.BaseFee != edgeAnn.FeeBaseMSat {
t.Fatalf("base fee of edge doesn't match: "+
"expected %v, got %v", edgeAnn.FeeBaseMSat,
edgeUpdate.BaseFee)
}
if edgeUpdate.FeeRate != edgeAnn.FeeProportionalMillionths {
t.Fatalf("fee rate of edge doesn't match: "+
"expected %v, got %v", edgeAnn.FeeProportionalMillionths,
edgeUpdate.FeeRate)
}
if edgeUpdate.TimeLockDelta != edgeAnn.TimeLockDelta {
t.Fatalf("time lock delta of edge doesn't match: "+
"expected %v, got %v", edgeAnn.TimeLockDelta,
edgeUpdate.TimeLockDelta)
}
require.EqualValues(t, chanValue, edgeUpdate.Capacity)
require.Equal(t, edgeAnn.MinHTLC, edgeUpdate.MinHTLC)
require.Equal(t, edgeAnn.MaxHTLC, edgeUpdate.MaxHTLC)
require.Equal(t, edgeAnn.FeeBaseMSat, edgeUpdate.BaseFee)
require.Equal(
t, edgeAnn.FeeProportionalMillionths,
edgeUpdate.FeeRate,
)
require.Equal(
t, edgeAnn.TimeLockDelta, edgeUpdate.TimeLockDelta,
)
require.Equal(
t, edgeAnn.ExtraOpaqueData, edgeUpdate.ExtraOpaqueData,
)
@@ -563,10 +530,7 @@ func TestEdgeUpdateNotification(t *testing.T) {
case ntfn := <-ntfnClient.TopologyChanges:
// For each processed announcement we should only receive a
// single announcement in a batch.
if len(ntfn.ChannelEdgeUpdates) != 1 {
t.Fatalf("expected 1 notification, instead have %v",
len(ntfn.ChannelEdgeUpdates))
}
require.Len(t, ntfn.ChannelEdgeUpdates, 1)
edgeUpdate := ntfn.ChannelEdgeUpdates[0]
nodeVertex := route.NewVertex(edgeUpdate.AdvertisingNode)
@@ -624,12 +588,11 @@ func TestNodeUpdateNotification(t *testing.T) {
// We only accept node announcements from nodes having a known channel,
// so create one now.
const chanValue = 10000
script, fundingTx, _, chanID, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
script, fundingTx, _, chanID := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(),
chanValue, startingBlockHeight,
)
require.NoError(t, err, "unable create channel edge")
// We'll also add a record for the block that included our funding
// transaction.
@@ -669,9 +632,7 @@ func TestNodeUpdateNotification(t *testing.T) {
// Adding the edge will add the nodes to the graph, but with no info
// except the pubkey known.
if err := ctx.builder.AddEdge(ctxb, edge); err != nil {
t.Fatalf("unable to add edge: %v", err)
}
require.NoError(t, ctx.builder.AddEdge(ctxb, edge))
// Create a new client to receive notifications.
ntfnClient, err := ctx.graph.SubscribeTopology()
@@ -679,12 +640,8 @@ func TestNodeUpdateNotification(t *testing.T) {
// Change network topology by adding the updated info for the two nodes
// to the channel router.
if err := ctx.builder.AddNode(ctxb, node1); err != nil {
t.Fatalf("unable to add node: %v", err)
}
if err := ctx.builder.AddNode(ctxb, node2); err != nil {
t.Fatalf("unable to add node: %v", err)
}
require.NoError(t, ctx.builder.AddNode(ctxb, node1))
require.NoError(t, ctx.builder.AddNode(ctxb, node2))
assertNodeNtfnCorrect := func(t *testing.T, ann *models.Node,
nodeUpdate *graphdb.NetworkNodeUpdate) {
@@ -693,15 +650,8 @@ func TestNodeUpdateNotification(t *testing.T) {
// The notification received should directly map the
// announcement originally sent.
if nodeUpdate.Addresses[0] != ann.Addresses[0] {
t.Fatalf("node address doesn't match: expected %v, got %v",
nodeUpdate.Addresses[0], ann.Addresses[0])
}
if !nodeUpdate.IdentityKey.IsEqual(nodeKey) {
t.Fatalf("node identity keys don't match: expected %x, "+
"got %x", nodeKey.SerializeCompressed(),
nodeUpdate.IdentityKey.SerializeCompressed())
}
require.Equal(t, ann.Addresses[0], nodeUpdate.Addresses[0])
require.True(t, nodeUpdate.IdentityKey.IsEqual(nodeKey))
featuresBuf := new(bytes.Buffer)
require.NoError(t, nodeUpdate.Features.Encode(featuresBuf))
@@ -733,10 +683,7 @@ func TestNodeUpdateNotification(t *testing.T) {
case ntfn := <-ntfnClient.TopologyChanges:
// For each processed announcement we should only receive a
// single announcement in a batch.
if len(ntfn.NodeUpdates) != 1 {
t.Fatalf("expected 1 notification, instead have %v",
len(ntfn.NodeUpdates))
}
require.Len(t, ntfn.NodeUpdates, 1)
nodeUpdate := ntfn.NodeUpdates[0]
nodeVertex := route.NewVertex(nodeUpdate.IdentityKey)
@@ -774,9 +721,7 @@ func TestNodeUpdateNotification(t *testing.T) {
nodeUpdateAnn.LastUpdate = node1.LastUpdate.Add(time.Second)
// Add new node topology update to the channel router.
if err := ctx.builder.AddNode(ctxb, &nodeUpdateAnn); err != nil {
t.Fatalf("unable to add node: %v", err)
}
require.NoError(t, ctx.builder.AddNode(ctxb, &nodeUpdateAnn))
// Once again a notification should be received reflecting the up to
// date node announcement.
@@ -784,10 +729,7 @@ func TestNodeUpdateNotification(t *testing.T) {
case ntfn := <-ntfnClient.TopologyChanges:
// For each processed announcement we should only receive a
// single announcement in a batch.
if len(ntfn.NodeUpdates) != 1 {
t.Fatalf("expected 1 notification, instead have %v",
len(ntfn.NodeUpdates))
}
require.Len(t, ntfn.NodeUpdates, 1)
nodeUpdate := ntfn.NodeUpdates[0]
assertNodeNtfnCorrect(t, &nodeUpdateAnn, nodeUpdate)
@@ -812,12 +754,11 @@ func TestNotificationCancellation(t *testing.T) {
// We'll create the utxo for a new channel.
const chanValue = 10000
script, fundingTx, chanPoint, chanID, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
script, fundingTx, chanPoint, chanID := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(),
chanValue, startingBlockHeight,
)
require.NoError(t, err, "unable create channel edge")
// We'll also add a record for the block that included our funding
// transaction.
@@ -859,17 +800,11 @@ func TestNotificationCancellation(t *testing.T) {
)
require.NoError(t, err)
if err := ctx.builder.AddEdge(ctxb, edge); err != nil {
t.Fatalf("unable to add edge: %v", err)
}
require.NoError(t, ctx.builder.AddEdge(ctxb, edge))
if err := ctx.builder.AddNode(ctxb, node1); err != nil {
t.Fatalf("unable to add node: %v", err)
}
require.NoError(t, ctx.builder.AddNode(ctxb, node1))
if err := ctx.builder.AddNode(ctxb, node2); err != nil {
t.Fatalf("unable to add node: %v", err)
}
require.NoError(t, ctx.builder.AddNode(ctxb, node2))
select {
// The notifications shouldn't be sent, however, the channel should be
@@ -897,12 +832,11 @@ func TestChannelCloseNotification(t *testing.T) {
// First we'll create the utxo for the channel to be "closed"
const chanValue = 10000
script, fundingTx, chanUtxo, chanID, err := createChannelEdge(
bitcoinKey1.SerializeCompressed(),
script, fundingTx, chanUtxo, chanID := createChannelEdge(
t, bitcoinKey1.SerializeCompressed(),
bitcoinKey2.SerializeCompressed(), chanValue,
startingBlockHeight,
)
require.NoError(t, err, "unable create channel edge")
// We'll also add a record for the block that included our funding
// transaction.
@@ -940,9 +874,7 @@ func TestChannelCloseNotification(t *testing.T) {
)
require.NoError(t, err)
if err := ctx.builder.AddEdge(ctxb, edge); err != nil {
t.Fatalf("unable to add edge: %v", err)
}
require.NoError(t, ctx.builder.AddEdge(ctxb, edge))
// With the channel edge now in place, we'll subscribe for topology
// notifications.
@@ -975,35 +907,19 @@ func TestChannelCloseNotification(t *testing.T) {
// We should have exactly a single notification for the channel
// "closed" above.
closedChans := ntfn.ClosedChannels
if len(closedChans) == 0 {
t.Fatal("close channel ntfn not populated")
} else if len(closedChans) != 1 {
t.Fatalf("only one should have been detected as closed, "+
"instead %v were", len(closedChans))
}
require.NotEmpty(t, closedChans)
require.Len(t, closedChans, 1)
// Ensure that the notification we received includes the proper
// update the for the channel that was closed in the generated
// block.
closedChan := closedChans[0]
if closedChan.ChanID != chanID.ToUint64() {
t.Fatalf("channel ID of closed channel doesn't match: "+
"expected %v, got %v", chanID.ToUint64(), closedChan.ChanID)
}
require.Equal(t, chanID.ToUint64(), closedChan.ChanID)
// TODO(roasbeef): this is a hack, needs to be removed
// after commitment fees are dynamic.
if closedChan.Capacity != chanValue {
t.Fatalf("capacity of closed channel doesn't match: "+
"expected %v, got %v", chanValue, closedChan.Capacity)
}
if closedChan.ClosedHeight != blockHeight {
t.Fatalf("close height of closed channel doesn't match: "+
"expected %v, got %v", blockHeight, closedChan.ClosedHeight)
}
if closedChan.ChanPoint != *chanUtxo {
t.Fatalf("chan point of closed channel doesn't match: "+
"expected %v, got %v", chanUtxo, closedChan.ChanPoint)
}
require.EqualValues(t, chanValue, closedChan.Capacity)
require.Equal(t, blockHeight, closedChan.ClosedHeight)
require.Equal(t, *chanUtxo, closedChan.ChanPoint)
case <-time.After(time.Second * 5):
t.Fatal("notification not sent")