lnd/itest/lnd_wallet_import_test.go

806 lines
24 KiB
Go
Raw Permalink Normal View History

2021-02-20 02:42:20 +01:00
package itest
import (
"bytes"
"fmt"
2021-02-20 02:42:20 +01:00
"testing"
"time"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/btcutil/hdkeychain"
2021-02-20 02:42:20 +01:00
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/davecgh/go-spew/spew"
"github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
"github.com/lightningnetwork/lnd/lntest"
"github.com/lightningnetwork/lnd/lntest/node"
2021-02-20 02:42:20 +01:00
"github.com/lightningnetwork/lnd/lnwallet"
"github.com/stretchr/testify/require"
)
const (
defaultAccount = lnwallet.DefaultAccountName
defaultImportedAccount = waddrmgr.ImportedAddrAccountName
)
// walletToLNAddrType maps walletrpc.AddressType to lnrpc.AddressType.
func walletToLNAddrType(t *testing.T,
addrType walletrpc.AddressType) lnrpc.AddressType {
2021-02-20 02:42:20 +01:00
switch addrType {
case walletrpc.AddressType_NESTED_WITNESS_PUBKEY_HASH,
walletrpc.AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
return lnrpc.AddressType_NESTED_PUBKEY_HASH
case walletrpc.AddressType_WITNESS_PUBKEY_HASH:
return lnrpc.AddressType_WITNESS_PUBKEY_HASH
case walletrpc.AddressType_TAPROOT_PUBKEY:
return lnrpc.AddressType_TAPROOT_PUBKEY
2021-02-20 02:42:20 +01:00
default:
t.Fatalf("unhandled addr type %v", addrType)
return 0
}
}
// newExternalAddr generates a new external address of an imported account for a
// pair of nodes, where one acts as the funder and the other as the signer.
func newExternalAddr(ht *lntest.HarnessTest, funder, signer *node.HarnessNode,
2021-02-20 02:42:20 +01:00
importedAccount string, addrType walletrpc.AddressType) string {
// We'll generate a new address for Carol from Dave's node to receive
// and fund a new channel.
req := &lnrpc.NewAddressRequest{
Type: walletToLNAddrType(ht.T, addrType),
2021-02-20 02:42:20 +01:00
Account: importedAccount,
}
funderResp := funder.RPC.NewAddress(req)
2021-02-20 02:42:20 +01:00
// Carol also needs to generate the address for the sake of this test
// to be able to sign the channel funding input.
req = &lnrpc.NewAddressRequest{
Type: walletToLNAddrType(ht.T, addrType),
}
signerResp := signer.RPC.NewAddress(req)
2021-02-20 02:42:20 +01:00
// Sanity check that the generated addresses match.
require.Equal(ht, funderResp.Address, signerResp.Address)
assertExternalAddrType(ht.T, funderResp.Address, addrType)
2021-02-20 02:42:20 +01:00
return funderResp.Address
}
// assertExternalAddrType asserts that an external address generated for an
// imported account is of the expected type.
func assertExternalAddrType(t *testing.T, addrStr string,
accountAddrType walletrpc.AddressType) {
addr, err := btcutil.DecodeAddress(addrStr, harnessNetParams)
require.NoError(t, err)
switch accountAddrType {
case walletrpc.AddressType_WITNESS_PUBKEY_HASH:
require.IsType(t, addr, &btcutil.AddressWitnessPubKeyHash{})
case walletrpc.AddressType_NESTED_WITNESS_PUBKEY_HASH,
walletrpc.AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
require.IsType(t, addr, &btcutil.AddressScriptHash{})
case walletrpc.AddressType_TAPROOT_PUBKEY:
require.IsType(t, addr, &btcutil.AddressTaproot{})
2021-02-20 02:42:20 +01:00
default:
t.Fatalf("unsupported account addr type %v", accountAddrType)
}
}
// assertOutputScriptType asserts that a transaction's output, indicated by the
// output with the given amount, has a script of the expected type. This assumes
// all transaction outputs have unique amounts.
func assertOutputScriptType(t *testing.T, expType txscript.ScriptClass,
tx *wire.MsgTx, outputAmt int64) {
for _, txOut := range tx.TxOut {
if txOut.Value != outputAmt {
continue
}
pkScript, err := txscript.ParsePkScript(txOut.PkScript)
require.NoError(t, err)
require.Equal(t, expType, pkScript.Class())
return
}
// No output with the given amount was found.
t.Fatalf("output with amount %v not found in transaction %v", outputAmt,
spew.Sdump(tx))
}
// psbtSendFromImportedAccount attempts to fund a PSBT from the given imported
// account, originating from the source node to the destination.
func psbtSendFromImportedAccount(ht *lntest.HarnessTest, srcNode, destNode,
signer *node.HarnessNode, account string,
2021-02-20 02:42:20 +01:00
accountAddrType walletrpc.AddressType) {
balanceResp := srcNode.RPC.WalletBalance()
require.Contains(ht, balanceResp.AccountBalance, account)
2021-02-20 02:42:20 +01:00
confBalance := balanceResp.AccountBalance[account].ConfirmedBalance
destAmt := confBalance - 10000
destAddrResp := destNode.RPC.NewAddress(&lnrpc.NewAddressRequest{
2021-02-20 02:42:20 +01:00
Type: lnrpc.AddressType_WITNESS_PUBKEY_HASH,
})
fundReq := &walletrpc.FundPsbtRequest{
Template: &walletrpc.FundPsbtRequest_Raw{
Raw: &walletrpc.TxTemplate{
Outputs: map[string]uint64{
destAddrResp.Address: uint64(destAmt),
},
},
},
Fees: &walletrpc.FundPsbtRequest_SatPerVbyte{
SatPerVbyte: 1,
},
Account: account,
}
fundResp := srcNode.RPC.FundPsbt(fundReq)
2021-02-20 02:42:20 +01:00
// Have Carol sign the PSBT input since Dave doesn't have any private
// key information.
finalizeReq := &walletrpc.FinalizePsbtRequest{
FundedPsbt: fundResp.FundedPsbt,
}
finalizeResp := signer.RPC.FinalizePsbt(finalizeReq)
2021-02-20 02:42:20 +01:00
// With the PSBT signed, we can broadcast the resulting transaction.
publishReq := &walletrpc.Transaction{
TxHex: finalizeResp.RawFinalTx,
}
srcNode.RPC.PublishTransaction(publishReq)
2021-02-20 02:42:20 +01:00
// Carol's balance from Dave's perspective should update accordingly.
var (
expTxFee int64
expChangeScriptType txscript.ScriptClass
)
switch accountAddrType {
case walletrpc.AddressType_WITNESS_PUBKEY_HASH:
expTxFee = 141
expChangeScriptType = txscript.WitnessV0PubKeyHashTy
2021-02-20 02:42:20 +01:00
case walletrpc.AddressType_NESTED_WITNESS_PUBKEY_HASH:
if account != defaultImportedAccount {
expTxFee = 165
expChangeScriptType = txscript.ScriptHashTy
break
}
// Spends from the default NP2WKH imported account have the same
// fee rate as the hybrid address type since a NP2WKH input is
// spent and a P2WKH change output is created.
fallthrough
2021-02-20 02:42:20 +01:00
case walletrpc.AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
expTxFee = 164
expChangeScriptType = txscript.WitnessV0PubKeyHashTy
case walletrpc.AddressType_TAPROOT_PUBKEY:
if account != defaultImportedAccount {
expTxFee = 143
expChangeScriptType = txscript.WitnessV1TaprootTy
break
}
// Spends from the default imported account fall back to a P2WKH
// change. We'll want to change that, but in a separate PR.
expTxFee = 131
expChangeScriptType = txscript.WitnessV0PubKeyHashTy
2021-02-20 02:42:20 +01:00
default:
ht.Fatalf("unsupported addr type %v", accountAddrType)
2021-02-20 02:42:20 +01:00
}
changeUtxoAmt := confBalance - destAmt - expTxFee
// If the transaction was created from the default imported account,
// then any change produced is moved to the default wallet account.
accountWithBalance := account
if account == defaultImportedAccount {
accountWithBalance = defaultAccount
}
ht.AssertWalletAccountBalance(
srcNode, accountWithBalance, 0, changeUtxoAmt,
)
ht.MineBlocksAndAssertNumTxes(1, 1)
ht.AssertWalletAccountBalance(
srcNode, accountWithBalance, changeUtxoAmt, 0,
)
2021-02-20 02:42:20 +01:00
// Finally, assert that the transaction has the expected change address
// type based on the account.
var tx wire.MsgTx
err := tx.Deserialize(bytes.NewReader(finalizeResp.RawFinalTx))
require.NoError(ht, err)
assertOutputScriptType(ht.T, expChangeScriptType, &tx, changeUtxoAmt)
2021-02-20 02:42:20 +01:00
}
// fundChanAndCloseFromImportedAccount attempts to a fund a channel from the
// given imported account, originating from the source node to the destination
// node. To ensure the channel is operational before closing it, a test payment
// is made. Several balance assertions are made along the way for the sake of
// correctness.
func fundChanAndCloseFromImportedAccount(ht *lntest.HarnessTest, srcNode,
destNode, signer *node.HarnessNode, account string,
2021-02-20 02:42:20 +01:00
accountAddrType walletrpc.AddressType, utxoAmt, chanSize int64) {
// Retrieve the current confirmed balance to make some assertions later
// on.
balanceResp := srcNode.RPC.WalletBalance()
require.Contains(ht, balanceResp.AccountBalance, account)
2021-02-20 02:42:20 +01:00
accountConfBalance := balanceResp.
AccountBalance[account].ConfirmedBalance
defaultAccountConfBalance := balanceResp.
AccountBalance[defaultAccount].ConfirmedBalance
// Now, start the channel funding process. We'll need to connect both
// nodes first.
ht.EnsureConnected(srcNode, destNode)
2021-02-20 02:42:20 +01:00
// The source node will then fund the channel through a PSBT shim.
pendingChanID := ht.Random32Bytes()
chanUpdates, rawPsbt := ht.OpenChannelPsbt(
srcNode, destNode, lntest.OpenChannelParams{
2021-02-20 02:42:20 +01:00
Amt: btcutil.Amount(chanSize),
FundingShim: &lnrpc.FundingShim{
Shim: &lnrpc.FundingShim_PsbtShim{
PsbtShim: &lnrpc.PsbtShim{
PendingChanId: pendingChanID,
2021-02-20 02:42:20 +01:00
},
},
},
},
)
fundReq := &walletrpc.FundPsbtRequest{
Template: &walletrpc.FundPsbtRequest_Psbt{
Psbt: rawPsbt,
},
Fees: &walletrpc.FundPsbtRequest_SatPerVbyte{
SatPerVbyte: 1,
},
Account: account,
}
fundResp := srcNode.RPC.FundPsbt(fundReq)
2021-02-20 02:42:20 +01:00
srcNode.RPC.FundingStateStep(&lnrpc.FundingTransitionMsg{
2021-02-20 02:42:20 +01:00
Trigger: &lnrpc.FundingTransitionMsg_PsbtVerify{
PsbtVerify: &lnrpc.FundingPsbtVerify{
PendingChanId: pendingChanID,
2021-02-20 02:42:20 +01:00
FundedPsbt: fundResp.FundedPsbt,
},
},
})
// Now that we have a PSBT to fund the channel, our signer needs to sign
// it.
finalizeReq := &walletrpc.FinalizePsbtRequest{
FundedPsbt: fundResp.FundedPsbt,
}
finalizeResp := signer.RPC.FinalizePsbt(finalizeReq)
2021-02-20 02:42:20 +01:00
// The source node can then submit the signed PSBT and complete the
// channel funding process.
srcNode.RPC.FundingStateStep(&lnrpc.FundingTransitionMsg{
2021-02-20 02:42:20 +01:00
Trigger: &lnrpc.FundingTransitionMsg_PsbtFinalize{
PsbtFinalize: &lnrpc.FundingPsbtFinalize{
PendingChanId: pendingChanID,
2021-02-20 02:42:20 +01:00
SignedPsbt: finalizeResp.SignedPsbt,
},
},
})
// We should receive a notification of the channel funding transaction
// being broadcast.
updateResp := ht.ReceiveOpenChannelUpdate(chanUpdates)
2021-02-20 02:42:20 +01:00
upd, ok := updateResp.Update.(*lnrpc.OpenStatusUpdate_ChanPending)
require.True(ht, ok)
2021-02-20 02:42:20 +01:00
// Mine enough blocks to announce the channel to the network, making
// balance assertions along the way.
var (
expChanTxFee int64
expChangeScriptType txscript.ScriptClass
)
switch accountAddrType {
case walletrpc.AddressType_WITNESS_PUBKEY_HASH:
expChanTxFee = 153
expChangeScriptType = txscript.WitnessV0PubKeyHashTy
2021-02-20 02:42:20 +01:00
case walletrpc.AddressType_NESTED_WITNESS_PUBKEY_HASH:
if account != defaultImportedAccount {
expChanTxFee = 177
expChangeScriptType = txscript.ScriptHashTy
break
}
// Spends from the default NP2WKH imported account have the same
// fee rate as the hybrid address type since a NP2WKH input is
// spent and a P2WKH change output is created.
fallthrough
2021-02-20 02:42:20 +01:00
case walletrpc.AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
expChanTxFee = 176
expChangeScriptType = txscript.WitnessV0PubKeyHashTy
case walletrpc.AddressType_TAPROOT_PUBKEY:
if account != defaultImportedAccount {
expChanTxFee = 155
expChangeScriptType = txscript.WitnessV1TaprootTy
break
}
// Spends from the default imported account fall back to a P2WKH
// change. We'll want to change that, but in a separate PR.
expChanTxFee = 143
expChangeScriptType = txscript.WitnessV0PubKeyHashTy
2021-02-20 02:42:20 +01:00
default:
ht.Fatalf("unsupported addr type %v", accountAddrType)
2021-02-20 02:42:20 +01:00
}
chanChangeUtxoAmt := utxoAmt - chanSize - expChanTxFee
txHash, err := chainhash.NewHash(upd.ChanPending.Txid)
require.NoError(ht, err)
2021-02-20 02:42:20 +01:00
// If we're spending from the default imported account, then any change
// outputs produced are moved to the default wallet account, so we
// should expect to see balances there.
var confBalanceAfterChan int64
if account == defaultImportedAccount {
confBalanceAfterChan = defaultAccountConfBalance
ht.AssertWalletAccountBalance(srcNode, account, 0, 0)
ht.AssertWalletAccountBalance(
srcNode, defaultAccount, defaultAccountConfBalance,
2021-02-20 02:42:20 +01:00
chanChangeUtxoAmt,
)
block := ht.MineBlocksAndAssertNumTxes(6, 1)[0]
ht.AssertTxInBlock(block, *txHash)
2021-02-20 02:42:20 +01:00
confBalanceAfterChan += chanChangeUtxoAmt
ht.AssertWalletAccountBalance(srcNode, account, 0, 0)
ht.AssertWalletAccountBalance(
srcNode, defaultAccount, confBalanceAfterChan, 0,
2021-02-20 02:42:20 +01:00
)
} else {
// Otherwise, all interactions remain within Carol's imported
// account.
confBalanceAfterChan = accountConfBalance - utxoAmt
ht.AssertWalletAccountBalance(
srcNode, account, confBalanceAfterChan,
2021-02-20 02:42:20 +01:00
chanChangeUtxoAmt,
)
block := ht.MineBlocksAndAssertNumTxes(6, 1)[0]
ht.AssertTxInBlock(block, *txHash)
2021-02-20 02:42:20 +01:00
confBalanceAfterChan += chanChangeUtxoAmt
ht.AssertWalletAccountBalance(
srcNode, account, confBalanceAfterChan, 0,
2021-02-20 02:42:20 +01:00
)
}
// Assert that the transaction has the expected change address type
// based on the account.
var tx wire.MsgTx
err = tx.Deserialize(bytes.NewReader(finalizeResp.RawFinalTx))
require.NoError(ht, err)
assertOutputScriptType(
ht.T, expChangeScriptType, &tx, chanChangeUtxoAmt,
)
2021-02-20 02:42:20 +01:00
// Wait for the channel to be announced by both parties.
chanPoint := &lnrpc.ChannelPoint{
FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
FundingTxidBytes: upd.ChanPending.Txid,
},
OutputIndex: upd.ChanPending.OutputIndex,
}
ht.AssertTopologyChannelOpen(srcNode, chanPoint)
ht.AssertTopologyChannelOpen(destNode, chanPoint)
2021-02-20 02:42:20 +01:00
// Send a test payment to ensure the channel is operating as normal.
const invoiceAmt = 100000
invoice := &lnrpc.Invoice{
2021-02-20 02:42:20 +01:00
Memo: "psbt import chan",
Value: invoiceAmt,
}
resp := destNode.RPC.AddInvoice(invoice)
2021-02-20 02:42:20 +01:00
ht.CompletePaymentRequests(srcNode, []string{resp.PaymentRequest})
2021-02-20 02:42:20 +01:00
// Now that we've confirmed the opened channel works, we'll close it.
ht.CloseChannel(srcNode, chanPoint)
2021-02-20 02:42:20 +01:00
// Since the channel still had funds left on the source node's side,
// they must've been redeemed after the close. Without a pre-negotiated
// close address, the funds will go into the source node's wallet
// instead of the imported account.
const chanCloseTxFee = 9650
2021-02-20 02:42:20 +01:00
balanceFromClosedChan := chanSize - invoiceAmt - chanCloseTxFee
if account == defaultImportedAccount {
ht.AssertWalletAccountBalance(srcNode, account, 0, 0)
ht.AssertWalletAccountBalance(
srcNode, defaultAccount,
2021-02-20 02:42:20 +01:00
confBalanceAfterChan+balanceFromClosedChan, 0,
)
} else {
ht.AssertWalletAccountBalance(
srcNode, account, confBalanceAfterChan, 0,
2021-02-20 02:42:20 +01:00
)
ht.AssertWalletAccountBalance(
srcNode, defaultAccount, balanceFromClosedChan, 0,
2021-02-20 02:42:20 +01:00
)
}
}
// testWalletImportAccount tests that an imported account can fund transactions
// and channels through PSBTs, by having one node (the one with the imported
// account) craft the transactions and another node act as the signer.
func testWalletImportAccount(ht *lntest.HarnessTest) {
2021-02-20 02:42:20 +01:00
testCases := []struct {
name string
addrType walletrpc.AddressType
}{
{
name: "standard BIP-0044",
addrType: walletrpc.AddressType_WITNESS_PUBKEY_HASH,
},
2021-02-20 02:42:20 +01:00
{
2022-10-25 18:55:26 +02:00
name: "standard BIP-0049",
addrType: walletrpc.
AddressType_NESTED_WITNESS_PUBKEY_HASH,
2021-02-20 02:42:20 +01:00
},
{
2022-10-25 18:55:26 +02:00
name: "lnd BIP-0049 variant",
addrType: walletrpc.
AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH,
2021-02-20 02:42:20 +01:00
},
{
name: "standard BIP-0084",
addrType: walletrpc.AddressType_WITNESS_PUBKEY_HASH,
},
{
name: "standard BIP-0086",
addrType: walletrpc.AddressType_TAPROOT_PUBKEY,
},
2021-02-20 02:42:20 +01:00
}
for _, tc := range testCases {
tc := tc
success := ht.Run(tc.name, func(tt *testing.T) {
testFunc := func(ht *lntest.HarnessTest) {
testWalletImportAccountScenario(
ht, tc.addrType,
)
}
st := ht.Subtest(tt)
st.RunTestCase(&lntest.TestCase{
Name: tc.name,
TestFunc: testFunc,
2021-02-20 02:42:20 +01:00
})
})
if !success {
// Log failure time to help relate the lnd logs to the
// failure.
ht.Logf("Failure time: %v", time.Now().Format(
2021-02-20 02:42:20 +01:00
"2006-01-02 15:04:05.000",
))
break
}
}
}
func testWalletImportAccountScenario(ht *lntest.HarnessTest,
2021-02-20 02:42:20 +01:00
addrType walletrpc.AddressType) {
// We'll start our test by having two nodes, Carol and Dave. Carol's
// default wallet account will be imported into Dave's node.
//
// NOTE: we won't use standby nodes here since the test will change
// each of the node's wallet state.
carol := ht.NewNode("carol", nil)
dave := ht.NewNode("dave", nil)
2021-02-20 02:42:20 +01:00
runWalletImportAccountScenario(ht, addrType, carol, dave)
2021-10-14 15:42:59 +02:00
}
func runWalletImportAccountScenario(ht *lntest.HarnessTest,
addrType walletrpc.AddressType, carol, dave *node.HarnessNode) {
2021-10-14 15:42:59 +02:00
const utxoAmt int64 = btcutil.SatoshiPerBitcoin
2021-02-20 02:42:20 +01:00
listReq := &walletrpc.ListAccountsRequest{
Name: "default",
AddressType: addrType,
}
listResp := carol.RPC.ListAccounts(listReq)
require.Len(ht, listResp.Accounts, 1)
2021-02-20 02:42:20 +01:00
carolAccount := listResp.Accounts[0]
const importedAccount = "carol"
importReq := &walletrpc.ImportAccountRequest{
Name: importedAccount,
ExtendedPublicKey: carolAccount.ExtendedPublicKey,
AddressType: addrType,
}
dave.RPC.ImportAccount(importReq)
2021-02-20 02:42:20 +01:00
// Try to import an account with the same name but with a different
// key scope. It should return an error.
otherAddrType := walletrpc.AddressType_TAPROOT_PUBKEY
if addrType == walletrpc.AddressType_TAPROOT_PUBKEY {
otherAddrType--
}
listReq = &walletrpc.ListAccountsRequest{
Name: "default",
AddressType: otherAddrType,
}
listResp = carol.RPC.ListAccounts(listReq)
require.Len(ht, listResp.Accounts, 1)
carolAccountOtherAddrType := listResp.Accounts[0]
errAccountExists := fmt.Sprintf(
"account '%s' already exists", importedAccount,
)
importReq = &walletrpc.ImportAccountRequest{
Name: importedAccount,
ExtendedPublicKey: carolAccountOtherAddrType.ExtendedPublicKey,
AddressType: otherAddrType,
}
err := dave.RPC.ImportAccountAssertErr(importReq)
require.ErrorContains(ht, err, errAccountExists)
2021-02-20 02:42:20 +01:00
// We'll generate an address for Carol from Dave's node to receive some
// funds.
externalAddr := newExternalAddr(
ht, dave, carol, importedAccount, addrType,
2021-02-20 02:42:20 +01:00
)
// Send coins to Carol's address and confirm them, making sure the
// balance updates accordingly.
alice := ht.Alice
req := &lnrpc.SendCoinsRequest{
2021-02-20 02:42:20 +01:00
Addr: externalAddr,
Amount: utxoAmt,
SatPerByte: 1,
}
alice.RPC.SendCoins(req)
2021-02-20 02:42:20 +01:00
ht.AssertWalletAccountBalance(dave, importedAccount, 0, utxoAmt)
ht.MineBlocksAndAssertNumTxes(1, 1)
ht.AssertWalletAccountBalance(dave, importedAccount, utxoAmt, 0)
2021-02-20 02:42:20 +01:00
// To ensure that Dave can use Carol's account as watch-only, we'll
// construct a PSBT that sends funds to Alice, which we'll then hand
// over to Carol to sign.
psbtSendFromImportedAccount(
ht, dave, alice, carol, importedAccount, addrType,
2021-02-20 02:42:20 +01:00
)
// We'll generate a new address for Carol from Dave's node to receive
// and fund a new channel.
externalAddr = newExternalAddr(
ht, dave, carol, importedAccount, addrType,
2021-02-20 02:42:20 +01:00
)
// Retrieve the current confirmed balance of the imported account for
// some assertions we'll make later on.
balanceResp := dave.RPC.WalletBalance()
require.Contains(ht, balanceResp.AccountBalance, importedAccount)
2022-10-25 18:55:26 +02:00
confBalance := balanceResp.AccountBalance[importedAccount].
ConfirmedBalance
2021-02-20 02:42:20 +01:00
// Send coins to Carol's address and confirm them, making sure the
// balance updates accordingly.
req = &lnrpc.SendCoinsRequest{
2021-02-20 02:42:20 +01:00
Addr: externalAddr,
Amount: utxoAmt,
SatPerByte: 1,
}
alice.RPC.SendCoins(req)
2021-02-20 02:42:20 +01:00
2022-10-25 18:55:26 +02:00
ht.AssertWalletAccountBalance(
dave, importedAccount, confBalance, utxoAmt,
)
ht.MineBlocksAndAssertNumTxes(1, 1)
2022-10-25 18:55:26 +02:00
ht.AssertWalletAccountBalance(
dave, importedAccount, confBalance+utxoAmt, 0,
)
2021-02-20 02:42:20 +01:00
// Now that we have enough funds, it's time to fund the channel, make a
// test payment, and close it. This contains several balance assertions
// along the way.
fundChanAndCloseFromImportedAccount(
ht, dave, alice, carol, importedAccount, addrType, utxoAmt,
2021-02-20 02:42:20 +01:00
int64(funding.MaxBtcFundingAmount),
)
}
// testWalletImportPubKey tests that an imported public keys can fund
// transactions and channels through PSBTs, by having one node (the one with the
// imported account) craft the transactions and another node act as the signer.
func testWalletImportPubKey(ht *lntest.HarnessTest) {
2021-02-20 02:42:20 +01:00
testCases := []struct {
name string
addrType walletrpc.AddressType
}{
{
2022-10-25 18:55:26 +02:00
name: "BIP-0049",
addrType: walletrpc.
AddressType_NESTED_WITNESS_PUBKEY_HASH,
2021-02-20 02:42:20 +01:00
},
{
name: "BIP-0084",
addrType: walletrpc.AddressType_WITNESS_PUBKEY_HASH,
},
{
name: "BIP-0086",
addrType: walletrpc.AddressType_TAPROOT_PUBKEY,
},
2021-02-20 02:42:20 +01:00
}
for _, tc := range testCases {
tc := tc
success := ht.Run(tc.name, func(tt *testing.T) {
testFunc := func(ht *lntest.HarnessTest) {
testWalletImportPubKeyScenario(
ht, tc.addrType,
)
}
st := ht.Subtest(tt)
st.RunTestCase(&lntest.TestCase{
Name: tc.name,
TestFunc: testFunc,
2021-02-20 02:42:20 +01:00
})
})
if !success {
// Log failure time to help relate the lnd logs to the
// failure.
ht.Logf("Failure time: %v", time.Now().Format(
2021-02-20 02:42:20 +01:00
"2006-01-02 15:04:05.000",
))
break
}
}
}
func testWalletImportPubKeyScenario(ht *lntest.HarnessTest,
2021-02-20 02:42:20 +01:00
addrType walletrpc.AddressType) {
const utxoAmt int64 = btcutil.SatoshiPerBitcoin
alice := ht.Alice
2021-02-20 02:42:20 +01:00
// We'll start our test by having two nodes, Carol and Dave.
//
// NOTE: we won't use standby nodes here since the test will change
// each of the node's wallet state.
carol := ht.NewNode("carol", nil)
dave := ht.NewNode("dave", nil)
2021-02-20 02:42:20 +01:00
// We'll define a helper closure that we'll use throughout the test to
// generate a new address of the given type from Carol's perspective,
// import it into Dave's wallet, and fund it.
importPubKey := func(keyIndex uint32, prevConfBalance,
prevUnconfBalance int64) {
2021-02-20 02:42:20 +01:00
// Retrieve Carol's account public key for the corresponding
// address type.
listReq := &walletrpc.ListAccountsRequest{
Name: "default",
AddressType: addrType,
}
listResp := carol.RPC.ListAccounts(listReq)
require.Len(ht, listResp.Accounts, 1)
2021-02-20 02:42:20 +01:00
p2wkhAccount := listResp.Accounts[0]
// Derive the external address at the given index.
accountPubKey, err := hdkeychain.NewKeyFromString(
p2wkhAccount.ExtendedPublicKey,
)
require.NoError(ht, err)
2021-02-20 02:42:20 +01:00
externalAccountExtKey, err := accountPubKey.Derive(0)
require.NoError(ht, err)
2022-10-25 18:55:26 +02:00
externalAddrExtKey, err := externalAccountExtKey.Derive(
keyIndex,
)
require.NoError(ht, err)
2021-02-20 02:42:20 +01:00
externalAddrPubKey, err := externalAddrExtKey.ECPubKey()
require.NoError(ht, err)
2021-02-20 02:42:20 +01:00
// Serialize as 32-byte x-only pubkey for Taproot addresses.
serializedPubKey := externalAddrPubKey.SerializeCompressed()
if addrType == walletrpc.AddressType_TAPROOT_PUBKEY {
serializedPubKey = schnorr.SerializePubKey(
externalAddrPubKey,
)
}
2021-02-20 02:42:20 +01:00
// Import the public key into Dave.
importReq := &walletrpc.ImportPublicKeyRequest{
PublicKey: serializedPubKey,
2021-02-20 02:42:20 +01:00
AddressType: addrType,
}
dave.RPC.ImportPublicKey(importReq)
2021-02-20 02:42:20 +01:00
// We'll also generate the same address for Carol, as it'll be
// required later when signing.
carolAddrResp := carol.RPC.NewAddress(&lnrpc.NewAddressRequest{
Type: walletToLNAddrType(ht.T, addrType),
})
2021-02-20 02:42:20 +01:00
// Send coins to Carol's address and confirm them, making sure
// the balance updates accordingly.
req := &lnrpc.SendCoinsRequest{
2021-02-20 02:42:20 +01:00
Addr: carolAddrResp.Address,
Amount: utxoAmt,
SatPerByte: 1,
}
alice.RPC.SendCoins(req)
2021-02-20 02:42:20 +01:00
ht.AssertWalletAccountBalance(
dave, defaultImportedAccount, prevConfBalance,
2021-02-20 02:42:20 +01:00
prevUnconfBalance+utxoAmt,
)
ht.MineBlocksAndAssertNumTxes(1, 1)
ht.AssertWalletAccountBalance(
dave, defaultImportedAccount,
2021-02-20 02:42:20 +01:00
prevConfBalance+utxoAmt, prevUnconfBalance,
)
}
// We'll have Carol generate a new external address, which we'll import
// into Dave.
importPubKey(0, 0, 0)
// To ensure that Dave can use Carol's public key as watch-only, we'll
// construct a PSBT that sends funds to Alice, which we'll then hand
// over to Carol to sign.
psbtSendFromImportedAccount(
ht, dave, alice, carol, defaultImportedAccount, addrType,
2021-02-20 02:42:20 +01:00
)
// We'll now attempt to fund a channel.
//
// We'll have Carol generate another external address, which we'll
// import into Dave again.
balanceResp := dave.RPC.WalletBalance()
require.Contains(ht, balanceResp.AccountBalance, defaultImportedAccount)
2021-02-20 02:42:20 +01:00
confBalance := balanceResp.
AccountBalance[defaultImportedAccount].ConfirmedBalance
importPubKey(1, confBalance, 0)
// Now that we have enough funds, it's time to fund the channel, make a
// test payment, and close it. This contains several balance assertions
// along the way.
fundChanAndCloseFromImportedAccount(
ht, dave, alice, carol, defaultImportedAccount, addrType,
2021-02-20 02:42:20 +01:00
utxoAmt, int64(funding.MaxBtcFundingAmount),
)
}