What changed, and why it matters
This commit changes how LND's wallet RPC lets users lock (lease) unspent bitcoin outputs. It adds a new 'no expiry' mode where a lease stays active until the output is spent and confirmed, instead of expiring after a set number of seconds. The change also removes an older confirmation-count based field from some responses and adds clearer error messages for conflicting lease settings. It is primarily a feature/API refactor, not a clear security fix or vulnerability.
Treat as a normal feature/API change. Review the generated protobuf changes (not shown) to confirm the new NoExpiry fields and removed count fields are correctly versioned. Ensure callers cannot accidentally create permanent locks by misusing the flag, and verify that owner-ID validation prevents the internal LND lock ID from being used for no-expiry leases.
Security signals we found
New RPC option changes lease lifetime semantics (no wall-clock expiry)
Stable error identities added for conflicting lease parameters and invalid owner IDs
Custom lock ID now required for persistent no-expiry input leases, with checks for zero and reserved internal IDs
Same-owner renewal preserves existing no-expiry/timed policy via readback
Old confirmation-count integration test removed; count response assignments retired
Evidence from the diff
The patch introduces a NoExpiry boolean flag to LeaseOutput and FundPsbt requests, mapping it internally to a release-after-spend-depth of 1 (noExpiryLeaseDepth). It reuses existing wallet lease acquisition and rollback logic, adds stable sentinel errors for conflicting lifetime settings and invalid custom lock IDs, and reports the effective policy via a NoExpiry boolean in responses. The old InputReleaseAfterSpendConfs / ReleaseAfterSpendConfs count-based fields are removed from the RPC integration test and response assignments, and the confirmation-count integration test is deleted. Unit tests cover acquisition, validation, same-owner renewal, and error identities.
Changed components
lnrpc/walletrpc/walletkit_server.golnrpc/walletrpc/walletkit_server_test.goitest/lnd_psbt_test.goitest/list_on_test.goInspect captured patch +325 / −273
### itest/list_on_test.go
@@ -326,10 +326,6 @@ var allTestCases = []*lntest.TestCase{
Name: "fund psbt custom lock",
TestFunc: testFundPsbtCustomLock,
},
- {
- Name: "fund psbt confirmation lease",
- TestFunc: testFundPsbtConfirmationLease,
- },
{
Name: "resolution handoff",
TestFunc: testResHandoff,
### itest/lnd_psbt_test.go
@@ -3,8 +3,6 @@ package itest
import (
"bytes"
"encoding/hex"
- "errors"
- "fmt"
"testing"
"time"
@@ -26,7 +24,6 @@ import (
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
"github.com/lightningnetwork/lnd/lntest"
"github.com/lightningnetwork/lnd/lntest/node"
- "github.com/lightningnetwork/lnd/lntest/wait"
"github.com/lightningnetwork/lnd/lnwallet/chanfunding"
"github.com/stretchr/testify/require"
)
@@ -2044,148 +2041,3 @@ func testFundPsbtCustomLock(ht *lntest.HarnessTest) {
leasesRespAfter := alice.RPC.ListLeases()
require.Empty(ht, leasesRespAfter.LockedUtxos)
}
-
-// testFundPsbtConfirmationLease verifies the complete persisted lease
-// lifecycle. The lease must survive wall-clock expiry before confirmation, a
-// shallow reorg, and a node restart, then release at its requested spend depth.
-func testFundPsbtConfirmationLease(ht *lntest.HarnessTest) {
- const (
- releaseDepth = uint32(3)
- lockDurationSecond = uint64(1)
- )
-
- alice := ht.NewNodeWithCoins("Alice", nil)
- lockID := ht.Random32Bytes()
- aliceAddr := alice.RPC.NewAddress(&lnrpc.NewAddressRequest{
- Type: lnrpc.AddressType_WITNESS_PUBKEY_HASH,
- })
-
- fundResp := alice.RPC.FundPsbt(&walletrpc.FundPsbtRequest{
- Template: &walletrpc.FundPsbtRequest_Raw{
- Raw: &walletrpc.TxTemplate{
- Outputs: map[string]uint64{
- aliceAddr.Address: 100_000,
- },
- },
- },
- Fees: &walletrpc.FundPsbtRequest_SatPerVbyte{
- SatPerVbyte: 2,
- },
- MinConfs: 1,
- CustomLockId: lockID,
- LockExpirationSeconds: lockDurationSecond,
- InputReleaseAfterSpendConfs: releaseDepth,
- })
- require.NotEmpty(ht, fundResp.LockedUtxos)
- for _, lease := range fundResp.LockedUtxos {
- require.Equal(ht, releaseDepth, lease.ReleaseAfterSpendConfs)
- require.Zero(ht, lease.ConfirmedSpendHeight)
- }
-
- // assertLeaseState waits for every lease created by this request to
- // report the expected persisted spend height.
- assertLeaseState := func(expectedSpendHeight int32) {
- err := wait.NoError(func() error {
- leases := alice.RPC.ListLeases().LockedUtxos
- if len(leases) != len(fundResp.LockedUtxos) {
- return fmt.Errorf("expected %d leases, got %d",
- len(fundResp.LockedUtxos), len(leases))
- }
-
- for _, lease := range leases {
- if !bytes.Equal(lockID, lease.Id) {
- return fmt.Errorf(
- "lease ID %x", lease.Id,
- )
- }
- if lease.Expiration == 0 {
- return errors.New("zero expiration")
- }
- if lease.ReleaseAfterSpendConfs !=
- releaseDepth {
-
- return fmt.Errorf(
- "depth: want %d, got %d",
- releaseDepth,
- lease.ReleaseAfterSpendConfs,
- )
- }
- if lease.ConfirmedSpendHeight !=
- expectedSpendHeight {
-
- return fmt.Errorf(
- "height: want %d, got %d",
- expectedSpendHeight,
- lease.ConfirmedSpendHeight,
- )
- }
- }
-
- return nil
- }, defaultTimeout)
- require.NoError(ht, err)
- }
-
- // assertLeaseReleased waits until spend maturity removes every lease
- // created by this request.
- assertLeaseReleased := func() {
- err := wait.NoError(func() error {
- leases := alice.RPC.ListLeases().LockedUtxos
- if len(leases) != 0 {
- return fmt.Errorf("expected no leases, got %d",
- len(leases))
- }
-
- return nil
- }, defaultTimeout)
- require.NoError(ht, err)
- }
-
- // Let the wall-clock deadline pass before broadcasting. A
- // confirmation-controlled lease must remain active for this entire gap.
- time.Sleep(2 * time.Second)
- assertLeaseState(0)
-
- finalizeResp := alice.RPC.FinalizePsbt(
- &walletrpc.FinalizePsbtRequest{
- FundedPsbt: fundResp.FundedPsbt,
- },
- )
- alice.RPC.PublishTransaction(&walletrpc.Transaction{
- TxHex: finalizeResp.RawFinalTx,
- })
-
- var finalTx wire.MsgTx
- err := finalTx.Deserialize(bytes.NewReader(finalizeResp.RawFinalTx))
- require.NoError(ht, err)
-
- spendBlock := ht.MineBlocksAndAssertNumTxes(1, 1)[0]
- spendHeight := int32(ht.CurrentHeight())
- ht.AssertTxInBlock(spendBlock, finalTx.TxHash())
- assertLeaseState(spendHeight)
-
- // Disconnect the spending block and extend the replacement chain
- // without the transaction. The lease must retain its disconnected-spend
- // marker.
- spendBlockHash := spendBlock.BlockHash()
- require.NoError(ht, ht.Miner().InvalidateBlock(&spendBlockHash))
- ht.MineEmptyBlocks(2)
- assertLeaseState(-1)
-
- // The disconnected state is durable across process restart.
- ht.RestartNode(alice)
- assertLeaseState(-1)
-
- // Reconfirm the transaction. The lease remains through depth two and is
- // released when the third confirmation connects.
- reconfirmedBlock := ht.MineBlocksAndAssertNumTxes(1, 1)[0]
- reconfirmedHeight := int32(ht.CurrentHeight())
- ht.AssertTxInBlock(reconfirmedBlock, finalTx.TxHash())
- assertLeaseState(reconfirmedHeight)
-
- ht.MineEmptyBlocks(1)
- assertLeaseState(reconfirmedHeight)
-
- ht.MineEmptyBlocks(1)
- assertLeaseReleased()
-}
### lnrpc/walletrpc/walletkit_server.go
@@ -52,7 +52,31 @@ import (
"gopkg.in/macaroon-bakery.v2/bakery"
)
+// noExpiryLeaseDepth reuses the wallet's no-timeout lifetime with cleanup at
+// the first confirmed spend, without adding another persisted lease policy.
+const noExpiryLeaseDepth uint32 = 1
+
var (
+ // errLeaseLifetimeConflict gives both handlers a stable identity for
+ // no-expiry requests that also select a competing duration.
+ errLeaseLifetimeConflict = errors.New("no-expiry cannot be combined " +
+ "with a duration")
+
+ // errMissingCustomLockID keeps missing-owner rejection independent of
+ // the diagnostic wording returned to RPC clients.
+ errMissingCustomLockID = errors.New("custom lock ID required for " +
+ "no-expiry input leases")
+
+ // errZeroCustomLockID keeps zero-owner rejection identifiable when its
+ // diagnostic wording changes.
+ errZeroCustomLockID = errors.New("custom lock ID must not be all " +
+ "zeros for no-expiry input leases")
+
+ // errReservedCustomLockID gives reserved-owner rejection a stable
+ // identity distinct from missing and zero owner IDs.
+ errReservedCustomLockID = errors.New("reserved custom lock ID cannot " +
+ "be used for no-expiry input leases")
+
// macaroonOps are the set of capabilities that our minted macaroon (if
// it doesn't already exist) will have.
macaroonOps = []bakery.Op{
@@ -476,6 +500,8 @@ func (w *WalletKit) ListUnspent(ctx context.Context,
// lock's expiration is returned. The expiration of the lock can be extended by
// successive invocations of this call. Outputs can be unlocked before their
// expiration through `ReleaseOutput`.
+// NoExpiry instead reserves the unused output without a timeout until owner
+// release or its first confirmed spend.
//
// If the output is not known, wtxmgr.ErrUnknownOutput is returned. If the
// output has already been locked to a different ID, then
@@ -510,7 +536,16 @@ func (w *WalletKit) LeaseOutput(ctx context.Context,
if req.ExpirationSeconds != 0 {
duration = time.Duration(req.ExpirationSeconds) * time.Second
}
- releaseAfterSpendConfs := req.ReleaseAfterSpendConfs
+
+ // Only the explicit flag selects the wallet's depth-one no-timeout
+ // lifetime. Reject durations that imply an expiry for this mode.
+ var releaseAfterSpendConfs uint32
+ if req.NoExpiry {
+ if req.ExpirationSeconds != 0 {
+ return nil, errLeaseLifetimeConflict
+ }
+ releaseAfterSpendConfs = noExpiryLeaseDepth
+ }
// Acquire the global coin selection lock to ensure there aren't any
// other concurrent processes attempting to lease the same UTXO.
@@ -543,28 +578,28 @@ func (w *WalletKit) LeaseOutput(ctx context.Context,
return nil, err
}
- // A zero-depth same-owner renewal preserves any existing confirmation
- // depth. Read it after the lease succeeds so this informational field
- // cannot prevent a legacy lease or extend the coin selection lock.
+ // A same-owner renewal preserves an existing no-expiry lifetime. Read
+ // it after success so informational readback cannot prevent acquisition
+ // or extend the coin selection lock.
if releaseAfterSpendConfs == 0 {
depth, err := storedLeaseDepth(w.cfg.Wallet, lockID, *op)
if err != nil {
- log.Warnf("Unable to report retained confirmation "+
- "depth for lease %v: %v", op, err)
+ log.Warnf("Unable to report no-expiry policy "+
+ "for lease %v: %v", op, err)
} else {
releaseAfterSpendConfs = depth
}
}
return &LeaseOutputResponse{
- Expiration: uint64(expiration.Unix()),
- ReleaseAfterSpendConfs: releaseAfterSpendConfs,
+ Expiration: uint64(expiration.Unix()),
+ NoExpiry: releaseAfterSpendConfs ==
+ noExpiryLeaseDepth,
}, nil
}
-// storedLeaseDepth returns the confirmation depth of an existing lease owned
-// by lockID. It lets a zero-depth renewal report the depth that the legacy
-// wallet lease method preserves.
+// storedLeaseDepth returns the wallet lifetime of an existing lease owned by
+// lockID so a renewal can acknowledge a preserved no-expiry reservation.
func storedLeaseDepth(wallet lnwallet.WalletController, lockID wtxmgr.LockID,
op wire.OutPoint) (uint32, error) {
@@ -1694,6 +1729,16 @@ func (w *WalletKit) LabelTransaction(ctx context.Context,
func (w *WalletKit) FundPsbt(_ context.Context,
req *FundPsbtRequest) (*FundPsbtResponse, error) {
+ // Normalize the explicit no-timeout option once so every funding mode
+ // uses the existing capability, owner checks, and acquisition rollback.
+ var releaseAfterSpendConfs uint32
+ if req.InputLeaseNoExpiry {
+ if req.LockExpirationSeconds != 0 {
+ return nil, errLeaseLifetimeConflict
+ }
+ releaseAfterSpendConfs = noExpiryLeaseDepth
+ }
+
var customLockID *wtxmgr.LockID
if len(req.CustomLockId) > 0 {
lockID := wtxmgr.LockID{}
@@ -1706,23 +1751,16 @@ func (w *WalletKit) FundPsbt(_ context.Context,
customLockID = &lockID
}
- if req.InputReleaseAfterSpendConfs > 0 {
+ if releaseAfterSpendConfs > 0 {
switch {
case customLockID == nil:
- return nil, errors.New("custom lock ID required for " +
- "confirmation-controlled input leases")
+ return nil, errMissingCustomLockID
case *customLockID == (wtxmgr.LockID{}):
- return nil, errors.New(
- "custom lock ID must not be all zeros for " +
- "confirmation-controlled input leases",
- )
+ return nil, errZeroCustomLockID
case *customLockID == chanfunding.LndInternalLockID:
- return nil, errors.New(
- "reserved custom lock ID cannot be used for " +
- "confirmation-controlled input leases",
- )
+ return nil, errReservedCustomLockID
}
}
@@ -1809,7 +1847,7 @@ func (w *WalletKit) FundPsbt(_ context.Context,
account, keyScopeFromChangeAddressType(req.ChangeType),
packet, minConfs, feeSatPerKW, coinSelectionStrategy,
customLockID, customLockDuration,
- req.InputReleaseAfterSpendConfs,
+ releaseAfterSpendConfs,
)
// The template is specified as a PSBT with the intention to perform
@@ -1902,7 +1940,7 @@ func (w *WalletKit) FundPsbt(_ context.Context,
account, changeIndex, packet, minConfs, changeType,
feeSatPerKW, coinSelectionStrategy, maxFeeRatio,
customLockID, customLockDuration,
- req.InputReleaseAfterSpendConfs,
+ releaseAfterSpendConfs,
)
// The template is specified as a RPC message. We need to create a new
@@ -1961,7 +1999,7 @@ func (w *WalletKit) FundPsbt(_ context.Context,
account, keyScopeFromChangeAddressType(req.ChangeType),
packet, minConfs, feeSatPerKW, coinSelectionStrategy,
customLockID, customLockDuration,
- req.InputReleaseAfterSpendConfs,
+ releaseAfterSpendConfs,
)
default:
@@ -2371,11 +2409,12 @@ func (w *WalletKit) lockAndCreateFundingResponse(packet *psbt.Packet,
return nil, fmt.Errorf("could not lock inputs: %w", err)
}
- // Convert the lock leases to the RPC format.
- rpcLocks := marshallLeases(locks)
- for _, lock := range rpcLocks {
+ // Newly acquired results lack the configured depth. Populate it before
+ // marshalling so FundPsbt and ListLeases share one readback path.
+ for _, lock := range locks {
lock.ReleaseAfterSpendConfs = releaseAfterSpendConfs
}
+ rpcLocks := marshallLeases(locks)
return &FundPsbtResponse{
FundedPsbt: buf.Bytes(),
@@ -2453,7 +2492,8 @@ func (w *WalletKit) handleChange(packet *psbt.Packet, changeIndex int32,
return newChangeIndex, nil
}
-// marshallLeases converts the lock leases to the RPC format.
+// marshallLeases converts lease results to RPC metadata, acknowledging the
+// wallet's first-confirmed-spend lifetime through the no-expiry boolean.
func marshallLeases(locks []*base.ListLeasedOutputResult) []*UtxoLease {
rpcLocks := make([]*UtxoLease, len(locks))
for idx, lock := range locks {
@@ -2463,11 +2503,12 @@ func marshallLeases(locks []*base.ListLeasedOutputResult) []*UtxoLease {
Outpoint: lnrpc.MarshalOutPoint(
&lock.Outpoint,
),
- Expiration: uint64(lock.Expiration.Unix()),
- PkScript: lock.PkScript,
- Value: uint64(lock.Value),
- ReleaseAfterSpendConfs: lock.ReleaseAfterSpendConfs,
- ConfirmedSpendHeight: lock.ConfirmedSpendHeight,
+ Expiration: uint64(lock.Expiration.Unix()),
+ PkScript: lock.PkScript,
+ Value: uint64(lock.Value),
+ ConfirmedSpendHeight: lock.ConfirmedSpendHeight,
+ NoExpiry: lock.ReleaseAfterSpendConfs ==
+ noExpiryLeaseDepth,
}
}
### lnrpc/walletrpc/walletkit_server_test.go
@@ -26,37 +26,63 @@ import (
"github.com/lightningnetwork/lnd/lnwallet"
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
"github.com/lightningnetwork/lnd/lnwallet/chanfunding"
+ testifymock "github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
-// TestMarshallLeasesIncludesSpendProgress verifies that ListLeases exposes
-// each confirmation-controlled lease's persisted spend progress.
+// TestMarshallLeasesIncludesSpendProgress verifies that lease responses
+// report the no-expiry lifetime alongside the stored spend height.
func TestMarshallLeasesIncludesSpendProgress(t *testing.T) {
t.Parallel()
- testCases := []int32{0, 123, -1}
- for _, spendHeight := range testCases {
- testName := fmt.Sprintf("height %d", spendHeight)
+ testCases := []struct {
+ depth uint32
+ spendHeight int32
+ noExpiry bool
+ }{
+ {
+ depth: 0,
+ spendHeight: 0,
+ noExpiry: false,
+ },
+ {
+ depth: 1,
+ spendHeight: 123,
+ noExpiry: true,
+ },
+ }
+ for _, testCase := range testCases {
+ testName := fmt.Sprintf("depth %d", testCase.depth)
t.Run(testName, func(t *testing.T) {
t.Parallel()
+ // Arrange timed and no-expiry wallet lifetimes so their
+ // response flags can distinguish them without a count.
lockedOutput := &wtxmgr.LockedOutput{
Outpoint: wire.OutPoint{Index: 2},
LockID: wtxmgr.LockID{1},
Expiration: time.Unix(123, 0),
- ReleaseAfterSpendConfs: 6,
- ConfirmedSpendHeight: spendHeight,
+ ReleaseAfterSpendConfs: testCase.depth,
+ ConfirmedSpendHeight: testCase.spendHeight,
}
locks := []*wallet.ListLeasedOutputResult{{
LockedOutput: lockedOutput,
Value: 1000,
PkScript: []byte{0x51},
}}
+ // Act by converting the same lease metadata returned by
+ // funding and listing through their shared marshaller.
rpcLocks := marshallLeases(locks)
+
+ // Assert the boolean reports the lifetime and preserves
+ // the independent spend-height readback.
require.Len(t, rpcLocks, 1)
require.Equal(
- t, spendHeight,
+ t, testCase.noExpiry, rpcLocks[0].NoExpiry,
+ )
+ require.Equal(
+ t, testCase.spendHeight,
rpcLocks[0].ConfirmedSpendHeight,
)
})
@@ -104,20 +130,109 @@ type mockCoinSelectionLocker struct {
fail bool
}
-// renewalWallet returns a persisted lease after extending it through the
-// legacy lease method.
-type renewalWallet struct {
- *leaseOptionsWallet
+// noExpiryLeaseWallet checks lease acquisition and renewal through the public
+// handler without substituting another implementation of lease lifetime rules.
+type noExpiryLeaseWallet struct {
+ lnwallet.WalletController
+ testifymock.Mock
+}
- leases []*wallet.ListLeasedOutputResult
- listErr error
+var _ lnwallet.OutputLeaserWithOptions = (*noExpiryLeaseWallet)(nil)
+
+// LeaseOutput models renewal through the existing zero-option wallet path.
+func (w *noExpiryLeaseWallet) LeaseOutput(id wtxmgr.LockID, op wire.OutPoint,
+ duration time.Duration) (time.Time, error) {
+
+ args := w.Called(id, op, duration)
+ expiration, _ := args.Get(0).(time.Time)
+ return expiration, args.Error(1)
+}
+
+// LeaseOutputWithOptions checks the persisted lifetime requested by the RPC.
+func (w *noExpiryLeaseWallet) LeaseOutputWithOptions(id wtxmgr.LockID,
+ op wire.OutPoint, duration time.Duration,
+ opts lnwallet.LeaseOutputOptions) (time.Time, error) {
+
+ args := w.Called(id, op, duration, opts)
+ expiration, _ := args.Get(0).(time.Time)
+ return expiration, args.Error(1)
}
-// ListLeasedOutputs returns the persisted leases visible after renewal.
-func (w *renewalWallet) ListLeasedOutputs() (
+// ListLeasedOutputs provides the effective policy after a same-owner renewal.
+func (w *noExpiryLeaseWallet) ListLeasedOutputs() (
[]*wallet.ListLeasedOutputResult, error) {
- return w.leases, w.listErr
+ args := w.Called()
+ leases, _ := args.Get(0).([]*wallet.ListLeasedOutputResult)
+ return leases, args.Error(1)
+}
+
+// TestLeaseOutputNoExpiry verifies the explicit flag acquires the wallet's
+// no-timeout lifetime and reports that policy to clients.
+func TestLeaseOutputNoExpiry(t *testing.T) {
+ t.Parallel()
+
+ // Arrange an exact wallet expectation and use the real coin-selection
+ // mutex so only the optional wallet capability needs to be mocked.
+ id := wtxmgr.LockID{1}
+ op := wire.OutPoint{Index: 1}
+ controller := &noExpiryLeaseWallet{}
+ defer controller.AssertExpectations(t)
+ controller.On(
+ "LeaseOutputWithOptions", id, op,
+ chanfunding.DefaultLockDuration,
+ lnwallet.LeaseOutputOptions{ReleaseAfterSpendConfs: 1},
+ ).Return(time.Unix(123, 0), nil).Once()
+ server := &WalletKit{cfg: &Config{
+ Wallet: controller,
+ CoinSelectionLocker: &lnwallet.LightningWallet{},
+ }}
+
+ // Act with no duration: the flag alone chooses the
+ // persisted reservation, without requiring a user-supplied count.
+ resp, err := server.LeaseOutput(t.Context(), &LeaseOutputRequest{
+ Id: id[:],
+ Outpoint: &lnrpc.OutPoint{
+ TxidBytes: op.Hash[:],
+ OutputIndex: op.Index,
+ },
+ NoExpiry: true,
+ })
+
+ // Assert the new response field acknowledges the installed policy;
+ // deferred mock verification checks the exact owner and lifetime once.
+ require.NoError(t, err)
+ require.True(t, resp.NoExpiry)
+}
+
+// TestLeaseOutputRejectsNoExpiryConflicts verifies both lease RPCs reject
+// competing lifetime settings before touching wallet state.
+func TestLeaseOutputRejectsNoExpiryConflicts(t *testing.T) {
+ t.Parallel()
+
+ // Arrange without a wallet so validation must reject the conflicting
+ // lifetimes before either handler can acquire a reservation.
+ server := &WalletKit{cfg: &Config{}}
+
+ // Act through both public request forms with a duration that cannot
+ // apply to the explicitly requested no-expiry lifetime.
+ _, leaseErr := server.LeaseOutput(t.Context(), &LeaseOutputRequest{
+ Id: bytes.Repeat([]byte{1}, 32),
+ Outpoint: &lnrpc.OutPoint{
+ TxidBytes: make([]byte, 32),
+ },
+ NoExpiry: true,
+ ExpirationSeconds: 1,
+ })
+ _, fundErr := server.FundPsbt(t.Context(), &FundPsbtRequest{
+ InputLeaseNoExpiry: true,
+ LockExpirationSeconds: 1,
+ })
+
+ // Assert both handlers expose the shared identity, so clients and
+ // regression coverage do not depend on diagnostic wording.
+ require.ErrorIs(t, leaseErr, errLeaseLifetimeConflict)
+ require.ErrorIs(t, fundErr, errLeaseLifetimeConflict)
}
// WithCoinSelectLock runs the callback and optionally returns a test error.
@@ -138,139 +253,187 @@ func (m *mockCoinSelectionLocker) WithCoinSelectLock(f func() error) error {
func TestLeaseOutputRejectsUnsupportedOptions(t *testing.T) {
t.Parallel()
- wallet := &legacyLeaseWallet{
- WalletController: &mock.WalletController{},
- }
- rpcServer, _, err := New(&Config{
- Wallet: &lnwallet.LightningWallet{
- WalletController: wallet,
- },
- CoinSelectionLocker: &mockCoinSelectionLocker{},
- })
- require.NoError(t, err)
+ // Arrange a concrete wallet with no underlying optional leaser. The
+ // existing resolver must reject it without invoking a wallet method.
+ rpcServer := &WalletKit{cfg: &Config{
+ Wallet: &lnwallet.LightningWallet{},
+ CoinSelectionLocker: &lnwallet.LightningWallet{},
+ }}
- _, err = rpcServer.LeaseOutput(t.Context(), &LeaseOutputRequest{
+ // Act with only the no-expiry flag so a competing duration cannot
+ // obscure the missing wallet capability.
+ _, err := rpcServer.LeaseOutput(t.Context(), &LeaseOutputRequest{
Id: bytes.Repeat([]byte{1}, 32),
Outpoint: &lnrpc.OutPoint{
TxidBytes: make([]byte, 32),
OutputIndex: 1,
},
- ExpirationSeconds: 60,
- ReleaseAfterSpendConfs: 6,
+ NoExpiry: true,
})
+
+ // Assert the capability error rather than accepting a timed fallback;
+ // the unconfigured wallet would fail if the handler called through it.
require.ErrorIs(t, err, errOutputLeaseOptionsUnsupported)
- require.Zero(t, wallet.leaseCalls,
- "unsupported options must not create a shorter legacy lease")
}
-// TestLeaseOutputReturnsEffectiveRenewalDepth verifies that renewing an
-// existing confirmation-controlled lease through the legacy zero-depth path
-// reports the non-zero depth retained by the wallet.
+// TestLeaseOutputReturnsEffectiveRenewalDepth verifies a same-owner renewal
+// acknowledges the timed or no-expiry lifetime preserved by the wallet.
func TestLeaseOutputReturnsEffectiveRenewalDepth(t *testing.T) {
t.Parallel()
- lockID := wtxmgr.LockID{1}
- outpoint := wire.OutPoint{Index: 1}
- controller := &renewalWallet{
- leaseOptionsWallet: &leaseOptionsWallet{
- WalletController: &mock.WalletController{},
+ testCases := []struct {
+ depth uint32
+ noExpiry bool
+ }{
+ {
+ depth: 1,
+ noExpiry: true,
},
- leases: []*wallet.ListLeasedOutputResult{{
- LockedOutput: &wtxmgr.LockedOutput{
+ {
+ depth: 0,
+ noExpiry: false,
+ },
+ }
+ for _, testCase := range testCases {
+ name := fmt.Sprintf("depth %d", testCase.depth)
+ t.Run(name, func(t *testing.T) {
+ t.Parallel()
+
+ // Arrange a zero-option renewal and one readback of its
+ // stored lifetime, with the real coin-selection mutex.
+ lockID := wtxmgr.LockID{1}
+ outpoint := wire.OutPoint{Index: 1}
+ controller := &noExpiryLeaseWallet{}
+ defer controller.AssertExpectations(t)
+ controller.On(
+ "LeaseOutput", lockID, outpoint, time.Minute,
+ ).Return(time.Unix(123, 0), nil).Once()
+ lockedOutput := &wtxmgr.LockedOutput{
Outpoint: outpoint,
LockID: lockID,
- ReleaseAfterSpendConfs: 6,
- },
- }},
- }
- rpcServer, _, err := New(&Config{
- Wallet: controller,
- CoinSelectionLocker: &mockCoinSelectionLocker{},
- })
- require.NoError(t, err)
+ ReleaseAfterSpendConfs: testCase.depth,
+ }
+ leases := []*wallet.ListLeasedOutputResult{
+ {
+ LockedOutput: lockedOutput,
+ },
+ }
+ controller.On("ListLeasedOutputs").Return(
+ leases, nil,
+ ).Once()
+ locker := &lnwallet.LightningWallet{}
+ server := &WalletKit{cfg: &Config{
+ Wallet: controller,
+ CoinSelectionLocker: locker,
+ }}
- resp, err := rpcServer.LeaseOutput(t.Context(), &LeaseOutputRequest{
- Id: lockID[:],
- Outpoint: &lnrpc.OutPoint{
- TxidBytes: make([]byte, 32),
- OutputIndex: outpoint.Index,
- },
- ExpirationSeconds: 60,
- })
- require.NoError(t, err)
- require.Equal(t, uint32(6), resp.ReleaseAfterSpendConfs)
- require.Equal(t, 1, controller.legacyCalls)
+ // Act without a new policy: the existing lease
+ // must keep its persisted lifetime on this renewal.
+ resp, err := server.LeaseOutput(
+ t.Context(), &LeaseOutputRequest{
+ Id: lockID[:],
+ Outpoint: &lnrpc.OutPoint{
+ TxidBytes: outpoint.Hash[:],
+ OutputIndex: outpoint.Index,
+ },
+ ExpirationSeconds: 60,
+ },
+ )
+
+ // Assert the boolean describes the retained lifetime,
+ // even though the renewal omitted the no-expiry flag.
+ require.NoError(t, err)
+ require.Equal(t, testCase.noExpiry, resp.NoExpiry)
+ })
+ }
}
-// TestLeaseOutputIgnoresRenewalDepthReadError verifies an informational depth
-// lookup cannot prevent a successful legacy lease.
+// TestLeaseOutputIgnoresRenewalDepthReadError verifies that failed policy
+// readback cannot turn successful lease acquisition into an RPC failure.
func TestLeaseOutputIgnoresRenewalDepthReadError(t *testing.T) {
t.Parallel()
+ // Arrange a successful renewal followed by failed policy readback.
+ // Reuse the wallet mock so both calls are checked without another
+ // implementation of the wallet interface.
lockID := wtxmgr.LockID{1}
- controller := &renewalWallet{
- leaseOptionsWallet: &leaseOptionsWallet{
- WalletController: &mock.WalletController{},
- },
- listErr: errors.New("list leases failed"),
- }
- rpcServer, _, err := New(&Config{
+ outpoint := wire.OutPoint{}
+ controller := &noExpiryLeaseWallet{}
+ defer controller.AssertExpectations(t)
+ controller.On(
+ "LeaseOutput", lockID, outpoint, time.Minute,
+ ).Return(time.Unix(123, 0), nil).Once()
+ controller.On("ListLeasedOutputs").Return(
+ []*wallet.ListLeasedOutputResult(nil),
+ errors.New("list leases failed"),
+ ).Once()
+ rpcServer := &WalletKit{cfg: &Config{
Wallet: controller,
- CoinSelectionLocker: &mockCoinSelectionLocker{},
- })
- require.NoError(t, err)
+ CoinSelectionLocker: &lnwallet.LightningWallet{},
+ }}
+ // Act through the timed renewal path, which reads the retained policy
+ // after the wallet has successfully acquired or extended the lease.
resp, err := rpcServer.LeaseOutput(t.Context(), &LeaseOutputRequest{
Id: lockID[:],
Outpoint: &lnrpc.OutPoint{
- TxidBytes: make([]byte, 32),
+ TxidBytes: outpoint.Hash[:],
},
ExpirationSeconds: 60,
})
+
+ // Assert acquisition still succeeds without claiming an unverified
+ // no-expiry policy; deferred verification checks each wallet call once.
require.NoError(t, err)
- require.Zero(t, resp.ReleaseAfterSpendConfs)
- require.Equal(t, 1, controller.legacyCalls)
+ require.False(t, resp.NoExpiry)
}
-// TestFundPsbtRequiresCustomLockID verifies confirmation-controlled input
+// TestFundPsbtRequiresCustomLockID verifies no-expiry input
// leases require an external, caller-specific owner ID.
func TestFundPsbtRequiresCustomLockID(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
lockID []byte
- expected string
+ expected error
}{
{
- name: "missing",
- expected: "custom lock ID required for " +
- "confirmation-controlled",
+ name: "missing",
+ expected: errMissingCustomLockID,
},
{
name: "all zero",
lockID: make([]byte, 32),
- expected: "custom lock ID must not be all zeros",
+ expected: errZeroCustomLockID,
},
{
name: "reserved internal",
lockID: chanfunding.LndInternalLockID[:],
- expected: "reserved custom lock ID cannot be used",
+ expected: errReservedCustomLockID,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()
+ // Arrange a no-expiry request with an unsafe owner and
+ // no wallet, requiring rejection before acquisition.
server := &WalletKit{cfg: &Config{}}
req := &FundPsbtRequest{
- InputReleaseAfterSpendConfs: 6,
+ InputLeaseNoExpiry: true,
+ CustomLockId: testCase.lockID,
}
- req.CustomLockId = testCase.lockID
+ // Act before template validation or funding can obscure
+ // the owner-ID rejection.
_, err := server.FundPsbt(t.Context(), req)
- require.ErrorContains(t, err, testCase.expected)
+
+ // Assert each invalid identity is rejected, requiring a
+ // caller-specific owner for a persistent reservation.
+ // Compare identities without matching message text.
+ require.ErrorIs(t, err, testCase.expected)
})
}
}Why this scored 28/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.