Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add ledger derivation at address index #17

Merged
merged 5 commits into from
Jul 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
168 changes: 100 additions & 68 deletions src/dlc-handlers/ledger-dlc-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ import {
getBalance,
getFeeRate,
getInputByPaymentTypeArray,
getInputIndicesByScript,
getUnspendableKeyCommittedToUUID,
} from '../functions/bitcoin/bitcoin-functions.js';
import {
addNativeSegwitSignaturesToPSBT,
addTaprootInputSignaturesToPSBT,
addFundingSignaturesBasedOnPaymentType,
addTaprooMultisigInputSignaturesToPSBT,
createDepositTransaction,
createFundingTransaction,
createWithdrawTransaction,
Expand All @@ -40,6 +41,7 @@ export class LedgerDLCHandler {
private ledgerApp: AppClient;
private masterFingerprint: string;
private walletAccountIndex: number;
private walletAddressIndex: number;
private fundingPaymentType: 'wpkh' | 'tr';
private policyInformation: LedgerPolicyInformation | undefined;
public payment: ExtendedPaymentInformation | undefined;
Expand All @@ -52,6 +54,7 @@ export class LedgerDLCHandler {
ledgerApp: AppClient,
masterFingerprint: string,
walletAccountIndex: number,
walletAddressIndex: number,
fundingPaymentType: 'wpkh' | 'tr',
bitcoinNetwork: Network,
bitcoinBlockchainAPI?: string,
Expand Down Expand Up @@ -89,6 +92,7 @@ export class LedgerDLCHandler {
this.ledgerApp = ledgerApp;
this.masterFingerprint = masterFingerprint;
this.walletAccountIndex = walletAccountIndex;
this.walletAddressIndex = walletAddressIndex;
this.fundingPaymentType = fundingPaymentType;
this.bitcoinNetwork = bitcoinNetwork;
}
Expand Down Expand Up @@ -185,13 +189,14 @@ export class LedgerDLCHandler {
fundingWalletPolicy,
null,
0,
0,
this.walletAddressIndex,
false
);

const fundingDerivedPublicKey = deriveUnhardenedPublicKey(
fundingExtendedPublicKey,
this.bitcoinNetwork
this.bitcoinNetwork,
this.walletAddressIndex
);

const fundingPayment =
Expand Down Expand Up @@ -321,7 +326,10 @@ export class LedgerDLCHandler {
const signingConfiguration = createBitcoinInputSigningConfiguration(
fundingTransaction,
this.walletAccountIndex,
this.bitcoinNetwork
this.walletAddressIndex,
multisigPayment,
this.bitcoinNetwork,
this.bitcoinNetworkIndex
);

const formattedFundingPSBT = Psbt.fromBuffer(Buffer.from(fundingTransaction.toPSBT()), {
Expand Down Expand Up @@ -394,7 +402,10 @@ export class LedgerDLCHandler {
const withdrawTransactionSigningConfiguration = createBitcoinInputSigningConfiguration(
withdrawTransaction,
this.walletAccountIndex,
this.bitcoinNetwork
this.walletAddressIndex,
multisigPayment,
this.bitcoinNetwork,
this.bitcoinNetworkIndex
);

const formattedWithdrawPSBT = Psbt.fromBuffer(Buffer.from(withdrawTransaction.toPSBT()), {
Expand Down Expand Up @@ -452,7 +463,10 @@ export class LedgerDLCHandler {
const depositTransactionSigningConfiguration = createBitcoinInputSigningConfiguration(
depositTransaction,
this.walletAccountIndex,
this.bitcoinNetwork
this.walletAddressIndex,
multisigPayment,
this.bitcoinNetwork,
this.bitcoinNetworkIndex
);

const formattedDepositPSBT = Psbt.fromBuffer(Buffer.from(depositTransaction.toPSBT()), {
Expand All @@ -466,22 +480,42 @@ export class LedgerDLCHandler {
);

const taprootInputsToSign = getTaprootInputsToSign(depositInputByPaymentTypeArray);
const nativeSegwitInputsToSign = getNativeSegwitInputsToSign(depositInputByPaymentTypeArray);

const taprootUserInputsToSign = taprootInputsToSign.filter(inputSigningConfig => {
return !inputSigningConfig.isMultisigInput;
});

const taprootMultisigInputsToSign = taprootInputsToSign.filter(inputSigningConfig => {
return inputSigningConfig.isMultisigInput;
});

await updateTaprootInputs(
taprootInputsToSign,
taprootMultisigInputsToSign,
taprootDerivedPublicKey,
this.masterFingerprint,
formattedDepositPSBT
);

await updateNativeSegwitInputs(
nativeSegwitInputsToSign,
fundingDerivedPublicKey,
this.masterFingerprint,
formattedDepositPSBT,
this.bitcoinBlockchainAPI
);
if (taprootUserInputsToSign.length !== 0) {
await updateTaprootInputs(
taprootUserInputsToSign,
fundingDerivedPublicKey,
this.masterFingerprint,
formattedDepositPSBT
);
}

const nativeSegwitInputsToSign = getNativeSegwitInputsToSign(depositInputByPaymentTypeArray);

if (nativeSegwitInputsToSign.length !== 0) {
await updateNativeSegwitInputs(
nativeSegwitInputsToSign,
fundingDerivedPublicKey,
this.masterFingerprint,
formattedDepositPSBT,
this.bitcoinBlockchainAPI
);
}

return formattedDepositPSBT;
}
Expand All @@ -490,61 +524,59 @@ export class LedgerDLCHandler {
psbt: Psbt,
transactionType: 'funding' | 'deposit' | 'withdraw'
): Promise<Transaction> {
let transaction: Transaction;

const { fundingWalletPolicy, multisigWalletPolicy, multisigWalletPolicyHMac } =
this.getPolicyInformation();
if (transactionType === 'funding') {
const signatures = await this.ledgerApp.signPsbt(psbt.toBase64(), fundingWalletPolicy, null);
switch (this.fundingPaymentType) {
case 'wpkh':
addNativeSegwitSignaturesToPSBT(psbt, signatures);
break;
case 'tr':
addTaprootInputSignaturesToPSBT('funding', psbt, signatures);
break;
default:
throw new Error('Invalid Funding Payment Type');
}
const fundingTransaction = Transaction.fromPSBT(psbt.toBuffer());
fundingTransaction.finalize();
return fundingTransaction;
} else if (transactionType === 'deposit') {
const multisigSignatures = await this.ledgerApp.signPsbt(
psbt.toBase64(),
multisigWalletPolicy,
multisigWalletPolicyHMac
);
addTaprootInputSignaturesToPSBT('depositWithdraw', psbt, multisigSignatures);
const userSignatures = await this.ledgerApp.signPsbt(
psbt.toBase64(),
fundingWalletPolicy,
null
);
switch (this.fundingPaymentType) {
case 'wpkh':
addNativeSegwitSignaturesToPSBT(psbt, userSignatures);
break;
case 'tr':
addTaprootInputSignaturesToPSBT('funding', psbt, userSignatures);
break;
default:
throw new Error('Invalid Funding Payment Type');
}
const userInputIndices = userSignatures.map(signature => signature[0]);

const depositTransaction = Transaction.fromPSBT(psbt.toBuffer());
userInputIndices.forEach(index => {
depositTransaction.finalizeIdx(index);
});
return depositTransaction;
} else {
const multisigSignatures = await this.ledgerApp.signPsbt(
psbt.toBase64(),
multisigWalletPolicy,
multisigWalletPolicyHMac
);
addTaprootInputSignaturesToPSBT('depositWithdraw', psbt, multisigSignatures);
const withdrawTransaction = Transaction.fromPSBT(psbt.toBuffer());
return withdrawTransaction;
switch (transactionType) {
case 'funding':
addFundingSignaturesBasedOnPaymentType(
psbt,
this.fundingPaymentType,
await this.ledgerApp.signPsbt(psbt.toBase64(), fundingWalletPolicy, null)
);
transaction = Transaction.fromPSBT(psbt.toBuffer());
transaction.finalize();
break;
case 'deposit':
addTaprooMultisigInputSignaturesToPSBT(
psbt,
await this.ledgerApp.signPsbt(
psbt.toBase64(),
multisigWalletPolicy,
multisigWalletPolicyHMac
)
);

addFundingSignaturesBasedOnPaymentType(
psbt,
this.fundingPaymentType,
await this.ledgerApp.signPsbt(psbt.toBase64(), fundingWalletPolicy, null)
);

transaction = Transaction.fromPSBT(psbt.toBuffer());

getInputIndicesByScript(this.getPayment().fundingPayment.script, transaction).forEach(
index => {
transaction.finalizeIdx(index);
}
);
break;
case 'withdraw':
addTaprooMultisigInputSignaturesToPSBT(
psbt,
await this.ledgerApp.signPsbt(
psbt.toBase64(),
multisigWalletPolicy,
multisigWalletPolicyHMac
)
);
transaction = Transaction.fromPSBT(psbt.toBuffer());
break;
default:
throw new Error('Invalid Transaction Type');
}
return transaction;
}
}
44 changes: 32 additions & 12 deletions src/functions/bitcoin/bitcoin-functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,11 @@ export function getFeeAmount(bitcoinAmount: number, feeBasisPoints: number): num
*/
export function deriveUnhardenedPublicKey(
extendedPublicKey: string,
bitcoinNetwork: Network
bitcoinNetwork: Network,
addressIndex: number = 0
): Buffer {
return bip32.fromBase58(extendedPublicKey, bitcoinNetwork).derivePath('0/0').publicKey;
return bip32.fromBase58(extendedPublicKey, bitcoinNetwork).derivePath(`0/${addressIndex}`)
.publicKey;
}

/**
Expand Down Expand Up @@ -367,31 +369,49 @@ function getAddressFromOutScript(script: Uint8Array, bitcoinNetwork: Network): s
export function createBitcoinInputSigningConfiguration(
transaction: Transaction,
walletAccountIndex: number,
bitcoinNetwork: Network
walletAddressIndex: number,
multisigPayment: P2TROut,
bitcoinNetwork: Network,
bitcoinNetworkIndex: number
): BitcoinInputSigningConfig[] {
const networkIndex = bitcoinNetwork === bitcoin ? 0 : 1;
const nativeSegwitDerivationPath = `m/84'/${bitcoinNetworkIndex}'/${walletAccountIndex}'/0/${walletAddressIndex}`;
const taprootDerivationPath = `m/86'/${bitcoinNetworkIndex}'/${walletAccountIndex}'/0/${walletAddressIndex}`;
const multisigDerivationPath = `m/86'/${bitcoinNetworkIndex}'/${walletAccountIndex}'/0/0`;

const nativeSegwitDerivationPath = `m/84'/${networkIndex}'/${walletAccountIndex}'/0/0`;
const taprootDerivationPath = `m/86'/${networkIndex}'/${walletAccountIndex}'/0/0`;
const multisigPaymentScript = multisigPayment.script;

const indexesToSign = createRangeFromLength(transaction.inputsLength);
return indexesToSign.map(inputIndex => {
return createRangeFromLength(transaction.inputsLength).map(inputIndex => {
const input = transaction.getInput(inputIndex);

if (isUndefined(input.index)) throw new Error('Input must have an index for payment type');

const paymentType = getInputPaymentType(input.index, input, bitcoinNetwork);

const witnessUTXOScript = input.witnessUtxo?.script;

if (isUndefined(witnessUTXOScript)) throw new Error('Witness UTXO Script is undefined');

switch (paymentType) {
case 'p2wpkh':
return {
index: inputIndex,
derivationPath: nativeSegwitDerivationPath,
isMultisigInput: false,
};
case 'p2tr':
return {
index: inputIndex,
derivationPath: taprootDerivationPath,
};
if (compareUint8Arrays(witnessUTXOScript, multisigPaymentScript)) {
return {
index: inputIndex,
derivationPath: multisigDerivationPath,
isMultisigInput: true,
};
} else {
return {
index: inputIndex,
derivationPath: taprootDerivationPath,
isMultisigInput: false,
};
}
default:
throw new Error('Unsupported Payment Type');
}
Expand Down
Loading
Loading