Verifying Proofs
This page shows how to verify a name resolution without trusting the indexer that served it. Every code sample here is executed against a live indexer before publication.
What verification gives you
A resolution answers "what address does richard.pivx point to?". Verifying it proves that
the answer is the one committed to the state root — and that the root is the anchor
contract's current one. An indexer that invents an address, serves a stale record, or omits a
name cannot produce a proof that passes these checks.
Nor can one that answers with another name's genuine record: the checks below bind the answer to the name you asked for.
There are three independent steps, and you need all three:
- The Merkle proof ties the record to a state root.
- The on-chain check ties that root to the anchor contract.
- The epoch check ties the contract's rules and history to the ones you have reviewed.
Step 1 alone is worthless: a malicious indexer can build an entire fake tree and serve consistent proofs against its own fake root. Step 2 is what makes the root meaningful, and Step 3 is what keeps it meaningful when the rules change or the state is rolled back.
Step 1 — verify the Merkle proof
The tree
PiNS uses a compact Sparse Merkle Tree over a 128-bit key space. A key is the first
16 bytes of SHA-256(domain_name). Two properties matter when writing a verifier:
- Proofs are short and variable-length. A leaf sits at the shallowest depth where its
key prefix is unique, so a proof carries
proof_depthsiblings — typically a handful, not 128. Never assume a fixed length; readproof_depthand check it matchesmerkle_proof.length. - An empty subtree is 32 zero bytes at every height. There is no ladder of precomputed empty-node hashes. The root of an empty tree is therefore all zeros.
The hash functions
Leaves and internal nodes are tagged so their hash domains cannot overlap. Omitting the tag byte is the single most common mistake — it produces a plausible-looking hash that never matches the root.
leaf = SHA-256( 0x00 ‖ domain ‖ owner_pubkey ‖ target_address ‖ price_le64 ‖ nonce_le64 )
node = SHA-256( 0x01 ‖ left ‖ right )
key = SHA-256( domain )[0..16]
domain and target_address are UTF-8 bytes with no length prefix; owner_pubkey is the
raw 32 bytes; price and nonce are unsigned 64-bit little-endian.
The traversal
Walk from the leaf back to the root. With n = proof_depth siblings, at step i the bit
that decides which side you are on is bit n - 1 - i of the key, counting from the most
significant bit of byte 0:
h = leaf
for i in 0..n:
h = key_bit(key, n-1-i) ? node(sibling[i], h) : node(h, sibling[i])
merkle_proof[0] is the sibling at the deepest level, closest to the leaf.
The terminal
Every proof carries a proof_terminal describing what sits at the end of the path:
| Terminal | Meaning |
|---|---|
Occupied | the key's own leaf is there — the name exists |
Vacant | an empty subtree is there — the name is unregistered |
Blocked | a different name's leaf is there — the name is unregistered, and the response includes that name's full record |
A successful resolution must be Occupied. Vacant and Blocked are absence proofs:
they let you verify that a name genuinely is not registered, rather than taking an
indexer's "not found" on faith. Reject any resolution whose terminal is not Occupied.
The resolve API does not return absence proofs yet: for a name it does not know, it answers
Domain not found with no proof at all. Until it does, treat a "not found" as unverified and
check it with a second indexer.
Code
The verifier takes the name you asked for as well as the answer, and hashes that name, never the domain_name the answer carries. Otherwise an indexer could answer with another name's genuine record and proof, which verify perfectly, and you would pay that name's owner. It also refuses fields of the wrong shape before hashing anything: the leaf has no length prefixes, so a field of the wrong length would shift bytes into its neighbour.
- Python
- PHP
- JavaScript
import hashlib
import re
import struct
LEAF_TAG, NODE_TAG = b"\x00", b"\x01"
KEY_LEN, MAX_DEPTH = 16, 128
def hash_leaf(domain, owner_pubkey_hex, target_address, price, nonce):
h = hashlib.sha256()
h.update(LEAF_TAG)
h.update(domain.encode())
h.update(bytes.fromhex(owner_pubkey_hex))
h.update(target_address.encode())
h.update(struct.pack("<Q", price))
h.update(struct.pack("<Q", nonce))
return h.digest()
def hash_node(left, right):
h = hashlib.sha256()
h.update(NODE_TAG)
h.update(left)
h.update(right)
return h.digest()
def key_of(domain):
return hashlib.sha256(domain.encode()).digest()[:KEY_LEN]
def key_bit(key, i):
return (key[i // 8] >> (7 - (i % 8))) & 1
def fold(key, start, siblings):
h, n = start, len(siblings)
for i, sib in enumerate(siblings):
h = hash_node(sib, h) if key_bit(key, n - 1 - i) else hash_node(h, sib)
return h
HEX32 = re.compile(r"[0-9a-f]{64}")
def verify_resolution(requested_name, entry, expected_root):
# The name you asked for, never the one the answer carries: an indexer could answer
# with another name's genuine record and proof, which verify perfectly.
name = requested_name.lower()
if entry["domain_name"] != name:
raise ValueError("the answer is for another name")
if entry["proof_terminal"] != "Occupied":
raise ValueError("a resolution must carry an Occupied terminal")
# The leaf has no length prefixes: refuse fields of the wrong shape before hashing.
if not HEX32.fullmatch(entry["owner_pubkey"]):
raise ValueError("owner_pubkey is not 32 bytes of lowercase hex")
for field in ("price", "nonce"):
if type(entry[field]) is not int or not 0 <= entry[field] < 2**64:
raise ValueError(f"{field} is not an unsigned 64-bit integer")
if not all(isinstance(s, str) and HEX32.fullmatch(s) for s in entry["merkle_proof"]):
raise ValueError("a sibling is not 32 bytes of lowercase hex")
siblings = [bytes.fromhex(s) for s in entry["merkle_proof"]]
if len(siblings) != entry["proof_depth"]:
raise ValueError("proof_depth does not match the sibling count")
if entry["proof_depth"] > MAX_DEPTH:
raise ValueError("proof depth exceeds MAX_DEPTH")
leaf = hash_leaf(
name,
entry["owner_pubkey"],
entry["target_address"],
entry["price"],
entry["nonce"],
)
root = fold(key_of(name), leaf, siblings)
return root.hex() == expected_root.lower()
<?php
const LEAF_TAG = "\x00";
const NODE_TAG = "\x01";
const KEY_LEN = 16;
const MAX_DEPTH = 128;
function hashLeaf(string $domain, string $ownerPubkeyHex, string $targetAddress, int $price, int $nonce): string
{
return hash('sha256',
LEAF_TAG
. $domain
. hex2bin($ownerPubkeyHex)
. $targetAddress
. pack('P', $price) // u64 little-endian
. pack('P', $nonce),
true);
}
function hashNode(string $left, string $right): string
{
return hash('sha256', NODE_TAG . $left . $right, true);
}
function keyOf(string $domain): string
{
return substr(hash('sha256', $domain, true), 0, KEY_LEN);
}
function keyBit(string $key, int $i): int
{
return (ord($key[intdiv($i, 8)]) >> (7 - ($i % 8))) & 1;
}
function fold(string $key, string $start, array $siblings): string
{
$h = $start;
$n = count($siblings);
foreach ($siblings as $i => $sib) {
$h = keyBit($key, $n - 1 - $i) === 1 ? hashNode($sib, $h) : hashNode($h, $sib);
}
return $h;
}
function verifyResolution(string $requestedName, array $entry, string $expectedRoot): bool
{
// The name you asked for, never the one the answer carries: an indexer could answer
// with another name's genuine record and proof, which verify perfectly.
$name = strtolower($requestedName);
if ($entry['domain_name'] !== $name) {
throw new RuntimeException('the answer is for another name');
}
if ($entry['proof_terminal'] !== 'Occupied') {
throw new RuntimeException('a resolution must carry an Occupied terminal');
}
// The leaf has no length prefixes: refuse fields of the wrong shape before hashing.
// The D modifier keeps `$` from matching before a trailing newline.
$hex32 = static fn($v): bool => is_string($v) && preg_match('/^[0-9a-f]{64}$/D', $v) === 1;
if (!$hex32($entry['owner_pubkey'])) {
throw new RuntimeException('owner_pubkey is not 32 bytes of lowercase hex');
}
foreach (['price', 'nonce'] as $field) {
// json_decode gives a float for an integer above PHP_INT_MAX, refused here too.
if (!is_int($entry[$field]) || $entry[$field] < 0) {
throw new RuntimeException("$field is not an unsigned 64-bit integer");
}
}
foreach ($entry['merkle_proof'] as $sibling) {
if (!$hex32($sibling)) {
throw new RuntimeException('a sibling is not 32 bytes of lowercase hex');
}
}
$siblings = array_map('hex2bin', $entry['merkle_proof']);
if (count($siblings) !== (int)$entry['proof_depth']) {
throw new RuntimeException('proof_depth does not match the sibling count');
}
if ((int)$entry['proof_depth'] > MAX_DEPTH) {
throw new RuntimeException('proof depth exceeds MAX_DEPTH');
}
$leaf = hashLeaf($name, $entry['owner_pubkey'], $entry['target_address'],
$entry['price'], $entry['nonce']);
return bin2hex(fold(keyOf($name), $leaf, $siblings)) === strtolower($expectedRoot);
}
import crypto from "node:crypto";
const LEAF_TAG = 0x00;
const NODE_TAG = 0x01;
const KEY_LEN = 16;
const MAX_DEPTH = 128;
const sha256 = (...parts) =>
crypto.createHash("sha256").update(Buffer.concat(parts)).digest();
const u64le = (v) => {
const b = Buffer.alloc(8);
b.writeBigUInt64LE(BigInt(v));
return b;
};
function hashLeaf(domain, ownerPubkeyHex, targetAddress, price, nonce) {
return sha256(
Buffer.from([LEAF_TAG]),
Buffer.from(domain, "utf8"),
Buffer.from(ownerPubkeyHex, "hex"),
Buffer.from(targetAddress, "utf8"),
u64le(price),
u64le(nonce),
);
}
const hashNode = (l, r) => sha256(Buffer.from([NODE_TAG]), l, r);
const keyOf = (domain) =>
crypto.createHash("sha256").update(domain, "utf8").digest().subarray(0, KEY_LEN);
const keyBit = (key, i) => (key[Math.floor(i / 8)] >> (7 - (i % 8))) & 1;
function fold(key, start, siblings) {
let h = start;
const n = siblings.length;
for (let i = 0; i < n; i++) {
h = keyBit(key, n - 1 - i) ? hashNode(siblings[i], h) : hashNode(h, siblings[i]);
}
return h;
}
const HEX32 = /^[0-9a-f]{64}$/;
// price and nonce as exact u64 values. JSON.parse reads an integer above 2^53 inexactly,
// and hashing it would hash a different number: such a value is refused, unless the
// response was parsed to keep it exact, as a BigInt (see below).
function u64(value, field) {
const n = typeof value === "bigint" ? value
: Number.isSafeInteger(value) ? BigInt(value) : null;
if (n === null || n < 0n || n >= 2n ** 64n) {
throw new Error(`${field} is not an exact unsigned 64-bit integer`);
}
return n;
}
export function verifyResolution(requestedName, entry, expectedRoot) {
// The name you asked for, never the one the answer carries: an indexer could answer
// with another name's genuine record and proof, which verify perfectly.
const name = requestedName.toLowerCase();
if (entry.domain_name !== name) {
throw new Error("the answer is for another name");
}
if (entry.proof_terminal !== "Occupied") {
throw new Error("a resolution must carry an Occupied terminal");
}
// The leaf has no length prefixes: refuse fields of the wrong shape before hashing.
if (typeof entry.owner_pubkey !== "string" || !HEX32.test(entry.owner_pubkey)) {
throw new Error("owner_pubkey is not 32 bytes of lowercase hex");
}
const price = u64(entry.price, "price");
const nonce = u64(entry.nonce, "nonce");
if (!entry.merkle_proof.every((s) => typeof s === "string" && HEX32.test(s))) {
throw new Error("a sibling is not 32 bytes of lowercase hex");
}
const siblings = entry.merkle_proof.map((s) => Buffer.from(s, "hex"));
if (siblings.length !== entry.proof_depth) {
throw new Error("proof_depth does not match the sibling count");
}
if (entry.proof_depth > MAX_DEPTH) {
throw new Error("proof depth exceeds MAX_DEPTH");
}
const leaf = hashLeaf(name, entry.owner_pubkey, entry.target_address, price, nonce);
return fold(keyOf(name), leaf, siblings).toString("hex") === expectedRoot.toLowerCase();
}
In JavaScript, JSON.parse reads an integer above 2^53 inexactly, so the sample refuses a price or nonce that large (a price above about 90 million PIVX) rather than hash a different number. To verify such a record, parse the response so that both stay exact (Node.js 21 or later, current browsers):
const body = JSON.parse(text, (key, value, context) =>
(key === "price" || key === "nonce") && typeof value === "number"
? BigInt(context.source)
: value);
Test your implementation against tampering
A verifier that always returns true passes every positive test. Before trusting yours,
change one byte of target_address, owner_pubkey or price in a real response and
confirm it now returns false. All three samples above are checked this way.
Then pass one name's genuine answer while asking for another: the verifier must refuse it. The samples are checked for this as well.
Step 2 — check the root against the anchor contract
A verified Merkle proof only says "this record is in some tree". To know it is in the real tree, ask the anchor contract on BNB Smart Chain whether that root is valid: accepted on-chain and not rolled back since.
Use isRootValid(bytes32) — selector 0x30ef41b4. It returns a single ABI-encoded
boolean: all this step needs, and simpler to parse than the (bool, uint32) pair
verifyRootValidity returns.
| Call | Selector | Returns |
|---|---|---|
isRootValid(bytes32) | 0x30ef41b4 | bool — accepted, and not rolled back since |
currentRoot() | 0xfdab463d | bytes32 — the latest accepted root |
verifyRootValidity(bytes32) | 0xc7179944 | (bool isValid, uint32 blockHeight) |
currentBlockHeight() | 0x367bf2f9 | uint32 — PIVX height of the latest root |
programVkey() | 0x09665ee7 | bytes32 — the circuit the contract enforces |
The samples read the contract at the newest finalized block, as indexers do: a root accepted in a block that is not final yet can still vanish in a chain reorganisation, and a payment made against it would rest on nothing. They ask for that block's number first and then read at it, because some public BSC endpoints refuse the finalized tag inside eth_call. Read currentRoot() and the calls of Step 3 at the same number, so that every answer describes the same block.
- Python
- PHP
- JavaScript
import requests
def evm_rpc(rpc_url, method, params):
payload = {"jsonrpc": "2.0", "method": method, "params": params, "id": 1}
r = requests.post(rpc_url, json=payload, timeout=15).json()
if "error" in r:
raise RuntimeError(f"EVM RPC error: {r['error']['message']}")
return r.get("result")
def finalized_block(rpc_url):
"""The newest finalized block, as a hex number. Asked for by number, because some public
BSC nodes refuse the "finalized" tag inside eth_call ("missing trie node")."""
block = evm_rpc(rpc_url, "eth_getBlockByNumber", ["finalized", False])
if not block or "number" not in block:
raise RuntimeError("the endpoint does not serve the finalized block")
return block["number"]
def is_root_valid(rpc_url, contract_address, smt_root, block):
"""Returns True if the anchor contract accepted this root and has not rolled it back."""
clean = smt_root.replace("0x", "").lower().rjust(64, "0")
result = evm_rpc(rpc_url, "eth_call", [{"to": contract_address, "data": f"0x30ef41b4{clean}"}, block]) or "0x"
# A bool is ABI-encoded as a full 32-byte word: 0x00..01 for true.
return int(result, 16) == 1 if result not in ("", "0x") else False
# block = finalized_block(rpc_url)
# is_root_valid(rpc_url, contract_address, entry["smt_root"], block)
<?php
function evmRpc(string $rpcUrl, string $method, array $params): mixed
{
$payload = ['jsonrpc' => '2.0', 'method' => $method, 'params' => $params, 'id' => 1];
$ch = curl_init($rpcUrl);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_TIMEOUT => 15,
]);
$response = curl_exec($ch);
if ($response === false) {
throw new RuntimeException('RPC request failed: ' . curl_error($ch));
}
$data = json_decode($response, true);
if (isset($data['error'])) {
throw new RuntimeException('EVM RPC error: ' . $data['error']['message']);
}
return $data['result'] ?? null;
}
// The newest finalized block, as a hex number. Asked for by number, because some public
// BSC nodes refuse the "finalized" tag inside eth_call ("missing trie node").
function finalizedBlock(string $rpcUrl): string
{
$block = evmRpc($rpcUrl, 'eth_getBlockByNumber', ['finalized', false]);
if (!is_array($block) || !is_string($block['number'] ?? null)) {
throw new RuntimeException('the endpoint does not serve the finalized block');
}
return $block['number'];
}
function isRootValid(string $rpcUrl, string $contractAddress, string $smtRoot, string $block): bool
{
$clean = str_pad(str_replace('0x', '', strtolower($smtRoot)), 64, '0', STR_PAD_LEFT);
$result = evmRpc($rpcUrl, 'eth_call', [['to' => $contractAddress, 'data' => '0x30ef41b4' . $clean], $block]) ?? '0x';
if ($result === '' || $result === '0x') {
return false;
}
// A bool is ABI-encoded as a full 32-byte word: 0x00..01 for true. The whole word is
// compared, as in the Python and JavaScript versions: its last digit alone would read
// an answer such as 0x…11 as true.
$word = substr($result, 2);
return ctype_xdigit($word) && ltrim($word, '0') === '1';
}
// $block = finalizedBlock($rpcUrl);
// isRootValid($rpcUrl, $contractAddress, $entry['smt_root'], $block);
async function evmRpc(rpcUrl, method, params) {
const response = await fetch(rpcUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ jsonrpc: "2.0", method, params, id: 1 }),
});
if (!response.ok) throw new Error(`RPC request failed: ${response.statusText}`);
const json = await response.json();
if (json.error) throw new Error(`EVM RPC error: ${json.error.message}`);
return json.result;
}
// The newest finalized block, as a hex number. Asked for by number, because some public
// BSC nodes refuse the "finalized" tag inside eth_call ("missing trie node").
async function finalizedBlock(rpcUrl) {
const block = await evmRpc(rpcUrl, "eth_getBlockByNumber", ["finalized", false]);
if (typeof block?.number !== "string") {
throw new Error("the endpoint does not serve the finalized block");
}
return block.number;
}
async function isRootValid(rpcUrl, contractAddress, smtRoot, block) {
const clean = smtRoot.replace(/^0x/, "").toLowerCase().padStart(64, "0");
const result = await evmRpc(rpcUrl, "eth_call", [
{ to: contractAddress, data: `0x30ef41b4${clean}` },
block,
]);
if (!result || result === "0x") return false;
// A bool is ABI-encoded as a full 32-byte word: 0x00..01 for true.
return BigInt(result) === 1n;
}
// const block = await finalizedBlock(rpcUrl);
// await isRootValid(rpcUrl, contractAddress, entry.smt_root, block);
Interpreting the answer
isRootValid | Meaning | What to do |
|---|---|---|
true, and the root equals currentRoot() | the indexer is fully synced | accept |
true, but the root is older than currentRoot() | the indexer lags behind the chain | do not send funds yet — wait or ask another indexer, then verify again |
false | this root was never accepted on-chain, or was rolled back | reject the resolution |
An older valid root is a real past state of the registry, not the current one. Since then the
name may have been transferred, sold or pointed at a new address, and a proof against the
older root still shows the previous answer. A slow indexer and one that withholds a recent
update look exactly the same here, so before paying, require the root to equal
currentRoot(). An honest indexer catches up shortly after each new batch. Showing the
record for information, marked as possibly out of date, is fine.
A false means the tree you verified against is not part of the registry's history as far as
the protocol is concerned: it was never accepted, or a rollback repudiated it. That is the
case an attacker-controlled indexer produces, and it is exactly what this step is for.
Step 3 — check the epoch
Steps 1 and 2 prove a record is in a tree the contract accepted. Two things can change what
that proves without any new batch: a rules change — a new circuit or verifier, and so a
new definition of what counts as proven — and a rollback, which makes an older root
current again and so re-points every name changed since, without a signature from its owner.
The contract counts both in epoch:
- It starts at 1 and goes up by one on every rules change and every rollback. It never goes down: a change and its reversal are two epochs, not a return to the first.
- A rules change is announced in advance. The owner's approval starts a timelock fixed at
deployment (
rulesTimelock, between 7 and 90 days), and the change can only be activated once the time inrulesChangeActivatesAt()has been reached. - A rollback can only target a root the contract accepted before, and only while batch
submission is paused. Every root above the target stops being valid at once, and Step 2
returns
falsefor each of them from then on.
So pin the epoch you have reviewed, and refuse to resolve under any other. Read it together with the root, in one call, so that both come from the same block:
| Call | Selector | Returns |
|---|---|---|
anchoredState() | 0x8d39310a | (bytes32 root, uint32 blockHeight, uint32 currentEpoch) |
epoch() | 0x900cf0cf | uint32 — the epoch in force |
rulesChangeActivatesAt() | 0x90b86556 | uint64 — when a scheduled rules change can be activated; 0 when none is scheduled |
anchoredState() returns three 32-byte words in that order: the root, the block height and
the epoch. The epoch is the integer in the third word.
The samples below add this step to those of Step 2, whose functions they reuse. At one
finalized block they read anchoredState(), refuse an epoch other than the one you pinned, and
then sort the root as the table in Step 2 does: accept for the current root, lagging for an
older valid one, reject for one the contract does not accept.
- Python
- PHP
- JavaScript
def anchored_state(rpc_url, contract_address, block):
"""anchoredState() at that block: (root as 64 hex digits, PIVX block height, epoch)."""
result = evm_rpc(rpc_url, "eth_call", [{"to": contract_address, "data": "0x8d39310a"}, block]) or "0x"
words = result[2:] if isinstance(result, str) else ""
# Three 32-byte words: nothing more, nothing less, and nothing but hex digits.
if len(words) != 192 or any(c not in "0123456789abcdefABCDEF" for c in words):
raise RuntimeError("unexpected anchoredState() answer")
return words[:64].lower(), int(words[64:128], 16), int(words[128:], 16)
def check_anchor(rpc_url, contract_address, smt_root, pinned_epoch):
"""Steps 2 and 3 at one finalized block. Returns "accept" for the current root, "lagging"
for an older valid one (do not send funds yet) and "reject" for one the contract does not
accept; raises when the epoch in force is not the one you pinned."""
block = finalized_block(rpc_url)
root, _height, epoch = anchored_state(rpc_url, contract_address, block)
if epoch != pinned_epoch:
raise RuntimeError(f"epoch {epoch} is in force, not the reviewed {pinned_epoch}: stop resolving")
if smt_root.replace("0x", "").lower().rjust(64, "0") == root:
return "accept"
return "lagging" if is_root_valid(rpc_url, contract_address, smt_root, block) else "reject"
# check_anchor(rpc_url, contract_address, entry["smt_root"], pinned_epoch)
<?php
// anchoredState() at that block: [root as 64 hex digits, PIVX block height, epoch].
function anchoredState(string $rpcUrl, string $contractAddress, string $block): array
{
$result = evmRpc($rpcUrl, 'eth_call', [['to' => $contractAddress, 'data' => '0x8d39310a'], $block]) ?? '0x';
$words = is_string($result) ? substr($result, 2) : '';
// Three 32-byte words: nothing more, nothing less, and nothing but hex digits.
if (strlen($words) !== 192 || !ctype_xdigit($words)) {
throw new RuntimeException('unexpected anchoredState() answer');
}
return [strtolower(substr($words, 0, 64)), hexdec(substr($words, 64, 64)), hexdec(substr($words, 128, 64))];
}
// Steps 2 and 3 at one finalized block. Returns 'accept' for the current root, 'lagging' for an
// older valid one (do not send funds yet) and 'reject' for one the contract does not accept;
// throws when the epoch in force is not the one you pinned.
function checkAnchor(string $rpcUrl, string $contractAddress, string $smtRoot, int $pinnedEpoch): string
{
$block = finalizedBlock($rpcUrl);
[$root, , $epoch] = anchoredState($rpcUrl, $contractAddress, $block);
if ($epoch !== $pinnedEpoch) {
throw new RuntimeException("epoch $epoch is in force, not the reviewed $pinnedEpoch: stop resolving");
}
if (str_pad(str_replace('0x', '', strtolower($smtRoot)), 64, '0', STR_PAD_LEFT) === $root) {
return 'accept';
}
return isRootValid($rpcUrl, $contractAddress, $smtRoot, $block) ? 'lagging' : 'reject';
}
// checkAnchor($rpcUrl, $contractAddress, $entry['smt_root'], $pinnedEpoch);
// anchoredState() at that block: { root (64 hex digits), blockHeight, epoch }.
async function anchoredState(rpcUrl, contractAddress, block) {
const result = await evmRpc(rpcUrl, "eth_call", [{ to: contractAddress, data: "0x8d39310a" }, block]);
const words = typeof result === "string" ? result.slice(2) : "";
// Three 32-byte words: nothing more, nothing less, and nothing but hex digits.
if (!/^[0-9a-fA-F]{192}$/.test(words)) throw new Error("unexpected anchoredState() answer");
return {
root: words.slice(0, 64).toLowerCase(),
blockHeight: Number(BigInt(`0x${words.slice(64, 128)}`)),
epoch: Number(BigInt(`0x${words.slice(128)}`)),
};
}
// Steps 2 and 3 at one finalized block. Returns "accept" for the current root, "lagging" for an
// older valid one (do not send funds yet) and "reject" for one the contract does not accept;
// throws when the epoch in force is not the one you pinned.
async function checkAnchor(rpcUrl, contractAddress, smtRoot, pinnedEpoch) {
const block = await finalizedBlock(rpcUrl);
const { root, epoch } = await anchoredState(rpcUrl, contractAddress, block);
if (epoch !== pinnedEpoch) {
throw new Error(`epoch ${epoch} is in force, not the reviewed ${pinnedEpoch}: stop resolving`);
}
if (smtRoot.replace(/^0x/, "").toLowerCase().padStart(64, "0") === root) return "accept";
return (await isRootValid(rpcUrl, contractAddress, smtRoot, block)) ? "lagging" : "reject";
}
// await checkAnchor(rpcUrl, contractAddress, entry.smt_root, pinnedEpoch);
| Epoch | What to do |
|---|---|
| equals your pinned epoch | carry on — Steps 1 and 2 hold under rules you have reviewed |
| higher than your pinned epoch | stop resolving. The EpochAdvanced, RulesChanged and RootRolledBack events say what happened; review it, then update your pin |
Indexers apply the same rule to themselves: a node stops following the chain when the
on-chain epoch moves past the one its operator reviewed, and reports that reviewed epoch as
anchored_epoch in Indexer info. It is the node's setting, not the epoch
of the root it serves: a node updated ahead of a scheduled rules change already reports the
coming epoch while the change waits out its timelock, and until then serves state made under
the epoch in force. So judge a resolution by the epoch read from the contract with the root,
as above, not by anchored_epoch; Step 2 shows whether the node's root is current.
Verifying the circuit itself
The steps above prove a record belongs to a root the contract accepted. The contract
only accepts a root if a valid ZK proof accompanied it — and that proof is checked against
programVkey, a 32-byte commitment to the exact compiled circuit.
You can confirm that key corresponds to the published source. Build the circuit in SP1's Docker image, which pins the toolchain and the build paths the key depends on, and print its key:
git clone https://github.com/PIVX-Name/pivx-name-prover
cd pivx-name-prover/program
cargo prove build --docker --tag v6.9.0 # no features = mainnet
cargo prove vkey --elf ../target/elf-compilation/docker/riscv64im-succinct-zkvm-elf/release/pins-program
Compare the resulting verification key with programVkey() (selector 0x09665ee7) on the
anchor contract. If they match, the contract is enforcing that exact source. Changing a
single line of the circuit produces a different key, so a modified circuit cannot be
substituted without the change being visible on-chain. Nor can it take effect quietly: a new
key goes through the timelocked rules change described in Step 3, and
advances the epoch.
The prover's README lists the key of each release and the commit it was built from.
Build with no extra features
A build without features produces the mainnet circuit that the deployed contract enforces. Any feature flag changes the compiled program and therefore its verification key, which will not match. A build outside Docker, or with another image tag, can give a different key too.
Verifying an SP1 proof directly
Proofs are standard SP1 Groth16 proofs and can be checked with the SP1 SDK:
use sp1_sdk::{ProverClient, SP1ProofWithPublicValues};
let client = ProverClient::from_env();
let (_, vk) = client.setup(ELF);
let proof = SP1ProofWithPublicValues::load("proof.bin")?;
client.verify(&proof, &vk)?;
The public values are the ABI encoding of (bytes32 old_root, bytes32 new_root, uint32 end_block_height) — the state transition the batch performed, and the PIVX block
height it covers.