Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 56 additions & 31 deletions lwwallet/chain_backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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()

Expand All @@ -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 {
Expand All @@ -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.
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}
}
}

Expand All @@ -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
Expand All @@ -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
}
Expand Down
176 changes: 172 additions & 4 deletions lwwallet/chain_backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package lwwallet

import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"fmt"
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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
Expand Down
Loading
Loading