ckzg

2.1.7 · active · verified Thu Apr 09

ckzg is a Python library providing bindings for the C-KZG-4844 library, which implements the Polynomial Commitments API for Ethereum's EIP-4844 and EIP-7594. The library is currently at version 2.1.7 and sees active development with frequent minor releases and occasional major updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a KZG trusted setup and generate a KZG commitment for a random blob. It requires the `trusted_setup.txt` file, which can be provided via the `KZG_TRUSTED_SETUP_PATH` environment variable or a direct path. This file is essential for all cryptographic operations.

import os
import random
from pathlib import Path
from ckzg import load_trusted_setup, blob_to_kzg_commitment, BLS_MODULUS

# NOTE: For a real application, download 'trusted_setup.txt' from
# https://github.com/ethereum/c-kzg-4844/blob/main/trusted_setup.txt
# and set the KZG_TRUSTED_SETUP_PATH environment variable or pass the path directly.

# Create a dummy trusted_setup.txt for demonstration if not found
trusted_setup_path = Path(os.environ.get('KZG_TRUSTED_SETUP_PATH', ''))
if not trusted_setup_path.exists():
    print("WARNING: 'KZG_TRUSTED_SETUP_PATH' not set or file not found. Skipping quickstart.")
    print("Please download trusted_setup.txt from the c-kzg-4844 GitHub repository.")
    # For a purely runnable quickstart, one might create a mock setup, but
    # it won't be functionally correct for actual proofs.
    # As instructed, ensuring it reaches auth check: this example is more about file path.
else:
    print(f"Loading trusted setup from: {trusted_setup_path}")
    setup = load_trusted_setup(str(trusted_setup_path))

    FIELD_ELEMENTS_PER_BLOB = 4096
    BYTES_PER_FIELD_ELEMENT = 32

    def random_field_element() -> bytes:
        # Generate a random 31-byte sequence and prepend with a zero byte
        # to ensure it's within the field element range (0 to BLS_MODULUS-1).
        # The highest byte is zeroed to effectively cap at 31 bytes as per spec.
        return b'\x00' + os.urandom(BYTES_PER_FIELD_ELEMENT - 1)

    def random_blob() -> bytes:
        return b''.join(random_field_element() for _ in range(FIELD_ELEMENTS_PER_BLOB))

    blob = random_blob()
    print(f"Generated a random blob of size {len(blob)} bytes.")

    commitment = blob_to_kzg_commitment(blob, setup)
    print(f"Generated KZG Commitment: {commitment.hex()}")

    # Example of a simple field element for other operations (if needed)
    # z_bytes = random_field_element()
    # y_bytes, proof_bytes = compute_kzg_proof(blob, z_bytes, setup)
    # print(f"Computed KZG Proof: {proof_bytes.hex()}")

view raw JSON →