Skip to content

Commit

Permalink
chore: friday signing progress, pt2
Browse files Browse the repository at this point in the history
  • Loading branch information
kyranjamie committed Nov 6, 2023
1 parent d45194b commit 8e51646
Show file tree
Hide file tree
Showing 8 changed files with 54 additions and 81 deletions.
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import { useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import { Outlet, Route, useLocation, useNavigate } from 'react-router-dom';
import { Outlet, Route, useLocation } from 'react-router-dom';

import { bytesToHex } from '@noble/hashes/utils';
import * as btc from '@scure/btc-signer';
import { hexToBytes } from '@stacks/common';
import { Psbt } from 'bitcoinjs-lib';
import get from 'lodash.get';

import { RouteUrls } from '@shared/route-urls';
Expand All @@ -19,8 +16,6 @@ import {
LedgerTxSigningProvider,
} from '@app/features/ledger/generic-flows/tx-signing/ledger-sign-tx.context';
import { useActionCancellableByUser } from '@app/features/ledger/utils/stacks-ledger-utils';
import { useSendFormNavigate } from '@app/pages/send/send-crypto-asset-form/hooks/use-send-form-navigate';
import { useBitcoinBroadcastTransaction } from '@app/query/bitcoin/transaction/use-bitcoin-broadcast-transaction';
import { useSignLedgerTx } from '@app/store/accounts/blockchain/bitcoin/native-segwit-account.hooks';

import { ConnectLedgerSignTx } from '../../generic-flows/tx-signing/steps/connect-ledger-sign-tx';
Expand Down Expand Up @@ -64,12 +59,10 @@ export function LedgerSignBitcoinTxContainer() {
const ledgerAnalytics = useLedgerAnalytics();
useScrollLock(true);

const navigate = useNavigate();
const canUserCancelAction = useActionCancellableByUser();
const [unsignedTransactionRaw, setUnsignedTransactionRaw] = useState<null | string>(null);
const [unsignedTransaction, setUnsignedTransaction] = useState<null | btc.Transaction>(null);
const signLedger = useSignLedgerTx();
const sendFormNavigate = useSendFormNavigate();

useEffect(() => {
const tx = get(location.state, 'tx');
Expand Down Expand Up @@ -104,7 +97,6 @@ export function LedgerSignBitcoinTxContainer() {
try {
const btcTx = await signLedger(bitcoinApp, unsignedTransaction.toPSBT());
if (!btcTx || !unsignedTransactionRaw) throw new Error('No tx returned');
console.log('response from ledger', { resp: btcTx });
ledgerNavigate.toAwaitingDeviceOperation({ hasApprovedOperation: true });
await delay(1000);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ export function useGenerateUnsignedOrdinalTx(trInput: TaprootUtxo) {
feeRate: values.feeRate,
});

console.log('result', result);

if (!result.success) return null;

const { inputs, outputs } = result;
Expand Down Expand Up @@ -100,17 +102,6 @@ export function useGenerateUnsignedOrdinalTx(trInput: TaprootUtxo) {
// Recipient and change outputs
outputs.forEach(output => tx.addOutputAddress(output.address, output.value, networkMode));

// We know the first is TR and the rest are native segwit
// for (let i = 0; i < tx.inputsLength; i++) {
// if (i === 0) {
// trSigner.signIndex(tx, i);
// continue;
// }
// nativeSegwitSigner.signIndex(tx, i);
// }

// tx.finalize();

tx.toPSBT();

return { hex: bytesToHex(tx.toPSBT()) };
Expand Down Expand Up @@ -164,9 +155,6 @@ export function useGenerateUnsignedOrdinalTx(trInput: TaprootUtxo) {
tx.addOutputAddress(values.recipient, BigInt(output.value), networkMode);
});

nativeSegwitSigner.sign(tx);
tx.finalize();

return { hex: tx.hex };
} catch (e) {
logger.error('Unable to sign transaction');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,16 @@ import * as yup from 'yup';
import { logger } from '@shared/logger';
import { OrdinalSendFormValues } from '@shared/models/form.model';
import { RouteUrls } from '@shared/route-urls';
import { noop } from '@shared/utils';

import { FormErrorMessages } from '@app/common/error-messages';
import { useAnalytics } from '@app/common/hooks/analytics/use-analytics';
import { formFeeRowValue } from '@app/common/send/utils';
import { useWalletType } from '@app/common/use-wallet-type';
import {
btcAddressNetworkValidator,
btcAddressValidator,
} from '@app/common/validation/forms/address-validators';
import { useNumberOfInscriptionsOnUtxo } from '@app/query/bitcoin/ordinals/inscriptions.hooks';
import { useSignBitcoinTx } from '@app/store/accounts/blockchain/bitcoin/bitcoin.hooks';
import { useCurrentNetwork } from '@app/store/networks/networks.selectors';

import { useSendInscriptionState } from '../components/send-inscription-container';
Expand All @@ -28,7 +27,7 @@ export function useSendInscriptionForm() {
const [isCheckingFees, setIsCheckingFees] = useState(false);
const analytics = useAnalytics();
const navigate = useNavigate();
const { whenWallet } = useWalletType();
const sign = useSignBitcoinTx();
const { inscription, utxo } = useSendInscriptionState();
const currentNetwork = useCurrentNetwork();

Expand Down Expand Up @@ -75,16 +74,10 @@ export function useSendInscriptionForm() {
setIsCheckingFees(false);
}

whenWallet({
software: () =>
navigate(
`/${RouteUrls.SendOrdinalInscription}/${RouteUrls.SendOrdinalInscriptionChooseFee}`,
{
state: { inscription, recipient: values.recipient, utxo },
}
),
ledger: noop,
})();
navigate(
`/${RouteUrls.SendOrdinalInscription}/${RouteUrls.SendOrdinalInscriptionChooseFee}`,
{ state: { inscription, recipient: values.recipient, utxo } }
);
},

async reviewTransaction(
Expand All @@ -101,22 +94,22 @@ export function useSendInscriptionForm() {
return;
}

const { hex } = resp;
const { hex: unsignedTransaction } = resp;

const signedTx = await sign(unsignedTransaction);

const feeRowValue = formFeeRowValue(values.feeRate, isCustomFee);
return navigate(
`/${RouteUrls.SendOrdinalInscription}/${RouteUrls.SendOrdinalInscriptionReview}`,
{
state: {
fee: feeValue,
inscription,
utxo,
recipient: values.recipient,
time,
feeRowValue,
tx: hex,
},
}
);
navigate(`/${RouteUrls.SendOrdinalInscription}/${RouteUrls.SendOrdinalInscriptionReview}`, {
state: {
fee: feeValue,
inscription,
utxo,
recipient: values.recipient,
time,
feeRowValue,
tx: hex,
},
});
},

validationSchema: yup.object({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { BitcoinChooseFee } from '@app/features/bitcoin-choose-fee/bitcoin-choos
import { useValidateBitcoinSpend } from '@app/features/bitcoin-choose-fee/hooks/use-validate-bitcoin-spend';

import { useSendInscriptionState } from './components/send-inscription-container';
import { useSignOrdinalsSoftwareWalletTx } from './hooks/use-generate-ordinal-tx';
import { useSendInscriptionFeesList } from './hooks/use-send-inscription-fees-list';
import { useSendInscriptionForm } from './hooks/use-send-inscription-form';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ function useBtcSendFormConfirmationState() {
export function BtcSendFormConfirmation() {
const navigate = useNavigate();
const { tx, recipient, fee, arrivesIn, feeRowValue } = useBtcSendFormConfirmationState();
console.log({ tx });

const { refetch } = useCurrentNativeSegwitUtxos();
const analytics = useAnalytics();

Expand All @@ -58,8 +58,6 @@ export function BtcSendFormConfirmation() {

const transaction = btc.Transaction.fromRaw(hexToBytes(tx));

// const psbt = Psbt.fromHex(transaction.toPSBT());

const decodedTx = decodeBitcoinTx(transaction.hex);

const nav = useSendFormNavigate();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ export function useBtcChooseFee() {
const generateTx = useGenerateSignedNativeSegwitTx();
const { setSelectedFeeType } = useSendBitcoinAssetContextState();
const calcMaxSpend = useCalculateMaxBitcoinSpend();
// const signLedger = useSignNativeSegwitLedgerTx();
const signTx = useSignBitcoinTx();
const amountAsMoney = createMoney(btcToSat(txValues.amount).toNumber(), 'BTC');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import AppClient from 'ledger-bitcoin';
import { getBitcoinJsLibNetworkConfigByMode } from '@shared/crypto/bitcoin/bitcoin.network';
import {
deriveAddressIndexZeroFromAccount,
ecdsaPublicKeyToSchnorr,
getInputPaymentType,
lookUpLedgerKeysByPath,
} from '@shared/crypto/bitcoin/bitcoin.utils';
Expand Down Expand Up @@ -43,7 +42,7 @@ import {
bitcoinAddressIndexSignerFactory,
useMakeBitcoinNetworkSignersForPaymentType,
} from './bitcoin-signer';
import { useCurrentAccountTaprootIndexZeroSigner } from './taproot-account.hooks';
import { useUpdateLedgerSpecificTaprootInputPropsForAdddressIndexZero } from './taproot-account.hooks';

const selectNativeSegwitAccountBuilder = bitcoinAccountBuilderFactory(
deriveNativeSegwitAccountFromRootKeychain,
Expand Down Expand Up @@ -138,28 +137,6 @@ export function getNativeSegwitMainnetAddressFromMnemonic(secretKey: string) {
};
}

export function useUpdateLedgerSpecificTaprootInputPropsForAdddressIndexZero() {
const taprootSigner = useCurrentAccountTaprootIndexZeroSigner();

return async (tx: Psbt, fingerprint: string, inputsToUpdate: number[] = []) => {
const inputsToSign =
inputsToUpdate.length > 0 ? inputsToUpdate : makeNumberRange(tx.inputCount);

inputsToSign.forEach(inputIndex => {
tx.updateInput(inputIndex, {
tapBip32Derivation: [
{
masterFingerprint: Buffer.from(fingerprint, 'hex'),
pubkey: Buffer.from(ecdsaPublicKeyToSchnorr(taprootSigner.publicKey)),
path: taprootSigner.derivationPath,
leafHashes: [],
},
],
});
});
};
}

export function useUpdateLedgerSpecificNativeSegwitInputPropsForAdddressIndexZero() {
const nativeSegwitSigner = useCurrentAccountNativeSegwitIndexZeroSigner();
const bitcoinClient = useBitcoinClient();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@ import { useMemo } from 'react';
import { useSelector } from 'react-redux';

import { createSelector } from '@reduxjs/toolkit';
import { Psbt } from 'bitcoinjs-lib';

import { BitcoinNetworkModes } from '@shared/constants';
import { lookUpLedgerKeysByPath } from '@shared/crypto/bitcoin/bitcoin.utils';
import {
ecdsaPublicKeyToSchnorr,
lookUpLedgerKeysByPath,
} from '@shared/crypto/bitcoin/bitcoin.utils';
import {
deriveTaprootAccount,
getTaprootAccountDerivationPath,
getTaprootPaymentFromAddressIndex,
} from '@shared/crypto/bitcoin/p2tr-address-gen';
import { makeNumberRange } from '@shared/utils';

import { selectCurrentNetwork, useCurrentNetwork } from '@app/store/networks/networks.selectors';
import { selectCurrentAccountIndex } from '@app/store/software-keys/software-key.selectors';
Expand Down Expand Up @@ -92,3 +97,25 @@ export function useCurrentAccountTaprootSigner() {
const network = useCurrentNetwork();
return useTaprootSigner(currentAccountIndex, network.chain.bitcoin.network);
}

export function useUpdateLedgerSpecificTaprootInputPropsForAdddressIndexZero() {
const taprootSigner = useCurrentAccountTaprootIndexZeroSigner();

return async (tx: Psbt, fingerprint: string, inputsToUpdate: number[] = []) => {
const inputsToSign =
inputsToUpdate.length > 0 ? inputsToUpdate : makeNumberRange(tx.inputCount);

inputsToSign.forEach(inputIndex => {
tx.updateInput(inputIndex, {
tapBip32Derivation: [
{
masterFingerprint: Buffer.from(fingerprint, 'hex'),
pubkey: Buffer.from(ecdsaPublicKeyToSchnorr(taprootSigner.publicKey)),
path: taprootSigner.derivationPath,
leafHashes: [],
},
],
});
});
};
}

0 comments on commit 8e51646

Please sign in to comment.