SHA256
200 lines
13 KiB
JavaScript
200 lines
13 KiB
JavaScript
// CORE v2 / CONTENT v1. Uses the existing ANS-104 signer; no new key store or transport.
|
|
import { bytesToBase64, base64ToBytes } 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 };
|
|
}
|
|
|
|
// Внутренний контейнер совпадает с Java; проверка подписей выполняется отдельно.
|
|
export const CORE_MAX_CORE_ITEM_BYTES = 65865;
|
|
export const CORE_MAX_CONTAINER_BYTES = 4 + CORE_MAX_CORE_ITEM_BYTES + CORE_MAX_ITEM_BYTES;
|
|
function checkContainerLengths(core, content) {
|
|
if (core < 116 || core > CORE_MAX_CORE_ITEM_BYTES || content < 116 || content > CORE_MAX_ITEM_BYTES) throw new Error('Invalid CORE/CONTENT container lengths');
|
|
}
|
|
export function packCoreContent(coreDataItem, contentDataItem) {
|
|
if (!(coreDataItem instanceof Uint8Array) || !(contentDataItem instanceof Uint8Array)) throw new Error('Invalid DataItem bytes');
|
|
checkContainerLengths(coreDataItem.length, contentDataItem.length);
|
|
const out = new Uint8Array(4 + coreDataItem.length + contentDataItem.length);
|
|
view(out).setUint32(0, coreDataItem.length);
|
|
out.set(coreDataItem, 4); out.set(contentDataItem, 4 + coreDataItem.length);
|
|
return out;
|
|
}
|
|
export function unpackCoreContent(bytes) {
|
|
if (!(bytes instanceof Uint8Array) || bytes.length < 236 || bytes.length > CORE_MAX_CONTAINER_BYTES) throw new Error('Invalid CORE/CONTENT container');
|
|
const n = view(bytes).getUint32(0);
|
|
checkContainerLengths(n, bytes.length - 4 - n);
|
|
return { coreDataItem: bytes.slice(4, 4 + n), contentDataItem: bytes.slice(4 + n) };
|
|
}
|
|
|
|
/** Adapter from existing semantic body factories to the wire format. */
|
|
export async function signEventContainer({ owner32, privateKey, blockNumber, prevBlockHash, timestamp, ...event }) {
|
|
const { content, line } = splitEventBody(event);
|
|
const pair = await signCoreContentPair({ owner32, privateKey, blockNumber, prevCoreHash32: coreHashBytes(prevBlockHash), timestamp, content, line });
|
|
return { bytes: packCoreContent(pair.coreDataItem, pair.contentDataItem), hash: coreHex(pair.coreHash32) };
|
|
}
|
|
|
|
/** Server ordinal is an index, not a signed part of CORE. */
|
|
export function readStoredLineMeta(bytes, ordinal) {
|
|
const { coreDataItem } = unpackCoreContent(bytes);
|
|
const { line } = decodeCore(parseAns104DataItem(coreDataItem).data);
|
|
if (!line || !Number.isInteger(ordinal) || ordinal < 0) throw new Error('Missing line or server line ordinal');
|
|
return { lineCode: line.lineCode > SHINE_CORE_MAX_BLOCK_NUMBER ? 0 : line.lineCode,
|
|
prevLineNumber: line.prevLineBlockNumber, prevLineHashHex: coreHex(line.prevLineCoreHash32), lineSequence: ordinal };
|
|
}
|
|
|
|
/** On transport ambiguity retry exactly the same bytes, never re-sign. On a
|
|
* rejection, recognize an already committed event only by exact canonical bytes. */
|
|
export async function submitSignedEvent(ws, cursor, signed) {
|
|
const payload = { ...cursor, blockBytesB64: bytesToBase64(signed.bytes) };
|
|
let response, uncertain = false;
|
|
try { response = await ws.request('AddBlock', payload); }
|
|
catch { uncertain = true; }
|
|
if (uncertain) {
|
|
try { response = await ws.request('AddBlock', payload); }
|
|
catch { /* canonical read below may still resolve delivery */ }
|
|
}
|
|
if (response?.status === 200) return response;
|
|
const tip = Number(response?.payload?.serverLastGlobalNumber ?? -1);
|
|
if (uncertain || tip >= cursor.blockNumber) {
|
|
let read;
|
|
try { read = await ws.request('GetBlockchainBlock', { blockchainName: cursor.blockchainName, blockNumber: cursor.blockNumber }); }
|
|
catch (error) { throw new Error('AddBlock outcome unknown; canonical read failed', { cause: error }); }
|
|
if (read?.status === 200 && String(read.payload?.blockHash || '').toLowerCase() === signed.hash &&
|
|
equal(base64ToBytes(read.payload?.blockBytesB64 || ''), signed.bytes)) {
|
|
return { status: 200, payload: { serverLastGlobalNumber: cursor.blockNumber, serverLastGlobalHash: signed.hash } };
|
|
}
|
|
if (read?.status !== 200 && (tip >= cursor.blockNumber || read?.status !== 404)) throw new Error('AddBlock outcome unknown; canonical read unavailable');
|
|
}
|
|
// Even if the second request received a rejection, the first may still be in flight.
|
|
if (uncertain) throw new Error('AddBlock outcome unknown; refresh history before retrying');
|
|
return response;
|
|
}
|