Coincurve: secp256k1 Elliptic Curve Operations

21.0.0 · active · verified Sat Apr 11

Coincurve is a Python library providing fast and secure bindings for libsecp256k1, the highly optimized C library used by Bitcoin Core for elliptic curve cryptography operations. It offers a clean, easy-to-use API for tasks like key generation, signing, and verification. The current version is 21.0.0, and it maintains frequent updates to libsecp256k1.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate a secp256k1 private key, derive its public key, sign a hashed message, and verify the signature using `coincurve`. Note that `private_key.sign()` produces a DER-encoded signature expected by `verify_signature`.

import os
from coincurve import PrivateKey, verify_signature
import hashlib

# 1. Generate a new private key (or use an existing one)
private_key = PrivateKey()

# Get the corresponding public key
public_key = private_key.public_key.format(compressed=True)
print(f"Public Key (compressed): {public_key.hex()}")

# 2. Define a message to sign (must be hashed to 32 bytes for signing)
message_str = "Hello, Coincurve!"
message_hash = hashlib.sha256(message_str.encode('utf-8')).digest()
print(f"Message hash: {message_hash.hex()}")

# 3. Sign the message
signature = private_key.sign(message_hash)
print(f"Signature (DER-encoded): {signature.hex()}")

# 4. Verify the signature using the public key and message hash
is_valid = verify_signature(signature, message_hash, public_key)

if is_valid:
    print("Signature is valid!")
else:
    print("Signature is INVALID.")

# Example of direct verification via PublicKey object (also works)
# is_valid_direct = private_key.public_key.verify(signature, message_hash)
# print(f"Signature is valid (direct Public Key method): {is_valid_direct}")

view raw JSON →