diff --git a/lwwallet/chain_backend.go b/lwwallet/chain_backend.go index aa7adeb1f..ae85dd117 100644 --- a/lwwallet/chain_backend.go +++ b/lwwallet/chain_backend.go @@ -713,12 +713,20 @@ func (b *ChainBackend) RegisterSpend(ctx context.Context, b.cancelSpendReg(id, reg) } - // Per-registration one-shot to handle outpoints that are - // already spent at registration time. See RegisterConf for the - // O(N²)-vs-O(1) rationale and the b.wg lifecycle note. + // Complete the initial spend check before returning. Lnd's transaction + // publisher performs a non-blocking read immediately after registering + // to distinguish a confirmed transaction from an RBF candidate. An + // asynchronous initial check can therefore make lnd replace an already + // confirmed sweep and terminally fail it with missing inputs. + // + // The check remains scoped to this registration, so registration is + // still O(1) rather than re-scanning all pending registrations. b.wg.Add(1) - //nolint:contextcheck // registration cancel/Stop own one-shot lifetime - go b.runSpendOneShot(id, reg) + if err := b.runSpendOneShot(ctx, id, reg); err != nil { + cancelFn() + + return nil, fmt.Errorf("initial spend lookup: %w", err) + } return &chainsource.SpendRegistration{ Spend: spendChan, @@ -752,36 +760,40 @@ func (b *ChainBackend) cancelSpendReg(id uint64, reg *spendRegistration) { // triggered at RegisterSpend time. The registration is NOT deleted // after delivery: a reorg may later reset it to stateWatching and // the next re-check must fire Spend again on the new chain. -func (b *ChainBackend) runSpendOneShot(id uint64, reg *spendRegistration) { +func (b *ChainBackend) runSpendOneShot(ctx context.Context, id uint64, + reg *spendRegistration) error { + defer b.wg.Done() select { case <-reg.cancelCh: - return + return context.Canceled case <-b.stopCh: - return + return context.Canceled default: } if reg.outpoint == nil { - return + return nil } - b.deliverSpendIfNew(id, reg) + return b.deliverSpendIfNew(ctx, id, reg) } // deliverSpendIfNew runs a spend re-check and fires the Spend // channel iff the registration is in stateWatching and a spend is // now available. Mirror of deliverConfIfNew; see that function's // comment for the regMu / channel-send ordering rationale. -func (b *ChainBackend) deliverSpendIfNew(id uint64, reg *spendRegistration) { +func (b *ChainBackend) deliverSpendIfNew(ctx context.Context, id uint64, + reg *spendRegistration) error { + reg.regMu.Lock() if reg.state == statePositive { reg.regMu.Unlock() - return + return nil } reg.regMu.Unlock() @@ -791,26 +803,24 @@ func (b *ChainBackend) deliverSpendIfNew(id uint64, reg *spendRegistration) { // did not parse and reorgSpendReg will fall back to a // conservative re-check rather than try to match against // ReorgEvent.Disconnected. - detail, spendingBlockHash, err := b.checkSingleSpend(reg) + detail, spendingBlockHash, err := b.checkSingleSpend(ctx, reg) if err != nil { - b.log.DebugS( - context.Background(), - "Spend status temporarily unavailable", + b.log.DebugS(ctx, "Spend status temporarily unavailable", slog.Uint64("reg_id", id), btclog.Fmt("err", "%v", err), ) - return + return err } if detail == nil { - return + return nil } reg.regMu.Lock() if reg.state == statePositive { reg.regMu.Unlock() - return + return nil } reg.state = statePositive if detail.SpenderTxHash != nil { @@ -822,18 +832,20 @@ func (b *ChainBackend) deliverSpendIfNew(id uint64, reg *spendRegistration) { select { case reg.spendChan <- detail: case <-reg.cancelCh: - return + return context.Canceled case <-b.stopCh: - return + return context.Canceled } - b.log.DebugS(context.Background(), + b.log.DebugS(ctx, "Spend registration fulfilled", slog.Uint64("reg_id", id), slog.String("outpoint", reg.outpoint.String()), slog.String("spender_txid", detail.SpenderTxHash.String())) + + return nil } // RegisterBlocks registers for new block notifications. @@ -1069,7 +1081,9 @@ func (b *ChainBackend) reorgSpendReg(id uint64, reg *spendRegistration, // was unparseable at delivery time. If the outpoint is // still spent by the same spender in the same block, // no reorg for this registration. - current, currentBlock, err := b.checkSingleSpend(reg) + current, currentBlock, err := b.checkSingleSpend( + context.Background(), reg, + ) if err != nil { b.log.DebugS( context.Background(), @@ -1120,7 +1134,13 @@ func (b *ChainBackend) reorgSpendReg(id uint64, reg *spendRegistration, slog.Uint64("reg_id", id), ) - b.deliverSpendIfNew(id, reg) + if err := b.deliverSpendIfNew( + context.Background(), id, reg, + ); err != nil { + + // The next tip or heartbeat will retry this watch. + return + } } // handleChainEvents drains the unified chain stream and dispatches @@ -1500,7 +1520,13 @@ func (b *ChainBackend) checkSpends() { continue } - b.deliverSpendIfNew(id, reg) + if err := b.deliverSpendIfNew( + context.Background(), id, reg, + ); err != nil { + + // This watch remains active for the next retry. + continue + } } } @@ -1511,15 +1537,16 @@ func (b *ChainBackend) checkSpends() { // interpreted as a reorg. The second return value is the block hash containing // the spending tx; a zero hash means only that the hash was unparseable while // the spend itself was valid. -func (b *ChainBackend) checkSingleSpend(reg *spendRegistration) ( - *chainsource.SpendDetail, chainhash.Hash, error) { +func (b *ChainBackend) checkSingleSpend(ctx context.Context, + reg *spendRegistration) (*chainsource.SpendDetail, chainhash.Hash, + error) { if reg.outpoint == nil { return nil, chainhash.Hash{}, nil } outspend, err := b.esplora.GetOutspend( - context.Background(), reg.outpoint.Hash, reg.outpoint.Index, + ctx, reg.outpoint.Hash, reg.outpoint.Index, ) if err != nil { return nil, chainhash.Hash{}, err @@ -1534,9 +1561,7 @@ func (b *ChainBackend) checkSingleSpend(reg *spendRegistration) ( return nil, chainhash.Hash{}, err } - spendingTx, err := b.esplora.GetRawTx( - context.Background(), *spenderHash, - ) + spendingTx, err := b.esplora.GetRawTx(ctx, *spenderHash) if err != nil { return nil, chainhash.Hash{}, err } diff --git a/lwwallet/chain_backend_test.go b/lwwallet/chain_backend_test.go index cfaa75fba..f72d43c65 100644 --- a/lwwallet/chain_backend_test.go +++ b/lwwallet/chain_backend_test.go @@ -2,6 +2,7 @@ package lwwallet import ( "bytes" + "context" "encoding/hex" "encoding/json" "fmt" @@ -416,8 +417,8 @@ func TestChainBackendConfRegistration(t *testing.T) { } } -// TestChainBackendSpendRegistration verifies that spend -// registrations fire when an output is spent. +// TestChainBackendSpendRegistration verifies that historical spends are +// buffered before registration returns. func TestChainBackendSpendRegistration(t *testing.T) { t.Parallel() @@ -499,9 +500,176 @@ func TestChainBackendSpendRegistration(t *testing.T) { require.Equal(t, uint32(1), spend.SpenderInputIndex) require.Equal(t, int32(99), spend.SpendingHeight) - case <-time.After(2 * time.Second): - t.Fatal("timed out waiting for spend notification") + default: + t.Fatal("historical spend was not available on return") + } +} + +// TestChainBackendSpendRegistrationLookupError verifies that a failed initial +// lookup leaves no registration that a caller could mistake for an unspent +// output. +func TestChainBackendSpendRegistrationLookupError(t *testing.T) { + t.Parallel() + + txid := chainhash.HashH([]byte("funding-tx")) + srv := mockEsploraServer( + t, func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/blocks/tip/height": + _, _ = fmt.Fprint(w, "100") + + case "/block-height/100": + h := chainhash.HashH([]byte("block-100")) + _, _ = fmt.Fprint(w, h.String()) + + default: + http.Error( + w, "backend unavailable", + http.StatusServiceUnavailable, + ) + } + }, + ) + + backend := NewChainBackend( + NewEsploraClient(srv.URL, btclog.Disabled), 50*time.Millisecond, + btclog.Disabled, + ) + require.NoError(t, backend.Start()) + defer func() { + require.NoError(t, backend.Stop()) + }() + + reg, err := backend.RegisterSpend( + t.Context(), &wire.OutPoint{ + Hash: txid, + }, + nil, + 90, + ) + require.ErrorContains(t, err, "initial spend lookup") + require.Nil(t, reg) + + backend.mu.Lock() + activeRegs := len(backend.spendRegs) + backend.mu.Unlock() + require.Zero(t, activeRegs) + + ctx, cancel := context.WithCancel(t.Context()) + cancel() + reg, err = backend.RegisterSpend( + ctx, &wire.OutPoint{ + Hash: txid, + }, + nil, + 90, + ) + require.ErrorIs(t, err, context.Canceled) + require.Nil(t, reg) + + backend.mu.Lock() + activeRegs = len(backend.spendRegs) + backend.mu.Unlock() + require.Zero(t, activeRegs) +} + +// TestChainBackendSpendRegistrationSharedTxTimeout verifies that a spend +// registration respects its context while another caller owns the shared raw +// transaction fetch. +func TestChainBackendSpendRegistrationSharedTxTimeout(t *testing.T) { + t.Parallel() + + txid := chainhash.HashH([]byte("funding-tx")) + spenderTxid := minimalRawTxID(t) + requestStarted := make(chan struct{}) + releaseRequest := make(chan struct{}) + var releaseOnce sync.Once + release := func() { + releaseOnce.Do(func() { close(releaseRequest) }) + } + defer release() + + srv := mockEsploraServer( + t, func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/blocks/tip/height": + _, _ = fmt.Fprint(w, "100") + + case "/block-height/100": + h := chainhash.HashH([]byte("block-100")) + _, _ = fmt.Fprint(w, h.String()) + + case "/tx/" + txid.String() + "/outspend/0": + _ = json.NewEncoder(w).Encode(esploraOutspend{ + Spent: true, + Txid: spenderTxid.String(), + Status: esploraStatus{ + Confirmed: true, + }, + }) + + case "/tx/" + spenderTxid.String() + "/raw": + close(requestStarted) + select { + case <-releaseRequest: + _, _ = w.Write(minimalRawTx()) + + case <-r.Context().Done(): + } + + default: + http.NotFound(w, r) + } + }, + ) + + client := NewEsploraClient(srv.URL, btclog.Disabled) + backend := NewChainBackend(client, time.Second, btclog.Disabled) + require.NoError(t, backend.Start()) + defer func() { + require.NoError(t, backend.Stop()) + }() + + leaderResult := make(chan error, 1) + go func() { + _, err := client.GetRawTx(t.Context(), spenderTxid) + leaderResult <- err + }() + select { + case <-requestStarted: + case <-time.After(time.Second): + t.Fatal("raw transaction request did not start") + } + + ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond) + defer cancel() + registrationResult := make(chan error, 1) + go func() { + reg, err := backend.RegisterSpend( + ctx, &wire.OutPoint{ + Hash: txid, + }, + nil, + 90, + ) + if reg != nil { + reg.Cancel() + } + registrationResult <- err + }() + + var regErr error + select { + case regErr = <-registrationResult: + case <-time.After(500 * time.Millisecond): + release() + regErr = <-registrationResult + t.Fatal("spend registration outlived its context") } + require.ErrorIs(t, regErr, context.DeadlineExceeded) + + release() + require.NoError(t, <-leaderResult) } // minimalRawTx returns a minimal valid serialized Bitcoin diff --git a/lwwallet/esplora.go b/lwwallet/esplora.go index 7036331ee..3ed973948 100644 --- a/lwwallet/esplora.go +++ b/lwwallet/esplora.go @@ -420,8 +420,6 @@ func (c *EsploraClient) GetRawBlockHeader(ctx context.Context, // misses for the same hash are coalesced via rawBlockSF — full // mainnet blocks approach 4 MiB so collapsing a thundering herd is // load-bearing for the rate-limit budget of the Esplora endpoint. -// -//nolint:dupl func (c *EsploraClient) GetRawBlock(ctx context.Context, blockHash chainhash.Hash) (*wire.MsgBlock, error) { @@ -568,8 +566,6 @@ func (c *EsploraClient) GetTxStatus(ctx context.Context, txid chainhash.Hash) ( // Results are memoized in txCache because a confirmed transaction's // contents are content-addressed by its txid. Concurrent misses for // the same txid are coalesced via txSF. -// -//nolint:dupl func (c *EsploraClient) GetRawTx(ctx context.Context, txid chainhash.Hash) ( *wire.MsgTx, error) { @@ -578,7 +574,7 @@ func (c *EsploraClient) GetRawTx(ctx context.Context, txid chainhash.Hash) ( return cached.tx, nil } - v, err, _ := c.txSF.Do(txid.String(), + resultCh := c.txSF.DoChan(txid.String(), func() (interface{}, error) { if cached, cErr := c.txCache.Get( txid, @@ -620,13 +616,20 @@ func (c *EsploraClient) GetRawTx(ctx context.Context, txid chainhash.Hash) ( return &tx, nil }) - if err != nil { - return nil, err + var result singleflight.Result + select { + case result = <-resultCh: + case <-ctx.Done(): + return nil, ctx.Err() + } + if result.Err != nil { + return nil, result.Err } - tx, ok := v.(*wire.MsgTx) + tx, ok := result.Val.(*wire.MsgTx) if !ok { - return nil, fmt.Errorf("raw tx singleflight returned %T", v) + return nil, fmt.Errorf("raw tx singleflight returned %T", + result.Val) } return tx, nil diff --git a/lwwallet/esplora_chain.go b/lwwallet/esplora_chain.go index 605a71622..0111dd338 100644 --- a/lwwallet/esplora_chain.go +++ b/lwwallet/esplora_chain.go @@ -5,6 +5,7 @@ import ( "fmt" "log/slog" "sort" + "strings" "sync" "time" @@ -832,6 +833,10 @@ func (s *EsploraChainService) Rescan(startHash *chainhash.Hash, if err != nil { return fmt.Errorf("get tip height for rescan: %w", err) } + if startHeight > tipHeight { + return fmt.Errorf("rescan start height %d exceeds tip %d", + startHeight, tipHeight) + } s.log.InfoS(ctx, "Starting chain rescan", slog.Int("start_height", int(startHeight)), @@ -842,7 +847,11 @@ func (s *EsploraChainService) Rescan(startHash *chainhash.Hash, // Collect all notifications first, then flush them // asynchronously. See method doc for deadlock rationale. - var pending []interface{} + var ( + pending []interface{} + finalHash chainhash.Hash + finalTime time.Time + ) // Ask the address index which transactions in this range are // relevant, instead of downloading every block and scanning it. @@ -891,6 +900,8 @@ func (s *EsploraChainService) Rescan(startHash *chainhash.Hash, }, Time: time.Unix(blockHeader.Timestamp, 0), } + finalHash = blockHash + finalTime = blockMeta.Time // Build records for whatever the index attributed to this // canonical block. An inconsistent index answer falls back to @@ -962,6 +973,15 @@ func (s *EsploraChainService) Rescan(startHash *chainhash.Hash, ) } + // btcwallet only marks its chain view synchronized after this terminal + // notification. Advancing SyncedTo without it leaves channel funding + // disabled even though every block has been processed. + pending = append(pending, &chain.RescanFinished{ + Hash: &finalHash, + Height: tipHeight, + Time: finalTime, + }) + s.log.InfoS(ctx, "Chain rescan complete", slog.Int("tip_height", int(tipHeight)), slog.Int("pending_notifications", len(pending)), @@ -1219,10 +1239,34 @@ func (s *EsploraChainService) TestMempoolAccept(txns []*wire.MsgTx, return results, nil } -// MapRPCErr passes through errors unchanged since the Esplora backend -// does not use RPC error codes. -func (s *EsploraChainService) MapRPCErr(err error) error { - return err +// MapRPCErr maps Bitcoin Core reject reasons returned by Esplora to the +// sentinel errors expected by btcwallet and lnd. +func (s *EsploraChainService) MapRPCErr(rpcErr error) error { + for code := chain.ErrMissingInputsOrSpent; code <= + chain.ErrBadWitnessNonStandard; code++ { + + if chainErrorMatches(rpcErr, code.Error()) { + return code + } + } + + for message, mappedErr := range chain.Bitcoind28ErrMap { + if chainErrorMatches(rpcErr, message) { + return mappedErr + } + } + + return fmt.Errorf("%w: %w", chain.ErrUndefined, rpcErr) +} + +// chainErrorMatches normalizes Core's dashed reject reasons before matching. +func chainErrorMatches(err error, pattern string) bool { + errText := strings.ReplaceAll(err.Error(), "-", " ") + pattern = strings.ReplaceAll(pattern, "-", " ") + + return strings.Contains( + strings.ToLower(errText), strings.ToLower(pattern), + ) } // handleChainEvents drains the unified chain stream and translates diff --git a/lwwallet/esplora_chain_test.go b/lwwallet/esplora_chain_test.go index 10737b818..6fbb10d1c 100644 --- a/lwwallet/esplora_chain_test.go +++ b/lwwallet/esplora_chain_test.go @@ -5,6 +5,7 @@ import ( "context" "encoding/hex" "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" @@ -21,6 +22,35 @@ import ( "github.com/stretchr/testify/require" ) +// TestEsploraChainServiceMapRPCErr verifies that Esplora's textual Core +// reject reasons retain the error identities consumed by lnd's sweeper. +func TestEsploraChainServiceMapRPCErr(t *testing.T) { + t.Parallel() + + service := &EsploraChainService{} + require.ErrorIs( + t, + service.MapRPCErr( + errors.New("missing-inputs"), + ), + chain.ErrMissingInputs, + ) + require.ErrorIs( + t, + service.MapRPCErr( + errors.New("mempool script verify flag failed"), + ), + chain.ErrNonMandatoryScriptVerifyFlag, + ) + require.ErrorIs( + t, + service.MapRPCErr( + errors.New("unknown rejection"), + ), + chain.ErrUndefined, + ) +} + // TestEsploraChainServiceStopCancelsRequestContext verifies that Stop cancels // the context used by chain.Interface methods. Btcwallet waits for its recovery // goroutine before it stops the chain client, so lwwallet must be able to diff --git a/lwwallet/esplora_filterblocks_test.go b/lwwallet/esplora_filterblocks_test.go index e7c018540..a140c4808 100644 --- a/lwwallet/esplora_filterblocks_test.go +++ b/lwwallet/esplora_filterblocks_test.go @@ -957,6 +957,12 @@ func TestRescanUsesIndexAndOrdersDependencies(t *testing.T) { t, svc.notifications, ) require.Equal(t, meta.Hash, wtxmgr.BlockMeta(connected).Hash) + + finished := requireNotification[*chain.RescanFinished]( + t, svc.notifications, + ) + require.Equal(t, meta.Hash, *finished.Hash) + require.Equal(t, meta.Height, finished.Height) require.Zero(t, idx.rawBlockFetches) } diff --git a/lwwallet/esplora_rescan_watch_test.go b/lwwallet/esplora_rescan_watch_test.go index 120454c9c..34cb88930 100644 --- a/lwwallet/esplora_rescan_watch_test.go +++ b/lwwallet/esplora_rescan_watch_test.go @@ -43,14 +43,16 @@ func TestRescanRetainsLiveChangeWatch(t *testing.T) { start := stub.hashFor(100) require.NoError(t, service.Rescan(&start, addresses, nil)) - // Drain the historical scan before driving the next live block. - for range 2 { - select { - case <-service.Notifications(): - case <-time.After(time.Second): - t.Fatal("missing historical rescan notification") - } - } + // Rescan flushes asynchronously. Validate the historical block pair + // and terminal event before driving the next live block. + historical := readSpendWatchBlock(t, service) + finished := requireNotification[*chain.RescanFinished]( + t, service.Notifications(), + ) + require.Equal(t, historical.Block.Height, finished.Height) + require.Equal(t, historical.Block.Hash, *finished.Hash) + require.Equal(t, historical.Block.Time, finished.Time) + script, err := txscript.PayToAddrScript(addresses[1]) require.NoError(t, err) funding := wire.OutPoint{Hash: chainhash.Hash{1}, Index: 0} @@ -75,19 +77,12 @@ func TestRescanRetainsLiveChangeWatch(t *testing.T) { stub.tipHeight = 101 stub.mu.Unlock() service.processTipEvent(t.Context(), tipEventFor(stub, 101)) - select { - case notification := <-service.Notifications(): - filtered, ok := notification.(chain.FilteredBlockConnected) - require.True(t, ok) - require.EqualValues(t, 101, filtered.Block.Height) - require.Len(t, filtered.RelevantTxs, 1) - require.Equal(t, spend.TxHash(), filtered.RelevantTxs[0].Hash) - require.Equal( - t, funding, - filtered.RelevantTxs[0].MsgTx.TxIn[0].PreviousOutPoint, - ) - - case <-time.After(time.Second): - t.Fatal("rescan change address missing from live notifications") - } + filtered := readSpendWatchBlock(t, service) + require.EqualValues(t, 101, filtered.Block.Height) + require.Len(t, filtered.RelevantTxs, 1) + require.Equal(t, spend.TxHash(), filtered.RelevantTxs[0].Hash) + require.Equal( + t, funding, + filtered.RelevantTxs[0].MsgTx.TxIn[0].PreviousOutPoint, + ) } diff --git a/lwwallet/esplora_spend_watch_test.go b/lwwallet/esplora_spend_watch_test.go index 83083ede5..c808c0d18 100644 --- a/lwwallet/esplora_spend_watch_test.go +++ b/lwwallet/esplora_spend_watch_test.go @@ -50,10 +50,14 @@ func readSpendWatchBlock(t *testing.T, if i == 0 { var ok bool filtered, ok = n.(chain.FilteredBlockConnected) - require.True(t, ok) + require.True( + t, ok, "unexpected notification %T", n, + ) } else { _, ok := n.(chain.BlockConnected) - require.True(t, ok) + require.True( + t, ok, "unexpected notification %T", n, + ) } case <-time.After(time.Second): @@ -114,7 +118,20 @@ func TestLiveWatchesIncludeInputOnlySpends(t *testing.T) { require.NoError( t, service.Rescan(&start, addresses, coins), ) - readSpendWatchBlock(t, service) + historical := readSpendWatchBlock(t, service) + + // Rescan flushes asynchronously. Observe its terminal + // event before delivering a live block to the same + // notification queue. + finished := requireNotification[*chain.RescanFinished]( + t, service.Notifications(), + ) + require.Equal( + t, historical.Block.Height, finished.Height, + ) + require.Equal(t, historical.Block.Hash, *finished.Hash) + require.Equal(t, historical.Block.Time, finished.Time) + height := int32(101) if mode == "live output" { installSpendWatchBlock(stub, height, funding)