証明の検証
このページでは、結果を返したインデクサーを信頼せずに名前解決を検証する方法を示します。 ここに載せたコード例はいずれも、公開前に実際に稼働しているインデクサーに対して実行されています。
検証によって得られるもの
名前解決は「richard.pivx はどのアドレスを指すか?」に答えます。それを検証すると、その答えが状態ルートに
コミットされたものであること、そしてそのルートがアンカーコントラクトの現在のルートであることを証明でき
ます。アドレスをでっち上げたり、古いレコードを返したり、名前を隠したりするインデクサーは、これらの検査を
通る証明を作れません。
別の名前の本物のレコードで答えるインデクサーも同様です。以下の検査は、応答をあなたが問い合わせた名前に結び付けます。
互いに独立した 3 つの手順があり、3 つとも必要です:
- マークル証明がレコードを状態ルートへ結びつけます。
- オンチェーンの確認がそのルートをアンカーコントラクトへ結びつけます。
- エポックの確認がコントラクトのルールと履歴を、あなたが確認済みのものへ結びつけます。
手順 1 だけでは無価値です。悪意あるインデクサーは偽のツリーを丸ごと作り、自分の偽ルートと辻褄の合う証明を返せるからです。そのルートに意味を与えるのが手順 2 であり、ルールが変わったり状態がロールバックされたりしたときにもその意味を保つのが手順 3 です。
手順 1 — マークル証明を検証する
ツリー
PiNS は 128 ビットの鍵空間上のコンパクト疎マークルツリーを使います。鍵は SHA-256(domain_name) の
先頭 16 バイトです。検証器を書くうえで重要な性質が 2 つあります:
- 証明は短く、長さは可変です。 葉は鍵の接頭辞が一意になる最も浅い深さに置かれるので、証明は
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 でどちら側にいるかを
決めるのは、0 バイト目の最上位ビットから数えた鍵の n - 1 - i 番目のビットです:
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」は未検証として扱い、2 つ目のインデクサーで確認してください。
コード
検証器は応答に加えて、あなたが問い合わせた名前を受け取り、応答に含まれる 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(約 9,000 万 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 のいずれか 1 バイトを書き換え、false が返ることを
確かめてください。上記の 3 つの例はいずれもこの方法で確認しています。
次に、ある名前を問い合わせながら、別の名前の本物の応答を渡してください。検証器はそれを拒否しなければなりません。各例はこの方法でも確認しています。
手順 2 — ルートをアンカーコントラクトと突き合わせる
検証済みのマークル証明が言えるのは「このレコードは何らかのツリーの中にある」ということだけです。それが 本物のツリーにあると知るには、BNB Smart Chain 上のアンカーコントラクトに、そのルートが有効か、つまり オンチェーンで受け入れられ、その後ロールバックされていないかを尋ねてください。
isRootValid(bytes32) を使います — セレクター 0x30ef41b4。ABI エンコードされた真偽値を 1 つ返すだけです。この手順に必要なのはそれだけで、(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 は、レコードがコントラクトの受け入れたツリーに含まれることを証明します。新しいバッチがなくても、その証明の意味を変えうるものが 2 つあります。ルール変更(新しい回路や検証器、つまり「証明済み」の新しい定義)と、ロールバックです。ロールバックは古いルートを再び現在のものにし、それ以降に変更されたすべての名前を、保有者の署名なしに以前の状態へ向け直します。コントラクトはこの両方を epoch で数えます:
- カウンターは 1 から始まり、ルール変更とロールバックのたびに 1 ずつ増えます。減ることはありません。変更とその取り消しは 2 つのエポックであり、最初のエポックに戻るわけではありません。
- ルール変更は事前に告知されます。所有者の承認によって、デプロイ時に固定されたタイムロック(
rulesTimelock、7〜90 日)が始まり、変更はrulesChangeActivatesAt()の時刻に達して初めて有効化できます。 - ロールバックの対象にできるのは、コントラクトが以前に受け入れたルートだけで、しかもバッチの提出が一時停止されている間に限られます。対象より上のルートはすべて即座に無効になり、以後、手順 2 はそれぞれに対して
falseを返します。
したがって、確認済みのエポックを固定し、それ以外のエポックでは解決を拒否してください。両方の値が同じブロックから得られるよう、エポックはルートと一緒に 1 回の呼び出しで読み取ります:
| 呼び出し | セレクター | 戻り値 |
|---|---|---|
anchoredState() | 0x8d39310a | (bytes32 root, uint32 blockHeight, uint32 currentEpoch) |
epoch() | 0x900cf0cf | uint32 — 現在有効なエポック |
rulesChangeActivatesAt() | 0x90b86556 | uint64 — 予定されたルール変更を有効化できる時刻。予定がなければ 0 |
anchoredState() は 32 バイトのワードを 3 つ、ルート、ブロック高、エポックの順に返します。エポックは 3 番目のワードの整数です。
以下の例は、手順 2 の例にこの手順を加えたもので、手順 2 の関数をそのまま使います。1 つのファイナライズ済みブロックで 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 証明が添えられていたときだけであり、その証明はコンパイル済みのまさにその回路への 32 バイトのコミットメントである programVkey に対して確認されます。
その鍵が公開されたソースコードに対応することは、次のように確かめられます。鍵が依存するツールチェーンと ビルドパスを固定する 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)と比べてください。
一致すれば、コントラクトはまさにそのソースコードを強制しています。回路を 1 行変えるだけで別の鍵になるので、
改変された回路をオンチェーンに痕跡を残さず差し替えることはできません。
また、黙って発効させることもできません。新しい鍵は手順 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 の
ブロック高です。