diff --git a/docs/release-notes/release-notes-next.md b/docs/release-notes/release-notes-next.md index 251589c38..57e9900d8 100644 --- a/docs/release-notes/release-notes-next.md +++ b/docs/release-notes/release-notes-next.md @@ -24,6 +24,15 @@ 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. + +* 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 7ebea3e9f..9213560f0 100644 --- a/instantout/instantout_test.go +++ b/instantout/instantout_test.go @@ -6,10 +6,12 @@ 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" "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" @@ -269,3 +271,56 @@ 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) + }) + } +} + +// 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 9a98020e4..f2173170d 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,17 @@ func (m *Manager) NewInstantOut(ctx context.Context, if err != nil { 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 "+ + "address type %T", sweepAddr) + } } m.Lock() diff --git a/liquidity/liquidity.go b/liquidity/liquidity.go index bcf8476f6..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" @@ -164,6 +165,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 " + @@ -304,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(): @@ -377,7 +376,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 } @@ -453,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 3b365cc01..4c2e9e552 100644 --- a/liquidity/parameters.go +++ b/liquidity/parameters.go @@ -7,9 +7,11 @@ 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" + "github.com/lightninglabs/loop/utils" "github.com/lightningnetwork/lnd/lnrpc/walletrpc" "github.com/lightningnetwork/lnd/lnwallet/chainfee" "github.com/lightningnetwork/lnd/lnwire" @@ -281,6 +283,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 != @@ -462,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 { @@ -477,11 +486,16 @@ 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 } + + err = utils.CheckAddrNetwork(destaddr, chainParams) + if err != nil { + return nil, err + } } } diff --git a/liquidity/parameters_test.go b/liquidity/parameters_test.go index 7af73c0dd..9360d4232 100644 --- a/liquidity/parameters_test.go +++ b/liquidity/parameters_test.go @@ -1,10 +1,15 @@ package liquidity import ( + "context" + "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/lightninglabs/loop/utils" "github.com/stretchr/testify/require" ) @@ -110,3 +115,153 @@ 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) + }) + } +} + +// TestSetParametersDestAddr verifies that the autoloop destination address is +// 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 + + p2pkh, err := btcutil.NewAddressPubKeyHash(make([]byte, 20), params) + require.NoError(t, err) + + p2sh, err := btcutil.NewAddressScriptHashFromHash( + make([]byte, 20), params, + ) + 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 + 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: "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", + }, + } + + 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, + ) + }) + } +} 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/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 new file mode 100644 index 000000000..0c4898c02 --- /dev/null +++ b/utils/address.go @@ -0,0 +1,45 @@ +package utils + +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 +// 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 + } +} + +// 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 new file mode 100644 index 000000000..22326a12b --- /dev/null +++ b/utils/address_test.go @@ -0,0 +1,129 @@ +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), + ) + }) + } +} + +// 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) + }) + } +}