Custom Python SegWit Auditor
Custom Python SegWit Auditor
In this final guide, we will build a Python script that calculates the Weight and Virtual Size (vSize) of a transaction. This script will help you understand why SegWit transactions are cheaper and how the "Witness Discount" is applied in practice.
The SegWit Auditor
import math
def audit_segwit_weight(base_bytes, witness_bytes):
print(f"--- SegWit Transaction Weight Audit ---")
# 1. Calculate Total Raw Size
total_raw_size = base_bytes + witness_bytes
print(f"[*] Raw Size on Disk: {total_raw_size} bytes")
# 2. Calculate Weight (WU)
# Formula: (Base * 3) + Total
# Which is equivalent to (Base * 4) + (Witness * 1)
weight = (base_bytes * 3) + total_raw_size
print(f"[*] Total Weight (WU): {weight} WU")
# 3. Calculate Virtual Size (vSize)
# Formula: Weight / 4 (rounded up)
vsize = math.ceil(weight / 4)
print(f"[*] Virtual Size (vSize): {vsize} vBytes")
# 4. Efficiency Analysis
savings = (1 - (vsize / total_raw_size)) * 100
print(f"[*] Discount Savings: {savings:.2f}% compared to raw size")
# --- Simulation ---
# Case 1: A typical P2WPKH (Native SegWit) transaction
# Base (Inputs/Outputs/Metadata) is ~110 bytes
# Witness (Signatures/Pubkeys) is ~110 bytes
print("Scenario: Standard Native SegWit (bc1q)")
audit_segwit_weight(110, 110)
print("\nScenario: Large Multi-Sig SegWit")
# More signatures mean more witness data
audit_segwit_weight(150, 400)
How to Run the Auditor
-
Ensure you have Python 3 installed.
-
Copy the code into a file named
segwit_auditor.py. -
Run it using
python3 segwit_auditor.py.
Technical Takeaways
-
The 4x Advantage: Notice how in the "Large Multi-Sig" scenario, the weight increases much more slowly than the raw size. This is the economic engine that makes complex scripts affordable on Bitcoin.
-
vSize vs Weight: Most block explorers and wallets show
vSizebecause it's easier for humans to compare to the old 1MB limit. However, the protocol only cares about the 4,000,000 Weight Units. -
Miner Selection: Miners select transactions for blocks based on their "Fee per vByte" (or Fee per Weight Unit), not their raw fee. This is why SegWit users get confirmed faster for lower prices.
Congratulations! You have completed the Segregated Witness (SegWit) module. You now understand the technical upgrade that fixed malleability, enabled Layer 2, and increased the capacity of the Bitcoin network.
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: