Праверка доказаў
Гэтая старонка паказвае, як праверыць вырашэнне імя, не давяраючы індэксатару, які яго выдаў. Кожны прыклад кода тут перад публікацыяй выконваецца на жывым індэксатары.
Што дае праверка
Вырашэнне імя адказвае на пытанне «на які адрас указвае richard.pivx?». Праверка даказвае, што
гэты адказ — менавіта той, які зафіксаваны ў корані стану, і што гэты корань —
бягучы корань якарнага кантракта. Індэксатар, які выдумае адрас, аддасць састарэлы запіс ці схавае імя, не зможа
прад'явіць доказ, які праходзіць гэтыя праверкі.
Не зможа і той, хто адкажа сапраўдным запісам іншага імя: праверкі ніжэй прывязваюць адказ да імя, якое вы запыталі.
Крокаў тры, яны незалежныя, і патрэбныя ўсе тры:
- Доказ Меркла звязвае запіс з коранем стану.
- Праверка ў блокчэйне звязвае гэты корань з якарным кантрактам.
- Праверка эпохі звязвае правілы і гісторыю кантракта з тымі, што вы праверылі.
Адзін толькі крок 1 бескарысны: шкодны індэксатар можа пабудаваць цэлае падробленае дрэва і выдаваць узгодненыя доказы адносна ўласнага падробленага кораня. Сэнс кораню надае менавіта крок 2, а крок 3 захоўвае гэты сэнс, калі мяняюцца правілы або стан адкочваецца.
Крок 1 — праверце доказ Меркла
Дрэва
PiNS выкарыстоўвае кампактнае разрэджанае дрэва Меркла над 128-бітавай прасторай ключоў. Ключ
— гэта першыя 16 байтаў SHA-256(domain_name). Пры напісанні верыфікатара важныя дзве
ўласцівасці:
- Доказы кароткія і зменнай даўжыні. Ліст размяшчаецца на мінімальнай глыбіні, дзе прэфікс
яго ключа ўнікальны, таму доказ нясе
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-бітавыя little-endian.
Абыход
Ідзіце ад ліста назад да кораня. Пры 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 resolve пакуль не вяртае доказаў адсутнасці: на імя, якога не ведае, ён адказвае
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 (цану вышэй за прыблізна 90 мільёнаў 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-байтавага абавязацельства да канкрэтнай скампіляванай схемы.
Пераканацца, што гэты ключ адпавядае апублікаванаму зыходнаму коду, можна так: збярыце схему ў Docker-вобразе SP1, які фіксуе тулчэйн і шляхі зборкі, ад якіх залежыць ключ, і выведзіце яе ключ:
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, і праверыць іх можна з дапамогай SDK SP1:
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)?;
Публічныя значэнні — гэта ABI-кадаванне (bytes32 old_root, bytes32 new_root, uint32 end_block_height): пераход стану, выкананы пакетам, і вышыня блока PIVX, якую ён пакрывае.