SHA256
294 lines
12 KiB
JavaScript
294 lines
12 KiB
JavaScript
import { parseAns104DataItem } from './ans104-data-item.js';
|
|
import { base64ToBytes, bytesToBase64Url, sha256Bytes } from './crypto-utils.js';
|
|
|
|
const FRAME_HEADER_SIZE = 88;
|
|
const LINE_PREFIX_SIZE = 44;
|
|
const FIXED_LINE_PREFIX_SIZE = 40;
|
|
const TD = new TextDecoder('utf-8', { fatal: true });
|
|
const ZERO_HASH = '0'.repeat(64);
|
|
|
|
function bytesToHex(bytes) {
|
|
return Array.from(bytes || [], (value) => Number(value).toString(16).padStart(2, '0')).join('');
|
|
}
|
|
|
|
class Reader {
|
|
constructor(bytes, offset = 0) {
|
|
this.bytes = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || []);
|
|
this.offset = Number(offset) || 0;
|
|
this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength);
|
|
}
|
|
|
|
ensure(length, label = 'данные') {
|
|
if (length < 0 || this.offset < 0 || this.offset + length > this.bytes.length) {
|
|
throw new Error(`Блок обрезан: не хватает данных (${label})`);
|
|
}
|
|
}
|
|
|
|
u8(label) { this.ensure(1, label); return this.bytes[this.offset++]; }
|
|
u16(label) { this.ensure(2, label); const value = this.view.getUint16(this.offset, false); this.offset += 2; return value; }
|
|
i32(label) { this.ensure(4, label); const value = this.view.getInt32(this.offset, false); this.offset += 4; return value; }
|
|
i64(label) { this.ensure(8, label); const value = this.view.getBigInt64(this.offset, false); this.offset += 8; return value; }
|
|
raw(length, label) { this.ensure(length, label); const value = this.bytes.slice(this.offset, this.offset + length); this.offset += length; return value; }
|
|
hash32(label) { return bytesToHex(this.raw(32, label)); }
|
|
text(length, label) { return TD.decode(this.raw(length, label)); }
|
|
textU8(label) { return this.text(this.u8(`${label} length`), label); }
|
|
textU16(label) { return this.text(this.u16(`${label} length`), label); }
|
|
remaining() { return this.bytes.length - this.offset; }
|
|
}
|
|
|
|
function parseLinePrefix(reader) {
|
|
return {
|
|
lineCode: reader.i32('lineCode'),
|
|
prevLineNumber: reader.i32('prevLineNumber'),
|
|
prevLineHash: reader.hash32('prevLineHash'),
|
|
lineSequence: reader.i32('lineSequence'),
|
|
};
|
|
}
|
|
|
|
function parseFixedLinePrefix(reader, name) {
|
|
return {
|
|
prevLineNumber: reader.i32(`prev${name}BlockNumber`),
|
|
prevLineHash: reader.hash32(`prev${name}BlockHash`),
|
|
lineSequence: reader.i32(`${name.toLowerCase()}Sequence`),
|
|
};
|
|
}
|
|
|
|
function parseTarget(reader) {
|
|
const login = reader.textU8('toLogin');
|
|
return {
|
|
toLogin: login,
|
|
toForkNumber: reader.u16('toForkNumber'),
|
|
toBlockNumber: reader.i32('toBlockGlobalNumber'),
|
|
toBlockHash: reader.hash32('toBlockHash'),
|
|
};
|
|
}
|
|
|
|
function parseCompactTarget(reader) {
|
|
return {
|
|
toBlockNumber: reader.i32('toBlockGlobalNumber'),
|
|
toBlockHash: reader.hash32('toBlockHash'),
|
|
};
|
|
}
|
|
|
|
function parseTextTail(reader) {
|
|
return reader.textU16('text');
|
|
}
|
|
|
|
function splitMessageText(rawText) {
|
|
let rest = String(rawText || '');
|
|
let attachmentsCount = 0;
|
|
const attachRe = /^<(?:SHiNE|S):(attach|att);[^>]*>\n?/u;
|
|
for (;;) {
|
|
const match = rest.match(attachRe);
|
|
if (!match) break;
|
|
attachmentsCount += 1;
|
|
rest = rest.slice(match[0].length);
|
|
}
|
|
return { text: rest.replace(/^\n+/u, ''), attachmentsCount };
|
|
}
|
|
|
|
function parseChannelMetaText(rawText) {
|
|
const rows = String(rawText || '').replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n');
|
|
let title = '';
|
|
let avatarAr = '';
|
|
let avatarPr = '';
|
|
const descriptionRows = [];
|
|
for (const row of rows) {
|
|
const titleMatch = row.match(/^<S:title;v=1;([^>]*)>$/u);
|
|
if (titleMatch) {
|
|
title = String(titleMatch[1] || '').trim();
|
|
continue;
|
|
}
|
|
const avatarMatch = row.match(/^<S:ava;v=2;([^>]*)>$/u);
|
|
if (avatarMatch) {
|
|
const arMatch = String(avatarMatch[1] || '').match(/(?:^|;)ar=([A-Za-z0-9_-]{43})(?:;|$)/u);
|
|
avatarAr = String(arMatch?.[1] || '').trim();
|
|
const prMatch = String(avatarMatch[1] || '').match(/(?:^|;)pr=([1-9A-HJ-NP-Za-km-z]{32,44})(?:;|$)/u);
|
|
avatarPr = String(prMatch?.[1] || '').trim();
|
|
continue;
|
|
}
|
|
descriptionRows.push(row);
|
|
}
|
|
return {
|
|
title,
|
|
avatarAr,
|
|
avatarPr,
|
|
description: descriptionRows.join('\n').trim(),
|
|
};
|
|
}
|
|
|
|
function parseTechBody(subType, body, frame) {
|
|
const reader = new Reader(body);
|
|
if (subType === 0) {
|
|
const magic = reader.text(5, 'HEADER magic');
|
|
if (magic !== 'SHiNE') throw new Error('Неправильная сигнатура HEADER');
|
|
const login = reader.textU8('HEADER login');
|
|
let license = null;
|
|
if (frame.version === 2) {
|
|
const marker = reader.text(15, 'HEADER license');
|
|
if (marker !== 'license:CC0-1.0') throw new Error('Неподдерживаемая лицензия HEADER');
|
|
license = 'CC0-1.0';
|
|
}
|
|
const initialBlockchainKey = bytesToBase64Url(reader.raw(32, 'initialBlockchainKey32'));
|
|
if (reader.remaining() !== 0) throw new Error('Неожиданные данные после HEADER');
|
|
return { kind: 'header', magic, login, license, initialBlockchainKey };
|
|
}
|
|
if (subType === 1) {
|
|
const line = parseLinePrefix(reader);
|
|
const channelName = reader.textU8('channelName');
|
|
const channelDescription = reader.textU16('channelDescription');
|
|
const channelType = reader.u16('channelType');
|
|
const channelTypeVersion = reader.u16('channelTypeVersion');
|
|
return {
|
|
kind: 'create_channel', line, channelName, channelDescription, channelType, channelTypeVersion,
|
|
channelRootBlockNumber: frame.blockNumber,
|
|
channelMeta: parseChannelMetaText(channelDescription),
|
|
};
|
|
}
|
|
if (subType === 2) {
|
|
const line = parseLinePrefix(reader);
|
|
const parentBlockchainKey = bytesToBase64Url(reader.raw(32, 'parentBlockchainKey'));
|
|
const forkPointBlockNumber = reader.i32('forkPointBlockNumber');
|
|
const forkPointBlockHash = reader.hash32('forkPointBlockHash');
|
|
const forkPointTimestampMs = Number(reader.i64('forkPointTimestampMs'));
|
|
const parentTipBlockNumber = reader.i32('parentTipBlockNumber');
|
|
const parentTipBlockHash = reader.hash32('parentTipBlockHash');
|
|
const parentTipTimestampMs = Number(reader.i64('parentTipTimestampMs'));
|
|
const discardedBlocksCount = reader.i32('discardedBlocksCount');
|
|
const reasonCode = reader.u8('reasonCode');
|
|
const comment = reader.textU16('comment');
|
|
return {
|
|
kind: 'fork', line, parentBlockchainKey, forkPointBlockNumber, forkPointBlockHash,
|
|
forkPointTimestampMs, parentTipBlockNumber, parentTipBlockHash, parentTipTimestampMs,
|
|
discardedBlocksCount, reasonCode, comment,
|
|
};
|
|
}
|
|
return { kind: 'unknown', rawBodyLength: body.length };
|
|
}
|
|
|
|
function parseTextBody(subType, body) {
|
|
const reader = new Reader(body);
|
|
if ([10, 90, 92, 100, 110, 120, 130].includes(subType)) {
|
|
const line = parseLinePrefix(reader);
|
|
const rawText = parseTextTail(reader);
|
|
const message = splitMessageText(rawText);
|
|
return {
|
|
kind: subType === 90 ? 'channel_meta' : subType === 92 ? 'channel_delete' : 'line_text',
|
|
line, rawText, text: message.text, attachmentsCount: message.attachmentsCount,
|
|
channelMeta: subType === 90 ? parseChannelMetaText(rawText) : null,
|
|
};
|
|
}
|
|
if (subType === 11) {
|
|
const line = parseLinePrefix(reader);
|
|
const target = parseCompactTarget(reader);
|
|
const rawText = parseTextTail(reader);
|
|
const message = splitMessageText(rawText);
|
|
return { kind: 'edit_post', line, target, rawText, text: message.text, attachmentsCount: message.attachmentsCount };
|
|
}
|
|
if ([20, 30].includes(subType)) {
|
|
const target = parseTarget(reader);
|
|
const rawText = parseTextTail(reader);
|
|
const message = splitMessageText(rawText);
|
|
return { kind: subType === 20 ? 'reply' : 'rating', target, rawText, text: message.text, attachmentsCount: message.attachmentsCount };
|
|
}
|
|
if (subType === 21) {
|
|
const target = parseCompactTarget(reader);
|
|
const rawText = parseTextTail(reader);
|
|
const message = splitMessageText(rawText);
|
|
return { kind: 'edit_reply', target, rawText, text: message.text, attachmentsCount: message.attachmentsCount };
|
|
}
|
|
if (subType === 50) {
|
|
const line = parseLinePrefix(reader);
|
|
const target = parseTarget(reader);
|
|
const rawText = parseTextTail(reader);
|
|
const message = splitMessageText(rawText);
|
|
return { kind: 'repost', line, target, rawText, text: message.text, attachmentsCount: message.attachmentsCount };
|
|
}
|
|
return { kind: 'unknown', rawBodyLength: body.length };
|
|
}
|
|
|
|
function parseReactionBody(subType, body) {
|
|
const reader = new Reader(body);
|
|
if (subType === 1 || subType === 2) return { kind: subType === 1 ? 'like' : 'unlike', target: parseTarget(reader) };
|
|
return { kind: 'unknown', rawBodyLength: body.length };
|
|
}
|
|
|
|
function parseConnectionBody(subType, body) {
|
|
const reader = new Reader(body);
|
|
const line = parseFixedLinePrefix(reader, 'Connection');
|
|
const target = parseTarget(reader);
|
|
return { kind: 'connection', subType, line, target };
|
|
}
|
|
|
|
function parseProfileBody(subType, body) {
|
|
if (subType !== 1) return { kind: 'unknown', rawBodyLength: body.length };
|
|
const reader = new Reader(body);
|
|
const line = parseFixedLinePrefix(reader, 'Profile');
|
|
const key = reader.textU16('paramKey');
|
|
const value = reader.textU16('paramValue');
|
|
return { kind: 'profile', line, key, value };
|
|
}
|
|
|
|
function parseStatusBody(subType, body) {
|
|
const reader = new Reader(body);
|
|
const target = parseTarget(reader);
|
|
const rawText = parseTextTail(reader);
|
|
const message = splitMessageText(rawText);
|
|
return { kind: 'status', subType, target, rawText, text: message.text, attachmentsCount: message.attachmentsCount };
|
|
}
|
|
|
|
function parseBody(type, subType, version, body, frame) {
|
|
// Only TECH HEADER subtype 0 has a second version; all other records stay v1.
|
|
if (version !== 1 && !(type === 0 && subType === 0 && version === 2)) {
|
|
return { kind: 'unsupported_version', rawBodyLength: body.length };
|
|
}
|
|
if (type === 0) return parseTechBody(subType, body, frame);
|
|
if (type === 1) return parseTextBody(subType, body);
|
|
if (type === 2) return parseReactionBody(subType, body);
|
|
if (type === 3) return parseConnectionBody(subType, body);
|
|
if (type === 4) return parseProfileBody(subType, body);
|
|
if (type === 5) return parseStatusBody(subType, body);
|
|
return { kind: 'unknown', rawBodyLength: body.length };
|
|
}
|
|
|
|
export function parseShineFrame(frameBytes) {
|
|
const frame = frameBytes instanceof Uint8Array ? frameBytes : new Uint8Array(frameBytes || []);
|
|
if (frame.length < FRAME_HEADER_SIZE) throw new Error('SHiNE Frame короче 88 байт');
|
|
const reader = new Reader(frame);
|
|
const frameCode = reader.u16('frameCode');
|
|
const prevHash = reader.hash32('prevHash32');
|
|
const back32Hash = reader.hash32('back32Hash32');
|
|
const blockSize = reader.i32('blockSize');
|
|
const blockNumber = reader.i32('blockNumber');
|
|
const timestampSeconds = reader.i64('timestamp');
|
|
const type = reader.u16('type');
|
|
const subType = reader.u16('subType');
|
|
const version = reader.u16('version');
|
|
if (frameCode !== 1) throw new Error(`Неподдерживаемый frameCode: ${frameCode}`);
|
|
if (blockSize !== frame.length) throw new Error(`Размер Frame не совпадает: ${blockSize} != ${frame.length}`);
|
|
const bodyBytes = reader.raw(reader.remaining(), 'body');
|
|
const meta = { frameCode, prevHash, back32Hash, blockSize, blockNumber, timestampMs: Number(timestampSeconds * 1000n), type, subType, version };
|
|
return { ...meta, body: parseBody(type, subType, version, bodyBytes, meta), bodyBytes };
|
|
}
|
|
|
|
export async function inspectBlockchainDataItem(blockBytesB64) {
|
|
const raw = base64ToBytes(String(blockBytesB64 || ''));
|
|
const dataItem = parseAns104DataItem(raw);
|
|
const frame = parseShineFrame(dataItem.data);
|
|
const dataItemId = bytesToBase64Url(await sha256Bytes(dataItem.signature));
|
|
return {
|
|
dataItemId,
|
|
arweaveUrl: `https://arweave.net/${dataItemId}`,
|
|
owner: bytesToBase64Url(dataItem.owner32),
|
|
signatureType: dataItem.sigType,
|
|
frame,
|
|
};
|
|
}
|
|
|
|
export const blockchainInspectorInternals = Object.freeze({
|
|
FRAME_HEADER_SIZE,
|
|
LINE_PREFIX_SIZE,
|
|
FIXED_LINE_PREFIX_SIZE,
|
|
ZERO_HASH,
|
|
});
|