@@ -117,10 +117,79 @@ export class Bitcoin {
117117 return psbt ; // Return the generated signature
118118 }
119119
120+ reconstructSignedTransaction = async ( {
121+ psbt,
122+ utxos,
123+ publicKey,
124+ signature,
125+ } ) => {
126+ const keyPair = {
127+ publicKey : Buffer . from ( publicKey , "hex" ) ,
128+ sign : async ( transactionHash ) => {
129+ const utxo = utxos [ 0 ] ; // The UTXO being spent
130+ const value = utxo . value ; // The value in satoshis of the UTXO being spent
131+
132+ if ( isNaN ( value ) ) {
133+ throw new Error (
134+ `Invalid value for UTXO at index ${ transactionHash } : ${ utxo . value } `
135+ ) ;
136+ }
137+
138+ const { big_r, s } = signature ;
139+
140+ // Reconstruct the signature
141+ const rHex = big_r . affine_point . slice ( 2 ) ; // Remove the "03" prefix
142+ let sHex = s . scalar ;
143+
144+ // Pad s if necessary
145+ if ( sHex . length < 64 ) {
146+ sHex = sHex . padStart ( 64 , "0" ) ;
147+ }
148+
149+ const rBuf = Buffer . from ( rHex , "hex" ) ;
150+ const sBuf = Buffer . from ( sHex , "hex" ) ;
151+
152+ // Combine r and s
153+ return Buffer . concat ( [ rBuf , sBuf ] ) ;
154+ } ,
155+ } ;
156+
157+ // Sign each input manually
158+ await Promise . all (
159+ utxos . map ( async ( _ , index ) => {
160+ try {
161+ await psbt . signInputAsync ( index , keyPair ) ;
162+ console . log ( `Input ${ index } signed successfully` ) ;
163+ } catch ( e ) {
164+ console . warn ( `Error signing input ${ index } :` , e ) ;
165+ }
166+ } )
167+ ) ;
168+
169+ psbt . finalizeAllInputs ( ) ; // Finalize the PSBT
170+
171+ return psbt ; // Return the generated signature
172+ } ;
173+
174+ reconstructSignedTransactionFromSessionStorage = async ( signature ) => {
175+ const { from, to, amount, utxos, publicKey } = JSON . parse (
176+ sessionStorage . getItem ( "btc_transaction" )
177+ ) ;
178+
179+ const psbt = await constructPsbt ( from , utxos , to , amount , this . networkId ) ;
180+
181+ return this . reconstructSignedTransaction ( {
182+ psbt,
183+ utxos,
184+ signature,
185+ publicKey,
186+ } ) ;
187+ } ;
188+
120189 broadcastTX = async ( signedTransaction ) => {
121190 // broadcast tx
122191 const bitcoinRpc = `https://blockstream.info/${ this . networkId === 'testnet' ? 'testnet' : '' } /api` ;
123- const res = await fetch ( `https://corsproxy.io/? ${ bitcoinRpc } /tx` , {
192+ const res = await fetch ( `${ bitcoinRpc } /tx` , {
124193 method : 'POST' ,
125194 body : signedTransaction . extractTransaction ( ) . toHex ( ) ,
126195 } ) ;
0 commit comments