验证证明
本页说明如何在不信任提供结果的索引器的前提下验证一次名称解析。 这里的每一段代码示例在发布前都会针对一个真实运行的索引器执行过。
验证能给你什么
一次解析回答的是「richard.pivx 指向哪个地址?」。验证它,则证明这个答案正是被承诺进状态根的那一个
——并且该根正是锚定合约当前的根。凭空捏造地址、给出过期记录或隐藏某个名称的索引器,都拿不出能通过
这些检查的证明。
用另一个名称的真实记录来应答的索引器同样做不到:下面的检查把应答绑定到你所查询的名称上。
这里有三个彼此独立的步骤,三者缺一不可:
- 默克尔证明把记录绑定到某个状态根。
- 链上校验把那个根绑定到锚定合约。
- 纪元校验把合约的规则与历史绑定到你已审查过的那一份。
仅有第 1 步毫无价值:恶意索引器完全可以构造一整棵伪造的树,并给出与自己伪根相自洽的证明。是第 2 步才让这个根有了意义,而在规则变更或状态回滚时,让这份意义得以保持的是第 3 步。
第 1 步 — 验证默克尔证明
这棵树
PiNS 使用基于 128 位密钥空间的紧凑稀疏默克尔树。密钥是 SHA-256(domain_name) 的前 16 个字节。
编写验证器时,有两个性质很重要:
- 证明很短,且长度可变。 叶子位于其密钥前缀唯一的最浅深度,因此一份证明携带
proof_depth个兄弟 节点——通常只有寥寥数个,而不是 128 个。切勿假定固定长度;请读取proof_depth并核对它与merkle_proof.length一致。 - 空子树在任何高度都是 32 个零字节。 并不存在一串预先算好的空节点哈希。因此空树的根全是零。
哈希函数
叶子与内部节点都带有标签,以免它们的哈希域相互重叠。漏掉标签字节是最常见的错误——它会算出一个看似 合理、却永远与根对不上的哈希。
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 与 target_address 是不带长度前缀的 UTF-8 字节;owner_pubkey 是原始的 32 字节;price
与 nonce 是无符号 64 位小端序整数。
遍历方式
从叶子往回走到根。在有 n = proof_depth 个兄弟节点的情况下,第 i 步决定你处于哪一侧的,是密钥的
第 n - 1 - i 位,从第 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] 是最深一层、离叶子最近的兄弟节点。
终端节点
每份证明都带有一个 proof_terminal,用来描述路径末端是什么:
| 终端节点 | 含义 |
|---|---|
Occupied | 那里是该密钥自己的叶子 — 名称存在 |
Vacant | 那里是一棵空子树 — 名称未注册 |
Blocked | 那里是另一个名称的叶子 — 该名称未注册,且响应中附带了那个名称的完整记录 |
成功的解析必须是 Occupied。Vacant 与 Blocked 是不存在证明:它们让你能够验证某个名称确实未被
注册,而不必凭信任接受索引器的「未找到」。请拒绝任何终端节点不是 Occupied 的解析结果。
解析 API 目前还不返回不存在证明:对于它不知道的名称,它会不带任何证明地回答 Domain not found。在此之前,请把「not found」视为未经验证,并用第二个索引器核实。
代码
验证器除了应答之外,还接收你所查询的名称,并且总是对这个名称做哈希,而不是应答里带的 domain_name。否则,索引器可以用另一个名称的真实记录和证明来应答,它们能完美通过验证,而你就会付款给那个名称的所有者。它还会在做任何哈希之前拒绝格式错误的字段:叶子没有长度前缀,长度错误的字段会把字节挤进相邻字段。
- 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();
}
在 JavaScript 中,JSON.parse 对大于 2^53 的整数读取不精确,因此示例会拒绝这么大的 price 或 nonce(价格高于约 9000 万 PIVX),而不是去哈希一个不同的数。要验证这样的记录,请以让两个值都保持精确的方式解析应答(Node.js 21 及以上、当前的浏览器):
const body = JSON.parse(text, (key, value, context) =>
(key === "price" || key === "nonce") && typeof value === "number"
? BigInt(context.source)
: value);
请针对篡改测试你的实现
一个永远返回 true 的验证器能通过任何正向测试。在信任自己的实现之前,请在一份真实响应中改动
target_address、owner_pubkey 或 price 的一个字节,并确认它现在返回 false。上面三段示例都是
这样检验过的。
然后,在查询一个名称时传入另一个名称的真实应答:验证器必须拒绝它。示例也用这种方式检验过。
第 2 步 — 拿这个根去比对锚定合约
一份通过验证的默克尔证明只说明「这条记录在某一棵树里」。要确认它在真正那棵树里,请去问 BNB Smart Chain 上的锚定合约,这个根是否有效:已在链上被接受,且此后未被回滚。
使用 isRootValid(bytes32) — 选择器 0x30ef41b4。它只返回单个 ABI 编码的布尔值:这一步所需的正是它,而且比 (bool, uint32) 二元组(verifyRootValidity 的返回值)更容易解析。
| 调用 | 选择器 | 返回 |
|---|---|---|
isRootValid(bytes32) | 0x30ef41b4 | bool — 已被接受,且此后未被回滚 |
currentRoot() | 0xfdab463d | bytes32 — 最近一次被接受的根 |
verifyRootValidity(bytes32) | 0xc7179944 | (bool isValid, uint32 blockHeight) |
currentBlockHeight() | 0x367bf2f9 | uint32 — 最新那个根对应的 PIVX 高度 |
programVkey() | 0x09665ee7 | bytes32 — 合约所强制要求的电路 |
示例与索引器一样,在最新的已最终确定(finalized)区块上读取合约:在尚未最终确定的区块中被接受的根,仍可能因链重组而消失,基于它的付款也就失去了依据。示例先查询该区块的编号,再在这个编号上读取,因为一些公共 BSC 端点不接受把 finalized 标签用在 eth_call 中。请在同一编号上读取 currentRoot() 和第 3 步中的调用,使所有应答描述的是同一个区块。
- 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);
如何理解返回结果
isRootValid | 含义 | 该怎么做 |
|---|---|---|
true,且该根等于 currentRoot() | 索引器已完全同步 | 接受 |
true,但该根比 currentRoot() 旧 | 索引器落后于链 | 暂时不要付款——等待,或换一个索引器查询,然后重新验证 |
false | 该根在链上从未被接受过,或已被回滚 | 拒绝这次解析 |
较旧但有效的根,是登记簿真实存在过的一个过去状态,而不是当前状态。在那之后,这个名称可能已被转让、出售,
或改为指向新的地址,而针对旧根的证明仍然给出之前的答案。一个只是落后的索引器,与一个故意扣下最新更新的
索引器,在这里看起来完全一样。因此在付款之前,务必要求该根等于 currentRoot()。诚实的索引器会在每个新
批次之后很快追上。仅作参考地展示这条记录、并标注其可能已过期,是可以的。
返回 false 意味着你所比对的那棵树,在协议看来不属于登记簿的历史:它要么从未被接受,要么已在回滚中被否定。
这正是被攻击者控制的索引器会造成的情形,而这一步存在的意义就在于此。
第 3 步 — 检查纪元
第 1、2 步证明某条记录位于合约接受过的一棵树中。有两件事可以在没有任何新批次的情况下改变这一证明的含义:规则变更——新的电路或验证器,也就是对何谓“已证明”的新定义——以及回滚,它会让一个更早的根重新成为当前根,从而在没有持有者签名的情况下,把此后变更过的每个名称重新指回原状。合约用 epoch 对这两者计数:
- 计数从 1 开始,每次规则变更和每次回滚都加一。它永远不会减少:一次变更及其撤销是两个纪元,而不是回到第一个。
- 规则变更会提前公告。所有者的批准会启动一个在部署时固定的时间锁(
rulesTimelock,7 到 90 天之间),只有到达rulesChangeActivatesAt()所示的时间之后,变更才能被激活。 - 回滚只能以合约此前接受过的根为目标,而且只能在批次提交暂停期间进行。目标之上的每个根都会立即失效,此后第 2 步对它们每一个都返回
false。
因此,请固定你已审查过的纪元,并拒绝在任何其他纪元下解析。请在一次调用中把它与根一起读取,使两者来自同一个区块:
| 调用 | 选择器 | 返回 |
|---|---|---|
anchoredState() | 0x8d39310a | (bytes32 root, uint32 blockHeight, uint32 currentEpoch) |
epoch() | 0x900cf0cf | uint32 — 当前生效的纪元 |
rulesChangeActivatesAt() | 0x90b86556 | uint64 — 已排期的规则变更何时可以激活;没有排期时为 0 |
anchoredState() 按顺序返回三个 32 字节字:根、区块高度和纪元。纪元就是第三个字中的整数。
下面的示例在第 2 步示例的基础上加入这一步,并复用其中的函数。它们在同一个已最终确定的区块上读取 anchoredState(),拒绝与你固定的纪元不同的纪元,然后像第 2 步的表格那样对根分类:当前的根为 accept,较早但有效的根为 lagging,合约不接受的根为 reject。
- 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);
| 纪元 | 该怎么做 |
|---|---|
| 等于你固定的纪元 | 继续——第 1、2 步在你审查过的规则下成立 |
| 高于你固定的纪元 | 停止解析。 EpochAdvanced、RulesChanged 和 RootRolledBack 事件说明发生了什么;审查之后,再更新你固定的纪元 |
索引器对自身也适用同一规则:当链上纪元超过其运营者审查过的纪元时,节点会停止跟随链,并在索引器信息中以 anchored_epoch 报告这个审查过的纪元。它是节点的设置,而不是它所提供的根的纪元:在计划中的规则变更之前已更新的节点,会在变更等待时间锁期间提前报告即将到来的纪元,并在此之前提供在现行纪元下形成的状态。因此,请按上文所述与根一起从合约读取的纪元来判断解析结果,而不是按 anchored_epoch;节点的根是否最新,由第 2 步判断。
验证电路本身
上面的步骤证明了某条记录属于合约接受过的某个根。而合约只有在伴随有效 ZK 证明时才会接受某个根——那份证明会针对 programVkey 进行校验,它是对确切已编译电路的 32 字节承诺。
你可以确认这个密钥与公开的源码相对应。在 SP1 的 Docker 镜像中构建电路(该镜像固定了密钥所依赖的工具链 和构建路径),然后打印它的密钥:
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
把得到的验证密钥与锚定合约上的 programVkey()(选择器 0x09665ee7)比较。若两者一致,合约强制要求
的就是这份确切源码。改动电路中的任何一行都会得到不同的密钥,因此被修改过的电路无法在链上不留痕迹地被
替换进去。
它也无法悄悄生效:新密钥要经过第 3 步所述的带时间锁的规则变更,并推进纪元。
证明器的 README 列出了每个版本的密钥及其构建所用的提交。
构建时不要启用额外特性
不启用任何特性的构建生成的正是已部署合约所强制要求的主网电路。任何特性开关都会改变 已编译的程序,从而改变它的验证密钥,届时便对不上了。 在 Docker 之外构建,或使用其他镜像标签,也可能得到不同的密钥。
直接验证一份 SP1 证明
这些证明是标准的 SP1 Groth16 证明,可以用 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)?;
其公开值是 (bytes32 old_root, bytes32 new_root, uint32 end_block_height) 的 ABI 编码——即该批次执行的状态转移,以及它所覆盖的 PIVX 区块高度。