Let me tell you about a weird negotiation problem I stumbled into.
Picture this: a corporate energy buyer needs to confirm that a hydrogen supplier holds at least 3,000 MWh of certified green credits before they'll sign a procurement contract. Fair enough. The supplier has the credits. They want the deal. So they share their actual inventory number.
And the moment they do, something shifts in the room.
Because now the buyer knows the supplier is sitting on 8,500 MWh. Suddenly the buyer has a very clear picture of how desperate that supplier is not. The leverage just moved. The deal terms are about to get worse for the supplier, and there is nothing they can do about it, because they already showed their hand.
I kept thinking about this problem. And I realised it was not really a negotiation problem. It was an information architecture problem. The supplier needed a way to say "yes, I qualify" without saying "and here is exactly how much I have."
That is what I built with H2Ledger: a decentralised marketplace for green hydrogen credits where suppliers can prove actualAmount >= threshold to a smart contract, with full cryptographic certainty, without the actual number ever appearing anywhere. Not on-chain. Not in the proof. Not in transit. Nowhere.
The tool that makes this possible is called a zero-knowledge proof. Let me show you how it works, what the code looks like, and honestly, what I wish I had done differently.
Before We Dive In: What Even Is a Zero-Knowledge Proof?
I promise this is not as scary as it sounds.
Think of it like this. Imagine your friend dares you to prove you know the combination to a safe, but you refuse to say the numbers out loud. A zero-knowledge proof is essentially a mathematical protocol that lets you win that dare. You convince the other party that a statement is true, without revealing the secret behind it.
More precisely, three things have to hold:
- Completeness: If you are telling the truth and you have the right secret, you can always produce a valid proof.
- Soundness: If you are lying, you cannot fake a valid proof. The math makes cheating computationally infeasible.
- Zero-knowledge: The person checking the proof learns only whether the statement is true or false. Nothing else leaks.
In H2Ledger, the statement is actualAmount >= threshold. The secret (called the "witness") is actualAmount. And the party checking the proof is not a human; it is a Solidity smart contract sitting on an EVM-compatible blockchain.
No trust required. No intermediary needed. Just math.
The Real Problem: Green Hydrogen Credit Markets Are Kind of a Disaster
Okay, "disaster" is strong. But the current state of things is genuinely fragile.
Right now, hydrogen credit markets deal with:
- Paper-based certification chains that have no on-chain anchor. The same certified credit can be quietly presented to multiple buyers across different negotiations. Nobody has a shared ledger to catch it.
- Siloed registries running under incompatible regulatory frameworks, with no interoperability. A buyer in Germany and a supplier in Chile might be working from entirely different certification standards with no way to verify across the gap.
- A forced choice between transparency and opacity. Put your credit balances on a public blockchain and every competitor can see your inventory in real time. Keep it off-chain and there is no trustless settlement mechanism. You have to pick your poison.
Zero-knowledge proofs let you step off that seesaw entirely. You get a shared ledger for settlement and privacy for the underlying figures. Both at the same time.
How H2Ledger Actually Works: The Three-Layer Picture
At a high level, the system has three layers that talk to each other:
[ Supplier (off-chain) ]
|
| Private: actualAmount (stays here, never transmitted)
v
[ Circom Circuit + Groth16 Prover ]
|
| Outputs: proof.json (256 bytes) + public.json (threshold only)
v
[ GreenHydrogenMarketplace.sol ]
|
| Delegates the heavy cryptographic check to:
v
[ Verifier.sol ] --> true / false
The supplier's actual inventory figure never leaves their machine. What travels on-chain is a 256-byte proof and the public threshold value. The smart contract checks the proof, confirms it is valid, and flips the order status to fulfilled. That is the entire settlement flow.
The ZK Circuit: Where the Magic Gets Boring (in a Good Way)
Circuits are the programs that ZK proof systems evaluate. I wrote mine in Circom 2.0, which is essentially a domain-specific language for expressing computations as systems of arithmetic constraints. Here is the core template:
template ThresholdVerification(n) {
signal input actualAmount; // Private: never leaves the prover's machine
signal input threshold; // Public: the buyer's stated minimum
signal output isValid; // 1 if actualAmount >= threshold, else 0
// Uses LessThan from circomlib to prove:
// NOT (actualAmount < threshold) = (actualAmount >= threshold)
}
When you compile this, it produces 128 R1CS constraints across 193 wires. Here is what those constraints actually do:
- 64 of them decompose both
actualAmountandthresholdinto their 64-bit binary representations. - The other 64 implement the bit-by-bit comparator that determines which number is larger.
A quick note on the 64-bit choice: hydrogen volumes in enterprise markets are measured in millions of MWh. A 64-bit field accommodates values up to 2^64, which gives roughly 2^40 headroom above anything you would ever trade. There is no practical ceiling concern.
The Groth16 prover takes this circuit, the witness, and a proving key from the setup ceremony, and outputs three elliptic curve group elements on BN254:
π_a, π_b, π_c
These three elements are the proof. Serialised, they always come out to exactly 256 bytes, regardless of what the witness contains. That fixed size is genuinely useful in practice: gas costs are predictable, ABI encoding is clean, and storage is a non-issue.
Proof generation takes about 1 to 2 seconds on a regular laptop, and it all happens off-chain. The blockchain never sees the compute; it only sees the output.
The Smart Contracts: Access Control That Actually Makes Sense
The onlyOwner Trap
Here is a pattern I wanted to avoid from the start.
A lot of contract systems default to a single onlyOwner modifier for every privileged operation. It is simple. It works. And in a single-actor system, it is probably fine.
But H2Ledger has three distinct actor types with completely different trust assumptions: Producers (suppliers holding credits), Buyers (companies publishing procurement orders), and Verifier Agents (credentialed parties who attest the legitimacy of underlying certifications off-chain). Funnelling all three through a single owner address creates a unilateral control point that fundamentally contradicts the trustless premise of the whole system.
So I built a role-based access layer instead. Each address gets assigned one of four states: NONE, PRODUCER, VERIFIER_AGENT, or BUYER. Every sensitive function checks the caller's role before anything else runs.
pragma solidity ^0.8.0;
import "./Verifier.sol";
contract GreenHydrogenMarketplace {
Verifier verifier;
enum Role { NONE, PRODUCER, VERIFIER_AGENT, BUYER }
mapping(address => Role) private roles;
address public admin;
modifier onlyRole(Role _required) {
require(roles[msg.sender] == _required, "Access denied: insufficient role");
_;
}
modifier onlyAdmin() {
require(msg.sender == admin, "Access denied: not admin");
_;
}
constructor(address _verifier) {
verifier = Verifier(_verifier);
admin = msg.sender;
}
function assignRole(address _account, Role _role) external onlyAdmin {
roles[_account] = _role;
}
}
The result: no address can wear two hats. A buyer cannot submit proofs. A producer cannot create orders. Role assignment itself is gated behind the admin key, which is the one remaining centralisation point I will address honestly in the learnings section below. The onlyRole modifier is composable, so extending this to new function types costs one line.
Creating an Order
Only BUYER addresses can create procurement orders. And once an order is created, the threshold is immutable. I want to highlight that last part because it matters more than it might seem.
If a buyer could lower the threshold after a supplier has already generated their proof, they could retroactively disqualify a supplier who legitimately met the original bar. Locking the threshold at creation time prevents that manipulation entirely.
struct ProcurementOrder {
address buyer;
address supplier;
uint256 threshold;
bool fulfilled;
}
mapping(uint256 => ProcurementOrder) public orders;
uint256 public nextOrderId;
function createOrder(address _supplier, uint256 _threshold)
external
onlyRole(Role.BUYER)
returns (uint256 orderId)
{
orderId = nextOrderId++;
orders[orderId] = ProcurementOrder({
buyer: msg.sender,
supplier: _supplier,
threshold: _threshold,
fulfilled: false
});
}
Proof Submission: Cheap Checks First, Expensive Check Last
This is where the ZK verification actually happens. When a supplier submits their proof, the contract runs five checks in deliberate order, from cheapest to most expensive:
- Role check: Is the caller a registered PRODUCER? (modifier, ~200 gas)
- Supplier identity: Is this the specific supplier bound to this order? (SLOAD, ~2,100 gas)
- Replay prevention: Has this order already been fulfilled? (SLOAD, ~2,100 gas)
- Threshold binding: Does the public signal match the stored threshold? (comparison, ~200 gas)
- Pairing check: Is the ZK proof cryptographically valid? (~285,000 gas)
The expensive pairing computation runs dead last. Every cheaper guard that fails before it saves the caller from spending 285k gas on a doomed transaction.
function submitThresholdProof(
uint256 orderId,
uint[2] calldata _pA,
uint[2][2] calldata _pB,
uint[2] calldata _pC,
uint[1] calldata _pubSignals
) external onlyRole(Role.PRODUCER) {
ProcurementOrder storage order = orders[orderId];
require(msg.sender == order.supplier, "Caller is not the designated supplier");
require(!order.fulfilled, "Order already fulfilled");
require(_pubSignals[0] == order.threshold, "Public signal does not match order threshold");
require(
verifier.verifyProof(_pA, _pB, _pC, _pubSignals),
"ZK proof verification failed"
);
order.fulfilled = true;
// Downstream: emit event, trigger escrow release, etc.
}
One check here deserves extra attention: _pubSignals[0] == order.threshold. This might look redundant but it is doing important work. Without it, a supplier could submit a valid proof generated against a different threshold (say, 1,000 MWh, which they easily meet) and pair it with an order that requires 3,000 MWh. The proof itself would pass the pairing check, because it is a valid proof for 1,000 MWh. Only this binding check catches the substitution and rejects it.
Performance Numbers: What Does This Actually Cost?
| Metric | Value |
|---|---|
| Proof size | 256 bytes (always fixed) |
| Proof generation time | 1 to 2 seconds (off-chain) |
| Verifier deployment gas | ~2,850,000 (one-time) |
| Per-proof verification gas | ~289,096 |
| Cost on Ethereum L1 at 30 Gwei | ~$0.87 per proof |
| Cost on Arbitrum or Optimism | ~$0.01 per proof |
For enterprise procurement deals where individual contracts are worth millions, $0.87 per verification on L1 is totally reasonable. For anything approaching higher frequency, L2 is the obvious path.
What I Got Right, and Where I Would Do Things Differently
The Good Stuff
Separating Verifier.sol from GreenHydrogenMarketplace.sol was the right architectural call. The verifier is a stateless cryptographic primitive with no business logic. Keeping it isolated means you can audit it independently from everything else. Smaller surface, cleaner audit scope.
The cheap-to-expensive ordering on submitThresholdProof also paid off during testing. Failed submissions on invalid inputs were consistently cheaper than they would have been with the pairing check running first.
The Honest Regrets
The trusted setup is my biggest unresolved liability. Groth16 requires a one-time MPC ceremony to generate the proving and verification keys. The PoC uses a simulated ceremony, which is fine for a research context. But in production, if any single participant in that ceremony retained their "toxic waste" (the secret randomness from their contribution), they could forge valid proofs for false claims indefinitely. A production deployment needs either a large, publicly verifiable MPC ceremony with auditable transcripts, or a migration to a setup-transparent proof system like PLONK or Halo2, where no trusted setup is needed at all.
The admin key is a trust bottleneck I did not fully solve. Right now, a single address controls role assignment for the entire marketplace. That is a meaningful centralisation risk. In the next version, the admin role should transfer to a Gnosis Safe multisig on day one, with a timelock on role assignment operations so participants have advance notice of any changes.
Gas can go lower. The BN254 pairing operations in Verifier.sol benefit significantly from the EIP-197 precompile on Ethereum. If the generated verifier correctly routes through it rather than computing in the EVM interpreter, verification cost drops by 30 to 40 percent. Worth measuring carefully before any production deployment.
The circuit only proves one thing. Real procurement contracts care about more than just volume. Purity grade, certification date, origin country; these all matter. Extending the circuit to a composite check (volume >= min_vol AND purity >= min_purity AND date >= cutoff) adds roughly 256 additional constraints and maybe doubles proof generation time. Both are well within practical limits, and it would make the system meaningfully more useful.
Run It Yourself
If you want to poke at the code:
git clone <your-repo-url>
cd h2ledger-poc
npm install
npm run verify
# Expected: OK
# (verifies the included proof where actualAmount=5000 >= threshold=3000)
And to see the circuit stats directly:
snarkjs r1cs info circuits/credit_proof.r1cs
# Curve: bn-128
# Constraints: 128
# Wires: 193
# Private Inputs: 1
# Public Inputs: 1
Why This Pattern Matters Beyond Hydrogen
Here is the thing I kept coming back to while building this: H2Ledger is not really a hydrogen project. It is a demonstration of a general-purpose pattern.
Any market where someone needs to prove a number meets a threshold, but revealing that number has a cost, is a candidate for this architecture. Credit scoring. Insurance underwriting. Supply chain vendor qualification. Payroll compliance audits. The circuit changes; the pattern does not.
Zero-knowledge proofs get talked about a lot in abstract terms. What I wanted to show here is that with Circom, SnarkJS, and a few hundred lines of Solidity, you can build something real with them in a matter of weeks. The tooling is genuinely usable. The math does not need to be magic; it just needs to be correctly wired together.
If you build something with a similar approach, or if you spot something I should fix, I would genuinely love to hear about it.
H2Ledger is a research proof of concept (v0.1.0). Proof system: Groth16 (BN254). Circuit: 128 constraints, 193 wires. Questions or collaboration: nioomeee@gmail.com

Top comments (0)