Custom Python Weight Calculator
Custom Python Weight Calculator
In this final guide, we will build a Python script that calculates the Raw Size, Stripped Size, Weight, and vSize of a SegWit transaction. This tool helps visualize exactly how much "discount" a transaction is receiving.
The Python Weight Auditor
import math
def calculate_weight_metrics(base_hex, witness_hex=""):
# base_hex: The part of the transaction without the witness
# witness_hex: The witness data (markers, flags, stacks)
# 1. Calculate Stripped Size
stripped_size = len(base_hex) // 2
# 2. Calculate Witness Size
# Note: In a real TX, markers (00) and flags (01) are witness data
witness_size = len(witness_hex) // 2
# 3. Calculate Total (Raw) Size
total_size = stripped_size + witness_size
# 4. Calculate Weight
# (Stripped * 4) + (Witness * 1)
weight = (stripped_size * 4) + (witness_size * 1)
# 5. Calculate vSize
# Weight divided by 4, rounded up
vsize = math.ceil(weight / 4)
print(f"--- Transaction Size Audit ---")
print(f"[*] Stripped Size: {stripped_size} bytes")
print(f"[*] Witness Size: {witness_size} bytes")
print(f"[*] Total Raw Size: {total_size} bytes")
print(f"------------------------------")
print(f"[*] Total Weight: {weight} WU")
print(f"[*] Virtual Size: {vsize} vBytes")
# Efficiency Gain
savings = (1 - (vsize / total_size)) * 100
print(f"[*] SegWit Savings: {savings:.1f}% vs Legacy")
# --- Simulation ---
# A typical P2WPKH Transaction:
# Base part (version, inputs, outputs, locktime) ~ 110 bytes
# Witness part (marker, flag, signatures) ~ 110 bytes
base_data = "01" * 110
witness_data = "ff" * 110
calculate_weight_metrics(base_data, witness_data)
How to Run the Auditor
-
Ensure you have Python 3 installed.
-
Copy the code into a file named
weight_auditor.py. -
Run it using
python3 weight_auditor.py.
Technical Takeaways
-
Normalization: Notice how
vSizeeffectively shrinks the witness data in the eyes of the fee-market. -
Constraint Logic: Miners must ensure the
Total Weightof all transactions in a block does not exceed 4,000,000 WU. They don't care about the Raw Size. -
Audit trail: By looking at the
SegWit Savings, you can see why it is economically irrational to use legacy addresses in the modern era.
Congratulations! You have completed the Transaction Size and Weight module. You now understand the physics of Bitcoin blockspace.
TeachMeBitcoin is an ad-free, open-source educational repository curated by a passionate team of Bitcoin researchers and educators for public benefit. If you found our articles helpful, please consider supporting our hosting and ongoing content updates with a clean donation: