İspatları doğrulama
Bu sayfa, bir isim çözümlemesini onu sunan indeksleyiciye güvenmeden nasıl doğrulayacağınızı gösterir. Buradaki her kod örneği, yayımlanmadan önce çalışan bir indeksleyiciye karşı çalıştırılır.
Doğrulama size ne kazandırır
Bir çözümleme şu soruyu yanıtlar: "richard.pivx hangi adrese işaret ediyor?" Onu doğrulamak,
yanıtın durum köküne taahhüt edilmiş yanıt olduğunu ve o kökün çıpa sözleşmesinin güncel kökü
olduğunu kanıtlar. Adres uyduran, eskimiş bir kayıt sunan ya da bir ismi gizleyen bir
indeksleyici, bu denetimleri geçen bir ispat üretemez.
Başka bir ismin gerçek kaydıyla yanıt veren bir indeksleyici de üretemez: aşağıdaki denetimler yanıtı sizin sorduğunuz isme bağlar.
Birbirinden bağımsız üç adım vardır ve üçüne de ihtiyacınız olur:
- Merkle ispatı, kaydı bir durum köküne bağlar.
- Zincir üzerindeki denetim, o kökü çıpa sözleşmesine bağlar.
- Dönem denetimi, sözleşmenin kurallarını ve geçmişini sizin incelediklerinize bağlar.
Tek başına 1. adım işe yaramaz: kötü niyetli bir indeksleyici, baştan sona sahte bir ağaç kurup kendi sahte köküyle tutarlı ispatlar sunabilir. Köke anlam kazandıran 2. adımdır; 3. adım ise kurallar değiştiğinde ya da durum geri alındığında bu anlamın korunmasını sağlar.
1. adım — Merkle ispatını doğrulayın
Ağaç
PiNS, 128 bitlik bir anahtar uzayı üzerinde kompakt seyrek Merkle ağacı kullanır. Bir anahtar,
SHA-256(domain_name) değerinin ilk 16 baytıdır. Doğrulayıcı yazarken iki özellik önemlidir:
- İspatlar kısadır ve uzunlukları değişkendir. Bir yaprak, anahtar önekinin benzersiz olduğu
en sığ derinlikte durur; dolayısıyla bir ispat
proof_depthkadar kardeş taşır — genellikle bir avuç, 128 değil. Asla sabit bir uzunluk varsaymayın;proof_depthdeğerini okuyun vemerkle_proof.lengthile eşleştiğini doğrulayın. - Boş bir alt ağaç her yükseklikte 32 sıfır bayttır. Boş düğümler için önceden hesaplanmış hash merdiveni yoktur. Bu yüzden boş bir ağacın kökü tamamen sıfırdır.
Hash fonksiyonları
Yapraklar ve iç düğümler, hash alanları çakışmasın diye etiketlenir. Etiket baytını atlamak, açık ara en yaygın hatadır — makul görünen ama kökle asla eşleşmeyen bir hash üretir.
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 ve target_address, uzunluk öneki olmayan UTF-8 baytlarıdır; owner_pubkey ham 32
bayttır; price ve nonce ise işaretsiz 64 bit little-endian değerlerdir.
Dolaşım
Yapraktan köke doğru ilerleyin. n = proof_depth kardeşle, i adımında hangi tarafta
olduğunuzu belirleyen bit, 0. baytın en anlamlı bitinden sayılarak anahtarın n - 1 - i
numaralı bitidir:
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], en derin seviyedeki, yaprağa en yakın kardeştir.
Terminal
Her ispat, yolun sonunda ne olduğunu anlatan bir proof_terminal taşır:
| Terminal | Anlamı |
|---|---|
Occupied | orada anahtarın kendi yaprağı var — isim mevcut |
Vacant | orada boş bir alt ağaç var — isim kayıtlı değil |
Blocked | orada başka bir ismin yaprağı var — isim kayıtlı değil ve yanıt o ismin tam kaydını içeriyor |
Başarılı bir çözümleme Occupied olmalıdır. Vacant ve Blocked, yokluk ispatlarıdır: bir
indeksleyicinin "bulunamadı" demesine inanmak yerine, bir ismin gerçekten kayıtlı olmadığını
doğrulamanızı sağlarlar. Terminali Occupied olmayan her çözümlemeyi reddedin.
Çözümleme API'si henüz yokluk ispatı döndürmez: tanımadığı bir isim için hiçbir ispat olmadan
Domain not found yanıtı verir. Bu değişene kadar bir "not found" yanıtını doğrulanmamış sayın
ve ikinci bir indeksleyiciyle denetleyin.
Kod
Doğrulayıcı, yanıtın yanı sıra sizin sorduğunuz ismi de alır ve yanıtın taşıdığı domain_name değerini değil, her zaman bu ismi hash'ler. Aksi halde bir indeksleyici, sorunsuzca doğrulanan başka bir ismin gerçek kaydı ve ispatıyla yanıt verebilir ve siz o ismin sahibine ödeme yaparsınız. Ayrıca hiçbir şeyi hash'lemeden önce biçimi yanlış alanları reddeder: yaprakta uzunluk önekleri yoktur, bu yüzden yanlış uzunlukta bir alan baytları komşu alana kaydırır.
- 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'te JSON.parse, 2^53'ten büyük tam sayıları kesin olmayan biçimde okur; bu yüzden örnek, başka bir sayıyı hash'lemek yerine bu kadar büyük bir price veya nonce değerini (yaklaşık 90 milyon PIVX'in üzerindeki bir fiyatı) reddeder. Böyle bir kaydı doğrulamak için yanıtı her iki değer de kesin kalacak şekilde ayrıştırın (Node.js 21 veya daha yenisi, güncel tarayıcılar):
const body = JSON.parse(text, (key, value, context) =>
(key === "price" || key === "nonce") && typeof value === "number"
? BigInt(context.source)
: value);
Uygulamanızı kurcalamaya karşı test edin
Her zaman true döndüren bir doğrulayıcı, tüm olumlu testleri geçer. Kendi doğrulayıcınıza
güvenmeden önce, gerçek bir yanıttaki target_address, owner_pubkey veya price alanının bir
baytını değiştirin ve artık false döndürdüğünü doğrulayın. Yukarıdaki üç örnek de bu yöntemle
denetlenmiştir.
Ardından bir ismi sorarken başka bir ismin gerçek yanıtını verin: doğrulayıcı bunu reddetmelidir. Örnekler bu yöntemle de denetlenmiştir.
2. adım — kökü çıpa sözleşmesiyle karşılaştırın
Doğrulanmış bir Merkle ispatı yalnızca "bu kayıt bir ağaçta" der. Gerçek ağaçta olduğunu bilmek için, BNB Smart Chain üzerindeki çıpa sözleşmesine o kökün geçerli olup olmadığını sorun: zincir üzerinde kabul edilmiş ve o zamandan beri geri alınmamış olmalı.
isRootValid(bytes32) kullanın — seçici 0x30ef41b4. ABI kodlu tek bir boole değeri döndürür: bu adımın ihtiyacı yalnızca budur ve (bool, uint32) çiftini (verifyRootValidity dönüş değeri) ayrıştırmaktan daha kolaydır.
| Çağrı | Seçici | Döndürdüğü |
|---|---|---|
isRootValid(bytes32) | 0x30ef41b4 | bool — kabul edilmiş ve o zamandan beri geri alınmamış mı |
currentRoot() | 0xfdab463d | bytes32 — kabul edilen en son kök |
verifyRootValidity(bytes32) | 0xc7179944 | (bool isValid, uint32 blockHeight) |
currentBlockHeight() | 0x367bf2f9 | uint32 — en son kökün PIVX yüksekliği |
programVkey() | 0x09665ee7 | bytes32 — sözleşmenin dayattığı devre |
Örnekler, sözleşmeyi indeksleyicilerin yaptığı gibi en yeni kesinleşmiş (finalized) blokta okur: henüz kesinleşmemiş bir blokta kabul edilen bir kök, zincirin yeniden düzenlenmesiyle hâlâ kaybolabilir ve ona dayanarak yapılan bir ödemenin hiçbir dayanağı kalmaz. Örnekler önce bu bloğun numarasını sorar, sonra o numarada okur; çünkü bazı herkese açık BSC uç noktaları finalized etiketini eth_call içinde reddeder. currentRoot() ve 3. adımdaki çağrıları da aynı numarada okuyun; böylece her yanıt aynı bloğu anlatır.
- 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);
Yanıtı yorumlama
isRootValid | Anlamı | Ne yapmalı |
|---|---|---|
true ve kök currentRoot() ile aynı | indeksleyici tümüyle senkronize | kabul edin |
true ama kök currentRoot() değerinden eski | indeksleyici zincirin gerisinde | henüz ödeme göndermeyin — bekleyin ya da başka bir indeksleyiciye sorun, sonra yeniden doğrulayın |
false | bu kök zincir üzerinde hiç kabul edilmedi ya da geri alındı | çözümlemeyi reddedin |
Daha eski ama geçerli bir kök, kütüğün gerçek bir geçmiş durumudur, ancak güncel durumu değildir.
O zamandan beri isim devredilmiş, satılmış ya da yeni bir adrese yönlendirilmiş olabilir ve eski
köke karşı bir ispat hâlâ önceki yanıtı gösterir. Yavaş bir indeksleyici ile yakın tarihli bir
güncellemeyi saklayan bir indeksleyici burada tıpatıp aynı görünür; bu yüzden ödeme yapmadan önce
kökün currentRoot() ile aynı olmasını şart koşun. Dürüst bir indeksleyici her yeni toplu işten
kısa süre sonra yetişir. Kaydı bilgi amacıyla, güncel olmayabileceği belirtilerek göstermekte
sakınca yoktur.
false yanıtı, karşılaştırdığınız ağacın protokol açısından kütüğün geçmişine ait olmadığı
anlamına gelir: ya hiç kabul edilmedi ya da bir geri alma işlemi onu geçersiz kıldı. Bu, tam da
saldırganın denetimindeki bir indeksleyicinin ürettiği durumdur ve bu adım tam olarak bunun
içindir.
3. adım — dönemi denetleyin
Birinci ve ikinci adımlar, bir kaydın sözleşmenin kabul ettiği bir ağaçta olduğunu ispatlar. İki şey, hiçbir yeni toplu iş olmadan bunun neyi ispatladığını değiştirebilir: bir kural değişikliği — yeni bir devre ya da doğrulayıcı, dolayısıyla neyin ispatlanmış sayıldığına dair yeni bir tanım — ve eski bir kökü yeniden geçerli kılarak o zamandan beri değişen her ismi sahibinin imzası olmadan yeniden yönlendiren bir geri alma. Sözleşme ikisini de epoch ile sayar:
- Sayaç 1'den başlar ve her kural değişikliğinde ve her geri almada bir artar. Asla azalmaz: bir değişiklik ve onun geri çevrilmesi iki dönemdir, ilkine dönüş değildir.
- Kural değişikliği önceden duyurulur. Sahibin onayı, dağıtım sırasında sabitlenen bir zaman kilidini (
rulesTimelock, 7 ile 90 gün arası) başlatır ve değişiklik ancakrulesChangeActivatesAt()içindeki zamana ulaşıldığında etkinleştirilebilir. - Geri alma yalnızca sözleşmenin daha önce kabul ettiği bir kökü hedefleyebilir ve yalnızca toplu iş gönderimi duraklatılmışken yapılabilir. Hedefin üstündeki her kök anında geçerliliğini yitirir ve o andan itibaren 2. adım her biri için
falsedöndürür.
Bu yüzden incelediğiniz dönemi sabitleyin ve başka herhangi bir dönem altında çözümleme yapmayı reddedin. Her ikisi de aynı bloktan gelsin diye onu kökle birlikte, tek bir çağrıda okuyun:
| Çağrı | Seçici | Döndürdüğü |
|---|---|---|
anchoredState() | 0x8d39310a | (bytes32 root, uint32 blockHeight, uint32 currentEpoch) |
epoch() | 0x900cf0cf | uint32 — yürürlükteki dönem |
rulesChangeActivatesAt() | 0x90b86556 | uint64 — planlanmış bir kural değişikliğinin ne zaman etkinleştirilebileceği; planlanmış değişiklik yoksa 0 |
anchoredState() şu sırayla üç adet 32 baytlık sözcük döndürür: kök, blok yüksekliği ve dönem. Dönem, üçüncü sözcükteki tamsayıdır.
Aşağıdaki örnekler bu adımı 2. adımın örneklerine ekler ve onların işlevlerini yeniden
kullanır. Tek bir kesinleşmiş blokta anchoredState() değerini okur, sabitlediğiniz dönemden
başka bir dönemi reddeder ve ardından kökü 2. adımdaki tablo gibi sınıflandırır: güncel kök
için accept, daha eski geçerli bir kök için lagging, sözleşmenin kabul etmediği bir kök
için 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);
| Dönem | Ne yapmalı |
|---|---|
| sabitlediğiniz döneme eşit | devam edin — 1. ve 2. adımlar incelediğiniz kurallar altında geçerlidir |
| sabitlediğiniz dönemden büyük | çözümlemeyi durdurun. EpochAdvanced, RulesChanged ve RootRolledBack olayları ne olduğunu söyler; inceleyin, ardından sabitlediğiniz dönemi güncelleyin |
İndeksleyiciler aynı kuralı kendilerine de uygular: zincir üzerindeki dönem operatörünün incelediği dönemi geçtiğinde düğüm zinciri izlemeyi bırakır ve incelenmiş bu dönemi İndeksleyici bilgisi içinde anchored_epoch olarak bildirir. Bu, düğümün sunduğu kökün dönemi değil, düğümün ayarıdır: planlanmış bir kural değişikliğinden önce güncellenen bir düğüm, değişiklik zaman kilidini beklerken gelecek dönemi şimdiden bildirir ve o zamana kadar yürürlükteki dönem altında oluşmuş durumu sunar. Bu yüzden bir çözümlemeyi anchored_epoch alanına göre değil, yukarıdaki gibi kökle birlikte sözleşmeden okunan döneme göre değerlendirin; düğümün kökünün güncel olup olmadığını 2. adım gösterir.
Devrenin kendisini doğrulamak
Yukarıdaki adımlar, bir kaydın sözleşmenin kabul ettiği bir köke ait olduğunu ispatlar. Sözleşme ise bir kökü ancak yanında geçerli bir ZK ispatı varsa kabul eder — ve o ispat, tam olarak derlenmiş devreye yapılmış 32 baytlık bir taahhüt olan programVkey karşısında denetlenir.
Bu anahtarın yayımlanmış kaynak koda karşılık geldiğini doğrulayabilirsiniz. Devreyi, anahtarın bağlı olduğu araç zincirini ve derleme yollarını sabitleyen SP1 Docker imajında derleyin ve anahtarını yazdırın:
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
Elde ettiğiniz doğrulama anahtarını, çıpa sözleşmesindeki programVkey() (seçici 0x09665ee7)
değeriyle karşılaştırın. Eşleşiyorlarsa sözleşme tam olarak o kaynak kodu dayatıyordur. Devrenin
tek bir satırını değiştirmek farklı bir anahtar üretir; dolayısıyla değiştirilmiş bir devre,
değişiklik zincir üzerinde görünmeden yerine konulamaz.
Sessizce yürürlüğe de giremez: yeni bir anahtar, 3. adımda anlatılan zaman kilitli kural değişikliğinden geçer ve dönemi ilerletir.
Prover'ın README dosyası her sürümün anahtarını ve derlendiği commit'i listeler.
Ek özellik olmadan derleyin
Özellik bayrağı olmadan yapılan bir derleme, yayımlanmış sözleşmenin dayattığı mainnet devresini üretir. Herhangi bir özellik bayrağı derlenen programı, dolayısıyla doğrulama anahtarını değiştirir ve bu anahtar artık eşleşmez. Docker dışında ya da başka bir imaj etiketiyle yapılan bir derleme de farklı bir anahtar verebilir.
Bir SP1 ispatını doğrudan doğrulamak
İspatlar standart SP1 Groth16 ispatlarıdır ve SP1 SDK ile denetlenebilir:
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)?;
Açık değerler (bytes32 old_root, bytes32 new_root, uint32 end_block_height) yapısının ABI kodlamasıdır — toplu işin gerçekleştirdiği durum geçişi
ve kapsadığı PIVX blok yüksekliği.