Step 1: Create Transaction Inputs
Each input in a Bitcoin transaction must specify:
- Transaction ID (32 bytes): Points to the UTXO being spent
- Output Index (4 bytes): Which output from that transaction
- ScriptSig: Placeholder for the unlocking script
- Sequence (4 bytes): Usually 0xFFFFFFFF
Input | Transaction ID (big-endian) | Output Index | Sequence |
---|---|---|---|
#1 | 9f96add4e4db413543df3eea1781c3be62637f1e2dd44069fa99801a88f7f7ff | 0 | eeffffff |
#2 | 8ac60eb9575db5b2d987e29f301b5b819ea83a5c6579d282d189cc04b8e151ef | 1 | ffffffff |
Note: In the transaction serialization below, these Transaction IDs are converted to little-endian format as required by the Bitcoin protocol.
1Transaction Breakdown:
2═══════════════════════════════════════════════════════════════════════════════════
3
4Version: 01000000
5
6Input Count: 02
7
8input[0]:
9Previous TXID: fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f
10Output Index: 00000000
11ScriptSig Size: 00
12ScriptSig:
13Sequence: eeffffff
14
15input[1]:
16Previous TXID: ef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a
17Output Index: 01000000
18ScriptSig Size: 00
19ScriptSig:
20Sequence: ffffffff
21
22Locktime: 11000000
Why are scriptSig fields empty?
Transaction signing follows a specific order:
- First, we create the transaction structure with empty scriptSig fields
- Then, we calculate the signature hash (sighash) for each input
- Finally, we add the signatures to create the complete transaction
Code Implementation
def create_input(
txid: str,
vout: int,
script_sig: bytes = b'',
sequence: bytes = b'\xff\xff\xff\xff'
) -> bytes:
# Convert txid from hex string and reverse (to little-endian)
txid_bytes = bytes.fromhex(txid)[::-1]
# Convert vout to 4 bytes, little-endian
vout_bytes = int_to_little_endian(vout, 4)
# Script length and script
script_sig_length = varint(len(script_sig))
return (
txid_bytes + # 32 bytes
vout_bytes + # 4 bytes
script_sig_length + # 1 byte
script_sig + # variable
sequence # 4 bytes
)
Helper Functions
Two essential encoding functions:
- int_to_little_endian: Converts integers to little-endian byte format
- varint: Encodes variable-length integers used for counts and lengths