watchtower/wtdb: update tests to use require package

In this commit, all the tests in the wtdb package are updated in order
to make use of the `require` package where appropriate.
This commit is contained in:
Elle Mouton committed 2022-10-13 11:30:26 +02:00
1 parent f815c88ee4
commit 5dabf7cb3e
3 files changed
+125 -317

No files matched your search

+87 -198
View File
@@ -1,11 +1,9 @@
package wtdb_test package wtdb_test
import ( import (
"bytes"
crand "crypto/rand" crand "crypto/rand"
"io" "io"
"net" "net"
"reflect"
"testing" "testing"
"github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcec/v2"
@@ -16,6 +14,7 @@ import (
"github.com/lightningnetwork/lnd/watchtower/wtdb" "github.com/lightningnetwork/lnd/watchtower/wtdb"
"github.com/lightningnetwork/lnd/watchtower/wtmock" "github.com/lightningnetwork/lnd/watchtower/wtmock"
"github.com/lightningnetwork/lnd/watchtower/wtpolicy" "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
"github.com/stretchr/testify/require"
) )
// clientDBInit is a closure used to initialize a wtclient.DB instance. // clientDBInit is a closure used to initialize a wtclient.DB instance.
@@ -43,10 +42,7 @@ func (h *clientDBHarness) insertSession(session *wtdb.ClientSession,
h.t.Helper() h.t.Helper()
err := h.db.CreateClientSession(session) err := h.db.CreateClientSession(session)
if err != expErr { require.ErrorIs(h.t, err, expErr)
h.t.Fatalf("expected create client session error: %v, got: %v",
expErr, err)
}
} }
func (h *clientDBHarness) listSessions( func (h *clientDBHarness) listSessions(
@@ -55,9 +51,7 @@ func (h *clientDBHarness) listSessions(
h.t.Helper() h.t.Helper()
sessions, err := h.db.ListClientSessions(id) sessions, err := h.db.ListClientSessions(id)
if err != nil { require.NoError(h.t, err, "unable to list client sessions")
h.t.Fatalf("unable to list client sessions: %v", err)
}
return sessions return sessions
} }
@@ -68,13 +62,8 @@ func (h *clientDBHarness) nextKeyIndex(id wtdb.TowerID,
h.t.Helper() h.t.Helper()
index, err := h.db.NextSessionKeyIndex(id, blobType) index, err := h.db.NextSessionKeyIndex(id, blobType)
if err != nil { require.NoError(h.t, err, "unable to create next session key index")
h.t.Fatalf("unable to create next session key index: %v", err) require.NotZero(h.t, index, "next key index should never be 0")
}
if index == 0 {
h.t.Fatalf("next key index should never be 0")
}
return index return index
} }
@@ -85,21 +74,11 @@ func (h *clientDBHarness) createTower(lnAddr *lnwire.NetAddress,
h.t.Helper() h.t.Helper()
tower, err := h.db.CreateTower(lnAddr) tower, err := h.db.CreateTower(lnAddr)
if err != expErr { require.ErrorIs(h.t, err, expErr)
h.t.Fatalf("expected create tower error: %v, got: %v", expErr, require.NotZero(h.t, tower.ID, "tower id should never be 0")
err)
}
if tower.ID == 0 {
h.t.Fatalf("tower id should never be 0")
}
for _, session := range h.listSessions(&tower.ID) { for _, session := range h.listSessions(&tower.ID) {
if session.Status != wtdb.CSessionActive { require.Equal(h.t, wtdb.CSessionActive, session.Status)
h.t.Fatalf("expected status for session %v to be %v, "+
"got %v", session.ID, wtdb.CSessionActive,
session.Status)
}
} }
return tower return tower
@@ -110,10 +89,9 @@ func (h *clientDBHarness) removeTower(pubKey *btcec.PublicKey, addr net.Addr,
h.t.Helper() h.t.Helper()
if err := h.db.RemoveTower(pubKey, addr); err != expErr { err := h.db.RemoveTower(pubKey, addr)
h.t.Fatalf("expected remove tower error: %v, got %v", expErr, require.ErrorIs(h.t, err, expErr)
err)
}
if expErr != nil { if expErr != nil {
return return
} }
@@ -122,40 +100,34 @@ func (h *clientDBHarness) removeTower(pubKey *btcec.PublicKey, addr net.Addr,
if addr != nil { if addr != nil {
tower, err := h.db.LoadTower(pubKey) tower, err := h.db.LoadTower(pubKey)
if err != nil { require.NoErrorf(h.t, err, "expected tower %x to still exist",
h.t.Fatalf("expected tower %x to still exist",
pubKeyStr) pubKeyStr)
}
removedAddr := addr.String() removedAddr := addr.String()
for _, towerAddr := range tower.Addresses { for _, towerAddr := range tower.Addresses {
if towerAddr.String() == removedAddr { require.NotEqualf(h.t, removedAddr, towerAddr,
h.t.Fatalf("address %v not removed for tower "+ "address %v not removed for tower %x",
"%x", removedAddr, pubKeyStr) removedAddr, pubKeyStr)
}
} }
} else { } else {
tower, err := h.db.LoadTower(pubKey) tower, err := h.db.LoadTower(pubKey)
if hasSessions && err != nil { if hasSessions {
h.t.Fatalf("expected tower %x with sessions to still "+ require.NoError(h.t, err, "expected tower %x with "+
"exist", pubKeyStr) "sessions to still exist", pubKeyStr)
} } else {
if !hasSessions && err == nil { require.Errorf(h.t, err, "expected tower %x with no "+
h.t.Fatalf("expected tower %x with no sessions to not "+ "sessions to not exist", pubKeyStr)
"exist", pubKeyStr)
}
if !hasSessions {
return return
} }
for _, session := range h.listSessions(&tower.ID) { for _, session := range h.listSessions(&tower.ID) {
if session.Status != wtdb.CSessionInactive { require.Equal(h.t, wtdb.CSessionInactive,
h.t.Fatalf("expected status for session %v to "+ session.Status, "expected status for session "+
"be %v, got %v", session.ID, "%v to be %v, got %v", session.ID,
wtdb.CSessionInactive, session.Status) wtdb.CSessionInactive, session.Status)
} }
} }
} }
}
func (h *clientDBHarness) loadTower(pubKey *btcec.PublicKey, func (h *clientDBHarness) loadTower(pubKey *btcec.PublicKey,
expErr error) *wtdb.Tower { expErr error) *wtdb.Tower {
@@ -163,10 +135,7 @@ func (h *clientDBHarness) loadTower(pubKey *btcec.PublicKey,
h.t.Helper() h.t.Helper()
tower, err := h.db.LoadTower(pubKey) tower, err := h.db.LoadTower(pubKey)
if err != expErr { require.ErrorIs(h.t, err, expErr)
h.t.Fatalf("expected load tower error: %v, got: %v", expErr,
err)
}
return tower return tower
} }
@@ -177,10 +146,7 @@ func (h *clientDBHarness) loadTowerByID(id wtdb.TowerID,
h.t.Helper() h.t.Helper()
tower, err := h.db.LoadTowerByID(id) tower, err := h.db.LoadTowerByID(id)
if err != expErr { require.ErrorIs(h.t, err, expErr)
h.t.Fatalf("expected load tower error: %v, got: %v", expErr,
err)
}
return tower return tower
} }
@@ -189,9 +155,7 @@ func (h *clientDBHarness) fetchChanSummaries() map[lnwire.ChannelID]wtdb.ClientC
h.t.Helper() h.t.Helper()
summaries, err := h.db.FetchChanSummaries() summaries, err := h.db.FetchChanSummaries()
if err != nil { require.NoError(h.t, err)
h.t.Fatalf("unable to fetch chan summaries: %v", err)
}
return summaries return summaries
} }
@@ -202,10 +166,7 @@ func (h *clientDBHarness) registerChan(chanID lnwire.ChannelID,
h.t.Helper() h.t.Helper()
err := h.db.RegisterChannel(chanID, sweepPkScript) err := h.db.RegisterChannel(chanID, sweepPkScript)
if err != expErr { require.ErrorIs(h.t, err, expErr)
h.t.Fatalf("expected register channel error: %v, got: %v",
expErr, err)
}
} }
func (h *clientDBHarness) commitUpdate(id *wtdb.SessionID, func (h *clientDBHarness) commitUpdate(id *wtdb.SessionID,
@@ -214,10 +175,7 @@ func (h *clientDBHarness) commitUpdate(id *wtdb.SessionID,
h.t.Helper() h.t.Helper()
lastApplied, err := h.db.CommitUpdate(id, update) lastApplied, err := h.db.CommitUpdate(id, update)
if err != expErr { require.ErrorIs(h.t, err, expErr)
h.t.Fatalf("expected commit update error: %v, got: %v",
expErr, err)
}
return lastApplied return lastApplied
} }
@@ -228,10 +186,7 @@ func (h *clientDBHarness) ackUpdate(id *wtdb.SessionID, seqNum uint16,
h.t.Helper() h.t.Helper()
err := h.db.AckUpdate(id, seqNum, lastApplied) err := h.db.AckUpdate(id, seqNum, lastApplied)
if err != expErr { require.ErrorIs(h.t, err, expErr)
h.t.Fatalf("expected commit update error: %v, got: %v",
expErr, err)
}
} }
// testCreateClientSession asserts various conditions regarding the creation of // testCreateClientSession asserts various conditions regarding the creation of
@@ -259,9 +214,9 @@ func testCreateClientSession(h *clientDBHarness) {
// First, assert that this session is not already present in the // First, assert that this session is not already present in the
// database. // database.
if _, ok := h.listSessions(nil)[session.ID]; ok { _, ok := h.listSessions(nil)[session.ID]
h.t.Fatalf("session for id %x should not exist yet", session.ID) require.Falsef(h.t, ok, "session for id %x should not exist yet",
} session.ID)
// Attempting to insert the client session without reserving a session // Attempting to insert the client session without reserving a session
// key index should fail. // key index should fail.
@@ -278,10 +233,8 @@ func testCreateClientSession(h *clientDBHarness) {
// successfully created, it should return the same index to maintain // successfully created, it should return the same index to maintain
// idempotency across restarts. // idempotency across restarts.
keyIndex2 := h.nextKeyIndex(session.TowerID, blobType) keyIndex2 := h.nextKeyIndex(session.TowerID, blobType)
if keyIndex != keyIndex2 { require.Equalf(h.t, keyIndex, keyIndex2, "next key index should "+
h.t.Fatalf("next key index should be idempotent: want: %v, "+ "be idempotent: want: %v, got %v", keyIndex, keyIndex2)
"got %v", keyIndex, keyIndex2)
}
// Now, set the client session's key index so that it is proper and // Now, set the client session's key index so that it is proper and
// insert it. This should succeed. // insert it. This should succeed.
@@ -289,9 +242,8 @@ func testCreateClientSession(h *clientDBHarness) {
h.insertSession(session, nil) h.insertSession(session, nil)
// Verify that the session now exists in the database. // Verify that the session now exists in the database.
if _, ok := h.listSessions(nil)[session.ID]; !ok { _, ok = h.listSessions(nil)[session.ID]
h.t.Fatalf("session for id %x should exist now", session.ID) require.Truef(h.t, ok, "session for id %x should exist now", session.ID)
}
// Attempt to insert the session again, which should fail due to the // Attempt to insert the session again, which should fail due to the
// session already existing. // session already existing.
@@ -300,9 +252,8 @@ func testCreateClientSession(h *clientDBHarness) {
// Finally, assert that reserving another key index succeeds with a // Finally, assert that reserving another key index succeeds with a
// different key index, now that the first one has been finalized. // different key index, now that the first one has been finalized.
keyIndex3 := h.nextKeyIndex(session.TowerID, blobType) keyIndex3 := h.nextKeyIndex(session.TowerID, blobType)
if keyIndex == keyIndex3 { require.NotEqualf(h.t, keyIndex, keyIndex3, "key index still "+
h.t.Fatalf("key index still reserved after creating session") "reserved after creating session")
}
} }
// testFilterClientSessions asserts that we can correctly filter client sessions // testFilterClientSessions asserts that we can correctly filter client sessions
@@ -343,15 +294,12 @@ func testFilterClientSessions(h *clientDBHarness) {
// them. // them.
for towerID, expectedSessions := range towerSessions { for towerID, expectedSessions := range towerSessions {
sessions := h.listSessions(&towerID) sessions := h.listSessions(&towerID)
if len(sessions) != len(expectedSessions) { require.Len(h.t, sessions, len(expectedSessions))
h.t.Fatalf("expected %v sessions for tower %v, got %v",
len(expectedSessions), towerID, len(sessions))
}
for _, expectedSession := range expectedSessions { for _, expectedSession := range expectedSessions {
if _, ok := sessions[expectedSession]; !ok { _, ok := sessions[expectedSession]
h.t.Fatalf("expected session %v for tower %v", require.Truef(h.t, ok, "expected session %v for "+
expectedSession, towerID) "tower %v", expectedSession, towerID)
}
} }
} }
} }
@@ -380,26 +328,18 @@ func testCreateTower(h *clientDBHarness) {
// Load the tower from the database and assert that it matches the tower // Load the tower from the database and assert that it matches the tower
// we created. // we created.
tower2 := h.loadTowerByID(tower.ID, nil) tower2 := h.loadTowerByID(tower.ID, nil)
if !reflect.DeepEqual(tower, tower2) { require.Equal(h.t, tower, tower2)
h.t.Fatalf("loaded tower mismatch, want: %v, got: %v",
tower, tower2) tower2 = h.loadTower(tower.IdentityKey, nil)
} require.Equal(h.t, tower, tower2)
tower2 = h.loadTower(pk, err)
if !reflect.DeepEqual(tower, tower2) {
h.t.Fatalf("loaded tower mismatch, want: %v, got: %v",
tower, tower2)
}
// Insert the address again into the database. Since the address is the // Insert the address again into the database. Since the address is the
// same, this should result in an unmodified tower record. // same, this should result in an unmodified tower record.
towerDupAddr := h.createTower(lnAddr, nil) towerDupAddr := h.createTower(lnAddr, nil)
if len(towerDupAddr.Addresses) != 1 { require.Lenf(h.t, towerDupAddr.Addresses, 1, "duplicate address "+
h.t.Fatalf("duplicate address should be deduped") "should be deduped")
}
if !reflect.DeepEqual(tower, towerDupAddr) { require.Equal(h.t, tower, towerDupAddr)
h.t.Fatalf("mismatch towers, want: %v, got: %v",
tower, towerDupAddr)
}
// Generate a new address for this tower. // Generate a new address for this tower.
addr2 := &net.TCPAddr{IP: []byte{0x02, 0x00, 0x00, 0x00}, Port: 9911} addr2 := &net.TCPAddr{IP: []byte{0x02, 0x00, 0x00, 0x00}, Port: 9911}
@@ -416,26 +356,18 @@ func testCreateTower(h *clientDBHarness) {
// Load the tower from the database, and assert that it matches the // Load the tower from the database, and assert that it matches the
// tower returned from creation. // tower returned from creation.
towerNewAddr2 := h.loadTowerByID(tower.ID, nil) towerNewAddr2 := h.loadTowerByID(tower.ID, nil)
if !reflect.DeepEqual(towerNewAddr, towerNewAddr2) { require.Equal(h.t, towerNewAddr, towerNewAddr2)
h.t.Fatalf("loaded tower mismatch, want: %v, got: %v",
towerNewAddr, towerNewAddr2) towerNewAddr2 = h.loadTower(tower.IdentityKey, nil)
} require.Equal(h.t, towerNewAddr, towerNewAddr2)
towerNewAddr2 = h.loadTower(pk, nil)
if !reflect.DeepEqual(towerNewAddr, towerNewAddr2) {
h.t.Fatalf("loaded tower mismatch, want: %v, got: %v",
towerNewAddr, towerNewAddr2)
}
// Assert that there are now two addresses on the tower object. // Assert that there are now two addresses on the tower object.
if len(towerNewAddr.Addresses) != 2 { require.Lenf(h.t, towerNewAddr.Addresses, 2, "new address should be "+
h.t.Fatalf("new address should be added") "added")
}
// Finally, assert that the new address was prepended since it is deemed // Finally, assert that the new address was prepended since it is deemed
// fresher. // fresher.
if !reflect.DeepEqual(tower.Addresses, towerNewAddr.Addresses[1:]) { require.Equal(h.t, tower.Addresses, towerNewAddr.Addresses[1:])
h.t.Fatalf("new address should be prepended")
}
} }
// testRemoveTower asserts the behavior of removing Tower objects as a whole and // testRemoveTower asserts the behavior of removing Tower objects as a whole and
@@ -443,9 +375,7 @@ func testCreateTower(h *clientDBHarness) {
func testRemoveTower(h *clientDBHarness) { func testRemoveTower(h *clientDBHarness) {
// Generate a random public key we'll use for our tower. // Generate a random public key we'll use for our tower.
pk, err := randPubKey() pk, err := randPubKey()
if err != nil { require.NoError(h.t, err)
h.t.Fatalf("unable to generate pubkey: %v", err)
}
// Removing a tower that does not exist within the database should // Removing a tower that does not exist within the database should
// result in a NOP. // result in a NOP.
@@ -523,28 +453,23 @@ func testRemoveTower(h *clientDBHarness) {
func testChanSummaries(h *clientDBHarness) { func testChanSummaries(h *clientDBHarness) {
// First, assert that this channel is not already registered. // First, assert that this channel is not already registered.
var chanID lnwire.ChannelID var chanID lnwire.ChannelID
if _, ok := h.fetchChanSummaries()[chanID]; ok { _, ok := h.fetchChanSummaries()[chanID]
h.t.Fatalf("pkscript for channel %x should not exist yet", require.Falsef(h.t, ok, "pkscript for channel %x should not exist yet",
chanID) chanID)
}
// Generate a random sweep pkscript and register it for this channel. // Generate a random sweep pkscript and register it for this channel.
expPkScript := make([]byte, 22) expPkScript := make([]byte, 22)
if _, err := io.ReadFull(crand.Reader, expPkScript); err != nil { _, err := io.ReadFull(crand.Reader, expPkScript)
h.t.Fatalf("unable to generate pkscript: %v", err) require.NoError(h.t, err)
}
h.registerChan(chanID, expPkScript, nil) h.registerChan(chanID, expPkScript, nil)
// Assert that the channel exists and that its sweep pkscript matches // Assert that the channel exists and that its sweep pkscript matches
// the one we registered. // the one we registered.
summary, ok := h.fetchChanSummaries()[chanID] summary, ok := h.fetchChanSummaries()[chanID]
if !ok { require.Truef(h.t, ok, "pkscript for channel %x should not exist yet",
h.t.Fatalf("pkscript for channel %x should not exist yet",
chanID) chanID)
} else if bytes.Compare(expPkScript, summary.SweepPkScript) != 0 { require.Equal(h.t, expPkScript, summary.SweepPkScript)
h.t.Fatalf("pkscript mismatch, want: %x, got: %x",
expPkScript, summary.SweepPkScript)
}
// Finally, assert that re-registering the same channel produces a // Finally, assert that re-registering the same channel produces a
// failure. // failure.
@@ -581,10 +506,7 @@ func testCommitUpdate(h *clientDBHarness) {
// succeed. The lastApplied value should be 0 since we have not received // succeed. The lastApplied value should be 0 since we have not received
// an ack from the tower. // an ack from the tower.
lastApplied := h.commitUpdate(&session.ID, update1, nil) lastApplied := h.commitUpdate(&session.ID, update1, nil)
if lastApplied != 0 { require.Zero(h.t, lastApplied)
h.t.Fatalf("last applied mismatch, want: 0, got: %v",
lastApplied)
}
// Assert that the committed update appears in the client session's // Assert that the committed update appears in the client session's
// CommittedUpdates map when loaded from disk and that there are no // CommittedUpdates map when loaded from disk and that there are no
@@ -600,10 +522,7 @@ func testCommitUpdate(h *clientDBHarness) {
// the on-disk update's hint). The lastApplied value should remain // the on-disk update's hint). The lastApplied value should remain
// unchanged. // unchanged.
lastApplied2 := h.commitUpdate(&session.ID, update1, nil) lastApplied2 := h.commitUpdate(&session.ID, update1, nil)
if lastApplied2 != lastApplied { require.Equal(h.t, lastApplied, lastApplied2)
h.t.Fatalf("last applied should not have changed, got %v",
lastApplied2)
}
// Assert that the loaded ClientSession is the same as before. // Assert that the loaded ClientSession is the same as before.
dbSession = h.listSessions(nil)[session.ID] dbSession = h.listSessions(nil)[session.ID]
@@ -621,10 +540,7 @@ func testCommitUpdate(h *clientDBHarness) {
// which should succeed. // which should succeed.
update2.SeqNum = 2 update2.SeqNum = 2
lastApplied3 := h.commitUpdate(&session.ID, update2, nil) lastApplied3 := h.commitUpdate(&session.ID, update2, nil)
if lastApplied3 != lastApplied { require.Equal(h.t, lastApplied, lastApplied3)
h.t.Fatalf("last applied should not have changed, got %v",
lastApplied3)
}
// Check that both updates now appear as committed on the ClientSession // Check that both updates now appear as committed on the ClientSession
// loaded from disk. // loaded from disk.
@@ -684,10 +600,7 @@ func testAckUpdate(h *clientDBHarness) {
// Commit to a random update at seqnum 1. // Commit to a random update at seqnum 1.
update1 := randCommittedUpdate(h.t, 1) update1 := randCommittedUpdate(h.t, 1)
lastApplied := h.commitUpdate(&session.ID, update1, nil) lastApplied := h.commitUpdate(&session.ID, update1, nil)
if lastApplied != 0 { require.Zero(h.t, lastApplied)
h.t.Fatalf("last applied mismatch, want: 0, got: %v",
lastApplied)
}
// Acking seqnum 1 should succeed. // Acking seqnum 1 should succeed.
h.ackUpdate(&session.ID, 1, 1, nil) h.ackUpdate(&session.ID, 1, 1, nil)
@@ -715,10 +628,7 @@ func testAckUpdate(h *clientDBHarness) {
// ack. // ack.
update2 := randCommittedUpdate(h.t, 2) update2 := randCommittedUpdate(h.t, 2)
lastApplied = h.commitUpdate(&session.ID, update2, nil) lastApplied = h.commitUpdate(&session.ID, update2, nil)
if lastApplied != 1 { require.EqualValues(h.t, 1, lastApplied)
h.t.Fatalf("last applied mismatch, want: 1, got: %v",
lastApplied)
}
// Ack seqnum 2. // Ack seqnum 2.
h.ackUpdate(&session.ID, 2, 2, nil) h.ackUpdate(&session.ID, 2, 2, nil)
@@ -756,10 +666,7 @@ func checkCommittedUpdates(t *testing.T, session *wtdb.ClientSession,
expUpdates = make([]wtdb.CommittedUpdate, 0) expUpdates = make([]wtdb.CommittedUpdate, 0)
} }
if !reflect.DeepEqual(session.CommittedUpdates, expUpdates) { require.Equal(t, expUpdates, session.CommittedUpdates)
t.Fatalf("committed updates mismatch, want: %v, got: %v",
expUpdates, session.CommittedUpdates)
}
} }
// checkAckedUpdates asserts that the AckedUpdates on a session match the // checkAckedUpdates asserts that the AckedUpdates on a session match the
@@ -774,10 +681,7 @@ func checkAckedUpdates(t *testing.T, session *wtdb.ClientSession,
expUpdates = make(map[uint16]wtdb.BackupID) expUpdates = make(map[uint16]wtdb.BackupID)
} }
if !reflect.DeepEqual(session.AckedUpdates, expUpdates) { require.Equal(t, expUpdates, session.AckedUpdates)
t.Fatalf("acked updates mismatch, want: %v, got: %v",
expUpdates, session.AckedUpdates)
}
} }
// TestClientDB asserts the behavior of a fresh client db, a reopened client db, // TestClientDB asserts the behavior of a fresh client db, a reopened client db,
@@ -795,14 +699,10 @@ func TestClientDB(t *testing.T) {
bdb, err := wtdb.NewBoltBackendCreator( bdb, err := wtdb.NewBoltBackendCreator(
true, t.TempDir(), "wtclient.db", true, t.TempDir(), "wtclient.db",
)(dbCfg) )(dbCfg)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to open db: %v", err)
}
db, err := wtdb.OpenClientDB(bdb) db, err := wtdb.OpenClientDB(bdb)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to open db: %v", err)
}
t.Cleanup(func() { t.Cleanup(func() {
db.Close() db.Close()
@@ -819,27 +719,19 @@ func TestClientDB(t *testing.T) {
bdb, err := wtdb.NewBoltBackendCreator( bdb, err := wtdb.NewBoltBackendCreator(
true, path, "wtclient.db", true, path, "wtclient.db",
)(dbCfg) )(dbCfg)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to open db: %v", err)
}
db, err := wtdb.OpenClientDB(bdb) db, err := wtdb.OpenClientDB(bdb)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to open db: %v", err)
}
db.Close() db.Close()
bdb, err = wtdb.NewBoltBackendCreator( bdb, err = wtdb.NewBoltBackendCreator(
true, path, "wtclient.db", true, path, "wtclient.db",
)(dbCfg) )(dbCfg)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to open db: %v", err)
}
db, err = wtdb.OpenClientDB(bdb) db, err = wtdb.OpenClientDB(bdb)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to reopen db: %v", err)
}
t.Cleanup(func() { t.Cleanup(func() {
db.Close() db.Close()
@@ -909,19 +801,16 @@ func TestClientDB(t *testing.T) {
// randCommittedUpdate generates a random committed update. // randCommittedUpdate generates a random committed update.
func randCommittedUpdate(t *testing.T, seqNum uint16) *wtdb.CommittedUpdate { func randCommittedUpdate(t *testing.T, seqNum uint16) *wtdb.CommittedUpdate {
var chanID lnwire.ChannelID var chanID lnwire.ChannelID
if _, err := io.ReadFull(crand.Reader, chanID[:]); err != nil { _, err := io.ReadFull(crand.Reader, chanID[:])
t.Fatalf("unable to generate chan id: %v", err) require.NoError(t, err)
}
var hint blob.BreachHint var hint blob.BreachHint
if _, err := io.ReadFull(crand.Reader, hint[:]); err != nil { _, err = io.ReadFull(crand.Reader, hint[:])
t.Fatalf("unable to generate breach hint: %v", err) require.NoError(t, err)
}
encBlob := make([]byte, blob.Size(blob.FlagCommitOutputs.Type())) encBlob := make([]byte, blob.Size(blob.FlagCommitOutputs.Type()))
if _, err := io.ReadFull(crand.Reader, encBlob); err != nil { _, err = io.ReadFull(crand.Reader, encBlob)
t.Fatalf("unable to generate encrypted blob: %v", err) require.NoError(t, err)
}
return &wtdb.CommittedUpdate{ return &wtdb.CommittedUpdate{
SeqNum: seqNum, SeqNum: seqNum,
+7 -25
View File
@@ -13,6 +13,7 @@ import (
"github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcec/v2"
"github.com/lightningnetwork/lnd/tor" "github.com/lightningnetwork/lnd/tor"
"github.com/lightningnetwork/lnd/watchtower/wtdb" "github.com/lightningnetwork/lnd/watchtower/wtdb"
"github.com/stretchr/testify/require"
) )
func randPubKey() (*btcec.PublicKey, error) { func randPubKey() (*btcec.PublicKey, error) {
@@ -134,10 +135,7 @@ func TestCodec(tt *testing.T) {
// Ensure encoding the object succeeds. // Ensure encoding the object succeeds.
var b bytes.Buffer var b bytes.Buffer
err := obj.Encode(&b) err := obj.Encode(&b)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to encode: %v", err)
return false
}
var obj2 dbObject var obj2 dbObject
switch obj.(type) { switch obj.(type) {
@@ -162,17 +160,10 @@ func TestCodec(tt *testing.T) {
// Ensure decoding the object succeeds. // Ensure decoding the object succeeds.
err = obj2.Decode(bytes.NewReader(b.Bytes())) err = obj2.Decode(bytes.NewReader(b.Bytes()))
if err != nil { require.NoError(t, err)
t.Fatalf("unable to decode: %v", err)
return false
}
// Assert the original and decoded object match. // Assert the original and decoded object match.
if !reflect.DeepEqual(obj, obj2) { require.Equal(t, obj, obj2)
t.Fatalf("encode/decode mismatch, want: %v, "+
"got: %v", obj, obj2)
return false
}
return true return true
} }
@@ -180,16 +171,10 @@ func TestCodec(tt *testing.T) {
customTypeGen := map[string]func([]reflect.Value, *rand.Rand){ customTypeGen := map[string]func([]reflect.Value, *rand.Rand){
"Tower": func(v []reflect.Value, r *rand.Rand) { "Tower": func(v []reflect.Value, r *rand.Rand) {
pk, err := randPubKey() pk, err := randPubKey()
if err != nil { require.NoError(t, err)
t.Fatalf("unable to generate pubkey: %v", err)
return
}
addrs, err := randAddrs(r) addrs, err := randAddrs(r)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to generate addrs: %v", err)
return
}
obj := wtdb.Tower{ obj := wtdb.Tower{
IdentityKey: pk, IdentityKey: pk,
@@ -260,10 +245,7 @@ func TestCodec(tt *testing.T) {
} }
err := quick.Check(test.scenario, config) err := quick.Check(test.scenario, config)
if err != nil { require.NoError(h, err)
t.Fatalf("fuzz checks for msg=%s failed: %v",
test.name, err)
}
}) })
} }
} }
+31 -94
View File
@@ -3,7 +3,6 @@ package wtdb_test
import ( import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"reflect"
"testing" "testing"
"github.com/btcsuite/btcd/chaincfg/chainhash" "github.com/btcsuite/btcd/chaincfg/chainhash"
@@ -14,6 +13,7 @@ import (
"github.com/lightningnetwork/lnd/watchtower/wtdb" "github.com/lightningnetwork/lnd/watchtower/wtdb"
"github.com/lightningnetwork/lnd/watchtower/wtmock" "github.com/lightningnetwork/lnd/watchtower/wtmock"
"github.com/lightningnetwork/lnd/watchtower/wtpolicy" "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
"github.com/stretchr/testify/require"
) )
var ( var (
@@ -48,10 +48,7 @@ func (h *towerDBHarness) insertSession(s *wtdb.SessionInfo, expErr error) {
h.t.Helper() h.t.Helper()
err := h.db.InsertSessionInfo(s) err := h.db.InsertSessionInfo(s)
if err != expErr { require.ErrorIs(h.t, err, expErr)
h.t.Fatalf("expected insert session error: %v, got : %v",
expErr, err)
}
} }
// getSession retrieves the session identified by id, asserting that the call // getSession retrieves the session identified by id, asserting that the call
@@ -62,10 +59,7 @@ func (h *towerDBHarness) getSession(id *wtdb.SessionID,
h.t.Helper() h.t.Helper()
session, err := h.db.GetSessionInfo(id) session, err := h.db.GetSessionInfo(id)
if err != expErr { require.ErrorIs(h.t, err, expErr)
h.t.Fatalf("expected get session error: %v, got: %v",
expErr, err)
}
return session return session
} }
@@ -79,10 +73,7 @@ func (h *towerDBHarness) insertUpdate(s *wtdb.SessionStateUpdate,
h.t.Helper() h.t.Helper()
lastApplied, err := h.db.InsertStateUpdate(s) lastApplied, err := h.db.InsertStateUpdate(s)
if err != expErr { require.ErrorIs(h.t, err, expErr)
h.t.Fatalf("expected insert update error: %v, got: %v",
expErr, err)
}
return lastApplied return lastApplied
} }
@@ -93,10 +84,7 @@ func (h *towerDBHarness) deleteSession(id wtdb.SessionID, expErr error) {
h.t.Helper() h.t.Helper()
err := h.db.DeleteSession(id) err := h.db.DeleteSession(id)
if err != expErr { require.ErrorIs(h.t, err, expErr)
h.t.Fatalf("expected deletion error: %v, got: %v",
expErr, err)
}
} }
// queryMatches queries that database for the passed breach hint, returning all // queryMatches queries that database for the passed breach hint, returning all
@@ -105,9 +93,7 @@ func (h *towerDBHarness) queryMatches(hint blob.BreachHint) []wtdb.Match {
h.t.Helper() h.t.Helper()
matches, err := h.db.QueryMatches([]blob.BreachHint{hint}) matches, err := h.db.QueryMatches([]blob.BreachHint{hint})
if err != nil { require.NoError(h.t, err)
h.t.Fatalf("unable to query matches: %v", err)
}
return matches return matches
} }
@@ -119,14 +105,10 @@ func (h *towerDBHarness) hasUpdate(hint blob.BreachHint) wtdb.Match {
h.t.Helper() h.t.Helper()
matches := h.queryMatches(hint) matches := h.queryMatches(hint)
if len(matches) != 1 { require.Len(h.t, matches, 1)
h.t.Fatalf("expected 1 match, found: %d", len(matches))
}
match := matches[0] match := matches[0]
if match.Hint != hint { require.Equal(h.t, hint, match.Hint)
h.t.Fatalf("expected hint: %x, got: %x", hint, match.Hint)
}
return match return match
} }
@@ -158,11 +140,7 @@ func testInsertSession(h *towerDBHarness) {
h.insertSession(session, nil) h.insertSession(session, nil)
session2 := h.getSession(&id, nil) session2 := h.getSession(&id, nil)
require.Equal(h.t, session, session2)
if !reflect.DeepEqual(session, session2) {
h.t.Fatalf("expected session: %v, got %v",
session, session2)
}
h.insertSession(session, nil) h.insertSession(session, nil)
@@ -211,28 +189,21 @@ func testMultipleMatches(h *towerDBHarness) {
// Query the db for matches on the chosen hint. // Query the db for matches on the chosen hint.
matches := h.queryMatches(hint) matches := h.queryMatches(hint)
if len(matches) != numUpdates { require.Len(h.t, matches, numUpdates)
h.t.Fatalf("num updates mismatch, want: %d, got: %d",
numUpdates, len(matches))
}
// Assert that the hints are what we asked for, and compute the set of // Assert that the hints are what we asked for, and compute the set of
// sessions returned. // sessions returned.
sessions := make(map[wtdb.SessionID]struct{}) sessions := make(map[wtdb.SessionID]struct{})
for _, match := range matches { for _, match := range matches {
if match.Hint != hint { require.Equal(h.t, hint, match.Hint)
h.t.Fatalf("hint mismatch, want: %v, got: %v",
hint, match.Hint)
}
sessions[match.ID] = struct{}{} sessions[match.ID] = struct{}{}
} }
// Assert that the sessions returned match the session ids of the // Assert that the sessions returned match the session ids of the
// sessions we initially created. // sessions we initially created.
for i := 0; i < numUpdates; i++ { for i := 0; i < numUpdates; i++ {
if _, ok := sessions[*id(i)]; !ok { _, ok := sessions[*id(i)]
h.t.Fatalf("match for session %v not found", *id(i)) require.Truef(h.t, ok, "match for session %v not found", *id(i))
}
} }
} }
@@ -242,33 +213,22 @@ func testMultipleMatches(h *towerDBHarness) {
func testLookoutTip(h *towerDBHarness) { func testLookoutTip(h *towerDBHarness) {
// Retrieve lookout tip on fresh db. // Retrieve lookout tip on fresh db.
epoch, err := h.db.GetLookoutTip() epoch, err := h.db.GetLookoutTip()
if err != nil { require.NoError(h.t, err)
h.t.Fatalf("unable to fetch lookout tip: %v", err)
}
// Assert that the epoch is nil. // Assert that the epoch is nil.
if epoch != nil { require.Nil(h.t, epoch)
h.t.Fatalf("lookout tip should not be set, found: %v", epoch)
}
// Create a closure that inserts an epoch, retrieves it, and asserts // Create a closure that inserts an epoch, retrieves it, and asserts
// that the returned epoch matches what was inserted. // that the returned epoch matches what was inserted.
setAndCheck := func(i int) { setAndCheck := func(i int) {
expEpoch := epochFromInt(1) expEpoch := epochFromInt(1)
err = h.db.SetLookoutTip(expEpoch) err = h.db.SetLookoutTip(expEpoch)
if err != nil { require.NoError(h.t, err)
h.t.Fatalf("unable to set lookout tip: %v", err)
}
epoch, err = h.db.GetLookoutTip() epoch, err = h.db.GetLookoutTip()
if err != nil { require.NoError(h.t, err)
h.t.Fatalf("unable to fetch lookout tip: %v", err)
}
if !reflect.DeepEqual(epoch, expEpoch) { require.Equal(h.t, expEpoch, epoch)
h.t.Fatalf("lookout tip mismatch, want: %v, got: %v",
expEpoch, epoch)
}
} }
// Set and assert the lookout tip. // Set and assert the lookout tip.
@@ -348,15 +308,10 @@ func testDeleteSession(h *towerDBHarness) {
// Assert that only one update is still present. // Assert that only one update is still present.
matches := h.queryMatches(hint) matches := h.queryMatches(hint)
if len(matches) != 1 { require.Len(h.t, matches, 1)
h.t.Fatalf("expected one update, found: %d", len(matches))
}
// Assert that the update belongs to the first session. // Assert that the update belongs to the first session.
if matches[0].ID != *id0 { require.Equal(h.t, *id0, matches[0].ID)
h.t.Fatalf("expected match for %v, instead is for: %v",
*id0, matches[0].ID)
}
// Finally, remove the first session added. // Finally, remove the first session added.
h.deleteSession(*id0, nil) h.deleteSession(*id0, nil)
@@ -366,9 +321,7 @@ func testDeleteSession(h *towerDBHarness) {
// No matches should exist for this hint. // No matches should exist for this hint.
matches = h.queryMatches(hint) matches = h.queryMatches(hint)
if len(matches) != 0 { require.Zero(h.t, len(matches))
h.t.Fatalf("expected zero updates, found: %d", len(matches))
}
} }
type stateUpdateTest struct { type stateUpdateTest struct {
@@ -403,10 +356,9 @@ func runStateUpdateTest(test stateUpdateTest) func(*towerDBHarness) {
*expSession = *test.session *expSession = *test.session
} }
if len(test.updates) != len(test.updateErrs) { require.Lenf(h.t, test.updates, len(test.updateErrs),
h.t.Fatalf("malformed test case, num updates " + "malformed test case, num updates should match num "+
"should match num errors") "errors")
}
// Send any updates provided in the test. // Send any updates provided in the test.
for i, update := range test.updates { for i, update := range test.updates {
@@ -430,10 +382,7 @@ func runStateUpdateTest(test stateUpdateTest) func(*towerDBHarness) {
expSession.ClientLastApplied = update.LastApplied expSession.ClientLastApplied = update.LastApplied
match := h.hasUpdate(update.Hint) match := h.hasUpdate(update.Hint)
if !reflect.DeepEqual(match.SessionInfo, expSession) { require.Equal(h.t, expSession, match.SessionInfo)
h.t.Fatalf("expected session: %v, got: %v",
expSession, match.SessionInfo)
}
} }
} }
} }
@@ -640,14 +589,10 @@ func TestTowerDB(t *testing.T) {
bdb, err := wtdb.NewBoltBackendCreator( bdb, err := wtdb.NewBoltBackendCreator(
true, path, "watchtower.db", true, path, "watchtower.db",
)(dbCfg) )(dbCfg)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to open db: %v", err)
}
db, err := wtdb.OpenTowerDB(bdb) db, err := wtdb.OpenTowerDB(bdb)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to open db: %v", err)
}
t.Cleanup(func() { t.Cleanup(func() {
db.Close() db.Close()
@@ -664,14 +609,10 @@ func TestTowerDB(t *testing.T) {
bdb, err := wtdb.NewBoltBackendCreator( bdb, err := wtdb.NewBoltBackendCreator(
true, path, "watchtower.db", true, path, "watchtower.db",
)(dbCfg) )(dbCfg)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to open db: %v", err)
}
db, err := wtdb.OpenTowerDB(bdb) db, err := wtdb.OpenTowerDB(bdb)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to open db: %v", err)
}
db.Close() db.Close()
// Open the db again, ensuring we test a // Open the db again, ensuring we test a
@@ -680,14 +621,10 @@ func TestTowerDB(t *testing.T) {
bdb, err = wtdb.NewBoltBackendCreator( bdb, err = wtdb.NewBoltBackendCreator(
true, path, "watchtower.db", true, path, "watchtower.db",
)(dbCfg) )(dbCfg)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to open db: %v", err)
}
db, err = wtdb.OpenTowerDB(bdb) db, err = wtdb.OpenTowerDB(bdb)
if err != nil { require.NoError(t, err)
t.Fatalf("unable to open db: %v", err)
}
t.Cleanup(func() { t.Cleanup(func() {
db.Close() db.Close()