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