TeachMeBitcoin

Custom Python Elliptic Curve Auditor

From TeachMeBitcoin, the free encyclopedia Reading time: 3 min

Custom Python Elliptic Curve Auditor

In this final guide, we will build a Python script that demonstrates the logic of Point Addition and Scalar Multiplication. Because the real secp256k1 curve involves numbers with 78 digits, we will use a "Toy Curve" with a small prime to visualize the math.

The Toy EC Auditor

# Toy Curve: y^2 = x^3 + 7 (mod 23)
P = 23 # A small prime field
A = 0
B = 7

def add_points(p1, p2, prime):
 """Adds two points on the curve."""
 if p1 is None: return p2
 if p2 is None: return p1

 x1, y1 = p1
 x2, y2 = p2

 if x1 == x2 and y1 != y2:
 return None # Result is Point at Infinity

 # 1. Calculate the slope (lambda)
 if x1 == x2: # Point Doubling
 slope = (3 * x1**2 + A) * pow(2 * y1, -1, prime)
 else: # Point Addition
 slope = (y2 - y1) * pow(x2 - x1, -1, prime)

 # 2. Calculate new x and y
 x3 = (slope**2 - x1 - x2) % prime
 y3 = (slope * (x1 - x3) - y1) % prime

 return (x3, y3)

# --- Simulation ---

# The Generator Point G for our toy curve
G = (3, 10) 
print(f"--- Toy Elliptic Curve Audit (mod {P}) ---")
print(f"[*] Generator Point G: {G}")

# Calculate 2G (Doubling)
two_g = add_points(G, G, P)
print(f"[*] Public Key (2G): {two_g}")

# Calculate 3G (Addition)
three_g = add_points(two_g, G, P)
print(f"[*] Public Key (3G): {three_g}")

# Calculate 4G (Doubling of 2G)
four_g = add_points(two_g, two_g, P)
print(f"[*] Public Key (4G): {four_g}")

How to Run the Auditor

  1. Ensure you have Python 3.8+ installed (for the pow(x, -1, p) modular inverse function).

  2. Copy the code into a file named ec_auditor.py.

  3. Run it using python3 ec_auditor.py.

Technical Takeaways

  1. Modular Inverse: Notice the pow(..., -1, prime). In modular arithmetic, we can't divide. Instead, we multiply by the "Modular Multiplicative Inverse."

  2. Wraparound: Notice how the points jump around (e.g., from (3, 10) to (21, 1)). There is no obvious visual pattern. This is why you can't "guess" the private key.

  3. Scaling to secp256k1: The logic for the real Bitcoin curve is identical. The only difference is that the prime P is $2^{256} - 2^{32} - 977$ instead of 23.

Congratulations! You have completed the Elliptic Curve Math (secp256k1) module. You now understand the deep mathematical "Firewall" that protects the ownership of every Bitcoin on earth.

☕ Help support TeachMeBitcoin

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:

Ethereum: 0x578417C51783663D8A6A811B3544E1f779D39A85
Bitcoin: bc1q77k9e95rn669kpzyjr8ke9w95zhk7pa5s63qzz
Solana: 4ycT2ayqeMucixj3wS8Ay8Tq9NRDYRPKYbj3UGESyQ4J
Address copied to clipboard!