Signing Transactions
In this tutorial, we'll learn how to sign a transaction by working with a real example from BIP143's test vectors.
The transaction has two inputs, but we'll focus specifically on signing the second input which is a P2WPKH (native SegWit) input.
The first input is a legacy P2PK input which uses a different signing method that we won't cover now.
Our goal is to create and sign this transaction:
Unsigned Raw Transaction:
----------------------
0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f
0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57
b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85
c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2
f0167faa815988ac11000000
Transaction Breakdown:
----------------------
nVersion: 01000000
txin: 02 fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f 00000000 00 eeffffff
ef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a 01000000 00 ffffffff
txout: 02 202cb20600000000 1976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac
9093510d00000000 1976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac
nLockTime: 11000000
Transaction Decoder Tool
💡 You can explore this transaction in detail using our Transaction Decoder tool.
Below is the complete transaction data. You can refer back to this whenever you need to check any details during the following steps:
Inputs
Input | Type | Previous Transaction ID | Output Index | Amount | ScriptPubKey | Private Key | Public Key |
---|---|---|---|---|---|---|---|
#0 | P2PK | 9f96ade4b41d5433f4eda31e1738ec2b36f6e7d1420d94a6af99801a88f7f7ff | 0 | 6.25 BTC | 2103c9f4836b9a4f77fc0d81f7bcb01b7f1b35916864b9476c241ce9fc198bd25432ac | bbc27228ddcb9209d7fd6f36b02f7dfa6252af40bb2f1cbc7a557da8027ff866 | 03c9f4836b9a4f77fc0d81f7bcb01b7f1b35916864b9476c241ce9fc198bd25432 |
#1 | P2WPKH | 8ac60eb9575db5b2d987e29f301b5b819ea83a5c6579d282d189cc04b8e151ef | 1 | 6 BTC | 00141d0f172a0ecb48aee1be1f2687d2963ae33f71a1 | 619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9 | 025476c2e83188368da1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee6357 |
Outputs
Output | Amount | ScriptPubKey |
---|---|---|
#0 | 1.1234 BTC (112,340,000 satoshis) | 1976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac |
#1 | 2.2345 BTC (223,450,000 satoshis) | 1976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac |
Steps We'll Follow
Create Base Transaction
Adding Inputs
Adding Outputs
Generate ScriptCode
Calculate Transaction Digest
Calculate Preimage and Sighash
Generate and Encode the Signature
Add Witness Field
Assemble Final Transaction
Each step will be explained in detail in the following sections, with code examples and tests using this exact transaction data.