Sübutların yoxlanması
Bu səhifə adın həllini onu təqdim edən indeksləyiciyə etibar etmədən necə yoxlayacağınızı göstərir. Buradakı hər kod nümunəsi dərc olunmazdan əvvəl işlək indeksləyiciyə qarşı icra olunur.
Yoxlama sizə nə verir
Ad həlli bu suala cavab verir: «richard.pivx hansı ünvana işarə edir?» Onu yoxlamaq cavabın
vəziyyət kökünə öhdəlik götürülmüş cavab olduğunu və həmin kökün lövbər müqaviləsinin cari kökü
olduğunu sübut edir. Ünvan uyduran, köhnəlmiş qeyd təqdim edən və ya adı gizlədən indeksləyici
bu yoxlamalardan keçən sübut yarada bilməz.
Başqa adın həqiqi qeydi ilə cavab verən indeksləyici də bunu bacarmaz: aşağıdakı yoxlamalar cavabı sizin soruşduğunuz ada bağlayır.
Üç müstəqil addım var və üçü də lazımdır:
- Merkle sübutu qeydi vəziyyət kökünə bağlayır.
- Zəncir üzərindəki yoxlama həmin kökü lövbər müqaviləsinə bağlayır.
- Epoxa yoxlaması müqavilənin qaydalarını və tarixçəsini sizin yoxladıqlarınıza bağlayır.
Təkbaşına 1-ci addım heç nəyə dəyməz: zərərli indeksləyici bütöv saxta ağac qurub öz saxta kökünə uyğun sübutlar təqdim edə bilər. Kökə məna verən məhz 2-ci addımdır, 3-cü addım isə qaydalar dəyişəndə və ya vəziyyət geri qaytarılanda bu mənanı qoruyur.
1-ci addım — Merkle sübutunu yoxlayın
Ağac
PiNS 128 bitlik açar fəzası üzərində kompakt seyrək Merkle ağacından istifadə edir. Açar —
SHA-256(domain_name) dəyərinin ilk 16 baytıdır. Doğrulayıcı yazarkən iki xüsusiyyət vacibdir:
- Sübutlar qısadır və uzunluğu dəyişkəndir. Yarpaq açar prefiksinin unikal olduğu ən az
dərinlikdə yerləşir, ona görə sübut
proof_depthsayda qonşu daşıyır — adətən bir neçə ədəd, 128 deyil. Heç vaxt sabit uzunluq fərz etməyin;proof_depthdəyərini oxuyun və onunmerkle_proof.lengthilə uyğun gəldiyini yoxlayın. - Boş alt ağac istənilən hündürlükdə 32 sıfır baytdır. Boş qovşaqlar üçün əvvəlcədən hesablanmış heş pilləkəni yoxdur. Buna görə boş ağacın kökü tamamilə sıfırdır.
Heş funksiyaları
Yarpaqlar və daxili qovşaqlar heş sahələri kəsişməsin deyə teqlənir. Teq baytını buraxmaq — ən çox yayılmış səhvdir: o, inandırıcı görünən, lakin köklə heç vaxt uyğun gəlməyən heş verir.
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 və target_address — uzunluq prefiksi olmayan UTF-8 baytlarıdır; owner_pubkey — xam 32
baytdır; price və nonce isə işarəsiz 64 bitlik little-endian dəyərlərdir.
Keçid
Yarpaqdan kökə doğru gedin. n = proof_depth qonşu ilə, i addımında hansı tərəfdə olduğunuzu
0-cı baytın ən əhəmiyyətli bitindən sayılmaqla açarın n - 1 - i nömrəli biti müəyyən edir:
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] — ən dərin səviyyədəki, yarpağa ən yaxın qonşudur.
Terminal
Hər sübut yolun sonunda nə olduğunu təsvir edən proof_terminal daşıyır:
| Terminal | Mənası |
|---|---|
Occupied | orada açarın öz yarpağı var — ad mövcuddur |
Vacant | orada boş alt ağac var — ad qeydiyyatda deyil |
Blocked | orada başqa adın yarpağı var — ad qeydiyyatda deyil və cavab həmin adın tam qeydini ehtiva edir |
Uğurlu həll Occupied olmalıdır. Vacant və Blocked — yoxluq sübutlarıdır: onlar
indeksləyicinin «tapılmadı» cavabına inanmaq əvəzinə adın həqiqətən qeydiyyatda olmadığını
yoxlamağa imkan verir. Terminalı Occupied olmayan hər həlli rədd edin.
Resolve API hələ yoxluq sübutlarını qaytarmır: tanımadığı ad üçün heç bir sübut olmadan
Domain not found cavabı verir. Bu dəyişənə qədər «not found» cavabını yoxlanılmamış sayın və onu
ikinci indeksləyici ilə yoxlayın.
Kod
Doğrulayıcı cavabla yanaşı sizin soruşduğunuz adı da qəbul edir və cavabın daşıdığı domain_name dəyərini deyil, məhz bu adı heşləyir. Əks halda indeksləyici başqa adın həqiqi qeydi və sübutu ilə cavab verə bilərdi, onlar qüsursuz yoxlanılır və siz o adın sahibinə ödəniş edərdiniz. Bundan əlavə, heç nəyi heşləməzdən əvvəl formaca səhv olan sahələri rədd edir: yarpaqda uzunluq prefiksləri yoxdur, ona görə də səhv uzunluqlu sahə baytları qonşu sahəyə sürüşdürərdi.
- 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-də JSON.parse 2^53-dən böyük tam ədədləri qeyri-dəqiq oxuyur, ona görə də nümunə başqa ədədi heşləmək əvəzinə belə böyük price və ya nonce dəyərini (təxminən 90 milyon PIVX-dən yuxarı qiyməti) rədd edir. Belə qeydi yoxlamaq üçün cavabı elə təhlil edin ki, hər iki dəyər dəqiq qalsın (Node.js 21 və ya daha yeni, müasir brauzerlər):
const body = JSON.parse(text, (key, value, context) =>
(key === "price" || key === "nonce") && typeof value === "number"
? BigInt(context.source)
: value);
Öz tətbiqinizi saxtakarlığa qarşı sınayın
Həmişə true qaytaran doğrulayıcı istənilən müsbət testdən keçir. Özünüzünkünə etibar etməzdən
əvvəl real cavabdakı target_address, owner_pubkey və ya price sahəsinin bir baytını dəyişin
və indi false qaytardığını təsdiqləyin. Yuxarıdakı üç nümunə də məhz belə yoxlanılıb.
Sonra bir adı soruşarkən başqa adın həqiqi cavabını ötürün: doğrulayıcı onu rədd etməlidir. Nümunələr bu üsulla da yoxlanılıb.
2-ci addım — kökü lövbər müqaviləsi ilə tutuşdurun
Yoxlanmış Merkle sübutu yalnız «bu qeyd hansısa ağacdadır» deyir. Onun həqiqi ağacda olduğunu bilmək üçün BNB Smart Chain üzərindəki lövbər müqaviləsindən həmin kökün etibarlı olub-olmadığını soruşun: zəncirdə qəbul edilmiş və o vaxtdan bəri geri qaytarılmamış olmalıdır.
isRootValid(bytes32) istifadə edin — seçici 0x30ef41b4. O, ABI kodlaşdırmasında tək bir məntiqi dəyər qaytarır: bu addıma lazım olan yalnız budur və onu təhlil etmək (bool, uint32) cütündən (verifyRootValidity qaytardığı dəyər) daha sadədir.
| Çağırış | Seçici | Qaytarır |
|---|---|---|
isRootValid(bytes32) | 0x30ef41b4 | bool — qəbul edilib və o vaxtdan bəri geri qaytarılmayıbmı |
currentRoot() | 0xfdab463d | bytes32 — qəbul edilmiş son kök |
verifyRootValidity(bytes32) | 0xc7179944 | (bool isValid, uint32 blockHeight) |
currentBlockHeight() | 0x367bf2f9 | uint32 — son kökün PIVX hündürlüyü |
programVkey() | 0x09665ee7 | bytes32 — müqavilənin tələb etdiyi sxem |
Nümunələr müqaviləni indeksləyicilər kimi ən son yekunlaşmış (finalized) blokda oxuyur: hələ yekun olmayan blokda qəbul edilmiş kök zəncirin yenidən təşkili zamanı hələ yox ola bilər və ona əsasən edilən ödənişin heç bir dayağı qalmaz. Nümunələr əvvəlcə bu blokun nömrəsini soruşur, sonra həmin nömrədə oxuyur, çünki bəzi ictimai BSC son nöqtələri finalized teqini eth_call daxilində rədd edir. currentRoot() və 3-cü addımdakı çağırışları da eyni nömrədə oxuyun ki, bütün cavablar eyni bloku təsvir etsin.
- 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);
Cavabın şərhi
isRootValid | Mənası | Nə etməli |
|---|---|---|
true və kök currentRoot() ilə eynidir | indeksləyici tam sinxronlaşıb | qəbul edin |
true, lakin kök currentRoot() dəyərindən köhnədir | indeksləyici zəncirdən geri qalır | hələ vəsait göndərməyin — gözləyin və ya başqa indeksləyiciyə müraciət edin, sonra yenidən yoxlayın |
false | bu kök zəncir üzərində heç vaxt qəbul edilməyib və ya geri qaytarılıb | həlli rədd edin |
Daha köhnə etibarlı kök reyestrin real keçmiş vəziyyətidir, lakin cari vəziyyəti deyil. O vaxtdan
bəri ad başqasına ötürülmüş, satılmış və ya yeni ünvana yönləndirilmiş ola bilər, köhnə kökə qarşı
sübut isə hələ də əvvəlki cavabı göstərir. Yavaş indeksləyici ilə son yeniləməni gizlədən
indeksləyici burada eyni görünür, ona görə də ödənişdən əvvəl kökün currentRoot() ilə eyni
olmasını tələb edin. Dürüst indeksləyici hər yeni paketdən qısa müddət sonra zəncirə çatır. Qeydi
məlumat üçün, köhnəlmiş ola biləcəyi qeyd edilərək göstərmək olar.
false cavabı o deməkdir ki, tutuşdurduğunuz ağac protokol baxımından reyestrin tarixçəsinə aid
deyil: ya heç vaxt qəbul edilməyib, ya da geri qaytarma zamanı ondan imtina edilib. Məhz bu hal
təcavüzkarın nəzarətindəki indeksləyicinin yaratdığı vəziyyətdir və bu addım məhz bunun üçündür.
3-cü addım — epoxanı yoxlayın
1-ci və 2-ci addımlar qeydin müqavilənin qəbul etdiyi ağacda olduğunu sübut edir. İki şey heç bir yeni paket olmadan bunun nəyi sübut etdiyini dəyişə bilər: qaydaların dəyişdirilməsi — yeni sxem və ya doğrulayıcı, deməli, nəyin sübut olunmuş sayıldığının yeni tərifi — və geri qaytarma: o, köhnə kökü yenidən cari edir və beləliklə o vaxtdan dəyişmiş hər adı sahibinin imzası olmadan yönləndirir. Müqavilə hər ikisini epoch ilə sayır:
- Sayğac 1-dən başlayır və hər qayda dəyişikliyində və hər geri qaytarmada bir vahid artır. Heç vaxt azalmır: dəyişiklik və onun ləğvi iki epoxadır, birinciyə qayıdış deyil.
- Qayda dəyişikliyi əvvəlcədən elan olunur. Sahibin təsdiqi yerləşdirmə zamanı müəyyən edilmiş zaman kilidini (
rulesTimelock, 7 ilə 90 gün arası) işə salır və dəyişiklik yalnızrulesChangeActivatesAt()göstərdiyi vaxta çatdıqdan sonra aktivləşdirilə bilər. - Geri qaytarma yalnız müqavilənin əvvəllər qəbul etdiyi kökü hədəf ala bilər və yalnız paketlərin göndərilməsi dayandırılmış olarkən. Hədəfdən yuxarıdakı bütün köklər dərhal etibarsız olur və bundan sonra 2-ci addım onların hər biri üçün
falseqaytarır.
Ona görə yoxladığınız epoxanı sabitləyin və başqa istənilən epoxa altında adları həll etməkdən imtina edin. Onu köklə birlikdə, bir çağırışla oxuyun ki, hər ikisi eyni blokdan gəlsin:
| Çağırış | Seçici | Qaytarır |
|---|---|---|
anchoredState() | 0x8d39310a | (bytes32 root, uint32 blockHeight, uint32 currentEpoch) |
epoch() | 0x900cf0cf | uint32 — qüvvədə olan epoxa |
rulesChangeActivatesAt() | 0x90b86556 | uint64 — planlaşdırılmış qayda dəyişikliyinin nə vaxt aktivləşdirilə biləcəyi; heç biri planlaşdırılmayıbsa 0 |
anchoredState() bu ardıcıllıqla üç 32 baytlıq söz qaytarır: kök, blok hündürlüyü və epoxa. Epoxa üçüncü sözdəki tam ədəddir.
Aşağıdakı nümunələr bu addımı 2-ci addımın nümunələrinə əlavə edir və onların funksiyalarından
istifadə edir. Bir yekunlaşmış blokda anchoredState() oxuyur, sabitlədiyiniz epoxadan fərqli
epoxanı rədd edir, sonra isə kökü 2-ci addımdakı cədvəl kimi təsnif edir: cari kök üçün
accept, daha köhnə etibarlı kök üçün lagging, müqavilənin qəbul etmədiyi kök üçün 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);
| Epoxa | Nə etməli |
|---|---|
| sabitlədiyiniz epoxaya bərabərdir | davam edin — 1-ci və 2-ci addımlar sizin yoxladığınız qaydalar altında qüvvədədir |
| sabitlədiyiniz epoxadan böyükdür | adların həllini dayandırın. EpochAdvanced, RulesChanged və RootRolledBack hadisələri nə baş verdiyini göstərir; onu yoxlayın, sonra sabitlədiyiniz epoxanı yeniləyin |
İndeksləyicilər eyni qaydanı özlərinə də tətbiq edir: zəncirdəki epoxa operatorun yoxladığını keçəndə qovşaq zənciri izləməyi dayandırır və bu yoxlanmış epoxanı İndeksləyici haqqında məlumat səhifəsində anchored_epoch kimi bildirir. Bu, qovşağın təqdim etdiyi kökün epoxası deyil, onun ayarıdır: planlaşdırılmış qayda dəyişikliyindən əvvəl yenilənmiş qovşaq dəyişiklik zaman kilidini gözlədiyi müddətdə artıq gələcək epoxanı bildirir və o vaxta qədər qüvvədə olan epoxa altında yaradılmış vəziyyəti təqdim edir. Ona görə nəticəni anchored_epoch-a görə deyil, yuxarıdakı kimi köklə birlikdə müqavilədən oxunan epoxaya görə qiymətləndirin; qovşağın kökünün aktual olub-olmadığını 2-ci addım göstərir.
Sxemin özünün yoxlanması
Yuxarıdakı addımlar qeydin müqavilənin qəbul etdiyi kökə aid olduğunu sübut edir. Müqavilə isə kökü yalnız yanında etibarlı ZK sübutu varsa qəbul edir — və həmin sübut konkret kompilyasiya edilmiş sxemə verilmiş 32 baytlıq öhdəlik olan programVkey qarşısında yoxlanılır.
Bu açarın dərc olunmuş mənbə koduna uyğun gəldiyini təsdiqləyə bilərsiniz. Sxemi açarın asılı olduğu alətlər zəncirini və yığma yollarını sabitləyən SP1 Docker obrazında kompilyasiya edin və onun açarını çap edin:
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
Alınan doğrulama açarını lövbər müqaviləsindəki programVkey() (seçici 0x09665ee7) dəyəri ilə
müqayisə edin. Onlar üst-üstə düşürsə, müqavilə məhz həmin mənbə kodunu tələb edir. Sxemin bir
sətrini dəyişmək başqa açar verir, ona görə dəyişdirilmiş sxemi dəyişiklik zəncirdə görünmədən
əvəzləmək mümkün deyil.
Səssizcə qüvvəyə minə də bilməz: yeni açar 3-cü addımda təsvir olunan zaman kilidli qayda dəyişikliyindən keçir və epoxanı artırır.
Prover-in README faylında hər buraxılışın açarı və onun yığıldığı commit sadalanır.
Əlavə xüsusiyyətlər olmadan kompilyasiya edin
Xüsusiyyət bayraqları olmadan kompilyasiya yerləşdirilmiş müqavilənin tələb etdiyi mainnet sxemini verir. İstənilən xüsusiyyət bayrağı kompilyasiya edilmiş proqramı, deməli onun doğrulama açarını dəyişir və bu açar artıq uyğun gəlməyəcək. Docker-dən kənar və ya başqa obraz teqi ilə kompilyasiya da fərqli açar verə bilər.
SP1 sübutunun birbaşa yoxlanması
Sübutlar standart SP1 Groth16 sübutlarıdır və SP1 SDK ilə yoxlana bilər:
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)?;
İctimai dəyərlər (bytes32 old_root, bytes32 new_root, uint32 end_block_height) strukturunun ABI kodlaşdırmasıdır — paketin həyata keçirdiyi vəziyyət
keçidi və onun əhatə etdiyi PIVX blok hündürlüyü.