From 49f86e2a4f725a0aac2cbc9ef14c042ca3ed91d3 Mon Sep 17 00:00:00 2001 From: ieow Date: Wed, 3 Jan 2024 15:15:21 +0800 Subject: [PATCH 1/3] fix: enable bitcoin signing --- .vscode/settings.json | 2 +- .../src/App.tsx | 95 +++++++++---------- .../src/utils.ts | 27 ++++-- 3 files changed, 67 insertions(+), 57 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index f49fd94..465cd7f 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,6 +1,6 @@ { "editor.codeActionsOnSave": { - "source.fixAll": true + "source.fixAll": "explicit" }, "eslint.workingDirectories": [ { diff --git a/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/App.tsx b/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/App.tsx index 081f9d4..5124284 100644 --- a/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/App.tsx +++ b/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/App.tsx @@ -7,8 +7,7 @@ import { generatePrivate } from "eccrypto"; import { useEffect, useState } from "react"; import swal from "sweetalert"; import { tKey } from "./tkey"; -import { addFactorKeyMetadata, setupWeb3, copyExistingTSSShareForNewFactor, addNewTSSShareAndFactor, getEcCrypto } from "./utils"; -import { utils } from "@toruslabs/tss-client"; +import { addFactorKeyMetadata, setupWeb3, copyExistingTSSShareForNewFactor, addNewTSSShareAndFactor, getEcCrypto, SigningParams } from "./utils"; import { OpenloginSessionManager } from "@toruslabs/openlogin-session-manager"; import { networks, Psbt } from "bitcoinjs-lib"; import ecc from "@bitcoinerlab/secp256k1"; @@ -20,7 +19,6 @@ import { ShareSerializationModule } from "@tkey-mpc/share-serialization"; import {TorusLoginResponse} from "@toruslabs/customauth"; import { SignerAsync } from "bitcoinjs-lib"; -const { getTSSPubKey } = utils; const ECPair = ECPairFactory(ecc); const uiConsole = (...args: any[]): void => { @@ -41,8 +39,10 @@ function App() { const [localFactorKey, setLocalFactorKey] = useState(null); const [oAuthShare, setOAuthShare] = useState(null); const [web3, setWeb3] = useState(null); - const [signingParams, setSigningParams] = useState(null); + const [signingParams, setSigningParams] = useState(null); const [bitcoinUTXID, setBitcoinUTXID] = useState(null); + const [latestBalance, setLatestBalance] = useState(null); + const [minerFee, setMinerFee] = useState(null); const [fundingTxIndex, setFundingTxIndex] = useState(null); const [sessionManager, setSessionManager] = useState>(new OpenloginSessionManager({})); @@ -67,7 +67,7 @@ function App() { try { await (tKey.serviceProvider as any).init(); const sessionId = localStorage.getItem("sessionId"); - const sessionManager = new OpenloginSessionManager({ + const sessionManager = new OpenloginSessionManager({ sessionTime: 86400, sessionId: sessionId!, }); @@ -75,6 +75,7 @@ function App() { if (sessionId) { const signingParams: any = await sessionManager!.authorizeSession(); uiConsole("signingParams", signingParams); + // signingParams["ecPublicKey"] = Buffer.from(signingParams.ecPublicKey.padStart(64, "0"), "hex"); const factorKeyMetadata = await tKey.storageLayer.getMetadata<{ message: string; @@ -104,7 +105,6 @@ function App() { privateKey: signingParams.oAuthShare, }; setLoginResponse(loginResponse); - signingParams["compressedTSSPubKey"] = Buffer.from(signingParams.compressedTSSPubKey.padStart(64, "0"), "hex"); setSigningParams(signingParams); uiConsole( @@ -127,8 +127,10 @@ function App() { // sets up web3 useEffect(() => { const localSetup = async () => { - const web3Local = await setupWeb3(loginResponse, signingParams); - setWeb3(web3Local); + if (signingParams) { + const web3Local = await setupWeb3(loginResponse, signingParams); + setWeb3(web3Local); + } }; if (signingParams) { localSetup(); @@ -155,11 +157,6 @@ function App() { } }; - useEffect(() => { - setBitcoinUTXID("Enter UTXID here") - setFundingTxIndex("FundingTxIndex (often 0)") - }, []); - const initializeNewKey = async () => { if (!tKey) { uiConsole("tKey not initialized yet"); @@ -239,32 +236,20 @@ function App() { setMetadataKey(metadataKey?.privKey.toString("hex")); const tssNonce: number = tKey.metadata.tssNonces![tKey.tssTag]; - // tssShare1 = TSS Share from the social login/ service provider - const tssShare1PubKeyDetails = await tKey.serviceProvider.getTSSPubKey(tKey.tssTag, tssNonce); - - const tssShare1PubKey = { - x: tssShare1PubKeyDetails.pubKey.x.toString("hex"), - y: tssShare1PubKeyDetails.pubKey.y.toString("hex"), - }; - - // tssShare2 = TSS Share from the local storage of the device const { tssShare: tssShare2, tssIndex: tssShare2Index } = await tKey.getTSSShare(factorKey); - const ec = getEcCrypto(); - const tssShare2ECPK = ec.curve.g.mul(tssShare2); - const tssShare2PubKey = { - x: tssShare2ECPK.getX().toString("hex"), - y: tssShare2ECPK.getY().toString("hex"), - }; - // 4. derive tss pub key, tss pubkey is implicitly formed using the dkgPubKey and the userShare (as well as userTSSIndex) - const tssPubKey = getTSSPubKey(tssShare1PubKey, tssShare2PubKey, tssShare2Index); + let tssPubKey = tKey.getTSSPub() + // const tssPubKey = getTSSPubKey(tssShare1PubKey, tssShare2PubKey, tssShare2Index); // console.log("tssPub", tssPubKey); - const compressedTSSPubKey = Buffer.from(`${tssPubKey.getX().toString(16, 64)}${tssPubKey.getY().toString(16, 64)}`, "hex"); - const prefixedCompressedTSSPubKey = Buffer.from(`04${compressedTSSPubKey.toString("hex")}`, "hex"); - const ECPubKey = ECPair.fromPublicKey(prefixedCompressedTSSPubKey, { network: testnet }); + const TSSPubKey = Buffer.from(`${tssPubKey.x.toString(16, 64)}${tssPubKey.y.toString(16, 64)}`, "hex"); + + const prefixedTSSPubKey = Buffer.from(`04${TSSPubKey.toString("hex")}`, "hex"); + const ECPubKey = ECPair.fromPublicKey(prefixedTSSPubKey, { network: testnet , compressed: true}); const { address: btcAddress } = p2pkh({ pubkey: ECPubKey.publicKey, network: testnet }); + + if (!btcAddress) throw new Error("Invalid address"); // 5. save factor key and other metadata if ( @@ -279,15 +264,16 @@ function App() { const nodeDetails = await tKey.serviceProvider.getTSSNodeDetails() - const signingParams = { - oAuthShare: OAuthShare, - factorKey, + const tsspubhex = Buffer.from(TSSPubKey).toString("hex"); + const signingParams : SigningParams = { + oAuthShare: OAuthShare.toString("hex"), + factorKey: factorKey.toString("hex"), btcAddress, - ecPublicKey: ECPubKey.publicKey, + ecPublicKey: ECPubKey.publicKey.toString("hex"), tssNonce, - tssShare2, + tssShare2 : tssShare2.toString("hex"), tssShare2Index, - compressedTSSPubKey, + compressedTSSPubKey: tsspubhex, signatures, userInfo: loginResponse!.userInfo, nodeDetails, @@ -315,14 +301,13 @@ function App() { } }; - async function createSession(signingParams: any) { + async function createSession(signingParams: SigningParams) { try { const sessionId = OpenloginSessionManager.generateRandomSessionKey(); sessionManager!.sessionId = sessionId!; if (!signingParams) { throw new Error("User not logged in"); } - signingParams["compressedTSSPubKey"] = Buffer.from(signingParams.compressedTSSPubKey).toString("hex"); await sessionManager!.createSession(signingParams); localStorage.setItem("sessionId", sessionId); uiConsole("Successfully created session"); @@ -374,6 +359,9 @@ function App() { if (!localFactorKey) { throw new Error("localFactorKey does not exist, cannot add factor pub"); } + if (!signingParams) { + throw new Error("signingParams does not exist, cannot add factor pub"); + } const backupFactorKey = new BN(generatePrivate()); const backupFactorPub = getPubKeyPoint(backupFactorKey); @@ -457,6 +445,10 @@ function App() { uiConsole("web3 not initialized yet"); return; } + if (!signingParams) { + uiConsole("signingParams not initialized yet"); + return; + } uiConsole("Bitcoin address", signingParams.btcAddress); return signingParams.btcAddress; }; @@ -470,6 +462,10 @@ function App() { uiConsole("invalid bitcoin utxid"); return; } + if (!signingParams) { + uiConsole("signingParams not initialized yet"); + return; + } try { parseInt(fundingTxIndex as string); } catch (e) { @@ -478,9 +474,10 @@ function App() { // unspent transaction const txId = bitcoinUTXID; // looks like this "bb072aa6a43af31642b635e82bd94237774f8240b3e6d99a1b659482dce013c6" - const total = 170; // 0.0000017 + const total = Number(latestBalance); // 1321953; // 0.0000017 + const value = 20; - const miner = 50; + const miner = Number(minerFee); // fetch transaction from testnet const txHex = await (await fetch(`https://blockstream.info/testnet/api/tx/${txId}/hex`)).text(); @@ -495,7 +492,7 @@ function App() { nonWitnessUtxo: Buffer.from(txHex, "hex"), }) .addOutput({ - address: outAddr, + address: outAddr!, value: value, }) .addOutput({ @@ -565,15 +562,17 @@ function App() { Get Testnet Bitcoin from Faucet - - setBitcoinUTXID(e.target.value)}> - setFundingTxIndex(e.target.value)}> +
+ setMinerFee(e.target.value)} placeholder="set Miner Fee"> + setLatestBalance(e.target.value)} placeholder="set latest balance"> + setBitcoinUTXID(e.target.value)} placeholder="set UTXID here"> + setFundingTxIndex(e.target.value)} placeholder="FundingTxIndex (often 0)">
- +

diff --git a/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/utils.ts b/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/utils.ts index 3cdbd14..2c68ea6 100644 --- a/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/utils.ts +++ b/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/utils.ts @@ -16,6 +16,21 @@ const parties = 4; const clientIndex = parties - 1; const tssImportUrl = `https://sapphire-dev-2-2.authnetwork.dev/tss/v1/clientWasm`; +export type SigningParams = { + oAuthShare: string; + factorKey: string; + btcAddress: string; + ecPublicKey: string; + tssNonce: number; + tssShare2: string; + tssShare2Index: number; + compressedTSSPubKey: string; + signatures: string[]; + userInfo: any; + nodeDetails: any; +}; + + const DELIMITERS = { Delimiter1: "\u001c", Delimiter2: "\u0015", @@ -46,10 +61,10 @@ export const generateTSSEndpoints = (tssNodeEndpoints: string[], parties: number return { endpoints, tssWSEndpoints, partyIndexes }; }; -export const setupWeb3 = async (loginReponse: any, signingParams: any) => { +export const setupWeb3 = async (loginReponse: any, signingParams: SigningParams) => { try { const { tssNonce, tssShare2, tssShare2Index, compressedTSSPubKey, signatures, ecPublicKey, nodeDetails } = signingParams; - // console.log("signingParams", compressedTSSPubKey.toString("hex")); + const tssShare2BN = new BN(tssShare2, 16); const { verifier, verifierId } = loginReponse.userInfo; @@ -75,7 +90,7 @@ export const setupWeb3 = async (loginReponse: any, signingParams: any) => { const participatingServerDKGIndexes = [1, 2, 3]; const dklsCoeff = getDKLSCoeff(true, participatingServerDKGIndexes, tssShare2Index); - const denormalisedShare = dklsCoeff.mul(tssShare2).umod(ec.curve.n); + const denormalisedShare = dklsCoeff.mul(tssShare2BN).umod(ec.curve.n); const share = Buffer.from(denormalisedShare.toString(16, 64), "hex").toString("base64"); if (!currentSession) { @@ -118,10 +133,6 @@ export const setupWeb3 = async (loginReponse: any, signingParams: any) => { throw new Error(`compressedTSSPubKey does not exist ${compressedTSSPubKey}`); } - const getPublic: () => Promise = async () => { - return compressedTSSPubKey; - }; - const toAsyncSigner = (signer: Signer): SignerAsync => { const ret: SignerAsync = { publicKey: signer.publicKey, @@ -143,7 +154,7 @@ export const setupWeb3 = async (loginReponse: any, signingParams: any) => { return ret; }; - const btcSigner = toAsyncSigner({ publicKey: ecPublicKey, sign: sign as any }); + const btcSigner = toAsyncSigner({ publicKey: Buffer.from(ecPublicKey, "hex"), sign: sign as any }); return btcSigner; // await ethereumSigningProvider.setupProvider({ sign, getPublic }); // // console.log(ethereumSigningProvider.provider); From 03523d2687ab5f556bd8fc894d4ffad423d535e7 Mon Sep 17 00:00:00 2001 From: ieow Date: Wed, 3 Jan 2024 17:08:07 +0800 Subject: [PATCH 2/3] fix: rename variable --- .../tkey-mpc-react-bitcoin-example/src/App.tsx | 10 ++++------ .../tkey-mpc-react-bitcoin-example/src/utils.ts | 10 +++++----- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/App.tsx b/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/App.tsx index 5124284..f0f3b64 100644 --- a/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/App.tsx +++ b/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/App.tsx @@ -75,7 +75,6 @@ function App() { if (sessionId) { const signingParams: any = await sessionManager!.authorizeSession(); uiConsole("signingParams", signingParams); - // signingParams["ecPublicKey"] = Buffer.from(signingParams.ecPublicKey.padStart(64, "0"), "hex"); const factorKeyMetadata = await tKey.storageLayer.getMetadata<{ message: string; @@ -239,13 +238,13 @@ function App() { const { tssShare: tssShare2, tssIndex: tssShare2Index } = await tKey.getTSSShare(factorKey); // 4. derive tss pub key, tss pubkey is implicitly formed using the dkgPubKey and the userShare (as well as userTSSIndex) - let tssPubKey = tKey.getTSSPub() + let tssPubKeyPoint = tKey.getTSSPub() // const tssPubKey = getTSSPubKey(tssShare1PubKey, tssShare2PubKey, tssShare2Index); // console.log("tssPub", tssPubKey); - const TSSPubKey = Buffer.from(`${tssPubKey.x.toString(16, 64)}${tssPubKey.y.toString(16, 64)}`, "hex"); + const tssPubKey = Buffer.from(`${tssPubKeyPoint.x.toString(16, 64)}${tssPubKeyPoint.y.toString(16, 64)}`, "hex"); - const prefixedTSSPubKey = Buffer.from(`04${TSSPubKey.toString("hex")}`, "hex"); + const prefixedTSSPubKey = Buffer.from(`04${tssPubKey.toString("hex")}`, "hex"); const ECPubKey = ECPair.fromPublicKey(prefixedTSSPubKey, { network: testnet , compressed: true}); const { address: btcAddress } = p2pkh({ pubkey: ECPubKey.publicKey, network: testnet }); @@ -264,7 +263,6 @@ function App() { const nodeDetails = await tKey.serviceProvider.getTSSNodeDetails() - const tsspubhex = Buffer.from(TSSPubKey).toString("hex"); const signingParams : SigningParams = { oAuthShare: OAuthShare.toString("hex"), factorKey: factorKey.toString("hex"), @@ -273,7 +271,7 @@ function App() { tssNonce, tssShare2 : tssShare2.toString("hex"), tssShare2Index, - compressedTSSPubKey: tsspubhex, + tssPubKey: tssPubKey.toString("hex"), signatures, userInfo: loginResponse!.userInfo, nodeDetails, diff --git a/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/utils.ts b/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/utils.ts index 2c68ea6..14944df 100644 --- a/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/utils.ts +++ b/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/utils.ts @@ -24,7 +24,7 @@ export type SigningParams = { tssNonce: number; tssShare2: string; tssShare2Index: number; - compressedTSSPubKey: string; + tssPubKey: string; signatures: string[]; userInfo: any; nodeDetails: any; @@ -63,7 +63,7 @@ export const generateTSSEndpoints = (tssNodeEndpoints: string[], parties: number export const setupWeb3 = async (loginReponse: any, signingParams: SigningParams) => { try { - const { tssNonce, tssShare2, tssShare2Index, compressedTSSPubKey, signatures, ecPublicKey, nodeDetails } = signingParams; + const { tssNonce, tssShare2, tssShare2Index, tssPubKey, signatures, ecPublicKey, nodeDetails } = signingParams; const tssShare2BN = new BN(tssShare2, 16); const { verifier, verifierId } = loginReponse.userInfo; @@ -107,7 +107,7 @@ export const setupWeb3 = async (loginReponse: any, signingParams: SigningParams) endpoints, sockets, share, - Buffer.from(compressedTSSPubKey, "hex").toString("base64"), + Buffer.from(tssPubKey, "hex").toString("base64"), true, tssImportUrl ); @@ -129,8 +129,8 @@ export const setupWeb3 = async (loginReponse: any, signingParams: SigningParams) return Promise.resolve(sigBuffer); }; - if (!compressedTSSPubKey) { - throw new Error(`compressedTSSPubKey does not exist ${compressedTSSPubKey}`); + if (!tssPubKey) { + throw new Error(`compressedTSSPubKey does not exist ${tssPubKey}`); } const toAsyncSigner = (signer: Signer): SignerAsync => { From a847d830292f3e267557d9c6961b73144f647a1f Mon Sep 17 00:00:00 2001 From: ieow Date: Tue, 23 Jan 2024 14:23:41 +0800 Subject: [PATCH 3/3] feat: add segwit tx signing --- .../src/App.tsx | 66 ++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/App.tsx b/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/App.tsx index f0f3b64..f976002 100644 --- a/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/App.tsx +++ b/tkey-mpc-web/tkey-mpc-react-bitcoin-example/src/App.tsx @@ -9,7 +9,7 @@ import swal from "sweetalert"; import { tKey } from "./tkey"; import { addFactorKeyMetadata, setupWeb3, copyExistingTSSShareForNewFactor, addNewTSSShareAndFactor, getEcCrypto, SigningParams } from "./utils"; import { OpenloginSessionManager } from "@toruslabs/openlogin-session-manager"; -import { networks, Psbt } from "bitcoinjs-lib"; +import { networks, Psbt, payments } from "bitcoinjs-lib"; import ecc from "@bitcoinerlab/secp256k1"; import ECPairFactory from "ecpair"; import { testnet } from "bitcoinjs-lib/src/networks"; @@ -508,6 +508,67 @@ function App() { console.log("signedTransaction: ", signedTransaction ); }; + + + const sendTransactionSegwit = async () => { + if (!web3) { + uiConsole("web3 not initialized yet"); + return; + } + + let account = payments.p2wpkh({ pubkey: web3.publicKey, network: testnet }); + + if (bitcoinUTXID?.length !== 64) { + uiConsole("invalid bitcoin utxid"); + return; + } + if (!signingParams) { + uiConsole("signingParams not initialized yet"); + return; + } + try { + parseInt(fundingTxIndex as string); + } catch (e) { + uiConsole("invalid funding tx index"); + return } + + // unspent transaction + const txId = bitcoinUTXID; // looks like this "bb072aa6a43af31642b635e82bd94237774f8240b3e6d99a1b659482dce013c6" + const total = Number(latestBalance); // 1321953; // 0.0000017 + + const value = 20; + const miner = Number(minerFee); + + const outAddr = await getAccounts(); + console.log(outAddr, typeof outAddr) + const psbt = new Psbt({ network: networks.testnet }) + .addInput({ + hash: txId, + index: parseInt(fundingTxIndex as string), + witnessUtxo: { + script: Buffer.from('0014' + account.hash?.toString("hex"), 'hex'), + value: total, + }, + }) + .addOutput({ + address: account.address!, + value: value, + }) + .addOutput({ + address: account.address!, + value: total - value - miner, + }); + + uiConsole("Signing transaction..."); + await psbt.signInputAsync(0, web3); + psbt.validateSignaturesOfInput(0, BTCValidator); + const validation = psbt.validateSignaturesOfInput(0, BTCValidator); + const signedTransaction = psbt.finalizeAllInputs().extractTransaction().toHex() + uiConsole("Signed Transaction: ", signedTransaction, "Copy the above into https://blockstream.info/testnet/tx/push"); + console.log(validation ? "Validated" : "failed"); + console.log("signedTransaction: ", signedTransaction ); + }; + const loggedInView = ( <>

Account Details

@@ -569,6 +630,9 @@ function App() { +