Files
SHiNE-server/shine-UI/js/services/core-content.js
T

160 lines
11 KiB
JavaScript

// CORE v2 / CONTENT v1. Uses the existing ANS-104 signer; no new key store or transport.
import { base64ToBytes, bytesToBase64Url } from './crypto-utils.js';
import { createAns104DataItem, parseAns104DataItem, verifyAns104DataItem, serializeAns104Tags } from './ans104-data-item.js';
import { SHINE_CORE_NAMESPACE, SHINE_CORE_MAX_BLOCK_NUMBER, SHINE_CORE_LINE_PROFILE,
SHINE_CORE_LINE_CONNECTION, SHINE_CORE_LINE_TECH } from './protocol-tags.js';
export const CORE_MAX_ITEM_BYTES = 8 * 1024 * 1024;
export const CORE_MAX_CONTENT_BYTES = CORE_MAX_ITEM_BYTES - 117;
const zero = new Uint8Array(32);
const channelTypes = new Set([10, 11, 50, 90, 92, 100, 110, 120, 130]);
const equal = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
export const coreHex = bytes => Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
export function coreHashBytes(hex) {
if (typeof hex !== 'string' || !/^[0-9a-f]{64}$/i.test(hex)) throw new Error('Invalid CORE hash');
return Uint8Array.from(hex.match(/../g), b => parseInt(b, 16));
}
function bytes32(bytes) {
if (!(bytes instanceof Uint8Array) || bytes.length !== 32) throw new Error('Expected 32 bytes');
return bytes;
}
function integer(value, max) {
if (!Number.isInteger(value) || value < 0 || value > max) throw new Error('Integer out of range');
return value;
}
function timestamp64(value) {
if (typeof value === 'number' && !Number.isSafeInteger(value)) throw new Error('Invalid timestamp');
if (typeof value !== 'number' && typeof value !== 'bigint') throw new Error('Invalid timestamp');
const n = BigInt(value);
if (n < 0n || n > 0x7fffffffffffffffn) throw new Error('Invalid timestamp');
return n;
}
const view = b => new DataView(b.buffer, b.byteOffset, b.byteLength);
const sha256 = async b => new Uint8Array(await crypto.subtle.digest('SHA-256', b));
export function encodeContent({ type, subType, version, body }) {
if (!(body instanceof Uint8Array) || body.length > CORE_MAX_CONTENT_BYTES - 7) throw new Error('Invalid CONTENT body length');
const out = new Uint8Array(7 + body.length), v = view(out);
out[0] = 1;
v.setUint16(1, integer(type, 65535)); v.setUint16(3, integer(subType, 65535)); v.setUint16(5, integer(version, 65535));
out.set(body, 7);
return out;
}
export function decodeContent(bytes) {
if (!(bytes instanceof Uint8Array) || bytes.length < 7 || bytes.length > CORE_MAX_CONTENT_BYTES || bytes[0] !== 1) throw new Error('Invalid CONTENT');
const v = view(bytes);
return { type: v.getUint16(1), subType: v.getUint16(3), version: v.getUint16(5), body: bytes.slice(7) };
}
export function encodeCore({ prevCoreHash32, blockNumber, timestamp, contentHash32, contentDataItemId32, line = null }) {
integer(blockNumber, SHINE_CORE_MAX_BLOCK_NUMBER);
bytes32(prevCoreHash32); bytes32(contentHash32); bytes32(contentDataItemId32);
if (blockNumber === 0 && (line !== null || !equal(prevCoreHash32, zero))) throw new Error('Invalid genesis CORE');
const out = new Uint8Array(line === null ? 109 : 149), v = view(out);
out[0] = 1; out.set(prevCoreHash32, 1); v.setInt32(33, blockNumber);
v.setBigInt64(37, timestamp64(timestamp)); out.set(contentHash32, 45); out.set(contentDataItemId32, 77);
if (line !== null) {
const code = integer(line.lineCode, 2147483647), prev = integer(line.prevLineBlockNumber, SHINE_CORE_MAX_BLOCK_NUMBER);
if (prev >= blockNumber || (code > 0 && code <= SHINE_CORE_MAX_BLOCK_NUMBER && (code >= blockNumber || prev < code))) throw new Error('Invalid CORE line predecessor');
v.setInt32(109, code); v.setInt32(113, prev); out.set(bytes32(line.prevLineCoreHash32), 117);
}
return out;
}
export function decodeCore(bytes) {
if (!(bytes instanceof Uint8Array) || ![109, 149].includes(bytes.length) || bytes[0] !== 1) throw new Error('Invalid CORE');
const v = view(bytes);
const result = { prevCoreHash32: bytes.slice(1, 33), blockNumber: v.getInt32(33), timestamp: v.getBigInt64(37),
contentHash32: bytes.slice(45, 77), contentDataItemId32: bytes.slice(77, 109),
line: bytes.length === 109 ? null : { lineCode: v.getInt32(109), prevLineBlockNumber: v.getInt32(113), prevLineCoreHash32: bytes.slice(117, 149) } };
encodeCore(result); // identical structural validation on read and write
return result;
}
export function coreTags(core) {
const tags = [{ name: 'App', value: SHINE_CORE_NAMESPACE }, { name: 'n', value: String(core.blockNumber) }];
if (core.line) {
const code = core.line.lineCode;
const special = { [SHINE_CORE_LINE_PROFILE]: 'P', [SHINE_CORE_LINE_CONNECTION]: 'C', [SHINE_CORE_LINE_TECH]: 'T' };
if (code > SHINE_CORE_MAX_BLOCK_NUMBER && !special[code]) throw new Error('Reserved CORE line');
tags.push({ name: 'l', value: special[code] ?? String(code) });
}
return tags;
}
function checkEventLine(content, core) {
const { type, subType, version } = content;
if (version !== 1) throw new Error('Unsupported CONTENT version for creation');
const header = type === 0 && subType === 0;
if (header !== (core.blockNumber === 0)) throw new Error('HEADER must be CORE #0');
const code = core.line?.lineCode;
if (type === 0 && !header) { if (code !== SHINE_CORE_LINE_TECH) throw new Error('Wrong TECH line'); }
else if (type === 3) { if (code !== SHINE_CORE_LINE_CONNECTION) throw new Error('Wrong CONNECTION line'); }
else if (type === 4) { if (code !== SHINE_CORE_LINE_PROFILE) throw new Error('Wrong PROFILE line'); }
else if (type === 1 && channelTypes.has(subType)) { integer(code, SHINE_CORE_MAX_BLOCK_NUMBER); }
else if (core.line !== null) throw new Error('Unexpected CORE line');
}
/** Temporary boundary for existing in-memory body factories. No Frame is constructed or signed. */
export function splitEventBody({ msgType, msgSubType, msgVersion = 1, bodyBytes }) {
if (!(bodyBytes instanceof Uint8Array)) throw new Error('Invalid event body');
const fixed = msgType === 3 || msgType === 4;
const tech = msgType === 0 && msgSubType === 1;
const channel = msgType === 1 && channelTypes.has(msgSubType);
if (msgType === 0 && ![0, 1].includes(msgSubType)) throw new Error('Use the dedicated CORE FORK path for rotation');
const prefix = fixed ? 40 : tech || channel ? 44 : 0;
if (bodyBytes.length < prefix) throw new Error('Truncated event line prefix');
let line = null;
if (prefix) {
const v = view(bodyBytes), offset = fixed ? 0 : 4;
if (tech && v.getInt32(0) !== 0) throw new Error('Invalid old TECH selector');
const code = msgType === 3 ? SHINE_CORE_LINE_CONNECTION : msgType === 4 ? SHINE_CORE_LINE_PROFILE : tech ? SHINE_CORE_LINE_TECH : v.getInt32(0);
line = { lineCode: code, prevLineBlockNumber: v.getInt32(offset), prevLineCoreHash32: bodyBytes.slice(offset + 4, offset + 36) };
}
return { content: { type: msgType, subType: msgSubType, version: msgVersion, body: bodyBytes.slice(prefix) }, line };
}
export async function signCoreContentPair({ owner32, privateKey, content, prevCoreHash32, blockNumber, timestamp, line = null }) {
bytes32(owner32);
checkEventLine(content, { blockNumber, line });
const contentBytes = encodeContent(content);
const contentDataItem = await createAns104DataItem({ owner32, privateKey, data: contentBytes, tags: [] });
if (contentDataItem.length > CORE_MAX_ITEM_BYTES) throw new Error('CONTENT ANS-104 too large');
const contentHash32 = await sha256(contentBytes);
const contentDataItemId32 = await sha256(parseAns104DataItem(contentDataItem).signature);
const core = { prevCoreHash32, blockNumber, timestamp, contentHash32, contentDataItemId32, line };
const coreBytes = encodeCore(core);
const coreDataItem = await createAns104DataItem({ owner32, privateKey, data: coreBytes, tags: coreTags(core) });
return { coreBytes, contentBytes, coreDataItem, contentDataItem, coreHash32: await sha256(coreBytes), contentHash32, contentDataItemId32 };
}
/** Verifies signed pair and owner binding, not history, semantics or authorization of the owner. */
export async function verifyCoreContentPair(coreItem, contentItem, expectedOwner32) {
bytes32(expectedOwner32);
for (const item of [coreItem, contentItem]) if (!(item instanceof Uint8Array) || item.length > CORE_MAX_ITEM_BYTES) throw new Error('Invalid ANS-104 size');
const [c, p] = await Promise.all([verifyAns104DataItem(coreItem), verifyAns104DataItem(contentItem)]);
if (!c.signatureValid || !p.signatureValid || !equal(c.owner32, expectedOwner32) || !equal(p.owner32, expectedOwner32)) throw new Error('Invalid pair signature or owner');
const core = decodeCore(c.data), content = decodeContent(p.data);
// This is the canonical encoding produced by the UI. General Arweave import validation is D.
if (c.target.length || c.anchor.length || p.target.length || p.anchor.length || c.tagsCount !== coreTags(core).length || p.tagsCount !== 0 || !equal(c.rawTags, serializeAns104Tags(coreTags(core))) || !equal(p.rawTags, serializeAns104Tags([]))) throw new Error('Invalid pair tags');
if (!equal(core.contentHash32, p.frameHashBytes) || !equal(core.contentDataItemId32, p.dataItemIdBytes)) throw new Error('CONTENT does not match CORE');
return { core, content, coreHash32: c.frameHashBytes, coreDataItemId32: c.dataItemIdBytes };
}
// Read the exact signed objects returned by the current WS API. A valid signature
// does not by itself establish the signer's authorization or canonical ancestry.
export async function readCoreBlock(row, { requireContent = false } = {}) {
const decodeItem = value => {
if (typeof value !== 'string' || !value || value.length > Math.ceil(CORE_MAX_ITEM_BYTES * 4 / 3) + 8) throw new Error('Invalid CORE/CONTENT DataItem size');
const raw = base64ToBytes(value);
if (!raw.length || raw.length > CORE_MAX_ITEM_BYTES) throw new Error('Invalid CORE/CONTENT DataItem size');
return raw;
};
const bytes = decodeItem(row?.coreDataItemB64);
const proof = await verifyAns104DataItem(bytes);
const core = decodeCore(proof.data);
const hash = coreHex(proof.frameHashBytes), actualId = bytesToBase64Url(proof.dataItemIdBytes);
const contentId = bytesToBase64Url(core.contentDataItemId32);
if (!proof.signatureValid || proof.target.length || proof.anchor.length || proof.tagsCount !== coreTags(core).length || !equal(proof.rawTags, serializeAns104Tags(coreTags(core)))) throw new Error('Invalid CORE signature or tags');
if (row.blockNumber !== core.blockNumber || row.coreHash !== hash || (row.blockHash != null && row.blockHash !== hash) || row.coreDataItemId !== actualId || row.contentHash !== coreHex(core.contentHash32) || row.contentDataItemId !== contentId) throw new Error('CORE response metadata mismatch');
let content = null, contentBytes = null, contentProof = null;
if (row.contentDataItemB64) {
contentBytes = decodeItem(row.contentDataItemB64);
({ content } = await verifyCoreContentPair(bytes, contentBytes, proof.owner32));
contentProof = { actualId: contentId, data: parseAns104DataItem(contentBytes).data, bytes: contentBytes };
} else if (requireContent) throw new Error('CONTENT unavailable');
return { ...proof, bytes, actualId, core, content, contentProof, coreHash: hash, contentStatus: row.contentStatus };
}