From c70e39cd21d8a118a04c5b11e6686de61258d818 Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Sat, 27 Aug 2022 15:04:55 +0800 Subject: [PATCH] multi: replace defer cleanup with `t.Cleanup` Signed-off-by: Eng Zer Jun --- channeldb/channel_test.go | 27 +- channeldb/db.go | 21 +- channeldb/db_test.go | 25 +- channeldb/forwarding_log_test.go | 12 +- channeldb/invoice_test.go | 60 +-- channeldb/meta_test.go | 20 +- channeldb/nodes_test.go | 6 +- channeldb/payment_control_test.go | 36 +- channeldb/payments_test.go | 7 +- channeldb/peers_test.go | 3 +- channeldb/reports_test.go | 9 +- channeldb/revocation_log_test.go | 12 +- channeldb/waitingproof_test.go | 3 +- channeldb/witness_cache_test.go | 12 +- contractcourt/breacharbiter_test.go | 105 +++-- contractcourt/chain_arbitrator_test.go | 34 +- contractcourt/chain_watcher_test.go | 20 +- contractcourt/channel_arbitrator_test.go | 45 +- contractcourt/commit_sweep_resolver_test.go | 4 +- contractcourt/htlc_incoming_resolver_test.go | 18 +- .../htlc_outgoing_contest_resolver_test.go | 4 +- contractcourt/htlc_success_resolver_test.go | 4 +- contractcourt/htlc_timeout_resolver_test.go | 2 +- contractcourt/nursery_store_test.go | 9 +- contractcourt/utils_test.go | 2 +- contractcourt/utxonursery_test.go | 6 +- lnwallet/channel_test.go | 400 +++++++----------- lnwallet/test_utils.go | 86 ++-- sweep/store_test.go | 7 +- 29 files changed, 393 insertions(+), 606 deletions(-) diff --git a/channeldb/channel_test.go b/channeldb/channel_test.go index eb7cff6f3..01145489c 100644 --- a/channeldb/channel_test.go +++ b/channeldb/channel_test.go @@ -346,9 +346,8 @@ func createTestChannelState(t *testing.T, cdb *ChannelStateDB) *OpenChannel { func TestOpenChannelPutGetDelete(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -487,11 +486,10 @@ func TestOptionalShutdown(t *testing.T) { test := test t.Run(test.name, func(t *testing.T) { - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) if err != nil { t.Fatalf("unable to make test database: %v", err) } - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -572,9 +570,8 @@ func assertRevocationLogEntryEqual(t *testing.T, c *ChannelCommitment, func TestChannelStateTransition(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -889,9 +886,8 @@ func TestChannelStateTransition(t *testing.T) { func TestFetchPendingChannels(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -960,9 +956,8 @@ func TestFetchPendingChannels(t *testing.T) { func TestFetchClosedChannels(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -1041,9 +1036,8 @@ func TestFetchWaitingCloseChannels(t *testing.T) { // We'll start by creating two channels within our test database. One of // them will have their funding transaction confirmed on-chain, while // the other one will remain unconfirmed. - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -1154,9 +1148,8 @@ func TestFetchWaitingCloseChannels(t *testing.T) { func TestRefresh(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -1298,12 +1291,11 @@ func TestCloseInitiator(t *testing.T) { t.Run(test.name, func(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) if err != nil { t.Fatalf("unable to make test database: %v", err) } - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -1345,12 +1337,11 @@ func TestCloseInitiator(t *testing.T) { // TestCloseChannelStatus tests setting of a channel status on the historical // channel on channel close. func TestCloseChannelStatus(t *testing.T) { - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) if err != nil { t.Fatalf("unable to make test database: %v", err) } - defer cleanUp() cdb := fullDB.ChannelStateDB() diff --git a/channeldb/db.go b/channeldb/db.go index 8fa236caf..f74745c23 100644 --- a/channeldb/db.go +++ b/channeldb/db.go @@ -4,9 +4,9 @@ import ( "bytes" "encoding/binary" "fmt" - "io/ioutil" "net" "os" + "testing" "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/wire" @@ -1655,33 +1655,28 @@ func (c *ChannelStateDB) FetchHistoricalChannel(outPoint *wire.OutPoint) ( // MakeTestDB creates a new instance of the ChannelDB for testing purposes. // A callback which cleans up the created temporary directories is also // returned and intended to be executed after the test completes. -func MakeTestDB(modifiers ...OptionModifier) (*DB, func(), error) { +func MakeTestDB(t *testing.T, modifiers ...OptionModifier) (*DB, error) { // First, create a temporary directory to be used for the duration of // this test. - tempDirName, err := ioutil.TempDir("", "channeldb") - if err != nil { - return nil, nil, err - } + tempDirName := t.TempDir() // Next, create channeldb for the first time. backend, backendCleanup, err := kvdb.GetTestBackend(tempDirName, "cdb") if err != nil { backendCleanup() - return nil, nil, err + return nil, err } cdb, err := CreateWithBackend(backend, modifiers...) if err != nil { backendCleanup() - os.RemoveAll(tempDirName) - return nil, nil, err + return nil, err } - cleanUp := func() { + t.Cleanup(func() { cdb.Close() backendCleanup() - os.RemoveAll(tempDirName) - } + }) - return cdb, cleanUp, nil + return cdb, nil } diff --git a/channeldb/db_test.go b/channeldb/db_test.go index adf95d79f..72a5cb4bd 100644 --- a/channeldb/db_test.go +++ b/channeldb/db_test.go @@ -36,7 +36,7 @@ func TestOpenWithCreate(t *testing.T) { dbPath := filepath.Join(tempDirName, "cdb") backend, cleanup, err := kvdb.GetTestBackend(dbPath, "cdb") require.NoError(t, err, "unable to get test db backend") - defer cleanup() + t.Cleanup(cleanup) cdb, err := CreateWithBackend(backend) require.NoError(t, err, "unable to create channeldb") @@ -72,7 +72,7 @@ func TestWipe(t *testing.T) { dbPath := filepath.Join(tempDirName, "cdb") backend, cleanup, err := kvdb.GetTestBackend(dbPath, "cdb") require.NoError(t, err, "unable to get test db backend") - defer cleanup() + t.Cleanup(cleanup) fullDB, err := CreateWithBackend(backend) require.NoError(t, err, "unable to create channeldb") @@ -101,9 +101,8 @@ func TestFetchClosedChannelForID(t *testing.T) { const numChans = 101 - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -172,9 +171,8 @@ func TestFetchClosedChannelForID(t *testing.T) { func TestAddrsForNode(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() graph := fullDB.ChannelGraph() @@ -226,9 +224,8 @@ func TestAddrsForNode(t *testing.T) { func TestFetchChannel(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -324,9 +321,8 @@ func genRandomChannelShell() (*ChannelShell, error) { func TestRestoreChannelShells(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -414,9 +410,8 @@ func TestRestoreChannelShells(t *testing.T) { func TestAbandonChannel(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -581,12 +576,11 @@ func TestFetchChannels(t *testing.T) { t.Run(test.name, func(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) if err != nil { t.Fatalf("unable to make test "+ "database: %v", err) } - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -652,9 +646,8 @@ func TestFetchChannels(t *testing.T) { // TestFetchHistoricalChannel tests lookup of historical channels. func TestFetchHistoricalChannel(t *testing.T) { - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() cdb := fullDB.ChannelStateDB() diff --git a/channeldb/forwarding_log_test.go b/channeldb/forwarding_log_test.go index db55b8438..7ac2dfbc5 100644 --- a/channeldb/forwarding_log_test.go +++ b/channeldb/forwarding_log_test.go @@ -20,9 +20,8 @@ func TestForwardingLogBasicStorageAndQuery(t *testing.T) { // First, we'll set up a test database, and use that to instantiate the // forwarding event log that we'll be using for the duration of the // test. - db, cleanUp, err := MakeTestDB() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to make test db") - defer cleanUp() log := ForwardingLog{ db: db, @@ -89,9 +88,8 @@ func TestForwardingLogQueryOptions(t *testing.T) { // First, we'll set up a test database, and use that to instantiate the // forwarding event log that we'll be using for the duration of the // test. - db, cleanUp, err := MakeTestDB() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to make test db") - defer cleanUp() log := ForwardingLog{ db: db, @@ -189,9 +187,8 @@ func TestForwardingLogQueryLimit(t *testing.T) { // First, we'll set up a test database, and use that to instantiate the // forwarding event log that we'll be using for the duration of the // test. - db, cleanUp, err := MakeTestDB() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to make test db") - defer cleanUp() log := ForwardingLog{ db: db, @@ -301,9 +298,8 @@ func TestForwardingLogStoreEvent(t *testing.T) { // First, we'll set up a test database, and use that to instantiate the // forwarding event log that we'll be using for the duration of the // test. - db, cleanUp, err := MakeTestDB() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to make test db") - defer cleanUp() log := ForwardingLog{ db: db, diff --git a/channeldb/invoice_test.go b/channeldb/invoice_test.go index cade00203..59faf329c 100644 --- a/channeldb/invoice_test.go +++ b/channeldb/invoice_test.go @@ -149,8 +149,7 @@ func TestInvoiceWorkflow(t *testing.T) { } func testInvoiceWorkflow(t *testing.T, test invWorkflowTest) { - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to make test db") // Create a fake invoice which we'll use several times in the tests @@ -293,8 +292,7 @@ func testInvoiceWorkflow(t *testing.T, test invWorkflowTest) { // TestAddDuplicatePayAddr asserts that the payment addresses of inserted // invoices are unique. func TestAddDuplicatePayAddr(t *testing.T) { - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) require.NoError(t, err) // Create two invoices with the same payment addr. @@ -320,8 +318,7 @@ func TestAddDuplicatePayAddr(t *testing.T) { // addresses to be inserted if they are blank to support JIT legacy keysend // invoices. func TestAddDuplicateKeysendPayAddr(t *testing.T) { - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) require.NoError(t, err) // Create two invoices with the same _blank_ payment addr. @@ -363,8 +360,7 @@ func TestAddDuplicateKeysendPayAddr(t *testing.T) { // ensures that the HTLC's payment hash always matches the payment hash in the // returned invoice. func TestFailInvoiceLookupMPPPayAddrOnly(t *testing.T) { - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) require.NoError(t, err) // Create and insert a random invoice. @@ -391,8 +387,7 @@ func TestFailInvoiceLookupMPPPayAddrOnly(t *testing.T) { // TestInvRefEquivocation asserts that retrieving or updating an invoice using // an equivocating InvoiceRef results in ErrInvRefEquivocation. func TestInvRefEquivocation(t *testing.T) { - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) require.NoError(t, err) // Add two random invoices. @@ -431,8 +426,7 @@ func TestInvRefEquivocation(t *testing.T) { func TestInvoiceCancelSingleHtlc(t *testing.T) { t.Parallel() - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to make test db") preimage := lntypes.Preimage{1} @@ -499,8 +493,7 @@ func TestInvoiceCancelSingleHtlc(t *testing.T) { func TestInvoiceCancelSingleHtlcAMP(t *testing.T) { t.Parallel() - db, cleanUp, err := MakeTestDB(OptionClock(testClock)) - defer cleanUp() + db, err := MakeTestDB(t, OptionClock(testClock)) require.NoError(t, err, "unable to make test db: %v", err) // We'll start out by creating an invoice and writing it to the DB. @@ -656,8 +649,7 @@ func TestInvoiceCancelSingleHtlcAMP(t *testing.T) { func TestInvoiceAddTimeSeries(t *testing.T) { t.Parallel() - db, cleanUp, err := MakeTestDB(OptionClock(testClock)) - defer cleanUp() + db, err := MakeTestDB(t, OptionClock(testClock)) require.NoError(t, err, "unable to make test db") _, err = db.InvoicesAddedSince(0) @@ -812,8 +804,7 @@ func TestSettleIndexAmpPayments(t *testing.T) { t.Parallel() testClock := clock.NewTestClock(testNow) - db, cleanUp, err := MakeTestDB(OptionClock(testClock)) - defer cleanUp() + db, err := MakeTestDB(t, OptionClock(testClock)) require.Nil(t, err) // First, we'll make a sample invoice that'll be paid to several times @@ -969,8 +960,7 @@ func TestSettleIndexAmpPayments(t *testing.T) { func TestScanInvoices(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() - defer cleanup() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to make test db") var invoices map[lntypes.Hash]*Invoice @@ -1028,8 +1018,7 @@ func TestScanInvoices(t *testing.T) { func TestDuplicateSettleInvoice(t *testing.T) { t.Parallel() - db, cleanUp, err := MakeTestDB(OptionClock(testClock)) - defer cleanUp() + db, err := MakeTestDB(t, OptionClock(testClock)) require.NoError(t, err, "unable to make test db") // We'll start out by creating an invoice and writing it to the DB. @@ -1087,8 +1076,7 @@ func TestDuplicateSettleInvoice(t *testing.T) { func TestQueryInvoices(t *testing.T) { t.Parallel() - db, cleanUp, err := MakeTestDB(OptionClock(testClock)) - defer cleanUp() + db, err := MakeTestDB(t, OptionClock(testClock)) require.NoError(t, err, "unable to make test db") // To begin the test, we'll add 50 invoices to the database. We'll @@ -1400,8 +1388,7 @@ func getUpdateInvoice(amt lnwire.MilliSatoshi) InvoiceUpdateCallback { func TestCustomRecords(t *testing.T) { t.Parallel() - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to make test db") preimage := lntypes.Preimage{1} @@ -1470,8 +1457,7 @@ func TestInvoiceHtlcAMPFields(t *testing.T) { } func testInvoiceHtlcAMPFields(t *testing.T, isAMP bool) { - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) require.Nil(t, err) testInvoice, err := randInvoice(1000) @@ -1652,8 +1638,7 @@ func TestHTLCSet(t *testing.T) { // TestAddInvoiceWithHTLCs asserts that you can't insert an invoice that already // has HTLCs. func TestAddInvoiceWithHTLCs(t *testing.T) { - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) require.Nil(t, err) testInvoice, err := randInvoice(1000) @@ -1672,8 +1657,7 @@ func TestAddInvoiceWithHTLCs(t *testing.T) { // that invoices with duplicate set ids are disallowed. func TestSetIDIndex(t *testing.T) { testClock := clock.NewTestClock(testNow) - db, cleanUp, err := MakeTestDB(OptionClock(testClock)) - defer cleanUp() + db, err := MakeTestDB(t, OptionClock(testClock)) require.Nil(t, err) // We'll start out by creating an invoice and writing it to the DB. @@ -1983,8 +1967,7 @@ func getUpdateInvoiceAMPSettle(setID *[32]byte, func TestUnexpectedInvoicePreimage(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() - defer cleanup() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to make test db") invoice, err := randInvoice(lnwire.MilliSatoshi(100)) @@ -2040,8 +2023,7 @@ func TestUpdateHTLCPreimages(t *testing.T) { } func testUpdateHTLCPreimages(t *testing.T, test updateHTLCPreimageTestCase) { - db, cleanup, err := MakeTestDB() - defer cleanup() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to make test db") // We'll start out by creating an invoice and writing it to the DB. @@ -2772,8 +2754,7 @@ func testUpdateHTLC(t *testing.T, test updateHTLCTest) { func TestDeleteInvoices(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() - defer cleanup() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to make test db") // Add some invoices to the test db. @@ -2856,9 +2837,8 @@ func TestDeleteInvoices(t *testing.T) { func TestAddInvoiceInvalidFeatureDeps(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to make test db") - defer cleanup() invoice, err := randInvoice(500) require.NoError(t, err) diff --git a/channeldb/meta_test.go b/channeldb/meta_test.go index 574744ba6..211429e35 100644 --- a/channeldb/meta_test.go +++ b/channeldb/meta_test.go @@ -15,8 +15,7 @@ import ( func applyMigration(t *testing.T, beforeMigration, afterMigration func(d *DB), migrationFunc migration, shouldFail bool, dryRun bool) { - cdb, cleanUp, err := MakeTestDB() - defer cleanUp() + cdb, err := MakeTestDB(t) if err != nil { t.Fatal(err) } @@ -86,8 +85,7 @@ func applyMigration(t *testing.T, beforeMigration, afterMigration func(d *DB), func TestVersionFetchPut(t *testing.T) { t.Parallel() - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) if err != nil { t.Fatal(err) } @@ -450,7 +448,7 @@ func TestMigrationReversion(t *testing.T) { backend, cleanup, err = kvdb.GetTestBackend(tempDirName, "cdb") require.NoError(t, err, "unable to get test db backend") - defer cleanup() + t.Cleanup(cleanup) _, err = CreateWithBackend(backend) if err != ErrDBReversion { @@ -498,8 +496,7 @@ func TestMigrationDryRun(t *testing.T) { func TestOptionalMeta(t *testing.T) { t.Parallel() - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) require.NoError(t, err) // Test read an empty optional meta. @@ -527,8 +524,7 @@ func TestOptionalMeta(t *testing.T) { func TestApplyOptionalVersions(t *testing.T) { t.Parallel() - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) require.NoError(t, err) // Overwrite the migration function so we can count how many times the @@ -581,8 +577,7 @@ func TestApplyOptionalVersions(t *testing.T) { func TestFetchMeta(t *testing.T) { t.Parallel() - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) require.NoError(t, err) meta := &Meta{} @@ -601,8 +596,7 @@ func TestFetchMeta(t *testing.T) { func TestMarkerAndTombstone(t *testing.T) { t.Parallel() - db, cleanUp, err := MakeTestDB() - defer cleanUp() + db, err := MakeTestDB(t) require.NoError(t, err) // Test that a generic marker is not present in a fresh DB. diff --git a/channeldb/nodes_test.go b/channeldb/nodes_test.go index 030cfb70f..b54cf0045 100644 --- a/channeldb/nodes_test.go +++ b/channeldb/nodes_test.go @@ -14,9 +14,8 @@ import ( func TestLinkNodeEncodeDecode(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() cdb := fullDB.ChannelStateDB() @@ -103,9 +102,8 @@ func TestLinkNodeEncodeDecode(t *testing.T) { func TestDeleteLinkNode(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() cdb := fullDB.ChannelStateDB() diff --git a/channeldb/payment_control_test.go b/channeldb/payment_control_test.go index 451f99a83..bcd4a834a 100644 --- a/channeldb/payment_control_test.go +++ b/channeldb/payment_control_test.go @@ -54,8 +54,7 @@ func genInfo() (*PaymentCreationInfo, *HTLCAttemptInfo, func TestPaymentControlSwitchFail(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() - defer cleanup() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to init db") pControl := NewPaymentControl(db) @@ -185,9 +184,7 @@ func TestPaymentControlSwitchFail(t *testing.T) { func TestPaymentControlSwitchDoubleSend(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() - defer cleanup() - + db, err := MakeTestDB(t) require.NoError(t, err, "unable to init db") pControl := NewPaymentControl(db) @@ -258,9 +255,7 @@ func TestPaymentControlSwitchDoubleSend(t *testing.T) { func TestPaymentControlSuccessesWithoutInFlight(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() - defer cleanup() - + db, err := MakeTestDB(t) require.NoError(t, err, "unable to init db") pControl := NewPaymentControl(db) @@ -287,9 +282,7 @@ func TestPaymentControlSuccessesWithoutInFlight(t *testing.T) { func TestPaymentControlFailsWithoutInFlight(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() - defer cleanup() - + db, err := MakeTestDB(t) require.NoError(t, err, "unable to init db") pControl := NewPaymentControl(db) @@ -311,9 +304,7 @@ func TestPaymentControlFailsWithoutInFlight(t *testing.T) { func TestPaymentControlDeleteNonInFlight(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() - defer cleanup() - + db, err := MakeTestDB(t) require.NoError(t, err, "unable to init db") // Create a sequence number for duplicate payments that will not collide @@ -520,8 +511,7 @@ func TestPaymentControlDeleteNonInFlight(t *testing.T) { func TestPaymentControlDeletePayments(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() - defer cleanup() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to init db") pControl := NewPaymentControl(db) @@ -574,8 +564,7 @@ func TestPaymentControlDeletePayments(t *testing.T) { func TestPaymentControlDeleteSinglePayment(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() - defer cleanup() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to init db") pControl := NewPaymentControl(db) @@ -678,9 +667,7 @@ func TestPaymentControlMultiShard(t *testing.T) { } runSubTest := func(t *testing.T, test testCase) { - db, cleanup, err := MakeTestDB() - defer cleanup() - + db, err := MakeTestDB(t) if err != nil { t.Fatalf("unable to init db: %v", err) } @@ -924,9 +911,7 @@ func TestPaymentControlMultiShard(t *testing.T) { func TestPaymentControlMPPRecordValidation(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() - defer cleanup() - + db, err := MakeTestDB(t) require.NoError(t, err, "unable to init db") pControl := NewPaymentControl(db) @@ -1017,8 +1002,7 @@ func TestDeleteFailedAttempts(t *testing.T) { } func testDeleteFailedAttempts(t *testing.T, keepFailedPaymentAttempts bool) { - db, cleanup, err := MakeTestDB() - defer cleanup() + db, err := MakeTestDB(t) require.NoError(t, err, "unable to init db") db.keepFailedPaymentAttempts = keepFailedPaymentAttempts diff --git a/channeldb/payments_test.go b/channeldb/payments_test.go index a2102bf3f..f10d5ef46 100644 --- a/channeldb/payments_test.go +++ b/channeldb/payments_test.go @@ -398,11 +398,10 @@ func TestQueryPayments(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() + db, err := MakeTestDB(t) if err != nil { t.Fatalf("unable to init db: %v", err) } - defer cleanup() // Make a preliminary query to make sure it's ok to // query when we have no payments. @@ -514,11 +513,9 @@ func TestQueryPayments(t *testing.T) { // case where a specific duplicate is not found and the duplicates bucket is not // present when we expect it to be. func TestFetchPaymentWithSequenceNumber(t *testing.T) { - db, cleanup, err := MakeTestDB() + db, err := MakeTestDB(t) require.NoError(t, err) - defer cleanup() - pControl := NewPaymentControl(db) // Generate a test payment which does not have duplicates. diff --git a/channeldb/peers_test.go b/channeldb/peers_test.go index b702c18df..9d32e50b4 100644 --- a/channeldb/peers_test.go +++ b/channeldb/peers_test.go @@ -10,9 +10,8 @@ import ( // TestFlapCount tests lookup and writing of flap count to disk. func TestFlapCount(t *testing.T) { - db, cleanup, err := MakeTestDB() + db, err := MakeTestDB(t) require.NoError(t, err) - defer cleanup() // Try to read flap count for a peer that we have no records for. _, err = db.ReadFlapCount(testPub) diff --git a/channeldb/reports_test.go b/channeldb/reports_test.go index 46bc39074..48a41914f 100644 --- a/channeldb/reports_test.go +++ b/channeldb/reports_test.go @@ -48,9 +48,8 @@ func TestPersistReport(t *testing.T) { test := test t.Run(test.name, func(t *testing.T) { - db, cleanup, err := MakeTestDB() + db, err := MakeTestDB(t) require.NoError(t, err) - defer cleanup() channelOutpoint := testChanPoint1 @@ -85,9 +84,8 @@ func TestPersistReport(t *testing.T) { // channel, testing that the appropriate error is returned based on the state // of the existing bucket. func TestFetchChannelReadBucket(t *testing.T) { - db, cleanup, err := MakeTestDB() + db, err := MakeTestDB(t) require.NoError(t, err) - defer cleanup() channelOutpoint := testChanPoint1 @@ -197,9 +195,8 @@ func TestFetchChannelWriteBucket(t *testing.T) { test := test t.Run(test.name, func(t *testing.T) { - db, cleanup, err := MakeTestDB() + db, err := MakeTestDB(t) require.NoError(t, err) - defer cleanup() // Update our db to the starting state we expect. err = kvdb.Update(db, test.setup, func() {}) diff --git a/channeldb/revocation_log_test.go b/channeldb/revocation_log_test.go index e20995733..405955f46 100644 --- a/channeldb/revocation_log_test.go +++ b/channeldb/revocation_log_test.go @@ -291,9 +291,8 @@ func TestDerializeRevocationLog(t *testing.T) { func TestFetchLogBucket(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err) - defer cleanUp() backend := fullDB.ChannelStateDB().backend @@ -326,9 +325,8 @@ func TestFetchLogBucket(t *testing.T) { func TestDeleteLogBucket(t *testing.T) { t.Parallel() - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err) - defer cleanUp() backend := fullDB.ChannelStateDB().backend @@ -423,9 +421,8 @@ func TestPutRevocationLog(t *testing.T) { for _, tc := range testCases { tc := tc - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err) - defer cleanUp() backend := fullDB.ChannelStateDB().backend @@ -523,9 +520,8 @@ func TestFetchRevocationLogCompatible(t *testing.T) { for _, tc := range testCases { tc := tc - fullDB, cleanUp, err := MakeTestDB() + fullDB, err := MakeTestDB(t) require.NoError(t, err) - defer cleanUp() backend := fullDB.ChannelStateDB().backend diff --git a/channeldb/waitingproof_test.go b/channeldb/waitingproof_test.go index 7432fbf61..1a00c829e 100644 --- a/channeldb/waitingproof_test.go +++ b/channeldb/waitingproof_test.go @@ -15,9 +15,8 @@ import ( func TestWaitingProofStore(t *testing.T) { t.Parallel() - db, cleanup, err := MakeTestDB() + db, err := MakeTestDB(t) require.NoError(t, err, "failed to make test database") - defer cleanup() proof1 := NewWaitingProof(true, &lnwire.AnnounceSignatures{ NodeSignature: wireSig, diff --git a/channeldb/witness_cache_test.go b/channeldb/witness_cache_test.go index c756bd3c9..861084499 100644 --- a/channeldb/witness_cache_test.go +++ b/channeldb/witness_cache_test.go @@ -13,9 +13,8 @@ import ( func TestWitnessCacheSha256Retrieval(t *testing.T) { t.Parallel() - cdb, cleanUp, err := MakeTestDB() + cdb, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() wCache := cdb.NewWitnessCache() @@ -54,9 +53,8 @@ func TestWitnessCacheSha256Retrieval(t *testing.T) { func TestWitnessCacheSha256Deletion(t *testing.T) { t.Parallel() - cdb, cleanUp, err := MakeTestDB() + cdb, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() wCache := cdb.NewWitnessCache() @@ -101,9 +99,8 @@ func TestWitnessCacheSha256Deletion(t *testing.T) { func TestWitnessCacheUnknownWitness(t *testing.T) { t.Parallel() - cdb, cleanUp, err := MakeTestDB() + cdb, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() wCache := cdb.NewWitnessCache() @@ -118,9 +115,8 @@ func TestWitnessCacheUnknownWitness(t *testing.T) { // TestAddSha256Witnesses tests that insertion using AddSha256Witnesses behaves // identically to the insertion via the generalized interface. func TestAddSha256Witnesses(t *testing.T) { - cdb, cleanUp, err := MakeTestDB() + cdb, err := MakeTestDB(t) require.NoError(t, err, "unable to make test database") - defer cleanUp() wCache := cdb.NewWitnessCache() diff --git a/contractcourt/breacharbiter_test.go b/contractcourt/breacharbiter_test.go index f50669cd4..e9d274f41 100644 --- a/contractcourt/breacharbiter_test.go +++ b/contractcourt/breacharbiter_test.go @@ -956,18 +956,18 @@ restartCheck: func initBreachedState(t *testing.T) (*BreachArbiter, *lnwallet.LightningChannel, *lnwallet.LightningChannel, - *lnwallet.LocalForceCloseSummary, chan *ContractBreachEvent, - func(), func()) { + *lnwallet.LocalForceCloseSummary, chan *ContractBreachEvent) { + // Create a pair of channels using a notifier that allows us to signal // a spend of the funding transaction. Alice's channel will be the on // observing a breach. - alice, bob, cleanUpChans, err := createInitChannels(t, 1) + alice, bob, err := createInitChannels(t, 1) require.NoError(t, err, "unable to create test channels") // Instantiate a breach arbiter to handle the breach of alice's channel. contractBreaches := make(chan *ContractBreachEvent) - brar, cleanUpArb, err := createTestArbiter( + brar, err := createTestArbiter( t, contractBreaches, alice.State().Db.GetParentDB(), ) require.NoError(t, err, "unable to initialize test breach arbiter") @@ -1003,8 +1003,7 @@ func initBreachedState(t *testing.T) (*BreachArbiter, t.Fatalf("Can't update the channel state: %v", err) } - return brar, alice, bob, bobClose, contractBreaches, cleanUpChans, - cleanUpArb + return brar, alice, bob, bobClose, contractBreaches } // TestBreachHandoffSuccess tests that a channel's close observer properly @@ -1012,10 +1011,7 @@ func initBreachedState(t *testing.T) (*BreachArbiter, // breach close. This test verifies correctness in the event that the handoff // experiences no interruptions. func TestBreachHandoffSuccess(t *testing.T) { - brar, alice, _, bobClose, contractBreaches, - cleanUpChans, cleanUpArb := initBreachedState(t) - defer cleanUpChans() - defer cleanUpArb() + brar, alice, _, bobClose, contractBreaches := initBreachedState(t) chanPoint := alice.ChanPoint @@ -1093,10 +1089,7 @@ func TestBreachHandoffSuccess(t *testing.T) { // arbiter fails to write the information to disk, and that a subsequent attempt // at the handoff succeeds. func TestBreachHandoffFail(t *testing.T) { - brar, alice, _, bobClose, contractBreaches, - cleanUpChans, cleanUpArb := initBreachedState(t) - defer cleanUpChans() - defer cleanUpArb() + brar, alice, _, bobClose, contractBreaches := initBreachedState(t) // Before alerting Alice of the breach, instruct our failing retribution // store to fail the next database operation, which we expect to write @@ -1140,11 +1133,10 @@ func TestBreachHandoffFail(t *testing.T) { assertNoArbiterBreach(t, brar, chanPoint) assertNotPendingClosed(t, alice) - brar, cleanUpArb, err := createTestArbiter( + brar, err := createTestArbiter( t, contractBreaches, alice.State().Db.GetParentDB(), ) require.NoError(t, err, "unable to initialize test breach arbiter") - defer cleanUpArb() // Signal a spend of the funding transaction and wait for the close // observer to exit. This time we are allowing the handoff to succeed. @@ -1183,9 +1175,7 @@ func TestBreachHandoffFail(t *testing.T) { // TestBreachCreateJusticeTx tests that we create three different variants of // the justice tx. func TestBreachCreateJusticeTx(t *testing.T) { - brar, _, _, _, _, cleanUpChans, cleanUpArb := initBreachedState(t) - defer cleanUpChans() - defer cleanUpArb() + brar, _, _, _, _ := initBreachedState(t) // In this test we just want to check that the correct inputs are added // to the justice tx, not that we create a valid spend, so we just set @@ -1564,10 +1554,7 @@ func TestBreachSpends(t *testing.T) { } func testBreachSpends(t *testing.T, test breachTest) { - brar, alice, _, bobClose, contractBreaches, - cleanUpChans, cleanUpArb := initBreachedState(t) - defer cleanUpChans() - defer cleanUpArb() + brar, alice, _, bobClose, contractBreaches := initBreachedState(t) var ( height = bobClose.ChanSnapshot.CommitHeight @@ -1783,10 +1770,7 @@ func testBreachSpends(t *testing.T, test breachTest) { // "split" the justice tx in case the first justice tx doesn't confirm within // a reasonable time. func TestBreachDelayedJusticeConfirmation(t *testing.T) { - brar, alice, _, bobClose, contractBreaches, - cleanUpChans, cleanUpArb := initBreachedState(t) - defer cleanUpChans() - defer cleanUpArb() + brar, alice, _, bobClose, contractBreaches := initBreachedState(t) var ( height = bobClose.ChanSnapshot.CommitHeight @@ -2123,7 +2107,7 @@ func assertNotPendingClosed(t *testing.T, c *lnwallet.LightningChannel) { // createTestArbiter instantiates a breach arbiter with a failing retribution // store, so that controlled failures can be tested. func createTestArbiter(t *testing.T, contractBreaches chan *ContractBreachEvent, - db *channeldb.DB) (*BreachArbiter, func(), error) { + db *channeldb.DB) (*BreachArbiter, error) { // Create a failing retribution store, that wraps a normal one. store := newFailingRetributionStore(func() RetributionStorer { @@ -2148,21 +2132,21 @@ func createTestArbiter(t *testing.T, contractBreaches chan *ContractBreachEvent, }) if err := ba.Start(); err != nil { - return nil, nil, err + return nil, err } + t.Cleanup(func() { + require.NoError(t, ba.Stop()) + }) - // The caller is responsible for closing the database. - cleanUp := func() { - ba.Stop() - } - - return ba, cleanUp, nil + return ba, nil } // createInitChannels creates two initialized test channels funded with 10 BTC, // with 5 BTC allocated to each side. Within the channel, Alice is the // initiator. -func createInitChannels(t *testing.T, revocationWindow int) (*lnwallet.LightningChannel, *lnwallet.LightningChannel, func(), error) { +func createInitChannels(t *testing.T, revocationWindow int) ( + *lnwallet.LightningChannel, *lnwallet.LightningChannel, error) { + aliceKeyPriv, aliceKeyPub := btcec.PrivKeyFromBytes( channels.AlicesPrivKey, ) @@ -2172,7 +2156,7 @@ func createInitChannels(t *testing.T, revocationWindow int) (*lnwallet.Lightning channelCapacity, err := btcutil.NewAmount(10) if err != nil { - return nil, nil, nil, err + return nil, nil, err } channelBal := channelCapacity / 2 @@ -2240,23 +2224,23 @@ func createInitChannels(t *testing.T, revocationWindow int) (*lnwallet.Lightning bobRoot, err := chainhash.NewHash(bobKeyPriv.Serialize()) if err != nil { - return nil, nil, nil, err + return nil, nil, err } bobPreimageProducer := shachain.NewRevocationProducer(*bobRoot) bobFirstRevoke, err := bobPreimageProducer.AtIndex(0) if err != nil { - return nil, nil, nil, err + return nil, nil, err } bobCommitPoint := input.ComputeCommitmentPoint(bobFirstRevoke[:]) aliceRoot, err := chainhash.NewHash(aliceKeyPriv.Serialize()) if err != nil { - return nil, nil, nil, err + return nil, nil, err } alicePreimageProducer := shachain.NewRevocationProducer(*aliceRoot) aliceFirstRevoke, err := alicePreimageProducer.AtIndex(0) if err != nil { - return nil, nil, nil, err + return nil, nil, err } aliceCommitPoint := input.ComputeCommitmentPoint(aliceFirstRevoke[:]) @@ -2266,23 +2250,29 @@ func createInitChannels(t *testing.T, revocationWindow int) (*lnwallet.Lightning false, 0, ) if err != nil { - return nil, nil, nil, err + return nil, nil, err } dbAlice, err := channeldb.Open(t.TempDir()) if err != nil { - return nil, nil, nil, err + return nil, nil, err } + t.Cleanup(func() { + require.NoError(t, dbAlice.Close()) + }) dbBob, err := channeldb.Open(t.TempDir()) if err != nil { - return nil, nil, nil, err + return nil, nil, err } + t.Cleanup(func() { + require.NoError(t, dbBob.Close()) + }) estimator := chainfee.NewStaticEstimator(12500, 0) feePerKw, err := estimator.EstimateFeePerKW(1) if err != nil { - return nil, nil, nil, err + return nil, nil, err } commitFee := feePerKw.FeeForWeight(input.CommitWeight) @@ -2309,7 +2299,7 @@ func createInitChannels(t *testing.T, revocationWindow int) (*lnwallet.Lightning var chanIDBytes [8]byte if _, err := io.ReadFull(crand.Reader, chanIDBytes[:]); err != nil { - return nil, nil, nil, err + return nil, nil, err } shortChanID := lnwire.NewShortChanIDFromInt( @@ -2360,25 +2350,31 @@ func createInitChannels(t *testing.T, revocationWindow int) (*lnwallet.Lightning aliceSigner, aliceChannelState, alicePool, ) if err != nil { - return nil, nil, nil, err + return nil, nil, err } alicePool.Start() + t.Cleanup(func() { + require.NoError(t, alicePool.Stop()) + }) bobPool := lnwallet.NewSigPool(1, bobSigner) channelBob, err := lnwallet.NewLightningChannel( bobSigner, bobChannelState, bobPool, ) if err != nil { - return nil, nil, nil, err + return nil, nil, err } bobPool.Start() + t.Cleanup(func() { + require.NoError(t, bobPool.Stop()) + }) addr := &net.TCPAddr{ IP: net.ParseIP("127.0.0.1"), Port: 18556, } if err := channelAlice.State().SyncPending(addr, 101); err != nil { - return nil, nil, nil, err + return nil, nil, err } addr = &net.TCPAddr{ @@ -2386,22 +2382,17 @@ func createInitChannels(t *testing.T, revocationWindow int) (*lnwallet.Lightning Port: 18555, } if err := channelBob.State().SyncPending(addr, 101); err != nil { - return nil, nil, nil, err - } - - cleanUpFunc := func() { - dbBob.Close() - dbAlice.Close() + return nil, nil, err } // Now that the channel are open, simulate the start of a session by // having Alice and Bob extend their revocation windows to each other. err = initRevocationWindows(channelAlice, channelBob, revocationWindow) if err != nil { - return nil, nil, nil, err + return nil, nil, err } - return channelAlice, channelBob, cleanUpFunc, nil + return channelAlice, channelBob, nil } // initRevocationWindows simulates a new channel being opened within the p2p diff --git a/contractcourt/chain_arbitrator_test.go b/contractcourt/chain_arbitrator_test.go index 4b491c8e4..9e90864d7 100644 --- a/contractcourt/chain_arbitrator_test.go +++ b/contractcourt/chain_arbitrator_test.go @@ -24,19 +24,20 @@ func TestChainArbitratorRepublishCloses(t *testing.T) { if err != nil { t.Fatal(err) } - defer db.Close() + t.Cleanup(func() { + require.NoError(t, db.Close()) + }) // Create 10 test channels and sync them to the database. const numChans = 10 var channels []*channeldb.OpenChannel for i := 0; i < numChans; i++ { - lChannel, _, cleanup, err := lnwallet.CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + lChannel, _, err := lnwallet.CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) if err != nil { t.Fatal(err) } - defer cleanup() channel := lChannel.State() @@ -94,11 +95,9 @@ func TestChainArbitratorRepublishCloses(t *testing.T) { if err := chainArb.Start(); err != nil { t.Fatal(err) } - defer func() { - if err := chainArb.Stop(); err != nil { - t.Fatal(err) - } - }() + t.Cleanup(func() { + require.NoError(t, chainArb.Stop()) + }) // Half of the channels should have had their closing tx re-published. if len(published) != numChans/2 { @@ -137,15 +136,16 @@ func TestResolveContract(t *testing.T) { db, err := channeldb.Open(t.TempDir()) require.NoError(t, err, "unable to open db") - defer db.Close() + t.Cleanup(func() { + require.NoError(t, db.Close()) + }) // With the DB created, we'll make a new channel, and mark it as // pending open within the database. - newChannel, _, cleanup, err := lnwallet.CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + newChannel, _, err := lnwallet.CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to make new test channel") - defer cleanup() channel := newChannel.State() channel.Db = db.ChannelStateDB() addr := &net.TCPAddr{ @@ -177,11 +177,9 @@ func TestResolveContract(t *testing.T) { if err := chainArb.Start(); err != nil { t.Fatal(err) } - defer func() { - if err := chainArb.Stop(); err != nil { - t.Fatal(err) - } - }() + t.Cleanup(func() { + require.NoError(t, chainArb.Stop()) + }) channelArb := chainArb.activeChannels[channel.FundingOutpoint] diff --git a/contractcourt/chain_watcher_test.go b/contractcourt/chain_watcher_test.go index 1dc738274..74559dbcf 100644 --- a/contractcourt/chain_watcher_test.go +++ b/contractcourt/chain_watcher_test.go @@ -25,11 +25,10 @@ func TestChainWatcherRemoteUnilateralClose(t *testing.T) { // First, we'll create two channels which already have established a // commitment contract between themselves. - aliceChannel, bobChannel, cleanUp, err := lnwallet.CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := lnwallet.CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // With the channels created, we'll now create a chain watcher instance // which will be watching for any closes of Alice's channel. @@ -110,11 +109,10 @@ func TestChainWatcherRemoteUnilateralClosePendingCommit(t *testing.T) { // First, we'll create two channels which already have established a // commitment contract between themselves. - aliceChannel, bobChannel, cleanUp, err := lnwallet.CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := lnwallet.CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // With the channels created, we'll now create a chain watcher instance // which will be watching for any closes of Alice's channel. @@ -255,13 +253,12 @@ func TestChainWatcherDataLossProtect(t *testing.T) { dlpScenario := func(t *testing.T, testCase dlpTestCase) bool { // First, we'll create two channels which already have // established a commitment contract between themselves. - aliceChannel, bobChannel, cleanUp, err := lnwallet.CreateTestChannels( - channeldb.SingleFunderBit, + aliceChannel, bobChannel, err := lnwallet.CreateTestChannels( + t, channeldb.SingleFunderBit, ) if err != nil { t.Fatalf("unable to create test channels: %v", err) } - defer cleanUp() // Based on the number of random updates for this state, make a // new HTLC to add to the commitment, and then lock in a state @@ -430,13 +427,12 @@ func TestChainWatcherLocalForceCloseDetect(t *testing.T) { // First, we'll create two channels which already have // established a commitment contract between themselves. - aliceChannel, bobChannel, cleanUp, err := lnwallet.CreateTestChannels( - channeldb.SingleFunderBit, + aliceChannel, bobChannel, err := lnwallet.CreateTestChannels( + t, channeldb.SingleFunderBit, ) if err != nil { t.Fatalf("unable to create test channels: %v", err) } - defer cleanUp() // We'll execute a number of state transitions based on the // randomly selected number from testing/quick. We do this to diff --git a/contractcourt/channel_arbitrator_test.go b/contractcourt/channel_arbitrator_test.go index c8f7e6e2b..6b9680e67 100644 --- a/contractcourt/channel_arbitrator_test.go +++ b/contractcourt/channel_arbitrator_test.go @@ -460,11 +460,9 @@ func TestChannelArbitratorCooperativeClose(t *testing.T) { if err := chanArbCtx.chanArb.Start(nil); err != nil { t.Fatalf("unable to start ChannelArbitrator: %v", err) } - defer func() { - if err := chanArbCtx.chanArb.Stop(); err != nil { - t.Fatalf("unable to stop chan arb: %v", err) - } - }() + t.Cleanup(func() { + require.NoError(t, chanArbCtx.chanArb.Stop()) + }) // It should start out in the default state. chanArbCtx.AssertState(StateDefault) @@ -681,11 +679,9 @@ func TestChannelArbitratorBreachClose(t *testing.T) { if err := chanArb.Start(nil); err != nil { t.Fatalf("unable to start ChannelArbitrator: %v", err) } - defer func() { - if err := chanArb.Stop(); err != nil { - t.Fatal(err) - } - }() + t.Cleanup(func() { + require.NoError(t, chanArb.Stop()) + }) // It should start out in the default state. chanArbCtx.AssertState(StateDefault) @@ -1990,11 +1986,9 @@ func TestChannelArbitratorPendingExpiredHTLC(t *testing.T) { if err := chanArb.Start(nil); err != nil { t.Fatalf("unable to start ChannelArbitrator: %v", err) } - defer func() { - if err := chanArb.Stop(); err != nil { - t.Fatalf("unable to stop chan arb: %v", err) - } - }() + t.Cleanup(func() { + require.NoError(t, chanArb.Stop()) + }) // Now that our channel arb has started, we'll set up // its contract signals channel so we can send it @@ -2098,14 +2092,13 @@ func TestRemoteCloseInitiator(t *testing.T) { t.Parallel() // First, create alice's channel. - alice, _, cleanUp, err := lnwallet.CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + alice, _, err := lnwallet.CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) if err != nil { t.Fatalf("unable to create test channels: %v", err) } - defer cleanUp() // Create a mock log which will not block the test's // expected number of transitions transitions, and has @@ -2148,11 +2141,9 @@ func TestRemoteCloseInitiator(t *testing.T) { t.Fatalf("unable to start "+ "ChannelArbitrator: %v", err) } - defer func() { - if err := chanArb.Stop(); err != nil { - t.Fatal(err) - } - }() + t.Cleanup(func() { + require.NoError(t, chanArb.Stop()) + }) // It should start out in the default state. chanArbCtx.AssertState(StateDefault) @@ -2501,11 +2492,9 @@ func TestChannelArbitratorAnchors(t *testing.T) { if err := chanArb.Start(nil); err != nil { t.Fatalf("unable to start ChannelArbitrator: %v", err) } - defer func() { - if err := chanArb.Stop(); err != nil { - t.Fatal(err) - } - }() + t.Cleanup(func() { + require.NoError(t, chanArb.Stop()) + }) signals := &ContractSignals{ ShortChanID: lnwire.ShortChannelID{}, diff --git a/contractcourt/commit_sweep_resolver_test.go b/contractcourt/commit_sweep_resolver_test.go index 17c02dd11..0583ce8ea 100644 --- a/contractcourt/commit_sweep_resolver_test.go +++ b/contractcourt/commit_sweep_resolver_test.go @@ -170,7 +170,7 @@ var _ UtxoSweeper = &mockSweeper{} // unencumbered by a time lock. func TestCommitSweepResolverNoDelay(t *testing.T) { t.Parallel() - defer timeout(t)() + defer timeout()() res := lnwallet.CommitOutputResolution{ SelfOutputSignDesc: input.SignDescriptor{ @@ -227,7 +227,7 @@ func TestCommitSweepResolverNoDelay(t *testing.T) { // that is encumbered by a time lock. sweepErr indicates whether the local node // fails to sweep the output. func testCommitSweepResolverDelay(t *testing.T, sweepErr error) { - defer timeout(t)() + defer timeout()() const sweepProcessInterval = 100 * time.Millisecond amt := int64(100) diff --git a/contractcourt/htlc_incoming_resolver_test.go b/contractcourt/htlc_incoming_resolver_test.go index 2f76a5321..3e78f1a29 100644 --- a/contractcourt/htlc_incoming_resolver_test.go +++ b/contractcourt/htlc_incoming_resolver_test.go @@ -36,7 +36,7 @@ var ( // for which the preimage is already known initially. func TestHtlcIncomingResolverFwdPreimageKnown(t *testing.T) { t.Parallel() - defer timeout(t)() + defer timeout()() ctx := newIncomingResolverTestContext(t, false) ctx.witnessBeacon.lookupPreimage[testResHash] = testResPreimage @@ -49,7 +49,7 @@ func TestHtlcIncomingResolverFwdPreimageKnown(t *testing.T) { // started. func TestHtlcIncomingResolverFwdContestedSuccess(t *testing.T) { t.Parallel() - defer timeout(t)() + defer timeout()() ctx := newIncomingResolverTestContext(t, false) ctx.resolve() @@ -65,7 +65,7 @@ func TestHtlcIncomingResolverFwdContestedSuccess(t *testing.T) { // htlc that times out after the resolver has been started. func TestHtlcIncomingResolverFwdContestedTimeout(t *testing.T) { t.Parallel() - defer timeout(t)() + defer timeout()() ctx := newIncomingResolverTestContext(t, false) @@ -104,7 +104,7 @@ func TestHtlcIncomingResolverFwdContestedTimeout(t *testing.T) { // has already expired when the resolver starts. func TestHtlcIncomingResolverFwdTimeout(t *testing.T) { t.Parallel() - defer timeout(t)() + defer timeout()() ctx := newIncomingResolverTestContext(t, true) ctx.witnessBeacon.lookupPreimage[testResHash] = testResPreimage @@ -117,7 +117,7 @@ func TestHtlcIncomingResolverFwdTimeout(t *testing.T) { // which the invoice has already been settled when the resolver starts. func TestHtlcIncomingResolverExitSettle(t *testing.T) { t.Parallel() - defer timeout(t)() + defer timeout()() ctx := newIncomingResolverTestContext(t, true) ctx.registry.notifyResolution = invoices.NewSettleResolution( @@ -149,7 +149,7 @@ func TestHtlcIncomingResolverExitSettle(t *testing.T) { // an invoice that is already canceled when the resolver starts. func TestHtlcIncomingResolverExitCancel(t *testing.T) { t.Parallel() - defer timeout(t)() + defer timeout()() ctx := newIncomingResolverTestContext(t, true) ctx.registry.notifyResolution = invoices.NewFailResolution( @@ -165,7 +165,7 @@ func TestHtlcIncomingResolverExitCancel(t *testing.T) { // for a hodl invoice that is settled after the resolver has started. func TestHtlcIncomingResolverExitSettleHodl(t *testing.T) { t.Parallel() - defer timeout(t)() + defer timeout()() ctx := newIncomingResolverTestContext(t, true) ctx.resolve() @@ -183,7 +183,7 @@ func TestHtlcIncomingResolverExitSettleHodl(t *testing.T) { // for a hodl invoice that times out. func TestHtlcIncomingResolverExitTimeoutHodl(t *testing.T) { t.Parallel() - defer timeout(t)() + defer timeout()() ctx := newIncomingResolverTestContext(t, true) @@ -220,7 +220,7 @@ func TestHtlcIncomingResolverExitTimeoutHodl(t *testing.T) { // for a hodl invoice that is canceled after the resolver has started. func TestHtlcIncomingResolverExitCancelHodl(t *testing.T) { t.Parallel() - defer timeout(t)() + defer timeout()() ctx := newIncomingResolverTestContext(t, true) diff --git a/contractcourt/htlc_outgoing_contest_resolver_test.go b/contractcourt/htlc_outgoing_contest_resolver_test.go index 1632cfac1..684812d48 100644 --- a/contractcourt/htlc_outgoing_contest_resolver_test.go +++ b/contractcourt/htlc_outgoing_contest_resolver_test.go @@ -23,7 +23,7 @@ const ( // timed out. func TestHtlcOutgoingResolverTimeout(t *testing.T) { t.Parallel() - defer timeout(t)() + defer timeout()() // Setup the resolver with our test resolution. ctx := newOutgoingResolverTestContext(t) @@ -44,7 +44,7 @@ func TestHtlcOutgoingResolverTimeout(t *testing.T) { // is claimed by the remote party. func TestHtlcOutgoingResolverRemoteClaim(t *testing.T) { t.Parallel() - defer timeout(t)() + defer timeout()() // Setup the resolver with our test resolution and start the resolution // process. diff --git a/contractcourt/htlc_success_resolver_test.go b/contractcourt/htlc_success_resolver_test.go index 2e11d7da2..7e9adcf81 100644 --- a/contractcourt/htlc_success_resolver_test.go +++ b/contractcourt/htlc_success_resolver_test.go @@ -477,7 +477,7 @@ type checkpoint struct { func testHtlcSuccess(t *testing.T, resolution lnwallet.IncomingHtlcResolution, checkpoints []checkpoint) { - defer timeout(t)() + defer timeout()() // We first run the resolver from start to finish, ensuring it gets // checkpointed at every expected stage. We store the checkpointed data @@ -521,7 +521,7 @@ func testHtlcSuccess(t *testing.T, resolution lnwallet.IncomingHtlcResolution, func runFromCheckpoint(t *testing.T, ctx *htlcResolverTestContext, expectedCheckpoints []checkpoint) [][]byte { - defer timeout(t)() + defer timeout()() var checkpointedState [][]byte diff --git a/contractcourt/htlc_timeout_resolver_test.go b/contractcourt/htlc_timeout_resolver_test.go index cfc093340..8b2451ed2 100644 --- a/contractcourt/htlc_timeout_resolver_test.go +++ b/contractcourt/htlc_timeout_resolver_test.go @@ -1286,7 +1286,7 @@ func TestHtlcTimeoutSecondStageSweeperRemoteSpend(t *testing.T) { func testHtlcTimeout(t *testing.T, resolution lnwallet.OutgoingHtlcResolution, checkpoints []checkpoint) { - defer timeout(t)() + defer timeout()() // We first run the resolver from start to finish, ensuring it gets // checkpointed at every expected stage. We store the checkpointed data diff --git a/contractcourt/nursery_store_test.go b/contractcourt/nursery_store_test.go index 5ea542c19..f82758901 100644 --- a/contractcourt/nursery_store_test.go +++ b/contractcourt/nursery_store_test.go @@ -53,9 +53,8 @@ func initIncubateTests() { // TestNurseryStoreInit verifies basic properties of the nursery store before // any modifying calls are made. func TestNurseryStoreInit(t *testing.T) { - cdb, cleanUp, err := channeldb.MakeTestDB() + cdb, err := channeldb.MakeTestDB(t) require.NoError(t, err, "unable to open channel db") - defer cleanUp() ns, err := NewNurseryStore(&chainHash, cdb) require.NoError(t, err, "unable to open nursery store") @@ -69,9 +68,8 @@ func TestNurseryStoreInit(t *testing.T) { // outputs through the nursery store, verifying the properties of the // intermediate states. func TestNurseryStoreIncubate(t *testing.T) { - cdb, cleanUp, err := channeldb.MakeTestDB() + cdb, err := channeldb.MakeTestDB(t) require.NoError(t, err, "unable to open channel db") - defer cleanUp() ns, err := NewNurseryStore(&chainHash, cdb) require.NoError(t, err, "unable to open nursery store") @@ -306,9 +304,8 @@ func TestNurseryStoreIncubate(t *testing.T) { // populated entries from the height index as it is purged, and that the last // purged height is set appropriately. func TestNurseryStoreGraduate(t *testing.T) { - cdb, cleanUp, err := channeldb.MakeTestDB() + cdb, err := channeldb.MakeTestDB(t) require.NoError(t, err, "unable to open channel db") - defer cleanUp() ns, err := NewNurseryStore(&chainHash, cdb) require.NoError(t, err, "unable to open nursery store") diff --git a/contractcourt/utils_test.go b/contractcourt/utils_test.go index 13dfd45a3..9a3c5308e 100644 --- a/contractcourt/utils_test.go +++ b/contractcourt/utils_test.go @@ -13,7 +13,7 @@ import ( ) // timeout implements a test level timeout. -func timeout(t *testing.T) func() { +func timeout() func() { done := make(chan struct{}) go func() { select { diff --git a/contractcourt/utxonursery_test.go b/contractcourt/utxonursery_test.go index 4563a8daa..99b139ea4 100644 --- a/contractcourt/utxonursery_test.go +++ b/contractcourt/utxonursery_test.go @@ -409,7 +409,6 @@ type nurseryTestContext struct { sweeper *mockSweeperFull timeoutChan chan chan time.Time t *testing.T - dbCleanup func() } func createNurseryTestContext(t *testing.T, @@ -419,7 +418,7 @@ func createNurseryTestContext(t *testing.T, // alternative, mocking nurseryStore, is not chosen because there is // still considerable logic in the store. - cdb, cleanup, err := channeldb.MakeTestDB() + cdb, err := channeldb.MakeTestDB(t) require.NoError(t, err, "unable to open channeldb") store, err := NewNurseryStore(&chainhash.Hash{}, cdb) @@ -480,7 +479,6 @@ func createNurseryTestContext(t *testing.T, sweeper: sweeper, timeoutChan: timeoutChan, t: t, - dbCleanup: cleanup, } ctx.receiveTx = func() wire.MsgTx { @@ -528,8 +526,6 @@ func (ctx *nurseryTestContext) notifyEpoch(height int32) { } func (ctx *nurseryTestContext) finish() { - defer ctx.dbCleanup() - // Add a final restart point in this state ctx.restart() diff --git a/lnwallet/channel_test.go b/lnwallet/channel_test.go index 1c43b707f..f35f4137d 100644 --- a/lnwallet/channel_test.go +++ b/lnwallet/channel_test.go @@ -68,9 +68,8 @@ func testAddSettleWorkflow(t *testing.T, tweakless bool) { chanType = channeldb.SingleFunderBit } - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels(chanType) + aliceChannel, bobChannel, err := CreateTestChannels(t, chanType) require.NoError(t, err, "unable to create test channels") - defer cleanUp() paymentPreimage := bytes.Repeat([]byte{1}, 32) paymentHash := sha256.Sum256(paymentPreimage) @@ -355,11 +354,10 @@ func TestChannelZeroAddLocalHeight(t *testing.T) { t.Parallel() // Create a test channel so that we can test the buggy behavior. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err) - defer cleanUp() // First we create an HTLC that Alice sends to Bob. htlc, _ := createHTLC(0, lnwire.MilliSatoshi(500000)) @@ -459,11 +457,10 @@ func TestCheckCommitTxSize(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // Check that weight estimation of the commitment transaction without // HTLCs is right. @@ -527,13 +524,12 @@ func TestCommitHTLCSigTieBreak(t *testing.T) { } func testCommitHTLCSigTieBreak(t *testing.T, restart bool) { - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) if err != nil { t.Fatalf("unable to create test channels; %v", err) } - defer cleanUp() const ( htlcAmt = lnwire.MilliSatoshi(20000000) @@ -662,11 +658,10 @@ func testCoopClose(t *testing.T, testCase *coopCloseTestCase) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - testCase.chanType, + aliceChannel, bobChannel, err := CreateTestChannels( + t, testCase.chanType, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() aliceDeliveryScript := bobsPrivKey[:] bobDeliveryScript := testHdSeed[:] @@ -774,11 +769,10 @@ func testForceClose(t *testing.T, testCase *forceCloseTestCase) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - testCase.chanType, + aliceChannel, bobChannel, err := CreateTestChannels( + t, testCase.chanType, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() bobAmount := bobChannel.channelState.LocalCommitment.LocalBalance @@ -1101,11 +1095,10 @@ func TestForceCloseDustOutput(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // We set both node's channel reserves to 0, to make sure // they can create small dust outputs without going under @@ -1209,11 +1202,10 @@ func TestDustHTLCFees(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() aliceStartingBalance := aliceChannel.channelState.LocalCommitment.LocalBalance @@ -1286,11 +1278,10 @@ func TestHTLCDustLimit(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // The amount of the HTLC should be above Alice's dust limit and below // Bob's dust limit. @@ -1364,13 +1355,13 @@ func TestHTLCSigNumber(t *testing.T) { // createChanWithHTLC is a helper method that sets ut two channels, and // adds HTLCs with the passed values to the channels. createChanWithHTLC := func(htlcValues ...btcutil.Amount) ( - *LightningChannel, *LightningChannel, func()) { + *LightningChannel, *LightningChannel) { // Create a test channel funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. Alice's dustlimit is 200 sat, while // Bob has 1300 sat. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) if err != nil { t.Fatalf("unable to create test channels: %v", err) @@ -1389,7 +1380,7 @@ func TestHTLCSigNumber(t *testing.T) { } } - return aliceChannel, bobChannel, cleanUp + return aliceChannel, bobChannel } // Calculate two values that will be below and above Bob's dust limit. @@ -1408,9 +1399,7 @@ func TestHTLCSigNumber(t *testing.T) { // Test that Bob will reject a commitment if Alice doesn't send enough // HTLC signatures. // =================================================================== - aliceChannel, bobChannel, cleanUp := createChanWithHTLC(aboveDust, - aboveDust) - defer cleanUp() + aliceChannel, bobChannel := createChanWithHTLC(aboveDust, aboveDust) aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() require.NoError(t, err, "Error signing next commitment") @@ -1431,8 +1420,7 @@ func TestHTLCSigNumber(t *testing.T) { // Test that Bob will reject a commitment if Alice doesn't send any // HTLC signatures. // =================================================================== - aliceChannel, bobChannel, cleanUp = createChanWithHTLC(aboveDust) - defer cleanUp() + aliceChannel, bobChannel = createChanWithHTLC(aboveDust) aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() require.NoError(t, err, "Error signing next commitment") @@ -1452,8 +1440,7 @@ func TestHTLCSigNumber(t *testing.T) { // ============================================================== // Test that sigs are not returned for HTLCs below dust limit. // ============================================================== - aliceChannel, bobChannel, cleanUp = createChanWithHTLC(belowDust) - defer cleanUp() + aliceChannel, bobChannel = createChanWithHTLC(belowDust) aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() require.NoError(t, err, "Error signing next commitment") @@ -1471,8 +1458,7 @@ func TestHTLCSigNumber(t *testing.T) { // ================================================================ // Test that sigs are correctly returned for HTLCs above dust limit. // ================================================================ - aliceChannel, bobChannel, cleanUp = createChanWithHTLC(aboveDust) - defer cleanUp() + aliceChannel, bobChannel = createChanWithHTLC(aboveDust) aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() require.NoError(t, err, "Error signing next commitment") @@ -1491,9 +1477,7 @@ func TestHTLCSigNumber(t *testing.T) { // Test that Bob will not validate a received commitment if Alice sends // signatures for HTLCs below the dust limit. // ==================================================================== - aliceChannel, bobChannel, cleanUp = createChanWithHTLC(belowDust, - aboveDust) - defer cleanUp() + aliceChannel, bobChannel = createChanWithHTLC(belowDust, aboveDust) // Alice should produce only one signature, since one HTLC is below // dust. @@ -1529,11 +1513,10 @@ func TestChannelBalanceDustLimit(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // To allow Alice's balance to get beneath her dust limit, set the // channel reserve to be 0. @@ -1594,11 +1577,10 @@ func TestStateUpdatePersistence(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() htlcAmt := lnwire.NewMSatFromSatoshis(5000) @@ -1919,11 +1901,10 @@ func TestCancelHTLC(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // Add a new HTLC from Alice to Bob, then trigger a new state // transition in order to include it in the latest state. @@ -2026,11 +2007,10 @@ func TestCooperativeCloseDustAdherence(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() aliceFeeRate := chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, @@ -2189,11 +2169,10 @@ func TestCooperativeCloseDustAdherence(t *testing.T) { func TestUpdateFeeAdjustments(t *testing.T) { t.Parallel() - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // First, we'll grab the current base fee rate as we'll be using this // to make relative adjustments int he fee rate. @@ -2244,11 +2223,10 @@ func TestUpdateFeeAdjustments(t *testing.T) { func TestUpdateFeeFail(t *testing.T) { t.Parallel() - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // Bob receives the update, that will apply to his commitment // transaction. @@ -2276,11 +2254,10 @@ func TestUpdateFeeFail(t *testing.T) { func TestUpdateFeeConcurrentSig(t *testing.T) { t.Parallel() - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() paymentPreimage := bytes.Repeat([]byte{1}, 32) paymentHash := sha256.Sum256(paymentPreimage) @@ -2352,11 +2329,10 @@ func TestUpdateFeeSenderCommits(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() paymentPreimage := bytes.Repeat([]byte{1}, 32) paymentHash := sha256.Sum256(paymentPreimage) @@ -2462,11 +2438,10 @@ func TestUpdateFeeReceiverCommits(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() paymentPreimage := bytes.Repeat([]byte{1}, 32) paymentHash := sha256.Sum256(paymentPreimage) @@ -2591,11 +2566,10 @@ func TestUpdateFeeReceiverSendsUpdate(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // Since Alice is the channel initiator, she should fail when receiving // fee update @@ -2620,11 +2594,10 @@ func TestUpdateFeeMultipleUpdates(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // Simulate Alice sending update fee message to bob. fee1 := chainfee.SatPerKWeight(333) @@ -2730,11 +2703,10 @@ func TestAddHTLCNegativeBalance(t *testing.T) { // We'll kick off the test by creating our channels which both are // loaded with 5 BTC each. - aliceChannel, _, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, _, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // We set the channel reserve to 0, such that we can add HTLCs all the // way to a negative balance. @@ -2811,11 +2783,10 @@ func TestChanSyncFullySynced(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // If we exchange channel sync messages from the get-go , then both // sides should conclude that no further synchronization is needed. @@ -2915,11 +2886,10 @@ func TestChanSyncOweCommitment(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() var fakeOnionBlob [lnwire.OnionPacketSize]byte copy(fakeOnionBlob[:], bytes.Repeat([]byte{0x05}, lnwire.OnionPacketSize)) @@ -3196,11 +3166,10 @@ func TestChanSyncOweCommitmentPendingRemote(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() var fakeOnionBlob [lnwire.OnionPacketSize]byte copy(fakeOnionBlob[:], bytes.Repeat([]byte{0x05}, lnwire.OnionPacketSize)) @@ -3315,11 +3284,10 @@ func TestChanSyncOweRevocation(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() chanID := lnwire.NewChanIDFromOutPoint( &aliceChannel.channelState.FundingOutpoint, @@ -3473,11 +3441,10 @@ func TestChanSyncOweRevocationAndCommit(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() htlcAmt := lnwire.NewMSatFromSatoshis(20000) @@ -3610,11 +3577,10 @@ func TestChanSyncOweRevocationAndCommitForceTransition(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() htlcAmt := lnwire.NewMSatFromSatoshis(20000) @@ -3795,11 +3761,10 @@ func TestChanSyncFailure(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() htlcAmt := lnwire.NewMSatFromSatoshis(20000) index := byte(0) @@ -4034,11 +3999,10 @@ func TestFeeUpdateRejectInsaneFee(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, _, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, _, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // Next, we'll try to add a fee rate to Alice which is 1,000,000x her // starting fee rate. @@ -4062,11 +4026,10 @@ func TestChannelRetransmissionFeeUpdate(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // First, we'll fetch the current fee rate present within the // commitment transactions. @@ -4225,11 +4188,10 @@ func TestFeeUpdateOldDiskFormat(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // helper that counts the number of updates, and number of fee updates // in the given log. @@ -4436,11 +4398,10 @@ func TestChanSyncUnableToSync(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // If we immediately send both sides a "bogus" ChanSync message, then // they both should conclude that they're unable to synchronize the @@ -4473,11 +4434,10 @@ func TestChanSyncInvalidLastSecret(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // We'll create a new instances of Alice before doing any state updates // such that we have the initial in memory state at the start of the @@ -4555,11 +4515,10 @@ func TestChanAvailableBandwidth(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() aliceReserve := lnwire.NewMSatFromSatoshis( aliceChannel.channelState.LocalChanCfg.ChanReserve, @@ -4687,11 +4646,10 @@ func TestChanAvailableBalanceNearHtlcFee(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // Alice and Bob start with half the channel capacity. aliceBalance := lnwire.NewMSatFromSatoshis(5 * btcutil.SatoshiPerBitcoin) @@ -4866,11 +4824,10 @@ func TestChanCommitWeightDustHtlcs(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() aliceDustlimit := lnwire.NewMSatFromSatoshis( aliceChannel.channelState.LocalChanCfg.DustLimit, @@ -4999,11 +4956,10 @@ func TestSignCommitmentFailNotLockedIn(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, _, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, _, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // Next, we'll modify Alice's internal state to omit knowledge of Bob's // next revocation point. @@ -5024,11 +4980,10 @@ func TestLockedInHtlcForwardingSkipAfterRestart(t *testing.T) { t.Parallel() // First, we'll make a channel between Alice and Bob. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // We'll now add two HTLC's from Alice to Bob, then Alice will initiate // a state transition. @@ -5318,11 +5273,10 @@ func TestInvalidCommitSigError(t *testing.T) { t.Parallel() // First, we'll make a channel between Alice and Bob. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // With the channel established, we'll now send a single HTLC from // Alice to Bob. @@ -5363,11 +5317,10 @@ func TestChannelUnilateralCloseHtlcResolution(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // We'll start off the test by adding an HTLC in both directions, then // initiating enough state transitions to lock both of them in. @@ -5519,11 +5472,10 @@ func TestChannelUnilateralClosePendingCommit(t *testing.T) { // Create a test channel which will be used for the duration of this // unittest. The channel will be funded evenly with Alice having 5 BTC, // and Bob having 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // First, we'll add an HTLC from Alice to Bob, just to be be able to // create a new state transition. @@ -5639,11 +5591,10 @@ func TestDesyncHTLCs(t *testing.T) { // We'll kick off the test by creating our channels which both are // loaded with 5 BTC each. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // First add one HTLC of value 4.1 BTC. htlcAmt := lnwire.NewMSatFromSatoshis(4.1 * btcutil.SatoshiPerBitcoin) @@ -5700,11 +5651,10 @@ func TestMaxAcceptedHTLCs(t *testing.T) { // We'll kick off the test by creating our channels which both are // loaded with 5 BTC each. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // One over the maximum number of HTLCs that either can accept. const numHTLCs = 12 @@ -5828,11 +5778,10 @@ func TestMaxAsynchronousHtlcs(t *testing.T) { // We'll kick off the test by creating our channels which both are // loaded with 5 BTC each. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // One over the maximum number of HTLCs that either can accept. const numHTLCs = 12 @@ -5941,11 +5890,10 @@ func TestMaxPendingAmount(t *testing.T) { // We'll kick off the test by creating our channels which both are // loaded with 5 BTC each. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // We set the remote required MaxPendingAmount to 3 BTC. We will // attempt to overflow this value and see if it gives us the @@ -6021,11 +5969,11 @@ func assertChannelBalances(t *testing.T, alice, bob *LightningChannel, func TestChanReserve(t *testing.T) { t.Parallel() - setupChannels := func() (*LightningChannel, *LightningChannel, func()) { + setupChannels := func() (*LightningChannel, *LightningChannel) { // We'll kick off the test by creating our channels which both // are loaded with 5 BTC each. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) if err != nil { t.Fatalf("unable to create test channels: %v", err) @@ -6054,10 +6002,9 @@ func TestChanReserve(t *testing.T) { bobChannel.channelState.LocalChanCfg.ChanReserve = bobMinReserve aliceChannel.channelState.RemoteChanCfg.ChanReserve = bobMinReserve - return aliceChannel, bobChannel, cleanUp + return aliceChannel, bobChannel } - aliceChannel, bobChannel, cleanUp := setupChannels() - defer cleanUp() + aliceChannel, bobChannel := setupChannels() aliceIndex := 0 bobIndex := 0 @@ -6111,8 +6058,7 @@ func TestChanReserve(t *testing.T) { // We must setup the channels again, since a violation of the channel // constraints leads to channel shutdown. - aliceChannel, bobChannel, cleanUp = setupChannels() - defer cleanUp() + aliceChannel, bobChannel = setupChannels() aliceIndex = 0 bobIndex = 0 @@ -6154,8 +6100,7 @@ func TestChanReserve(t *testing.T) { // We must setup the channels again, since a violation of the channel // constraints leads to channel shutdown. - aliceChannel, bobChannel, cleanUp = setupChannels() - defer cleanUp() + aliceChannel, bobChannel = setupChannels() aliceIndex = 0 bobIndex = 0 @@ -6229,13 +6174,12 @@ func TestChanReserveRemoteInitiator(t *testing.T) { t.Parallel() // We start out with a channel where both parties have 5 BTC. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) if err != nil { t.Fatal(err) } - defer cleanUp() // Set Alice's channel reserve to be 5 BTC-commitfee. This means she // has just enough balance to cover the comitment fee, but not enough @@ -6282,13 +6226,12 @@ func TestChanReserveRemoteInitiator(t *testing.T) { func TestChanReserveLocalInitiatorDustHtlc(t *testing.T) { t.Parallel() - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) if err != nil { t.Fatal(err) } - defer cleanUp() // The amount of the HTLC should not be considered dust according to // Alice's dust limit (200 sat), but be dust according to Bob's dust @@ -6329,11 +6272,10 @@ func TestMinHTLC(t *testing.T) { // We'll kick off the test by creating our channels which both are // loaded with 5 BTC each. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // We set Alice's MinHTLC to 0.1 BTC. We will attempt to send an // HTLC BELOW this value to trigger the ErrBelowMinHTLC error. @@ -6379,11 +6321,10 @@ func TestInvalidHTLCAmt(t *testing.T) { // We'll kick off the test by creating our channels which both are // loaded with 5 BTC each. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // We'll set the min HTLC values for each party to zero, which // technically would permit zero-value HTLCs. @@ -6415,11 +6356,10 @@ func TestNewBreachRetributionSkipsDustHtlcs(t *testing.T) { // We'll kick off the test by creating our channels which both are // loaded with 5 BTC each. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() var fakeOnionBlob [lnwire.OnionPacketSize]byte copy(fakeOnionBlob[:], bytes.Repeat([]byte{0x05}, lnwire.OnionPacketSize)) @@ -6586,11 +6526,10 @@ func compareLogs(a, b *updateLog) error { func TestChannelRestoreUpdateLogs(t *testing.T) { t.Parallel() - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // First, we'll add an HTLC from Alice to Bob, which we will lock in on // Bob's commit, but not on Alice's. @@ -6731,11 +6670,10 @@ func restoreAndAssert(t *testing.T, channel *LightningChannel, numAddsLocal, func TestChannelRestoreUpdateLogsFailedHTLC(t *testing.T) { t.Parallel() - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // First, we'll add an HTLC from Alice to Bob, and lock it in for both. htlcAmount := lnwire.NewMSatFromSatoshis(20000) @@ -6834,11 +6772,10 @@ func TestChannelRestoreUpdateLogsFailedHTLC(t *testing.T) { func TestDuplicateFailRejection(t *testing.T) { t.Parallel() - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // First, we'll add an HTLC from Alice to Bob, and lock it in for both // parties. @@ -6902,11 +6839,10 @@ func TestDuplicateFailRejection(t *testing.T) { func TestDuplicateSettleRejection(t *testing.T) { t.Parallel() - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // First, we'll add an HTLC from Alice to Bob, and lock it in for both // parties. @@ -6969,11 +6905,10 @@ func TestDuplicateSettleRejection(t *testing.T) { func TestChannelRestoreCommitHeight(t *testing.T) { t.Parallel() - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // helper method to check add heights of the htlcs found in the given // log after a restore. @@ -7198,11 +7133,10 @@ func TestChannelRestoreCommitHeight(t *testing.T) { func TestForceCloseFailLocalDataLoss(t *testing.T) { t.Parallel() - aliceChannel, _, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderBit, + aliceChannel, _, err := CreateTestChannels( + t, channeldb.SingleFunderBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // Now that we have our set of channels, we'll modify the channel state // to have a non-default channel flag. @@ -7227,11 +7161,10 @@ func TestForceCloseFailLocalDataLoss(t *testing.T) { func TestForceCloseBorkedState(t *testing.T) { t.Parallel() - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // Do the commitment dance until Bob sends a revocation so Alice is // able to receive the revocation, and then also make a new state @@ -7317,11 +7250,10 @@ func TestChannelMaxFeeRate(t *testing.T) { } } - aliceChannel, _, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, _, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() if err := quick.Check(propertyTest(aliceChannel), nil); err != nil { t.Fatal(err) @@ -7333,12 +7265,11 @@ func TestChannelMaxFeeRate(t *testing.T) { assertMaxFeeRate(aliceChannel, 0.0000001, chainfee.FeePerKwFloor) // Check that anchor channels are capped at their max fee rate. - anchorChannel, _, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit | - channeldb.AnchorOutputsBit | channeldb.ZeroHtlcTxFeeBit, + anchorChannel, _, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit| + channeldb.AnchorOutputsBit|channeldb.ZeroHtlcTxFeeBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() if err = quick.Check(propertyTest(anchorChannel), nil); err != nil { t.Fatal(err) @@ -7397,13 +7328,12 @@ func TestIdealCommitFeeRate(t *testing.T) { // Test ideal fee rates for a non-anchor channel t.Run("non-anchor-channel", func(t *testing.T) { - aliceChannel, _, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, _, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) if err != nil { t.Fatalf("unable to create test channels: %v", err) } - defer cleanUp() err = quick.Check(propertyTest(aliceChannel), nil) if err != nil { @@ -7439,15 +7369,14 @@ func TestIdealCommitFeeRate(t *testing.T) { // Test ideal fee rates for an anchor channel t.Run("anchor-channel", func(t *testing.T) { - anchorChannel, _, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit | - channeldb.AnchorOutputsBit | + anchorChannel, _, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit| + channeldb.AnchorOutputsBit| channeldb.ZeroHtlcTxFeeBit, ) if err != nil { t.Fatalf("unable to create test channels: %v", err) } - defer cleanUp() err = quick.Check(propertyTest(anchorChannel), nil) if err != nil { @@ -7532,11 +7461,10 @@ func (fee) Generate(r *rand.Rand, _ int) reflect.Value { func TestChannelFeeRateFloor(t *testing.T) { t.Parallel() - alice, bob, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + alice, bob, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err, "unable to create test channels") - defer cleanUp() // Set the fee rate to the proposing fee rate floor. minFee := chainfee.FeePerKwFloor @@ -8826,11 +8754,10 @@ func TestChannelUnsignedAckedFailure(t *testing.T) { t.Parallel() // Create a test channel so that we can test the buggy behavior. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err) - defer cleanUp() // First we create an HTLC that Alice sends to Bob. htlc, _ := createHTLC(0, lnwire.MilliSatoshi(500000)) @@ -8937,11 +8864,10 @@ func TestChannelLocalUnsignedUpdatesFailure(t *testing.T) { t.Parallel() // Create a test channel so that we can test the buggy behavior. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err) - defer cleanUp() // First we create an htlc that Bob sends to Alice. htlc, _ := createHTLC(0, lnwire.MilliSatoshi(500000)) @@ -9025,11 +8951,10 @@ func TestChannelSignedAckRegression(t *testing.T) { t.Parallel() // Create test channels to test out this state transition. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err) - defer cleanUp() // Create an HTLC that Bob will send to Alice. htlc, preimage := createHTLC(0, lnwire.MilliSatoshi(5000000)) @@ -9129,11 +9054,10 @@ func TestMayAddOutgoingHtlc(t *testing.T) { // The default channel created as a part of the test fixture already // has a MinHTLC value of zero, so we don't need to do anything here // other than create it. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.SingleFunderTweaklessBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.SingleFunderTweaklessBit, ) require.NoError(t, err) - defer cleanUp() // The channels start out with a 50/50 balance, so both sides should be // able to add an outgoing HTLC with no specific amount added. @@ -9166,11 +9090,10 @@ func TestMayAddOutgoingHtlc(t *testing.T) { func TestIsChannelClean(t *testing.T) { t.Parallel() - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( - channeldb.ZeroHtlcTxFeeBit, + aliceChannel, bobChannel, err := CreateTestChannels( + t, channeldb.ZeroHtlcTxFeeBit, ) require.NoError(t, err) - defer cleanUp() // Channel state should be clean at the start of the test. assertCleanOrDirty(true, aliceChannel, bobChannel, t) @@ -9327,9 +9250,8 @@ func testGetDustSum(t *testing.T, chantype channeldb.ChannelType) { // This makes a channel with Alice's dust limit set to 200sats and // Bob's dust limit set to 1300sats. - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels(chantype) + aliceChannel, bobChannel, err := CreateTestChannels(t, chantype) require.NoError(t, err) - defer cleanUp() // Use a function closure to assert the dust sum for a passed channel's // local and remote commitments match the expected values. @@ -9508,11 +9430,10 @@ func TestCreateHtlcRetribution(t *testing.T) { testAmt := btcutil.Amount(100) // Create a test channel. - aliceChannel, _, cleanUp, err := CreateTestChannels( - channeldb.ZeroHtlcTxFeeBit, + aliceChannel, _, err := CreateTestChannels( + t, channeldb.ZeroHtlcTxFeeBit, ) require.NoError(t, err) - defer cleanUp() // Prepare the params needed to call the function. Note that the values // here are not necessary "cryptography-correct", we just use them to @@ -9566,11 +9487,10 @@ func TestCreateBreachRetribution(t *testing.T) { } // Create a test channel. - aliceChannel, _, cleanUp, err := CreateTestChannels( - channeldb.ZeroHtlcTxFeeBit, + aliceChannel, _, err := CreateTestChannels( + t, channeldb.ZeroHtlcTxFeeBit, ) require.NoError(t, err) - defer cleanUp() // Prepare the params needed to call the function. Note that the values // here are not necessary "cryptography-correct", we just use them to @@ -9716,11 +9636,10 @@ func TestCreateBreachRetributionLegacy(t *testing.T) { dummyPrivate, _ := btcec.PrivKeyFromBytes([]byte{1}) // Create a test channel. - aliceChannel, _, cleanUp, err := CreateTestChannels( - channeldb.ZeroHtlcTxFeeBit, + aliceChannel, _, err := CreateTestChannels( + t, channeldb.ZeroHtlcTxFeeBit, ) require.NoError(t, err) - defer cleanUp() // Prepare the params needed to call the function. Note that the values // here are not necessary "cryptography-correct", we just use them to @@ -9794,9 +9713,8 @@ func TestNewBreachRetribution(t *testing.T) { func testNewBreachRetribution(t *testing.T, chanType channeldb.ChannelType) { t.Parallel() - aliceChannel, bobChannel, cleanUp, err := CreateTestChannels(chanType) + aliceChannel, bobChannel, err := CreateTestChannels(t, chanType) require.NoError(t, err) - defer cleanUp() breachHeight := uint32(101) stateNum := uint64(0) diff --git a/lnwallet/test_utils.go b/lnwallet/test_utils.go index f1209d701..e8fe5d62a 100644 --- a/lnwallet/test_utils.go +++ b/lnwallet/test_utils.go @@ -5,10 +5,9 @@ import ( "encoding/binary" "encoding/hex" "io" - "io/ioutil" prand "math/rand" "net" - "os" + "testing" "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcutil" @@ -20,6 +19,7 @@ import ( "github.com/lightningnetwork/lnd/lnwallet/chainfee" "github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/shachain" + "github.com/stretchr/testify/require" ) var ( @@ -103,17 +103,15 @@ var ( // CreateTestChannels creates to fully populated channels to be used within // testing fixtures. The channels will be returned as if the funding process // has just completed. The channel itself is funded with 10 BTC, with 5 BTC -// allocated to each side. Within the channel, Alice is the initiator. The -// function also returns a "cleanup" function that is meant to be called once -// the test has been finalized. The clean up function will remote all temporary -// files created. If tweaklessCommits is true, then the commits within the -// channels will use the new format, otherwise the legacy format. -func CreateTestChannels(chanType channeldb.ChannelType) ( - *LightningChannel, *LightningChannel, func(), error) { +// allocated to each side. Within the channel, Alice is the initiator. If +// tweaklessCommits is true, then the commits within the channels will use the +// new format, otherwise the legacy format. +func CreateTestChannels(t *testing.T, chanType channeldb.ChannelType) ( + *LightningChannel, *LightningChannel, error) { channelCapacity, err := btcutil.NewAmount(testChannelCapacity) if err != nil { - return nil, nil, nil, err + return nil, nil, err } channelBal := channelCapacity / 2 @@ -202,23 +200,23 @@ func CreateTestChannels(chanType channeldb.ChannelType) ( bobRoot, err := chainhash.NewHash(bobKeys[0].Serialize()) if err != nil { - return nil, nil, nil, err + return nil, nil, err } bobPreimageProducer := shachain.NewRevocationProducer(*bobRoot) bobFirstRevoke, err := bobPreimageProducer.AtIndex(0) if err != nil { - return nil, nil, nil, err + return nil, nil, err } bobCommitPoint := input.ComputeCommitmentPoint(bobFirstRevoke[:]) aliceRoot, err := chainhash.NewHash(aliceKeys[0].Serialize()) if err != nil { - return nil, nil, nil, err + return nil, nil, err } alicePreimageProducer := shachain.NewRevocationProducer(*aliceRoot) aliceFirstRevoke, err := alicePreimageProducer.AtIndex(0) if err != nil { - return nil, nil, nil, err + return nil, nil, err } aliceCommitPoint := input.ComputeCommitmentPoint(aliceFirstRevoke[:]) @@ -227,33 +225,29 @@ func CreateTestChannels(chanType channeldb.ChannelType) ( bobCommitPoint, *fundingTxIn, chanType, isAliceInitiator, 0, ) if err != nil { - return nil, nil, nil, err + return nil, nil, err } - alicePath, err := ioutil.TempDir("", "alicedb") + dbAlice, err := channeldb.Open(t.TempDir()) if err != nil { - return nil, nil, nil, err + return nil, nil, err } + t.Cleanup(func() { + require.NoError(t, dbAlice.Close()) + }) - dbAlice, err := channeldb.Open(alicePath) + dbBob, err := channeldb.Open(t.TempDir()) if err != nil { - return nil, nil, nil, err - } - - bobPath, err := ioutil.TempDir("", "bobdb") - if err != nil { - return nil, nil, nil, err - } - - dbBob, err := channeldb.Open(bobPath) - if err != nil { - return nil, nil, nil, err + return nil, nil, err } + t.Cleanup(func() { + require.NoError(t, dbBob.Close()) + }) estimator := chainfee.NewStaticEstimator(6000, 0) feePerKw, err := estimator.EstimateFeePerKW(1) if err != nil { - return nil, nil, nil, err + return nil, nil, err } commitFee := calcStaticFee(chanType, 0) var anchorAmt btcutil.Amount @@ -305,7 +299,7 @@ func CreateTestChannels(chanType channeldb.ChannelType) ( var chanIDBytes [8]byte if _, err := io.ReadFull(rand.Reader, chanIDBytes[:]); err != nil { - return nil, nil, nil, err + return nil, nil, err } shortChanID := lnwire.NewShortChanIDFromInt( @@ -358,9 +352,12 @@ func CreateTestChannels(chanType channeldb.ChannelType) ( aliceSigner, aliceChannelState, alicePool, ) if err != nil { - return nil, nil, nil, err + return nil, nil, err } alicePool.Start() + t.Cleanup(func() { + require.NoError(t, alicePool.Stop()) + }) obfuscator := createStateHintObfuscator(aliceChannelState) @@ -369,21 +366,24 @@ func CreateTestChannels(chanType channeldb.ChannelType) ( bobSigner, bobChannelState, bobPool, ) if err != nil { - return nil, nil, nil, err + return nil, nil, err } bobPool.Start() + t.Cleanup(func() { + require.NoError(t, bobPool.Stop()) + }) err = SetStateNumHint( aliceCommitTx, 0, obfuscator, ) if err != nil { - return nil, nil, nil, err + return nil, nil, err } err = SetStateNumHint( bobCommitTx, 0, obfuscator, ) if err != nil { - return nil, nil, nil, err + return nil, nil, err } addr := &net.TCPAddr{ @@ -391,7 +391,7 @@ func CreateTestChannels(chanType channeldb.ChannelType) ( Port: 18556, } if err := channelAlice.channelState.SyncPending(addr, 101); err != nil { - return nil, nil, nil, err + return nil, nil, err } addr = &net.TCPAddr{ @@ -400,25 +400,17 @@ func CreateTestChannels(chanType channeldb.ChannelType) ( } if err := channelBob.channelState.SyncPending(addr, 101); err != nil { - return nil, nil, nil, err - } - - cleanUpFunc := func() { - os.RemoveAll(bobPath) - os.RemoveAll(alicePath) - - alicePool.Stop() - bobPool.Stop() + return nil, nil, err } // Now that the channel are open, simulate the start of a session by // having Alice and Bob extend their revocation windows to each other. err = initRevocationWindows(channelAlice, channelBob) if err != nil { - return nil, nil, nil, err + return nil, nil, err } - return channelAlice, channelBob, cleanUpFunc, nil + return channelAlice, channelBob, nil } // initRevocationWindows simulates a new channel being opened within the p2p diff --git a/sweep/store_test.go b/sweep/store_test.go index 0096b5563..39b20681c 100644 --- a/sweep/store_test.go +++ b/sweep/store_test.go @@ -15,15 +15,10 @@ func TestStore(t *testing.T) { t.Run("bolt", func(t *testing.T) { // Create new store. - cdb, cleanUp, err := channeldb.MakeTestDB() + cdb, err := channeldb.MakeTestDB(t) if err != nil { t.Fatalf("unable to open channel db: %v", err) } - defer cleanUp() - - if err != nil { - t.Fatal(err) - } testStore(t, func() (SweeperStore, error) { var chain chainhash.Hash