From de0dacf5960f56579c6a1729897cba708162c600 Mon Sep 17 00:00:00 2001 From: Boris Nagaev Date: Sat, 7 Nov 2026 16:07:28 +0000 Subject: [PATCH 1/3] multi: check destination address types explicitly Loop Out accepts only P2PKH, P2SH, P2WPKH, P2WSH and P2TR destination addresses. Instant Out and the autoloop destination accepted any type that the address decoder returns, which for Instant Out included raw public keys. The btcd v2 address package also decodes pay-to-anchor addresses, which anyone can spend. Move the Loop Out check into utils.IsSupportedDestAddr. Apply it to Instant Out before the swap starts and to the autoloop parameters when they are validated, so that a decoder change can't widen the accepted destination types. --- instantout/instantout_test.go | 35 ++++++++++++++++++ instantout/manager.go | 7 ++++ liquidity/liquidity.go | 5 +++ liquidity/parameters.go | 7 ++++ liquidity/parameters_test.go | 51 ++++++++++++++++++++++++++ loopd/swapclient_server.go | 10 ++---- utils/address.go | 22 ++++++++++++ utils/address_test.go | 67 +++++++++++++++++++++++++++++++++++ 8 files changed, 196 insertions(+), 8 deletions(-) create mode 100644 utils/address.go create mode 100644 utils/address_test.go diff --git a/instantout/instantout_test.go b/instantout/instantout_test.go index 7ebea3e9f..be1a37b1a 100644 --- a/instantout/instantout_test.go +++ b/instantout/instantout_test.go @@ -6,6 +6,7 @@ import ( "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcutil" + "github.com/btcsuite/btcd/chaincfg" "github.com/btcsuite/btcd/wire" "github.com/lightninglabs/lndclient" "github.com/lightninglabs/loop/fsm" @@ -269,3 +270,37 @@ func TestNewInstantOutRejectsNegativeMaxSwapFee(t *testing.T) { _, err := manager.NewInstantOut(t.Context(), nil, "", -1) require.ErrorContains(t, err, "maximum swap fee must not be negative") } + +// TestNewInstantOutRejectsUnsupportedDestAddr verifies that an instant out +// cannot pay to a destination type that loop out rejects. +func TestNewInstantOutRejectsUnsupportedDestAddr(t *testing.T) { + tests := []struct { + name string + addr string + }{ + { + // The compressed secp256k1 generator point. + name: "raw public key", + addr: "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce" + + "28d959f2815b16f81798", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + // A manager that only knows the network verifies that + // the destination is rejected before the swap starts. + manager := &Manager{ + cfg: &Config{Network: &chaincfg.MainNetParams}, + } + + _, err := manager.NewInstantOut( + t.Context(), nil, test.addr, 0, + ) + require.ErrorContains( + t, err, "unsupported destination address type", + ) + require.Empty(t, manager.activeInstantOuts) + }) + } +} diff --git a/instantout/manager.go b/instantout/manager.go index 9a98020e4..1a53af032 100644 --- a/instantout/manager.go +++ b/instantout/manager.go @@ -11,6 +11,7 @@ import ( "github.com/lightninglabs/loop/fsm" "github.com/lightninglabs/loop/instantout/reservation" "github.com/lightninglabs/loop/swapserverrpc" + "github.com/lightninglabs/loop/utils" "github.com/lightningnetwork/lnd/lntypes" ) @@ -154,6 +155,12 @@ func (m *Manager) NewInstantOut(ctx context.Context, if err != nil { return nil, err } + + // Reject the destination types that loop out rejects too. + if !utils.IsSupportedDestAddr(sweepAddr) { + return nil, fmt.Errorf("unsupported destination "+ + "address type %T", sweepAddr) + } } m.Lock() diff --git a/liquidity/liquidity.go b/liquidity/liquidity.go index bcf8476f6..f77741e5e 100644 --- a/liquidity/liquidity.go +++ b/liquidity/liquidity.go @@ -164,6 +164,11 @@ var ( // a extended public key account is set. ErrAmbiguousDestAddr = errors.New("ambiguous destination address") + // ErrUnsupportedDestAddr is returned when the destination address has + // a type that loop out does not pay to. + ErrUnsupportedDestAddr = errors.New("unsupported destination address " + + "type") + // ErrAccountAndAddrType indicates if an account is set but the // account address type is not or vice versa. ErrAccountAndAddrType = errors.New("account and address type have " + diff --git a/liquidity/parameters.go b/liquidity/parameters.go index 3b365cc01..05ffc20f5 100644 --- a/liquidity/parameters.go +++ b/liquidity/parameters.go @@ -10,6 +10,7 @@ import ( "github.com/lightninglabs/lndclient" clientrpc "github.com/lightninglabs/loop/looprpc" "github.com/lightninglabs/loop/swap" + "github.com/lightninglabs/loop/utils" "github.com/lightningnetwork/lnd/lnrpc/walletrpc" "github.com/lightningnetwork/lnd/lnwallet/chainfee" "github.com/lightningnetwork/lnd/lnwire" @@ -281,6 +282,12 @@ func (p Parameters) validate(minConfs int32, openChans []lndclient.ChannelInfo, return ErrAmbiguousDestAddr } + // Autoloop must not sweep to a destination type that loop out + // rejects. + if p.DestAddr != nil && !utils.IsSupportedDestAddr(p.DestAddr) { + return fmt.Errorf("%w: %T", ErrUnsupportedDestAddr, p.DestAddr) + } + // If an account is specified the respective address type must be // specified as well, or both must be unset. if len(p.Account) == 0 != diff --git a/liquidity/parameters_test.go b/liquidity/parameters_test.go index 7af73c0dd..7d469eaf2 100644 --- a/liquidity/parameters_test.go +++ b/liquidity/parameters_test.go @@ -1,8 +1,11 @@ package liquidity import ( + "encoding/hex" "testing" + "github.com/btcsuite/btcd/btcutil" + "github.com/btcsuite/btcd/chaincfg" clientrpc "github.com/lightninglabs/loop/looprpc" "github.com/lightninglabs/loop/swap" "github.com/stretchr/testify/require" @@ -110,3 +113,51 @@ func TestValidateRestrictions(t *testing.T) { }) } } + +// TestParametersRejectUnsupportedDestAddr verifies that autoloop cannot sweep +// to a destination type that loop out rejects. +func TestParametersRejectUnsupportedDestAddr(t *testing.T) { + params := &chaincfg.MainNetParams + + p2wpkh, err := btcutil.NewAddressWitnessPubKeyHash( + make([]byte, 20), params, + ) + require.NoError(t, err) + + // The compressed secp256k1 generator point serves as a raw public key. + pubKey, err := hex.DecodeString("0279be667ef9dcbbac55a06295ce870b0" + + "7029bfcdb2dce28d959f2815b16f81798") + require.NoError(t, err) + + rawPubKey, err := btcutil.NewAddressPubKey(pubKey, params) + require.NoError(t, err) + + tests := []struct { + name string + addr btcutil.Address + err error + }{ + { + name: "p2wpkh", + addr: p2wpkh, + }, + { + name: "raw public key", + addr: rawPubKey, + err: ErrUnsupportedDestAddr, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + cfg, _ := newTestConfig() + manager := NewManager(cfg) + + newParams := defaultParameters + newParams.DestAddr = test.addr + + err := manager.setParameters(t.Context(), newParams) + require.ErrorIs(t, err, test.err) + }) + } +} diff --git a/loopd/swapclient_server.go b/loopd/swapclient_server.go index 9cbd6b207..e6fcf499e 100644 --- a/loopd/swapclient_server.go +++ b/loopd/swapclient_server.go @@ -38,6 +38,7 @@ import ( "github.com/lightninglabs/loop/staticaddr/withdraw" "github.com/lightninglabs/loop/swap" "github.com/lightninglabs/loop/swapserverrpc" + "github.com/lightninglabs/loop/utils" "github.com/lightninglabs/taproot-assets/rfqmath" "github.com/lightningnetwork/lnd/lnrpc/walletrpc" "github.com/lightningnetwork/lnd/lntypes" @@ -3055,14 +3056,7 @@ func validateLoopOutRequest(ctx context.Context, lnd lndclient.LightningClient, // Check that the provided destination address is a supported // address format. - switch sweepAddr.(type) { - case *btcutil.AddressTaproot, - *btcutil.AddressWitnessScriptHash, - *btcutil.AddressWitnessPubKeyHash, - *btcutil.AddressScriptHash, - *btcutil.AddressPubKeyHash: - - default: + if !utils.IsSupportedDestAddr(sweepAddr) { return 0, errInvalidAddress } diff --git a/utils/address.go b/utils/address.go new file mode 100644 index 000000000..c14a66be9 --- /dev/null +++ b/utils/address.go @@ -0,0 +1,22 @@ +package utils + +import "github.com/btcsuite/btcd/btcutil" + +// IsSupportedDestAddr returns whether addr has a type that Loop pays swap and +// sweep outputs to: P2PKH, P2SH, P2WPKH, P2WSH or P2TR. It rejects any other +// type that an address decoder may return, such as a raw public key or a +// pay-to-anchor output, which anyone can spend. +func IsSupportedDestAddr(addr btcutil.Address) bool { + switch addr.(type) { + case *btcutil.AddressPubKeyHash, + *btcutil.AddressScriptHash, + *btcutil.AddressWitnessPubKeyHash, + *btcutil.AddressWitnessScriptHash, + *btcutil.AddressTaproot: + + return true + + default: + return false + } +} diff --git a/utils/address_test.go b/utils/address_test.go new file mode 100644 index 000000000..cc4a205b5 --- /dev/null +++ b/utils/address_test.go @@ -0,0 +1,67 @@ +package utils + +import ( + "encoding/hex" + "testing" + + "github.com/btcsuite/btcd/btcutil" + "github.com/btcsuite/btcd/chaincfg" + "github.com/stretchr/testify/require" +) + +// TestIsSupportedDestAddr checks which address types are accepted as swap +// and sweep destinations. +func TestIsSupportedDestAddr(t *testing.T) { + t.Parallel() + + params := &chaincfg.MainNetParams + hash20 := make([]byte, 20) + hash32 := make([]byte, 32) + + // The compressed secp256k1 generator point serves as a raw public key. + pubKey, err := hex.DecodeString("0279be667ef9dcbbac55a06295ce870b0" + + "7029bfcdb2dce28d959f2815b16f81798") + require.NoError(t, err) + + p2pkh, err := btcutil.NewAddressPubKeyHash(hash20, params) + require.NoError(t, err) + + p2sh, err := btcutil.NewAddressScriptHashFromHash(hash20, params) + require.NoError(t, err) + + p2wpkh, err := btcutil.NewAddressWitnessPubKeyHash(hash20, params) + require.NoError(t, err) + + p2wsh, err := btcutil.NewAddressWitnessScriptHash(hash32, params) + require.NoError(t, err) + + p2tr, err := btcutil.NewAddressTaproot(hash32, params) + require.NoError(t, err) + + p2pk, err := btcutil.NewAddressPubKey(pubKey, params) + require.NoError(t, err) + + tests := []struct { + name string + addr btcutil.Address + supported bool + }{ + {name: "p2pkh", addr: p2pkh, supported: true}, + {name: "p2sh", addr: p2sh, supported: true}, + {name: "p2wpkh", addr: p2wpkh, supported: true}, + {name: "p2wsh", addr: p2wsh, supported: true}, + {name: "p2tr", addr: p2tr, supported: true}, + {name: "raw public key", addr: p2pk, supported: false}, + {name: "nil", addr: nil, supported: false}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + require.Equal( + t, test.supported, IsSupportedDestAddr(test.addr), + ) + }) + } +} From 81f2c3e3ce7f3c13790c7ffee9c9367f0defa9cf Mon Sep 17 00:00:00 2001 From: Boris Nagaev Date: Sat, 7 Nov 2026 18:23:01 +0000 Subject: [PATCH 2/3] liquidity: decode the autoloop destination for the active network RpcToParameters decoded the autoloop destination address with nil chain parameters. For P2PKH and P2SH addresses and raw public keys, the decoder dereferences the parameters, so a SetLiquidityParams call with such an address panicked. loopd does not recover from panics in RPC handlers, so the daemon crashed. Pass the chain parameters of the active network to RpcToParameters and decode the address with them. A raw public key now decodes and fails the destination type check. --- docs/release-notes/release-notes-next.md | 4 ++ liquidity/liquidity.go | 2 +- liquidity/parameters.go | 10 +-- liquidity/parameters_test.go | 82 ++++++++++++++++++++++++ 4 files changed, 93 insertions(+), 5 deletions(-) diff --git a/docs/release-notes/release-notes-next.md b/docs/release-notes/release-notes-next.md index 251589c38..48e3c008a 100644 --- a/docs/release-notes/release-notes-next.md +++ b/docs/release-notes/release-notes-next.md @@ -24,6 +24,10 @@ keeps the deposits locked and sweeps the htlc timeout path once the htlc times out. +* Setting a P2PKH or P2SH address or a raw public key as the autoloop + destination no longer crashes loopd. The address is now decoded for the + active network, and a raw public key is rejected. + #### Maintenance #### Contributors (Alphabetical Order) diff --git a/liquidity/liquidity.go b/liquidity/liquidity.go index f77741e5e..bd4ae8f39 100644 --- a/liquidity/liquidity.go +++ b/liquidity/liquidity.go @@ -382,7 +382,7 @@ func (m *Manager) GetParameters() Parameters { func (m *Manager) SetParameters(ctx context.Context, req *clientrpc.LiquidityParameters) error { - params, err := RpcToParameters(req) + params, err := RpcToParameters(req, m.cfg.Lnd.ChainParams) if err != nil { return err } diff --git a/liquidity/parameters.go b/liquidity/parameters.go index 05ffc20f5..0971ba613 100644 --- a/liquidity/parameters.go +++ b/liquidity/parameters.go @@ -7,6 +7,7 @@ import ( "time" "github.com/btcsuite/btcd/btcutil" + "github.com/btcsuite/btcd/chaincfg" "github.com/lightninglabs/lndclient" clientrpc "github.com/lightninglabs/loop/looprpc" "github.com/lightninglabs/loop/swap" @@ -469,9 +470,10 @@ func loopInSourceToRPC(source LoopInSource) (clientrpc.LoopInSource, error) { } // RpcToParameters takes a `LiquidityParameters` and creates a `Parameters` -// from it. -func RpcToParameters(req *clientrpc.LiquidityParameters) (*Parameters, - error) { +// from it. It decodes the autoloop destination address for the network with +// the given chain parameters. +func RpcToParameters(req *clientrpc.LiquidityParameters, + chainParams *chaincfg.Params) (*Parameters, error) { feeLimit, err := rpcToFee(req) if err != nil { @@ -484,7 +486,7 @@ func RpcToParameters(req *clientrpc.LiquidityParameters) (*Parameters, destaddr = nil } else { destaddr, err = btcutil.DecodeAddress( - req.AutoloopDestAddress, nil, + req.AutoloopDestAddress, chainParams, ) if err != nil { return nil, err diff --git a/liquidity/parameters_test.go b/liquidity/parameters_test.go index 7d469eaf2..cde7b2f16 100644 --- a/liquidity/parameters_test.go +++ b/liquidity/parameters_test.go @@ -1,6 +1,7 @@ package liquidity import ( + "context" "encoding/hex" "testing" @@ -161,3 +162,84 @@ func TestParametersRejectUnsupportedDestAddr(t *testing.T) { }) } } + +// TestSetParametersDestAddr verifies that the autoloop destination address is +// decoded for the active network. Base58 addresses and raw public keys used to +// crash loopd, because the decoder dereferences the chain parameters for them. +func TestSetParametersDestAddr(t *testing.T) { + _, lnd := newTestConfig() + params := lnd.ChainParams + + p2pkh, err := btcutil.NewAddressPubKeyHash(make([]byte, 20), params) + require.NoError(t, err) + + p2sh, err := btcutil.NewAddressScriptHashFromHash( + make([]byte, 20), params, + ) + require.NoError(t, err) + + mainnetP2PKH, err := btcutil.NewAddressPubKeyHash( + make([]byte, 20), &chaincfg.MainNetParams, + ) + require.NoError(t, err) + + tests := []struct { + name string + addr string + destAddr btcutil.Address + err error + }{ + { + name: "p2pkh", + addr: p2pkh.EncodeAddress(), + destAddr: p2pkh, + }, + { + name: "p2sh", + addr: p2sh.EncodeAddress(), + destAddr: p2sh, + }, + { + // The compressed secp256k1 generator point. + name: "raw public key", + addr: "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce" + + "28d959f2815b16f81798", + err: ErrUnsupportedDestAddr, + }, + { + name: "p2pkh of another network", + addr: mainnetP2PKH.EncodeAddress(), + err: btcutil.ErrUnknownAddressType, + }, + { + name: "default", + addr: "default", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + cfg, _ := newTestConfig() + cfg.PutLiquidityParams = func(context.Context, + []byte) error { + + return nil + } + manager := NewManager(cfg) + + req, err := ParametersToRpc(defaultParameters) + require.NoError(t, err) + req.AutoloopDestAddress = test.addr + + err = manager.SetParameters(t.Context(), req) + require.ErrorIs(t, err, test.err) + if test.err != nil { + return + } + + require.Equal( + t, test.destAddr, manager.GetParameters().DestAddr, + ) + }) + } +} From 148d480f3cea485c45a8cddb75a04362f71be8b2 Mon Sep 17 00:00:00 2001 From: Boris Nagaev Date: Sat, 7 Nov 2026 18:27:13 +0000 Subject: [PATCH 3/3] multi: reject destination addresses of other networks Loop Out rejects a destination address that does not belong to the active network. Autoloop, Instant Out, static address withdrawals and manual HTLC sweeps did not. The decoder accepts bech32 addresses of all known networks, and their output scripts don't depend on the network, so these paths paid to the same witness program on the active network. Add utils.CheckAddrNetwork and call it after each of these decodes. Earlier versions saved the autoloop destination without the check. If the saved destination belongs to another network, loopd removes it at startup and autoloop pays to wallet addresses, because failing to start would leave no way to change the parameters. --- docs/release-notes/release-notes-next.md | 5 ++ instantout/instantout_test.go | 20 ++++++++ instantout/manager.go | 5 ++ liquidity/liquidity.go | 41 ++++++++++++---- liquidity/liquidity_test.go | 42 ++++++++++++++++ liquidity/parameters.go | 5 ++ liquidity/parameters_test.go | 26 +++++++++- loopd/sweep_htlc.go | 6 +++ loopd/sweep_htlc_test.go | 14 ++++++ staticaddr/withdraw/manager.go | 7 +++ staticaddr/withdraw/manager_test.go | 10 ++++ utils/address.go | 25 +++++++++- utils/address_test.go | 62 ++++++++++++++++++++++++ 13 files changed, 256 insertions(+), 12 deletions(-) diff --git a/docs/release-notes/release-notes-next.md b/docs/release-notes/release-notes-next.md index 48e3c008a..57e9900d8 100644 --- a/docs/release-notes/release-notes-next.md +++ b/docs/release-notes/release-notes-next.md @@ -28,6 +28,11 @@ destination no longer crashes loopd. The address is now decoded for the active network, and a raw public key is rejected. +* Autoloop, Instant Out, static address withdrawals and manual HTLC sweeps now + reject destination addresses of another network, as Loop Out already did. If + the saved autoloop destination belongs to another network, loopd removes it + at startup, and autoloop pays to wallet addresses. + #### Maintenance #### Contributors (Alphabetical Order) diff --git a/instantout/instantout_test.go b/instantout/instantout_test.go index be1a37b1a..9213560f0 100644 --- a/instantout/instantout_test.go +++ b/instantout/instantout_test.go @@ -11,6 +11,7 @@ import ( "github.com/lightninglabs/lndclient" "github.com/lightninglabs/loop/fsm" "github.com/lightninglabs/loop/instantout/reservation" + "github.com/lightninglabs/loop/utils" "github.com/lightningnetwork/lnd/input" "github.com/lightningnetwork/lnd/lnwire" "github.com/stretchr/testify/require" @@ -304,3 +305,22 @@ func TestNewInstantOutRejectsUnsupportedDestAddr(t *testing.T) { }) } } + +// TestNewInstantOutRejectsWrongNetworkDestAddr verifies that an instant out +// cannot pay to an address of another network. +func TestNewInstantOutRejectsWrongNetworkDestAddr(t *testing.T) { + addr, err := btcutil.NewAddressWitnessPubKeyHash( + make([]byte, 20), &chaincfg.TestNet3Params, + ) + require.NoError(t, err) + + // A manager that only knows the network verifies that the destination + // is rejected before the swap starts. + manager := &Manager{cfg: &Config{Network: &chaincfg.MainNetParams}} + + _, err = manager.NewInstantOut( + t.Context(), nil, addr.EncodeAddress(), 0, + ) + require.ErrorIs(t, err, utils.ErrWrongNetwork) + require.Empty(t, manager.activeInstantOuts) +} diff --git a/instantout/manager.go b/instantout/manager.go index 1a53af032..f2173170d 100644 --- a/instantout/manager.go +++ b/instantout/manager.go @@ -156,6 +156,11 @@ func (m *Manager) NewInstantOut(ctx context.Context, return nil, err } + err = utils.CheckAddrNetwork(sweepAddr, m.cfg.Network) + if err != nil { + return nil, err + } + // Reject the destination types that loop out rejects too. if !utils.IsSupportedDestAddr(sweepAddr) { return nil, fmt.Errorf("unsupported destination "+ diff --git a/liquidity/liquidity.go b/liquidity/liquidity.go index bd4ae8f39..346088940 100644 --- a/liquidity/liquidity.go +++ b/liquidity/liquidity.go @@ -50,6 +50,7 @@ import ( "github.com/lightninglabs/loop/loopdb" clientrpc "github.com/lightninglabs/loop/looprpc" "github.com/lightninglabs/loop/swap" + "github.com/lightninglabs/loop/utils" "github.com/lightninglabs/taproot-assets/rfqmsg" "github.com/lightningnetwork/lnd/clock" "github.com/lightningnetwork/lnd/funding" @@ -309,19 +310,12 @@ func (m *Manager) Run(ctx context.Context) error { m.cfg.AutoloopTicker.Resume() defer m.cfg.AutoloopTicker.Stop() - // Before we start the main loop, load the params from db. - req, err := m.loadParams(ctx) + // Before we start the main loop, restore the params from db. + err := m.restoreParams(ctx) if err != nil { return err } - // Set the params if there's one. - if req != nil { - if err := m.SetParameters(ctx, req); err != nil { - return err - } - } - for { select { case <-m.cfg.AutoloopTicker.Ticks(): @@ -458,6 +452,35 @@ func (m *Manager) saveParams(ctx context.Context, req proto.Message) error { return nil } +// restoreParams sets the parameters saved in the db, if there are any. +func (m *Manager) restoreParams(ctx context.Context) error { + req, err := m.loadParams(ctx) + if err != nil { + return err + } + + // There is nothing to restore if no params were saved. + if req == nil { + return nil + } + + err = m.SetParameters(ctx, req) + if !errors.Is(err, utils.ErrWrongNetwork) { + return err + } + + // Earlier versions saved the autoloop destination address without + // checking its network. Remove such an address, so that autoloop pays + // to wallet addresses, instead of failing to start: the params can't + // be changed while loopd is down. + log.Warnf("Removing the saved autoloop destination address %v: %v", + req.AutoloopDestAddress, err) + + req.AutoloopDestAddress = "" + + return m.SetParameters(ctx, req) +} + // loadParams unmarshals a serialized RPC request from db and returns the RPC // request. func (m *Manager) loadParams(ctx context.Context) ( diff --git a/liquidity/liquidity_test.go b/liquidity/liquidity_test.go index a7f8977aa..0af5f373a 100644 --- a/liquidity/liquidity_test.go +++ b/liquidity/liquidity_test.go @@ -8,6 +8,7 @@ import ( "time" "github.com/btcsuite/btcd/btcutil" + "github.com/btcsuite/btcd/chaincfg" "github.com/lightninglabs/lndclient" "github.com/lightninglabs/loop" "github.com/lightninglabs/loop/labels" @@ -441,6 +442,47 @@ func TestPersistParams(t *testing.T) { ) } +// TestRestoreParamsWrongNetworkDestAddr verifies that loopd removes a saved +// autoloop destination address of another network at startup, instead of +// failing to start. +func TestRestoreParamsWrongNetworkDestAddr(t *testing.T) { + ctx := t.Context() + + var paramsBytes []byte + cfg, _ := newTestConfig() + cfg.FetchLiquidityParams = func(context.Context) ([]byte, error) { + return paramsBytes, nil + } + cfg.PutLiquidityParams = func(_ context.Context, data []byte) error { + paramsBytes = data + + return nil + } + manager := NewManager(cfg) + + // The mock lnd runs on testnet3. Earlier versions could save a mainnet + // destination address there. + destAddr, err := btcutil.NewAddressWitnessPubKeyHash( + make([]byte, 20), &chaincfg.MainNetParams, + ) + require.NoError(t, err) + + req, err := ParametersToRpc(defaultParameters) + require.NoError(t, err) + req.AutoloopDestAddress = destAddr.EncodeAddress() + req.AutoMaxInFlight = 3 + require.NoError(t, manager.saveParams(ctx, req)) + + // The other params are restored without the destination address. + require.NoError(t, manager.restoreParams(ctx)) + require.Nil(t, manager.GetParameters().DestAddr) + require.Equal(t, 3, manager.GetParameters().MaxAutoInFlight) + + req, err = manager.loadParams(ctx) + require.NoError(t, err) + require.Empty(t, req.AutoloopDestAddress) +} + // TestStaticAddressAutoloopRequiresExperimental verifies that static-address // loop-in sources are rejected unless the daemon enabled the experimental // static autoloop path. diff --git a/liquidity/parameters.go b/liquidity/parameters.go index 0971ba613..4c2e9e552 100644 --- a/liquidity/parameters.go +++ b/liquidity/parameters.go @@ -491,6 +491,11 @@ func RpcToParameters(req *clientrpc.LiquidityParameters, if err != nil { return nil, err } + + err = utils.CheckAddrNetwork(destaddr, chainParams) + if err != nil { + return nil, err + } } } diff --git a/liquidity/parameters_test.go b/liquidity/parameters_test.go index cde7b2f16..9360d4232 100644 --- a/liquidity/parameters_test.go +++ b/liquidity/parameters_test.go @@ -9,6 +9,7 @@ import ( "github.com/btcsuite/btcd/chaincfg" clientrpc "github.com/lightninglabs/loop/looprpc" "github.com/lightninglabs/loop/swap" + "github.com/lightninglabs/loop/utils" "github.com/stretchr/testify/require" ) @@ -164,8 +165,9 @@ func TestParametersRejectUnsupportedDestAddr(t *testing.T) { } // TestSetParametersDestAddr verifies that the autoloop destination address is -// decoded for the active network. Base58 addresses and raw public keys used to -// crash loopd, because the decoder dereferences the chain parameters for them. +// decoded and checked for the active network. Base58 addresses and raw public +// keys used to crash loopd, because the decoder dereferences the chain +// parameters for them. func TestSetParametersDestAddr(t *testing.T) { _, lnd := newTestConfig() params := lnd.ChainParams @@ -178,11 +180,21 @@ func TestSetParametersDestAddr(t *testing.T) { ) require.NoError(t, err) + p2wpkh, err := btcutil.NewAddressWitnessPubKeyHash( + make([]byte, 20), params, + ) + require.NoError(t, err) + mainnetP2PKH, err := btcutil.NewAddressPubKeyHash( make([]byte, 20), &chaincfg.MainNetParams, ) require.NoError(t, err) + mainnetP2WPKH, err := btcutil.NewAddressWitnessPubKeyHash( + make([]byte, 20), &chaincfg.MainNetParams, + ) + require.NoError(t, err) + tests := []struct { name string addr string @@ -206,11 +218,21 @@ func TestSetParametersDestAddr(t *testing.T) { "28d959f2815b16f81798", err: ErrUnsupportedDestAddr, }, + { + name: "p2wpkh", + addr: p2wpkh.EncodeAddress(), + destAddr: p2wpkh, + }, { name: "p2pkh of another network", addr: mainnetP2PKH.EncodeAddress(), err: btcutil.ErrUnknownAddressType, }, + { + name: "p2wpkh of another network", + addr: mainnetP2WPKH.EncodeAddress(), + err: utils.ErrWrongNetwork, + }, { name: "default", addr: "default", diff --git a/loopd/sweep_htlc.go b/loopd/sweep_htlc.go index 771df0b64..1851af219 100644 --- a/loopd/sweep_htlc.go +++ b/loopd/sweep_htlc.go @@ -207,6 +207,12 @@ func sweepHtlc(ctx context.Context, req *looprpc.SweepHtlcRequest, return nil, status.Errorf(codes.InvalidArgument, "invalid dest_address: %v", err) } + + err = utils.CheckAddrNetwork(sweepAddr, chainParams) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, + "invalid dest_address: %v", err) + } } var ( diff --git a/loopd/sweep_htlc_test.go b/loopd/sweep_htlc_test.go index 88d0fbb2a..93c2804ee 100644 --- a/loopd/sweep_htlc_test.go +++ b/loopd/sweep_htlc_test.go @@ -183,6 +183,20 @@ var sweepHtlcTests = []struct { req.HtlcAddress = "notanaddress" }, }, + { + name: "dest address of another network", + amount: 100_000, + satPerVByte: 10, + expectErrMsg: "invalid dest_address: address belongs to " + + "another network", + expectLogs: []string{}, + expectRegister: false, + modifyReq: func(req *looprpc.SweepHtlcRequest) { + // A mainnet P2WPKH address from BIP 173. The mock lnd + // runs on testnet3. + req.DestAddress = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4" + }, + }, { name: "no matching swap", amount: 100_000, diff --git a/staticaddr/withdraw/manager.go b/staticaddr/withdraw/manager.go index 3940c36fd..fb0018945 100644 --- a/staticaddr/withdraw/manager.go +++ b/staticaddr/withdraw/manager.go @@ -22,6 +22,7 @@ import ( "github.com/lightninglabs/loop/staticaddr/deposit" "github.com/lightninglabs/loop/staticaddr/staticutil" staticaddressrpc "github.com/lightninglabs/loop/swapserverrpc" + "github.com/lightninglabs/loop/utils" "github.com/lightningnetwork/lnd/funding" "github.com/lightningnetwork/lnd/input" "github.com/lightningnetwork/lnd/lnrpc" @@ -560,6 +561,12 @@ func (m *Manager) withdrawalAddress(ctx context.Context, destAddr string, if err != nil { return nil, err } + + err = utils.CheckAddrNetwork(address, m.cfg.ChainParams) + if err != nil { + return nil, err + } + if prevPkScript == nil { return address, nil } diff --git a/staticaddr/withdraw/manager_test.go b/staticaddr/withdraw/manager_test.go index fdd2dc01f..7e17d74f8 100644 --- a/staticaddr/withdraw/manager_test.go +++ b/staticaddr/withdraw/manager_test.go @@ -14,6 +14,7 @@ import ( "github.com/lightninglabs/loop/staticaddr/deposit" "github.com/lightninglabs/loop/swapserverrpc" "github.com/lightninglabs/loop/test" + "github.com/lightninglabs/loop/utils" "github.com/lightningnetwork/lnd/funding" "github.com/lightningnetwork/lnd/input" "github.com/lightningnetwork/lnd/lnrpc" @@ -753,6 +754,15 @@ func TestWithdrawalAddress(t *testing.T) { require.NoError(t, err) require.Equal(t, walletAddress.String(), address.String()) + // A withdrawal can't pay to an address of another network. + mainnetAddress, err := btcutil.NewAddressTaproot( + bytes.Repeat([]byte{3}, 32), &chaincfg.MainNetParams, + ) + require.NoError(t, err) + + _, err = m.withdrawalAddress(t.Context(), mainnetAddress.String(), nil) + require.ErrorIs(t, err, utils.ErrWrongNetwork) + // A fee bump pays the address of the withdrawal that it replaces, and // can't request another one. address, err = m.withdrawalAddress(t.Context(), "", prevWithdrawalTx) diff --git a/utils/address.go b/utils/address.go index c14a66be9..0c4898c02 100644 --- a/utils/address.go +++ b/utils/address.go @@ -1,6 +1,16 @@ package utils -import "github.com/btcsuite/btcd/btcutil" +import ( + "errors" + "fmt" + + "github.com/btcsuite/btcd/btcutil" + "github.com/btcsuite/btcd/chaincfg" +) + +// ErrWrongNetwork is returned when an address belongs to another network than +// the active one. +var ErrWrongNetwork = errors.New("address belongs to another network") // IsSupportedDestAddr returns whether addr has a type that Loop pays swap and // sweep outputs to: P2PKH, P2SH, P2WPKH, P2WSH or P2TR. It rejects any other @@ -20,3 +30,16 @@ func IsSupportedDestAddr(addr btcutil.Address) bool { return false } } + +// CheckAddrNetwork returns an error wrapping ErrWrongNetwork if addr does not +// belong to the network with the given chain parameters. The decoder accepts +// bech32 addresses of all known networks, and their output scripts don't +// depend on the network. +func CheckAddrNetwork(addr btcutil.Address, params *chaincfg.Params) error { + if addr.IsForNet(params) { + return nil + } + + return fmt.Errorf("%w, the active network is %v", ErrWrongNetwork, + params.Name) +} diff --git a/utils/address_test.go b/utils/address_test.go index cc4a205b5..22326a12b 100644 --- a/utils/address_test.go +++ b/utils/address_test.go @@ -65,3 +65,65 @@ func TestIsSupportedDestAddr(t *testing.T) { }) } } + +// TestCheckAddrNetwork checks that an address is only accepted on its own +// network. +func TestCheckAddrNetwork(t *testing.T) { + t.Parallel() + + hash20 := make([]byte, 20) + + p2pkh, err := btcutil.NewAddressPubKeyHash( + hash20, &chaincfg.MainNetParams, + ) + require.NoError(t, err) + + p2wpkh, err := btcutil.NewAddressWitnessPubKeyHash( + hash20, &chaincfg.MainNetParams, + ) + require.NoError(t, err) + + regtestP2WPKH, err := btcutil.NewAddressWitnessPubKeyHash( + hash20, &chaincfg.RegressionNetParams, + ) + require.NoError(t, err) + + tests := []struct { + name string + addr btcutil.Address + params *chaincfg.Params + err error + }{ + { + name: "p2pkh", + addr: p2pkh, + params: &chaincfg.MainNetParams, + }, + { + name: "p2pkh of another network", + addr: p2pkh, + params: &chaincfg.TestNet3Params, + err: ErrWrongNetwork, + }, + { + name: "p2wpkh", + addr: p2wpkh, + params: &chaincfg.MainNetParams, + }, + { + name: "p2wpkh of another network", + addr: regtestP2WPKH, + params: &chaincfg.MainNetParams, + err: ErrWrongNetwork, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + err := CheckAddrNetwork(test.addr, test.params) + require.ErrorIs(t, err, test.err) + }) + } +}