You have a directory of files that need a timestamp proof: build artifacts, exports, scanned documents, a backlog that was never anchored. A for-loop that calls the API once per file works until it hits a rate limit or crashes halfway with no record of what went through.

Two facts from the ProofLedger v1 spec shape the right design. POST /api/v1/proofs/batch takes up to 100 hashes in one call. And every call made with an API key is limited to 120 requests per minute per key, with Retry-After on a 429. One call per hundred files means the rate limit is rarely what slows you down. The rest of this post is the worker built around those two facts: hash locally, submit in chunks of 100, honour Retry-After, and write progress to disk after every chunk so a crash costs one chunk, not the job.

Hash locally first

The API anchors a SHA-256 digest. The file itself stays on your machine, so step one is always a local hash, read in chunks so memory stays flat for a 4 GB video and a 10-page PDF alike.

import hashlib

def hash_file(path: str) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()

Hashing is where a thread pool earns its place in this job. It is I/O bound, and ThreadPoolExecutor with as_completed lets you hash a large tree while the first chunks are already being submitted.

One call, up to 100 hashes

Each item in a batch is sha256 (required), plus an optional external_id (your own record id, up to 128 characters, never shown publicly) and an optional filename. Give every item an external_id. An item whose external_id already exists on the account comes back as exists with the existing proof and costs nothing, which is what makes a rerun safe. The hash itself is a good external_id when you have no database id: same bytes, same proof. A file path is a poor one, because a file that changed but kept its name would come back as its old proof.

curl -X POST https://proofledger.io/api/v1/proofs/batch \
  -H "Authorization: Bearer sk_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: batch-2026-10-18-001" \
  -d '{"items":[{"sha256":"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2","external_id":"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2","filename":"report-q3.pdf"}]}'

The response carries a batch_id, a summary with received, created, exists and invalid counts, the plan figures monthly_limit, used_this_month, remaining and overage, and an items array. Each item has its index, a result of created, exists or invalid, an error string when invalid, and the proof (its id, polygon_status, certificate_url, verification_url and the other summary fields). The status is 201 when at least one proof was created and 200 when every valid item already existed.

The Idempotency-Key header is optional but worth sending. A resend with the same key and the same body within 24 hours replays the stored response with Idempotent-Replayed: true, so a timeout on a batch cannot double-submit it. The same key with a different body is refused with 422.

Reading a 429 correctly

Two different things answer 429 here, and they want different handling.

The per-key rate limit: 120 requests a minute in a fixed window. Retry-After says how many seconds to wait, and X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset are on every keyed response. Sleep for the header's value and resend.

The monthly allowance: on Free, if the new items would pass this month's 100 API proofs, nothing is recorded, the reply is 429, and it says how many remain. Retrying that in a loop is pointless. Developer and Platform continue past their allowance at a per-proof price, and the batch response reports how many of its proofs were overage.

The worker below sleeps and retries while a 429 carries Retry-After, and stops and prints the error text when it keeps coming. On Free that text tells you how many proofs are left this month.

The worker

import hashlib, json, os, sys, time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import requests

BATCH_URL = "https://proofledger.io/api/v1/proofs/batch"
HEADERS = {"Authorization": f"Bearer {os.environ['PROOFLEDGER_API_KEY']}"}
PROGRESS_FILE = "anchor_progress.json"
CHUNK = 100
HASH_WORKERS = 8


def hash_file(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def load_progress():
    p = Path(PROGRESS_FILE)
    return json.loads(p.read_text()) if p.exists() else {}


def save_progress(progress):
    Path(PROGRESS_FILE).write_text(json.dumps(progress, indent=2))


def submit_batch(items):
    body = {"items": items}
    key = "batch-" + hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
    headers = {**HEADERS, "Idempotency-Key": key}
    for attempt in range(6):
        resp = requests.post(BATCH_URL, json=body, headers=headers, timeout=60)
        if resp.status_code in (200, 201):
            return resp.json()
        if resp.status_code == 429:
            wait = resp.headers.get("Retry-After")
            if wait is None or attempt == 5:
                raise RuntimeError(f"429: {resp.text}")
            time.sleep(int(wait))
            continue
        if resp.status_code in (400, 401, 403, 422):
            raise RuntimeError(f"{resp.status_code}: {resp.text}")
        time.sleep(2 ** attempt)  # 5xx: back off and retry
    raise RuntimeError("batch failed after 6 attempts")


def main(directory):
    progress = load_progress()
    files = [p for p in Path(directory).rglob("*") if p.is_file()]

    pending = {}
    with ThreadPoolExecutor(max_workers=HASH_WORKERS) as pool:
        futures = {pool.submit(hash_file, str(p)): p for p in files}
        for fut in as_completed(futures):
            digest = fut.result()
            if digest not in progress:
                pending[digest] = futures[fut].name

    todo = list(pending.items())
    print(f"{len(files)} files, {len(todo)} to submit")

    for i in range(0, len(todo), CHUNK):
        chunk = todo[i:i + CHUNK]
        items = [{"sha256": d, "external_id": d, "filename": n} for d, n in chunk]
        result = submit_batch(items)
        for item in result["items"]:
            digest = items[item["index"]]["sha256"]
            if item["result"] == "invalid":
                progress[digest] = {"error": item.get("error")}
                continue
            proof = item["proof"]
            progress[digest] = {"id": proof["id"], "result": item["result"],
                                "certificate_url": proof["certificate_url"]}
        save_progress(progress)
        s = result["summary"]
        print(f"chunk {i // CHUNK + 1}: created {s['created']}, exists {s['exists']}, "
              f"invalid {s['invalid']}, remaining this month {result['remaining']}")


if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else ".")

A few notes on the choices.

Progress is keyed by digest, not by path. A renamed or moved file is not resubmitted, and two files with identical bytes collapse into one item. If a file might be overwritten between runs, this is still correct: new bytes mean a new digest and a new item.

Progress is written after every chunk. A crash costs at most one chunk of work, and resubmitting that chunk is safe twice over: the Idempotency-Key replays it if the body is identical, and external_id returns exists for anything that went through.

An invalid item is recorded with its error so the run can finish; delete that entry to retry it after fixing the cause.

After the job: catching up on anchors

A new proof is polygon_status: "PENDING" and usually ANCHORED within a minute. You do not need to poll each id. GET /api/v1/proofs?anchored_since=2026-10-18T00:00:00Z returns the account's proofs whose Polygon anchor landed after that time, newest first, cursor paged (next_cursor, limit up to 200), so a nightly job can pick up everything that finished since its last check. Or register a webhook with POST /api/v1/webhooks and receive a proof.polygon.anchored event per proof, with the proof's bundle in data.bundle.

Once a proof is anchored, fetch its bundle with GET /api/v1/proof/{id}/bundle?download=1 and save it next to the file. That one JSON document holds the hash, the chain, the transaction id and the anchor time.

When one request per file fits better

If files arrive one at a time rather than as a directory, POST /api/v1/proof with the same external_id and Idempotency-Key habits is the right call, and a small thread pool of around five workers with the same 429 handling is plenty. More threads mostly buy more 429s, since the per-key limit is 120 requests a minute either way. Its 201 response also carries duplicate_of, an object with the id and created_at of the earliest proof for that hash from any account, when the bytes were anchored before.

Checking a proof without ProofLedger

With the bundle saved beside the file, verify-proof verify report-q3.pdf --proof report-q3.pdf.proof.json (PyPI or npm) recomputes the hash and checks it against the bundle with no network call, then prints the Polygon transaction to look up on any block explorer. Neither step needs ProofLedger to be reachable. The full API reference is at https://proofledger.io/api.html.