File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Example: Signing a Bitcoin transaction using bitcoinjs-lib
3+ *
4+ * This demo creates a dummy transaction, signs it using a random private key,
5+ * and prints both the raw transaction hex and the public address.
6+ */
7+
8+ import * as bitcoin from 'bitcoinjs-lib' ;
9+ import { ECPairFactory } from 'ecpair' ;
10+ import * as tinysecp from 'tiny-secp256k1' ;
11+
12+ const ECPair = ECPairFactory ( tinysecp ) ;
13+
14+ export function signExampleTx ( ) {
15+ const keyPair = ECPair . makeRandom ( ) ;
16+ const { address } = bitcoin . payments . p2wpkh ( { pubkey : keyPair . publicKey } ) ;
17+
18+ // Create a fake transaction
19+ const psbt = new bitcoin . Psbt ( { network : bitcoin . networks . testnet } ) ;
20+ psbt . addInput ( {
21+ hash : 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' ,
22+ index : 0 ,
23+ witnessUtxo : {
24+ script : bitcoin . payments . p2wpkh ( { pubkey : keyPair . publicKey } ) . output ,
25+ value : 10_000 ,
26+ } ,
27+ } ) ;
28+ psbt . addOutput ( {
29+ address : address ,
30+ value : 9_000 ,
31+ } ) ;
32+
33+ // Sign & finalize
34+ psbt . signAllInputs ( keyPair ) ;
35+ psbt . finalizeAllInputs ( ) ;
36+
37+ const txHex = psbt . extractTransaction ( ) . toHex ( ) ;
38+ console . log ( 'Signed transaction (hex):' , txHex ) ;
39+ console . log ( 'Sender address:' , address ) ;
40+ return txHex ;
41+ }
42+
43+ // Uncomment below for direct testing
44+ // signExampleTx();
You can’t perform that action at this time.
0 commit comments