SHA256
80 lines
4.8 KiB
JavaScript
80 lines
4.8 KiB
JavaScript
import { verifyAns104DataItem } from './ans104-data-item.js';
|
|
import { base64ToBytes, bytesToBase64Url } from './crypto-utils.js';
|
|
import { readShineUserPda } from './shine-user-pda-service.js';
|
|
|
|
const HASH_RE = /^[0-9a-f]{64}$/iu;
|
|
const DATA_ITEM_ID_RE = /^[A-Za-z0-9_-]{43}$/u;
|
|
const MAX_SIGNED_BYTES = 8 * 1024 * 1024;
|
|
|
|
function hex(bytes) {
|
|
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
}
|
|
function equalBytes(left, right) {
|
|
return left.length === right.length && left.every((byte, index) => byte === right[index]);
|
|
}
|
|
export function arweaveBlockUrl(id) {
|
|
return DATA_ITEM_ID_RE.test(String(id || '')) ? `https://arweave.net/raw/${id}` : '';
|
|
}
|
|
export function signedDataItemFilename(chain, number) {
|
|
const safe = String(chain || 'block').replace(/[^a-z0-9@._-]/giu, '_').slice(0, 100);
|
|
return `SHiNE-${safe}-${Number(number)}.ans104`;
|
|
}
|
|
|
|
/** Получаем полный оригинал по существующему публичному API (не «от Arweave»). */
|
|
export async function readSignedBlock({ authService, blockchainName, blockNumber, blockHash, dataItemId }) {
|
|
const resp = await authService.ws.request('GetBlockchainBlock', { blockchainName, blockNumber });
|
|
if (Number(resp?.status) !== 200) throw new Error('GetBlockchainBlock: блок недоступен');
|
|
const body = resp?.payload || resp;
|
|
if (!HASH_RE.test(String(body?.blockHash || '')) || String(body.blockHash).toLowerCase() !== String(blockHash).toLowerCase()) {
|
|
throw new Error('Сервер вернул другой хеш блока');
|
|
}
|
|
const rawText = String(body?.blockBytesB64 || '');
|
|
if (rawText.length > Math.ceil(MAX_SIGNED_BYTES * 4 / 3) + 8) throw new Error('Размер подписанного блока превышает лимит');
|
|
const bytes = base64ToBytes(rawText);
|
|
if (!bytes.length || bytes.length > MAX_SIGNED_BYTES) throw new Error('Некорректный размер блока');
|
|
const proof = await verifyAns104DataItem(bytes);
|
|
if (!proof.signatureValid) throw new Error('Недействительная подпись ANS-104');
|
|
if (hex(proof.frameHashBytes) !== String(blockHash).toLowerCase()) throw new Error('Хеш содержимого блока не совпал');
|
|
const actualId = bytesToBase64Url(proof.dataItemIdBytes);
|
|
if (dataItemId && actualId !== dataItemId) throw new Error('Идентификатор Arweave отличается от ожидаемого');
|
|
return { bytes, ...proof, actualId };
|
|
}
|
|
|
|
/** Вспомогательная независимая сверка: шлюз возвращает payload, а не ANS-104 оболочку. */
|
|
export async function checkArweavePayload(dataItemId, signedPayload) {
|
|
const url = arweaveBlockUrl(dataItemId);
|
|
if (!url) return { status: 'unavailable', reason: 'Нет идентификатора Arweave' };
|
|
try {
|
|
const response = await fetch(url, { cache: 'no-store', signal: AbortSignal.timeout(15000) });
|
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
const length = Number(response.headers.get('Content-Length') || 0);
|
|
if (length > MAX_SIGNED_BYTES) throw new Error('Слишком большой ответ шлюза');
|
|
const raw = new Uint8Array(await response.arrayBuffer());
|
|
if (raw.length > MAX_SIGNED_BYTES) throw new Error('Слишком большой ответ шлюза');
|
|
return equalBytes(raw, signedPayload)
|
|
? { status: 'valid' }
|
|
: { status: 'invalid', reason: 'Содержимое Arweave не совпадает с подписанным блоком' };
|
|
} catch (error) {
|
|
return { status: 'unavailable', reason: String(error?.message || error) };
|
|
}
|
|
}
|
|
|
|
export async function checkSolanaAuthor({ authorLogin, blockchainName, owner32, solanaEndpoint }) {
|
|
const forkMatch = String(blockchainName || '').match(/-(\d{3})$/u);
|
|
const forkIndex = forkMatch ? Number(forkMatch[1]) - 1 : -1;
|
|
if (forkIndex < 0 || !authorLogin || !solanaEndpoint) {
|
|
return { status: 'unavailable', reason: 'Недостаточно данных для проверки Solana' };
|
|
}
|
|
try {
|
|
const pda = await readShineUserPda({ login: authorLogin, solanaEndpoint });
|
|
const key = pda?.forks?.[forkIndex]?.blockchainKey;
|
|
if (!key) return { status: 'unavailable', reason: 'Исторический ключ форка отсутствует в PDA' };
|
|
return equalBytes(new Uint8Array(key), owner32)
|
|
? { status: 'valid', reason: `Solana PDA, форк ${forkMatch[1]}` }
|
|
: { status: 'invalid', reason: 'Ключ подписанта не совпадает с ключом форка в Solana PDA' };
|
|
} catch (error) {
|
|
// FREE_CERT может не иметь PDA: это не доказательство подделки.
|
|
return { status: 'unavailable', reason: String(error?.message || error) };
|
|
}
|
|
}
|