SHA256
Новый формат блоков CORE/CONTENT test5595
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { formatDateTime } from '../i18n/format.js';
|
||||
import { escapeHtml } from '../services/attachment-format.js';
|
||||
import { arweaveBlockUrl, checkArweavePayload, checkSolanaAuthor, readSignedBlock, signedDataItemFilename } from '../services/blockchain-proof-service.js';
|
||||
import { arweaveBlockUrl, checkArweavePair, checkSolanaAuthor, readSignedBlock, signedDataItemFilename } from '../services/blockchain-proof-service.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
|
||||
const validHash = (value) => /^[0-9a-f]{64}$/iu.test(String(value || ''));
|
||||
@@ -147,9 +147,8 @@ export function openBlockchainDetailsModal(details, { authService, solanaEndpoin
|
||||
results.hidden = false; results.textContent = label('checking');
|
||||
try {
|
||||
const proof = await signedBlock();
|
||||
const id = currentVersion().arweaveDataItemId || proof.actualId;
|
||||
const [arweave, solana] = await Promise.all([
|
||||
checkArweavePayload(id, proof.data),
|
||||
checkArweavePair(proof),
|
||||
checkSolanaAuthor({ authorLogin: details.authorLogin, blockchainName: details.authorBlockchainName,
|
||||
owner32: proof.owner32, solanaEndpoint }),
|
||||
]);
|
||||
|
||||
@@ -4897,8 +4897,8 @@
|
||||
"verified": "verified",
|
||||
"failed": "does not match",
|
||||
"not_verified": "not verified",
|
||||
"signature": "Ed25519 signature",
|
||||
"integrity": "Block integrity and DataItem ID",
|
||||
"signature": "CORE and CONTENT signatures (Ed25519)",
|
||||
"integrity": "CORE, CONTENT and DataItem ID integrity",
|
||||
"arweave_check": "Data in Arweave",
|
||||
"solana_check": "Author key in Solana",
|
||||
"signed_check": "Signed record",
|
||||
|
||||
@@ -4897,8 +4897,8 @@
|
||||
"verified": "подтверждено",
|
||||
"failed": "не совпадает",
|
||||
"not_verified": "не проверено",
|
||||
"signature": "Подпись Ed25519",
|
||||
"integrity": "Целостность блока и DataItem ID",
|
||||
"signature": "Подписи CORE и CONTENT (Ed25519)",
|
||||
"integrity": "Целостность CORE, CONTENT и их ID",
|
||||
"arweave_check": "Данные в Arweave",
|
||||
"solana_check": "Ключ автора в Solana",
|
||||
"signed_check": "Подписанный блок",
|
||||
|
||||
@@ -441,12 +441,13 @@ function createEntryCard({ item, inspection, parseError, channelNames, blockchai
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_017'), `#${item.blockNumber}`);
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_018'), formatDate(item.timestampMs));
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_019'), item.blockHash, { code: true });
|
||||
if (inspection?.dataItemId) addDetailRow(info, 'DataItem ID', inspection.dataItemId, { code: true });
|
||||
if (inspection?.dataItemId) addDetailRow(info, 'CORE DataItem ID', inspection.dataItemId, { code: true });
|
||||
if (inspection?.contentDataItemId) addDetailRow(info, 'CONTENT DataItem ID', inspection.contentDataItemId, { code: true });
|
||||
|
||||
const body = frame?.body || {};
|
||||
if (body.line) {
|
||||
if (Number.isInteger(Number(body.line.lineCode))) addDetailRow(info, t('screens.my_blockchain_view.text_020'), `#${body.line.lineCode}`);
|
||||
if (Number.isInteger(Number(body.line.lineSequence))) addDetailRow(info, t('screens.my_blockchain_view.text_021'), body.line.lineSequence);
|
||||
if (Number.isInteger(body.line.lineSequence)) addDetailRow(info, t('screens.my_blockchain_view.text_021'), body.line.lineSequence);
|
||||
}
|
||||
if (body.kind === 'profile') {
|
||||
addDetailRow(info, t('screens.my_blockchain_view.text_022'), body.key);
|
||||
@@ -576,7 +577,7 @@ export function render({ navigate, chrome }, { historyOnly = false } = {}) {
|
||||
const rows = await Promise.all((data.blocks || []).map(async (item) => {
|
||||
if (!item?.blockBytesB64) return { item, inspection: null, parseError: t('screens.my_blockchain_view.text_066') };
|
||||
try {
|
||||
const inspection = await inspectBlockchainDataItem(item.blockBytesB64);
|
||||
const inspection = await inspectBlockchainDataItem(item.blockBytesB64, item.thisLineNumber);
|
||||
const body = inspection?.frame?.body;
|
||||
if (inspection?.frame?.type === 0 && inspection?.frame?.subType === 1) {
|
||||
const root = Number(inspection.frame.blockNumber);
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as explorerCanvasView from './network-canvas-v4/network-view.js';
|
||||
|
||||
const NETWORK_VERSION_STORAGE_KEY = 'shine.network.version';
|
||||
const MODES = new Set(['legacy', 'modern', 'explorer', 'explorer-canvas']);
|
||||
const DEFAULT_MODE = 'explorer-canvas';
|
||||
|
||||
// Нижняя вкладка сбрасывает только исследованный граф V3/V4, не изображения и не V1/V2.
|
||||
window.addEventListener('shine:network-tab-enter', explorerNetworkView.resetExplorerOnTabEntry);
|
||||
@@ -15,9 +16,9 @@ export const pageMeta = modernNetworkView.pageMeta;
|
||||
function selectedMode() {
|
||||
try {
|
||||
const saved = window.localStorage.getItem(NETWORK_VERSION_STORAGE_KEY);
|
||||
return MODES.has(saved) ? saved : 'modern';
|
||||
return MODES.has(saved) ? saved : DEFAULT_MODE;
|
||||
} catch {
|
||||
return 'modern';
|
||||
return DEFAULT_MODE;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +45,7 @@ function createModeSwitcher(mode, navigate) {
|
||||
`;
|
||||
select.value = mode;
|
||||
select.addEventListener('change', () => {
|
||||
const nextMode = MODES.has(select.value) ? select.value : 'modern';
|
||||
const nextMode = MODES.has(select.value) ? select.value : DEFAULT_MODE;
|
||||
saveMode(nextMode);
|
||||
navigate?.('network-view');
|
||||
});
|
||||
|
||||
@@ -39,9 +39,8 @@ import {
|
||||
saveEncryptedUserSecrets,
|
||||
saveSessionMaterial,
|
||||
} from './key-vault.js';
|
||||
import { createAns104DataItem, parseAns104DataItem } from './ans104-data-item.js';
|
||||
import { signEventContainer, submitSignedEvent, readStoredLineMeta } from './core-content.js';
|
||||
import { defaultServerWs } from '../deploy-config.js';
|
||||
import { SHINE_APP_TAG_NAME, SHINE_APP_TAG_VALUE, SHINE_CHANNEL_TAG_NAME, SHINE_TYPE_TAG_NAME } from './protocol-tags.js';
|
||||
|
||||
const BCH_SUFFIX = '001';
|
||||
const ZERO64 = '0'.repeat(64);
|
||||
@@ -541,9 +540,7 @@ function extractContactsFromDialogs(dialogs) {
|
||||
return out;
|
||||
}
|
||||
|
||||
export const HEADER_LICENSE_CC0 = 'CC0-1.0';
|
||||
export const HEADER_LICENSE_FIELD_CC0 = `license:${HEADER_LICENSE_CC0}`;
|
||||
export const HEADER_VERSION_CC0 = 2;
|
||||
export const HEADER_VERSION = 1;
|
||||
|
||||
function makeHeaderBodyBytes({ login, initialBlockchainKey32 }) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
@@ -559,7 +556,6 @@ function makeHeaderBodyBytes({ login, initialBlockchainKey32 }) {
|
||||
utf8Bytes('SHiNE'),
|
||||
int8Byte(loginBytes.length),
|
||||
loginBytes,
|
||||
utf8Bytes(HEADER_LICENSE_FIELD_CC0),
|
||||
keyBytes,
|
||||
);
|
||||
}
|
||||
@@ -892,42 +888,6 @@ function resolveLatestLineStep(message) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function bytesToHexLower(bytes) {
|
||||
return Array.from(bytes || [], (value) => Number(value).toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
function parseStoredLineMeta(blockBytesB64, { fixedLine = false } = {}) {
|
||||
const raw = base64ToBytes(String(blockBytesB64 || ''));
|
||||
const frame = parseAns104DataItem(raw).data;
|
||||
const bodyOffset = 88;
|
||||
const minLength = fixedLine ? bodyOffset + 40 : bodyOffset + 44;
|
||||
if (!(frame instanceof Uint8Array) || frame.length < minLength) throw new Error('Некорректный line-блок');
|
||||
const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
|
||||
if (fixedLine) {
|
||||
return {
|
||||
lineCode: 0,
|
||||
prevLineNumber: view.getInt32(bodyOffset, false),
|
||||
prevLineHashHex: bytesToHexLower(frame.slice(bodyOffset + 4, bodyOffset + 36)),
|
||||
lineSequence: view.getInt32(bodyOffset + 36, false),
|
||||
};
|
||||
}
|
||||
return {
|
||||
lineCode: view.getInt32(bodyOffset, false),
|
||||
prevLineNumber: view.getInt32(bodyOffset + 4, false),
|
||||
prevLineHashHex: bytesToHexLower(frame.slice(bodyOffset + 8, bodyOffset + 40)),
|
||||
lineSequence: view.getInt32(bodyOffset + 40, false),
|
||||
};
|
||||
}
|
||||
|
||||
function typeIndexTagValue(msgType) {
|
||||
switch (Number(msgType)) {
|
||||
case MSG_TYPE_TECH: return 'tech';
|
||||
case MSG_TYPE_CONNECTION: return 'conn';
|
||||
case MSG_TYPE_USER_PROFILE: return 'prof';
|
||||
default: return '';
|
||||
}
|
||||
}
|
||||
|
||||
function isLineConflictError(error) {
|
||||
return new Set([
|
||||
'BAD_PREV_LINE_NUMBER',
|
||||
@@ -937,26 +897,6 @@ function isLineConflictError(error) {
|
||||
]).has(String(error?.code || '').toUpperCase());
|
||||
}
|
||||
|
||||
function buildBlockPreimage({ prevBlockHashHex, back32HashHex, blockNumber, msgType, msgSubType, msgVersion = 1, bodyBytes }) {
|
||||
const prevHashBytes = hexToBytes(normalizeHex32(prevBlockHashHex));
|
||||
const back32HashBytes = hexToBytes(normalizeHex32(back32HashHex, ZERO64));
|
||||
const body = bodyBytes || new Uint8Array(0);
|
||||
const blockSize = 2 + 32 + 32 + 4 + 4 + 8 + 2 + 2 + 2 + body.length;
|
||||
|
||||
return concatBytes(
|
||||
int16Bytes(1),
|
||||
prevHashBytes,
|
||||
back32HashBytes,
|
||||
int32Bytes(blockSize),
|
||||
int32Bytes(blockNumber),
|
||||
int64Bytes(Math.floor(Date.now() / 1000)),
|
||||
int16Bytes(msgType),
|
||||
int16Bytes(msgSubType),
|
||||
int16Bytes(msgVersion),
|
||||
body
|
||||
);
|
||||
}
|
||||
|
||||
function buildRemoteBlockBodyBytes({ msgType, msgSubType, msgVersion = 1, bodyBytes }) {
|
||||
const body = bodyBytes || new Uint8Array(0);
|
||||
return concatBytes(
|
||||
@@ -1676,87 +1616,15 @@ export class AuthService {
|
||||
};
|
||||
}
|
||||
|
||||
async submitPreparedAddBlock({ login, storagePwd, blockchainName, blockNumber, prevBlockHash, preimage, ansTags }) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const cleanBlockchainName = String(blockchainName || '').trim();
|
||||
const cleanPrevBlockHash = normalizeHex32(prevBlockHash, ZERO_HASH_HEX);
|
||||
if (!cleanLogin || !cleanBlockchainName) throw new Error('submitPreparedAddBlock: missing login/blockchainName');
|
||||
if (!(preimage instanceof Uint8Array) || preimage.length === 0) {
|
||||
throw new Error('submitPreparedAddBlock: bad preimage');
|
||||
}
|
||||
|
||||
const savedKeys = await loadEncryptedUserSecrets(cleanLogin, storagePwd);
|
||||
const blockchainPrivatePkcs8 = String(savedKeys?.blockchainKey || '').trim();
|
||||
if (blockchainPrivatePkcs8) {
|
||||
const privateKey = await importPkcs8Ed25519(blockchainPrivatePkcs8);
|
||||
const owner32 = base64ToBytes(await publicKeyB64FromPkcs8Ed25519(blockchainPrivatePkcs8));
|
||||
const dataItemBytes = await createAns104DataItem({
|
||||
owner32,
|
||||
privateKey,
|
||||
data: preimage,
|
||||
tags: Array.isArray(ansTags) && ansTags.length ? ansTags : [{ name: SHINE_APP_TAG_NAME, value: SHINE_APP_TAG_VALUE }],
|
||||
});
|
||||
return this.ws.request('AddBlock', {
|
||||
blockchainName: cleanBlockchainName,
|
||||
blockNumber: Number(blockNumber),
|
||||
prevBlockHash: cleanPrevBlockHash,
|
||||
blockBytesB64: bytesToBase64(dataItemBytes),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
const remoteSessionId = String(this.remoteAddBlockSessionId || '').trim();
|
||||
if (!remoteSessionId) {
|
||||
throw new Error('На устройстве нет blockchain key и не выбрана homeserver-сессия для remote AddBlock');
|
||||
}
|
||||
|
||||
const signalRequestId = createSignalRequestId('remote-addblock');
|
||||
const responseWait = this.waitForSignal({
|
||||
signalType: SIGNAL_TYPE_REMOTE_ADDBLOCK_RESULT,
|
||||
signalRequestId,
|
||||
timeoutMs: 20000,
|
||||
});
|
||||
|
||||
const signalData = {
|
||||
operation: SIGNAL_TYPE_REMOTE_ADDBLOCK_REQUEST,
|
||||
signalRequestId,
|
||||
login: cleanLogin,
|
||||
blockchainName: cleanBlockchainName,
|
||||
blockNumber: Number(blockNumber),
|
||||
prevBlockHash: cleanPrevBlockHash,
|
||||
blockPreimageB64: bytesToBase64(preimage),
|
||||
};
|
||||
|
||||
await this.sendSignal({
|
||||
toLogin: cleanLogin,
|
||||
targetMode: SIGNAL_TARGET_SINGLE,
|
||||
targetSessionId: remoteSessionId,
|
||||
signalType: SIGNAL_TYPE_REMOTE_ADDBLOCK_REQUEST,
|
||||
signalRequestId,
|
||||
data: JSON.stringify(signalData),
|
||||
storagePwd,
|
||||
includeClientSignature: true,
|
||||
});
|
||||
|
||||
const signalPayload = await responseWait;
|
||||
let result = {};
|
||||
try {
|
||||
result = JSON.parse(String(signalPayload?.data || '{}'));
|
||||
} catch {
|
||||
throw new Error('Некорректный ответ remote AddBlock от homeserver');
|
||||
}
|
||||
if (!result?.ok) {
|
||||
throw new Error(String(result?.errorMessage || result?.error || 'remote_addblock_failed'));
|
||||
}
|
||||
|
||||
return {
|
||||
status: 200,
|
||||
payload: {
|
||||
serverLastGlobalNumber: Number(result?.serverLastGlobalNumber ?? blockNumber),
|
||||
serverLastGlobalHash: String(result?.serverLastGlobalHash || ZERO_HASH_HEX),
|
||||
remote: true,
|
||||
},
|
||||
};
|
||||
async submitPreparedAddBlock({ login, storagePwd, blockchainName, blockNumber, prevBlockHash, event }) {
|
||||
const savedKeys = await loadEncryptedUserSecrets(login, storagePwd);
|
||||
const pkcs8 = String(savedKeys?.blockchainKey || '').trim();
|
||||
if (!pkcs8) throw new Error('Blockchain key unavailable for local signing');
|
||||
const privateKey = await importPkcs8Ed25519(pkcs8);
|
||||
const owner32 = base64ToBytes(await publicKeyB64FromPkcs8Ed25519(pkcs8));
|
||||
const signed = await signEventContainer({ ...event, owner32, privateKey, blockNumber,
|
||||
prevBlockHash, timestamp: Math.floor(Date.now() / 1000) });
|
||||
return submitSignedEvent(this.ws, { blockchainName, blockNumber, prevBlockHash }, signed);
|
||||
}
|
||||
|
||||
async submitRemoteAddBlockBody({ login, storagePwd, blockchainName, blockBodyBytes }) {
|
||||
@@ -1818,53 +1686,27 @@ export class AuthService {
|
||||
};
|
||||
}
|
||||
|
||||
async runAddBlockWithRetry({ login, storagePwd, resolveFreshState, buildPreimage, ansTags }) {
|
||||
let freshState = await resolveFreshState();
|
||||
let blockchainName = String(freshState?.blockchainName || '').trim();
|
||||
async runAddBlockWithRetry({ login, storagePwd, resolveFreshState, event }) {
|
||||
const freshState = await resolveFreshState();
|
||||
const blockchainName = String(freshState?.blockchainName || '').trim();
|
||||
if (!blockchainName) throw new Error('runAddBlockWithRetry: blockchainName is empty');
|
||||
|
||||
const tryAdd = async (cursor) => {
|
||||
const blockNumber = Number(cursor?.serverLastGlobalNumber ?? -1) + 1;
|
||||
const prevBlockHash = normalizeHex32(cursor?.serverLastGlobalHash, ZERO64);
|
||||
const back32Hash = blockNumber < 32
|
||||
? ZERO64
|
||||
: normalizeHex32(await this.getBlockHashByNumber(blockchainName, blockNumber - 32), ZERO64);
|
||||
if (blockNumber >= 32 && back32Hash === ZERO64) {
|
||||
throw new Error(`Не удалось получить hash блока #${blockNumber - 32} для back32Hash`);
|
||||
}
|
||||
const preimage = await buildPreimage({ blockNumber, prevBlockHash, back32Hash, blockchainName });
|
||||
return this.submitPreparedAddBlock({
|
||||
login,
|
||||
storagePwd,
|
||||
blockchainName,
|
||||
blockNumber,
|
||||
prevBlockHash,
|
||||
preimage,
|
||||
ansTags,
|
||||
});
|
||||
};
|
||||
|
||||
let cursor = freshState.cursor;
|
||||
let response = await tryAdd(cursor);
|
||||
if (response.status !== 200) {
|
||||
const knownNum = Number(response?.payload?.serverLastGlobalNumber);
|
||||
const knownHash = String(response?.payload?.serverLastGlobalHash || '');
|
||||
if (Number.isFinite(knownNum) && /^[0-9a-fA-F]{64}$/.test(knownHash)) {
|
||||
cursor = { serverLastGlobalNumber: knownNum, serverLastGlobalHash: knownHash.toLowerCase() };
|
||||
response = await tryAdd(cursor);
|
||||
} else {
|
||||
freshState = await resolveFreshState();
|
||||
blockchainName = String(freshState?.blockchainName || blockchainName).trim() || blockchainName;
|
||||
cursor = freshState.cursor;
|
||||
response = await tryAdd(cursor);
|
||||
const tryAdd = cursor => this.submitPreparedAddBlock({ login, storagePwd, blockchainName,
|
||||
blockNumber: Number(cursor?.serverLastGlobalNumber ?? -1) + 1,
|
||||
prevBlockHash: normalizeHex32(cursor?.serverLastGlobalHash, ZERO64), event });
|
||||
let response = await tryAdd(freshState.cursor);
|
||||
// Only a definitive global cursor conflict allows a new signature. An ambiguous
|
||||
// delivery is handled by submitSignedEvent using the original signed bytes.
|
||||
const code = String(response?.payload?.code || response?.code || '').toLowerCase();
|
||||
if (response.status !== 200 && ['bad_block_number', 'bad_prev_hash'].includes(code)) {
|
||||
const refreshed = await resolveFreshState();
|
||||
if (refreshed.blockchainName !== blockchainName) throw new Error('Blockchain changed during AddBlock');
|
||||
// HEADER must never be recreated at a nonzero number.
|
||||
if (!(event.msgType === MSG_TYPE_TECH && event.msgSubType === MSG_SUBTYPE_TECH_HEADER)) {
|
||||
response = await tryAdd(refreshed.cursor);
|
||||
}
|
||||
}
|
||||
|
||||
if (response.status !== 200) throw opError('AddBlock', response);
|
||||
return {
|
||||
response,
|
||||
blockchainName,
|
||||
};
|
||||
return { response, blockchainName };
|
||||
}
|
||||
|
||||
async addBlockSigned({ login, storagePwd, msgType, msgSubType, msgVersion = 1, bodyBytes, channelSlug = '', _skipHeaderEnsure = false }) {
|
||||
@@ -1892,26 +1734,11 @@ export class AuthService {
|
||||
return response.payload || {};
|
||||
}
|
||||
|
||||
const ansTags = [{ name: SHINE_APP_TAG_NAME, value: SHINE_APP_TAG_VALUE }];
|
||||
const typeIndexTag = typeIndexTagValue(msgType);
|
||||
if (typeIndexTag) ansTags.push({ name: SHINE_TYPE_TAG_NAME, value: typeIndexTag });
|
||||
const cleanChannelSlug = String(channelSlug || '').trim();
|
||||
if (cleanChannelSlug) ansTags.push({ name: SHINE_CHANNEL_TAG_NAME, value: cleanChannelSlug });
|
||||
|
||||
const { response, blockchainName } = await this.runAddBlockWithRetry({
|
||||
login: cleanLogin,
|
||||
storagePwd,
|
||||
resolveFreshState: () => this.resolveFreshBlockchainCursor(cleanLogin),
|
||||
ansTags,
|
||||
buildPreimage: async ({ blockNumber, prevBlockHash, back32Hash }) => buildBlockPreimage({
|
||||
prevBlockHashHex: prevBlockHash,
|
||||
back32HashHex: back32Hash,
|
||||
blockNumber,
|
||||
msgType,
|
||||
msgSubType,
|
||||
msgVersion,
|
||||
bodyBytes,
|
||||
}),
|
||||
event: { msgType, msgSubType, msgVersion, bodyBytes },
|
||||
});
|
||||
|
||||
const payload = response.payload || {};
|
||||
@@ -1952,7 +1779,7 @@ export class AuthService {
|
||||
storagePwd,
|
||||
msgType: MSG_TYPE_TECH,
|
||||
msgSubType: MSG_SUBTYPE_TECH_HEADER,
|
||||
msgVersion: HEADER_VERSION_CC0,
|
||||
msgVersion: HEADER_VERSION,
|
||||
// HEADER хранит исходный регистр неизменяемого имени из Solana/Arweave.
|
||||
// Нормализация нужна только для уникальности и имени самой цепочки.
|
||||
bodyBytes: makeHeaderBodyBytes({ login: registeredLogin, initialBlockchainKey32 }),
|
||||
@@ -2328,7 +2155,6 @@ export class AuthService {
|
||||
msgType,
|
||||
subTypes = null,
|
||||
lineCode = null,
|
||||
fixedLine = false,
|
||||
stopAtBlock = 0,
|
||||
}) {
|
||||
const cleanBch = String(blockchainName || '').trim();
|
||||
@@ -2348,7 +2174,7 @@ export class AuthService {
|
||||
if (Number(block?.msgType) !== Number(msgType)) continue;
|
||||
if (subtypeSet && !subtypeSet.has(Number(block?.msgSubType))) continue;
|
||||
if (!block?.blockBytesB64) continue;
|
||||
const meta = parseStoredLineMeta(block.blockBytesB64, { fixedLine });
|
||||
const meta = readStoredLineMeta(base64ToBytes(block.blockBytesB64), block.thisLineNumber);
|
||||
if (lineCode != null && Number(meta.lineCode) !== Number(lineCode)) continue;
|
||||
return {
|
||||
blockNumber,
|
||||
@@ -2384,7 +2210,6 @@ export class AuthService {
|
||||
msgType: config.msgType,
|
||||
subTypes: config.subTypes || null,
|
||||
lineCode: kindKey === 'tech' ? 0 : null,
|
||||
fixedLine: kindKey !== 'tech',
|
||||
stopAtBlock: 0,
|
||||
});
|
||||
if (latest) {
|
||||
@@ -2573,7 +2398,6 @@ export class AuthService {
|
||||
MSG_SUBTYPE_TEXT_COURSE,
|
||||
],
|
||||
lineCode,
|
||||
fixedLine: false,
|
||||
stopAtBlock: lineCode,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { unpackCoreContent, verifyCoreContentPair } from './core-content.js';
|
||||
import { parseAns104DataItem } from './ans104-data-item.js';
|
||||
import { base64ToBytes, bytesToBase64Url, sha256Bytes } from './crypto-utils.js';
|
||||
import { base64ToBytes, bytesToBase64Url } from './crypto-utils.js';
|
||||
|
||||
const FRAME_HEADER_SIZE = 88;
|
||||
const LINE_PREFIX_SIZE = 44;
|
||||
@@ -134,7 +135,7 @@ function parseTechBody(subType, body, frame) {
|
||||
return { kind: 'header', magic, login, license, initialBlockchainKey };
|
||||
}
|
||||
if (subType === 1) {
|
||||
const line = parseLinePrefix(reader);
|
||||
const line = frame.signedLine ?? parseLinePrefix(reader);
|
||||
const channelName = reader.textU8('channelName');
|
||||
const channelDescription = reader.textU16('channelDescription');
|
||||
const channelType = reader.u16('channelType');
|
||||
@@ -146,7 +147,7 @@ function parseTechBody(subType, body, frame) {
|
||||
};
|
||||
}
|
||||
if (subType === 2) {
|
||||
const line = parseLinePrefix(reader);
|
||||
const line = frame.signedLine ?? parseLinePrefix(reader);
|
||||
const parentBlockchainKey = bytesToBase64Url(reader.raw(32, 'parentBlockchainKey'));
|
||||
const forkPointBlockNumber = reader.i32('forkPointBlockNumber');
|
||||
const forkPointBlockHash = reader.hash32('forkPointBlockHash');
|
||||
@@ -166,10 +167,10 @@ function parseTechBody(subType, body, frame) {
|
||||
return { kind: 'unknown', rawBodyLength: body.length };
|
||||
}
|
||||
|
||||
function parseTextBody(subType, body) {
|
||||
function parseTextBody(subType, body, frame) {
|
||||
const reader = new Reader(body);
|
||||
if ([10, 90, 92, 100, 110, 120, 130].includes(subType)) {
|
||||
const line = parseLinePrefix(reader);
|
||||
const line = frame.signedLine ?? parseLinePrefix(reader);
|
||||
const rawText = parseTextTail(reader);
|
||||
const message = splitMessageText(rawText);
|
||||
return {
|
||||
@@ -179,7 +180,7 @@ function parseTextBody(subType, body) {
|
||||
};
|
||||
}
|
||||
if (subType === 11) {
|
||||
const line = parseLinePrefix(reader);
|
||||
const line = frame.signedLine ?? parseLinePrefix(reader);
|
||||
const target = parseCompactTarget(reader);
|
||||
const rawText = parseTextTail(reader);
|
||||
const message = splitMessageText(rawText);
|
||||
@@ -198,7 +199,7 @@ function parseTextBody(subType, body) {
|
||||
return { kind: 'edit_reply', target, rawText, text: message.text, attachmentsCount: message.attachmentsCount };
|
||||
}
|
||||
if (subType === 50) {
|
||||
const line = parseLinePrefix(reader);
|
||||
const line = frame.signedLine ?? parseLinePrefix(reader);
|
||||
const target = parseTarget(reader);
|
||||
const rawText = parseTextTail(reader);
|
||||
const message = splitMessageText(rawText);
|
||||
@@ -213,17 +214,17 @@ function parseReactionBody(subType, body) {
|
||||
return { kind: 'unknown', rawBodyLength: body.length };
|
||||
}
|
||||
|
||||
function parseConnectionBody(subType, body) {
|
||||
function parseConnectionBody(subType, body, frame) {
|
||||
const reader = new Reader(body);
|
||||
const line = parseFixedLinePrefix(reader, 'Connection');
|
||||
const line = frame.signedLine ?? parseFixedLinePrefix(reader, 'Connection');
|
||||
const target = parseTarget(reader);
|
||||
return { kind: 'connection', subType, line, target };
|
||||
}
|
||||
|
||||
function parseProfileBody(subType, body) {
|
||||
function parseProfileBody(subType, body, frame) {
|
||||
if (subType !== 1) return { kind: 'unknown', rawBodyLength: body.length };
|
||||
const reader = new Reader(body);
|
||||
const line = parseFixedLinePrefix(reader, 'Profile');
|
||||
const line = frame.signedLine ?? parseFixedLinePrefix(reader, 'Profile');
|
||||
const key = reader.textU16('paramKey');
|
||||
const value = reader.textU16('paramValue');
|
||||
return { kind: 'profile', line, key, value };
|
||||
@@ -243,10 +244,10 @@ function parseBody(type, subType, version, body, frame) {
|
||||
return { kind: 'unsupported_version', rawBodyLength: body.length };
|
||||
}
|
||||
if (type === 0) return parseTechBody(subType, body, frame);
|
||||
if (type === 1) return parseTextBody(subType, body);
|
||||
if (type === 1) return parseTextBody(subType, body, frame);
|
||||
if (type === 2) return parseReactionBody(subType, body);
|
||||
if (type === 3) return parseConnectionBody(subType, body);
|
||||
if (type === 4) return parseProfileBody(subType, body);
|
||||
if (type === 3) return parseConnectionBody(subType, body, frame);
|
||||
if (type === 4) return parseProfileBody(subType, body, frame);
|
||||
if (type === 5) return parseStatusBody(subType, body);
|
||||
return { kind: 'unknown', rawBodyLength: body.length };
|
||||
}
|
||||
@@ -271,18 +272,21 @@ export function parseShineFrame(frameBytes) {
|
||||
return { ...meta, body: parseBody(type, subType, version, bodyBytes, meta), bodyBytes };
|
||||
}
|
||||
|
||||
export async function inspectBlockchainDataItem(blockBytesB64) {
|
||||
export async function inspectBlockchainDataItem(blockBytesB64, thisLineNumber = null) {
|
||||
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,
|
||||
};
|
||||
const { coreDataItem, contentDataItem } = unpackCoreContent(raw);
|
||||
const dataItem = parseAns104DataItem(coreDataItem);
|
||||
const { core, content, coreDataItemId32 } = await verifyCoreContentPair(coreDataItem, contentDataItem, dataItem.owner32);
|
||||
const signedLine = core.line ? { lineCode: core.line.lineCode, prevLineNumber: core.line.prevLineBlockNumber,
|
||||
prevLineHash: bytesToHex(core.line.prevLineCoreHash32), lineSequence: Number.isInteger(thisLineNumber) ? thisLineNumber : null } : null;
|
||||
const { type, subType, version, body: bodyBytes } = content;
|
||||
const meta = { frameCode: 1, prevHash: bytesToHex(core.prevCoreHash32), blockSize: raw.length,
|
||||
blockNumber: core.blockNumber, timestampMs: Number(core.timestamp * 1000n), type, subType, version, signedLine };
|
||||
const frame = { ...meta, body: parseBody(type, subType, version, bodyBytes, meta), bodyBytes };
|
||||
const dataItemId = bytesToBase64Url(coreDataItemId32);
|
||||
return { dataItemId, contentDataItemId: bytesToBase64Url(core.contentDataItemId32),
|
||||
arweaveUrl: `https://arweave.net/${dataItemId}`, owner: bytesToBase64Url(dataItem.owner32),
|
||||
signatureType: dataItem.sigType, frame };
|
||||
}
|
||||
|
||||
export const blockchainInspectorInternals = Object.freeze({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { verifyAns104DataItem } from './ans104-data-item.js';
|
||||
import { parseAns104DataItem } from './ans104-data-item.js';
|
||||
import { unpackCoreContent, verifyCoreContentPair, CORE_MAX_CONTAINER_BYTES } from './core-content.js';
|
||||
import { base64ToBytes, bytesToBase64Url } from './crypto-utils.js';
|
||||
import { readShineUserPda } from './shine-user-pda-service.js';
|
||||
|
||||
@@ -17,7 +18,7 @@ export function arweaveBlockUrl(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`;
|
||||
return `SHiNE-${safe}-${Number(number)}.shine-pair`;
|
||||
}
|
||||
|
||||
/** Получаем полный оригинал по существующему публичному API (не «от Arweave»). */
|
||||
@@ -29,15 +30,18 @@ export async function readSignedBlock({ authService, blockchainName, blockNumber
|
||||
throw new Error('Сервер вернул другой хеш блока');
|
||||
}
|
||||
const rawText = String(body?.blockBytesB64 || '');
|
||||
if (rawText.length > Math.ceil(MAX_SIGNED_BYTES * 4 / 3) + 8) throw new Error('Размер подписанного блока превышает лимит');
|
||||
if (rawText.length > Math.ceil(CORE_MAX_CONTAINER_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 (!bytes.length || bytes.length > CORE_MAX_CONTAINER_BYTES) throw new Error('Некорректный размер блока');
|
||||
const { coreDataItem, contentDataItem } = unpackCoreContent(bytes);
|
||||
const item = parseAns104DataItem(coreDataItem);
|
||||
const proof = await verifyCoreContentPair(coreDataItem, contentDataItem, item.owner32);
|
||||
if (proof.core.blockNumber !== Number(blockNumber)) throw new Error('Сервер вернул другой номер блока');
|
||||
if (hex(proof.coreHash32) !== String(blockHash).toLowerCase()) throw new Error('Хеш CORE не совпал');
|
||||
const actualId = bytesToBase64Url(proof.coreDataItemId32);
|
||||
if (dataItemId && actualId !== dataItemId) throw new Error('Идентификатор Arweave отличается от ожидаемого');
|
||||
return { bytes, ...proof, actualId };
|
||||
return { bytes, ...proof, owner32: item.owner32, data: item.data, actualId,
|
||||
contentId: bytesToBase64Url(proof.core.contentDataItemId32), contentData: parseAns104DataItem(contentDataItem).data };
|
||||
}
|
||||
|
||||
/** Вспомогательная независимая сверка: шлюз возвращает payload, а не ANS-104 оболочку. */
|
||||
@@ -77,3 +81,13 @@ export async function checkSolanaAuthor({ authorLogin, blockchainName, owner32,
|
||||
return { status: 'unavailable', reason: String(error?.message || error) };
|
||||
}
|
||||
}
|
||||
|
||||
/** Both payloads must be available and match the original signed pair. */
|
||||
export async function checkArweavePair(proof) {
|
||||
const [core, content] = await Promise.all([
|
||||
checkArweavePayload(proof.actualId, proof.data), checkArweavePayload(proof.contentId, proof.contentData),
|
||||
]);
|
||||
const status = [core.status, content.status].includes('invalid') ? 'invalid' :
|
||||
[core.status, content.status].every(s => s === 'valid') ? 'valid' : 'unavailable';
|
||||
return { status, reason: [core.reason && `CORE: ${core.reason}`, content.reason && `CONTENT: ${content.reason}`].filter(Boolean).join('; ') };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
import { createAns104DataItem, createAns104DataItemWithRawParts, parseAns104DataItem } from './ans104-data-item.js';
|
||||
import { parseAns104DataItem } from './ans104-data-item.js';
|
||||
import { base64ToBytes, bytesToBase64 } from './crypto-utils.js';
|
||||
import { updateShineUserPdaOnSolana, readShineUserPda } from './shine-user-pda-service.js';
|
||||
import { updateEncryptedUserSecrets } from './key-vault.js';
|
||||
import { SHINE_APP_TAG_NAME, SHINE_APP_TAG_VALUE, SHINE_TYPE_TAG_NAME } from './protocol-tags.js';
|
||||
import { SHINE_CORE_LINE_TECH } from './protocol-tags.js';
|
||||
import { unpackCoreContent, decodeCore, decodeContent, signCoreContentPair, packCoreContent } from './core-content.js';
|
||||
|
||||
const TE = new TextEncoder();
|
||||
const ZERO_HASH = '0'.repeat(64);
|
||||
const TECH_FORK_SUBTYPE = 2;
|
||||
|
||||
function payload(resp) { return resp?.payload && typeof resp.payload === 'object' ? resp.payload : (resp || {}); }
|
||||
@@ -33,44 +33,19 @@ function hexToBytes(hex) {
|
||||
const s=String(hex||'').trim().toLowerCase(); if(!/^[0-9a-f]{64}$/.test(s)) throw new Error('Ожидался SHA-256 hash');
|
||||
const out=new Uint8Array(32); for(let i=0;i<32;i++) out[i]=parseInt(s.slice(i*2,i*2+2),16); return out;
|
||||
}
|
||||
function bytesToHex(bytes) { return Array.from(bytes || [], (b)=>b.toString(16).padStart(2,'0')).join(''); }
|
||||
function normalizeComment(value) { return String(value || '').trim().replace(/\r\n/g,'\n').replace(/\r/g,'\n'); }
|
||||
function readFrameTimestampMs(frame) {
|
||||
if (!(frame instanceof Uint8Array) || frame.length < 82) throw new Error('Некорректный SHiNE Frame');
|
||||
const seconds = new DataView(frame.buffer, frame.byteOffset, frame.byteLength).getBigInt64(74, false);
|
||||
return Number(seconds * 1000n);
|
||||
function readStoredPair(block) {
|
||||
const {coreDataItem,contentDataItem}=unpackCoreContent(base64ToBytes(block.blockBytesB64));
|
||||
return {core:decodeCore(parseAns104DataItem(coreDataItem).data),content:decodeContent(parseAns104DataItem(contentDataItem).data)};
|
||||
}
|
||||
function readFrameType(frame) {
|
||||
if (!(frame instanceof Uint8Array) || frame.length < 88) throw new Error('Некорректный SHiNE Frame');
|
||||
const view=new DataView(frame.buffer,frame.byteOffset,frame.byteLength);
|
||||
return { type:view.getUint16(82,false), subType:view.getUint16(84,false) };
|
||||
}
|
||||
function readExplicitLinePrefix(frame) {
|
||||
if (!(frame instanceof Uint8Array) || frame.length < 132) throw new Error('Некорректный line Frame');
|
||||
const view=new DataView(frame.buffer,frame.byteOffset,frame.byteLength);
|
||||
return {
|
||||
lineCode:view.getInt32(88,false),
|
||||
prevLineNumber:view.getInt32(92,false),
|
||||
prevLineHash:bytesToHex(frame.slice(96,128)),
|
||||
lineSequence:view.getInt32(128,false),
|
||||
};
|
||||
}
|
||||
function makeForkBody({ lineCode=0, prevLineNumber, prevLineHash, lineSequence, oldBlockchainKeyB64, forkPointBlock, forkPointHash, forkPointTimestampMs, parentTipBlock, parentTipHash, parentTipTimestampMs, reasonCode, comment }) {
|
||||
function timestampMs(pair) { return Number(pair.core.timestamp * 1000n); }
|
||||
function makeForkBody({ oldBlockchainKeyB64, forkPointBlock, forkPointHash, forkPointTimestampMs, parentTipBlock, parentTipHash, parentTipTimestampMs, reasonCode, comment }) {
|
||||
const oldKey=base64ToBytes(oldBlockchainKeyB64); if(oldKey.length!==32) throw new Error('Некорректный старый blockchain key');
|
||||
const c=TE.encode(normalizeComment(comment)); if(c.length>1024) throw new Error('Комментарий больше 1024 UTF-8 байт');
|
||||
const discarded=Number(parentTipBlock)-Number(forkPointBlock);
|
||||
if(discarded<0) throw new Error('Некорректная точка fork');
|
||||
if(Number(lineCode)!==0 || !Number.isInteger(Number(prevLineNumber)) || Number(prevLineNumber)<0 || !Number.isInteger(Number(lineSequence)) || Number(lineSequence)<1) {
|
||||
throw new Error('Некорректная TECH line для FORK');
|
||||
}
|
||||
return concat(be32(lineCode),be32(prevLineNumber),hexToBytes(prevLineHash),be32(lineSequence),oldKey,be32(forkPointBlock),hexToBytes(forkPointHash),be64(forkPointTimestampMs),be32(parentTipBlock),hexToBytes(parentTipHash),be64(parentTipTimestampMs),be32(discarded),Uint8Array.of(Number(reasonCode)),be16(c.length),c);
|
||||
return concat(oldKey,be32(forkPointBlock),hexToBytes(forkPointHash),be64(forkPointTimestampMs),be32(parentTipBlock),hexToBytes(parentTipHash),be64(parentTipTimestampMs),be32(discarded),Uint8Array.of(Number(reasonCode)),be16(c.length),c);
|
||||
}
|
||||
function makeFrame({ prevHash, back32Hash=ZERO_HASH, blockNumber, type, subType, version=1, body, timestampMs=Date.now() }) {
|
||||
const bodyBytes=body || new Uint8Array(0);
|
||||
const size=2+32+32+4+4+8+2+2+2+bodyBytes.length;
|
||||
return concat(be16(1),hexToBytes(prevHash),hexToBytes(back32Hash),be32(size),be32(blockNumber),be64(Math.floor(Number(timestampMs)/1000)),be16(type),be16(subType),be16(version),bodyBytes);
|
||||
}
|
||||
|
||||
export const KEY_ROTATION_REASONS = Object.freeze([
|
||||
{ code:1, label:'Обычная смена пароля / ключей' },
|
||||
{ code:2, label:'Возможная компрометация ключей' },
|
||||
@@ -99,19 +74,13 @@ export class KeyRotationClient {
|
||||
async #resolveTechLineTail(source, cutoff) {
|
||||
for(let n=Number(cutoff);n>0;n--) {
|
||||
const block=await this.getBlock(source,n);
|
||||
const parsed=parseAns104DataItem(base64ToBytes(block.blockBytesB64));
|
||||
const kind=readFrameType(parsed.data);
|
||||
const {core,content:kind}=readStoredPair(block);
|
||||
if(kind.type!==0 || (kind.subType!==1 && kind.subType!==TECH_FORK_SUBTYPE)) continue;
|
||||
const line=readExplicitLinePrefix(parsed.data);
|
||||
if(line.lineCode!==0 || line.lineSequence<1) throw new Error(`Некорректная TECH line в блоке #${n}`);
|
||||
return {
|
||||
prevLineNumber:n,
|
||||
prevLineHash:String(block.blockHash||''),
|
||||
lineSequence:line.lineSequence+1,
|
||||
};
|
||||
if(core.line?.lineCode!==SHINE_CORE_LINE_TECH) throw new Error(`Некорректная TECH line в блоке #${n}`);
|
||||
return {prevLineNumber:n,prevLineHash:String(block.blockHash||'')};
|
||||
}
|
||||
const header=await this.getBlock(source,0);
|
||||
return { prevLineNumber:0, prevLineHash:String(header.blockHash||''), lineSequence:1 };
|
||||
return { prevLineNumber:0, prevLineHash:String(header.blockHash||'') };
|
||||
}
|
||||
|
||||
async copyCandidateChain({ rotation, newBundle, onProgress=()=>{} }) {
|
||||
@@ -125,30 +94,25 @@ export class KeyRotationClient {
|
||||
const forkSource=await this.getBlock(source,cutoff);
|
||||
const tipBlock=Number(rotation.sourceTipBlock);
|
||||
const tipSource=tipBlock===cutoff?forkSource:await this.getBlock(source,tipBlock);
|
||||
const forkParsed=parseAns104DataItem(base64ToBytes(forkSource.blockBytesB64));
|
||||
const tipParsed=parseAns104DataItem(base64ToBytes(tipSource.blockBytesB64));
|
||||
const forkParsed=readStoredPair(forkSource);
|
||||
const tipParsed=readStoredPair(tipSource);
|
||||
const techTail=await this.#resolveTechLineTail(source,cutoff);
|
||||
const forkBody=makeForkBody({
|
||||
lineCode:0, prevLineNumber:techTail.prevLineNumber, prevLineHash:techTail.prevLineHash, lineSequence:techTail.lineSequence,
|
||||
oldBlockchainKeyB64:rotation.oldBlockchainKey, forkPointBlock:cutoff, forkPointHash:rotation.forkFromHash,
|
||||
forkPointTimestampMs:readFrameTimestampMs(forkParsed.data), parentTipBlock:tipBlock, parentTipHash:rotation.sourceTipHash,
|
||||
parentTipTimestampMs:readFrameTimestampMs(tipParsed.data), reasonCode:rotation.reasonCode, comment:rotation.comment,
|
||||
forkPointTimestampMs:timestampMs(forkParsed), parentTipBlock:tipBlock, parentTipHash:rotation.sourceTipHash,
|
||||
parentTipTimestampMs:timestampMs(tipParsed), reasonCode:rotation.reasonCode, comment:rotation.comment,
|
||||
});
|
||||
const techTimestampMs=Number(rotation.createdAtMs)||readFrameTimestampMs(tipParsed.data)+1000;
|
||||
const techTimestampMs=Number(rotation.createdAtMs)||timestampMs(tipParsed)+1000;
|
||||
const techBlockNumber=cutoff+1;
|
||||
const techBack32Hash=techBlockNumber<32?ZERO_HASH:String((await this.getBlock(source,techBlockNumber-32)).blockHash||'');
|
||||
const techFrame=makeFrame({prevHash:rotation.forkFromHash,back32Hash:techBack32Hash,blockNumber:techBlockNumber,type:0,subType:TECH_FORK_SUBTYPE,version:1,body:forkBody,timestampMs:techTimestampMs});
|
||||
const techRaw=await createAns104DataItem({owner32,privateKey,data:techFrame,tags:[{name:SHINE_APP_TAG_NAME,value:SHINE_APP_TAG_VALUE},{name:SHINE_TYPE_TAG_NAME,value:'tech'}]});
|
||||
const pair=await signCoreContentPair({owner32,privateKey,blockNumber:techBlockNumber,
|
||||
timestamp:Math.floor(techTimestampMs/1000),prevCoreHash32:hexToBytes(rotation.forkFromHash),
|
||||
content:{type:0,subType:TECH_FORK_SUBTYPE,version:1,body:forkBody},
|
||||
line:{lineCode:SHINE_CORE_LINE_TECH,prevLineBlockNumber:techTail.prevLineNumber,prevLineCoreHash32:hexToBytes(techTail.prevLineHash)}});
|
||||
const techRaw=packCoreContent(pair.coreDataItem,pair.contentDataItem);
|
||||
await this.addCandidate({blockNumber:techBlockNumber,prevBlockHash:rotation.forkFromHash,blockBytesB64:bytesToBase64(techRaw)});
|
||||
onProgress({phase:'copy',current:1,total:1});
|
||||
}
|
||||
|
||||
async #sourcePrevHash(source, blockNumber) {
|
||||
if(blockNumber<=0) return ZERO_HASH;
|
||||
const prev=await this.getBlock(source,blockNumber-1);
|
||||
return String(prev.blockHash||'');
|
||||
}
|
||||
|
||||
async waitUntilPublished({ timeoutMs=180000, onProgress=()=>{} }={}) {
|
||||
const started=Date.now();
|
||||
while(Date.now()-started<timeoutMs) {
|
||||
|
||||
@@ -5,3 +5,12 @@ export const SHINE_APP_TAG_NAME = 'App';
|
||||
export const SHINE_APP_TAG_VALUE = SHINE_PROTOCOL_NAMESPACE;
|
||||
export const SHINE_CHANNEL_TAG_NAME = 'c';
|
||||
export const SHINE_TYPE_TAG_NAME = 't';
|
||||
|
||||
// Активная эпоха CORE/CONTENT.
|
||||
export const SHINE_CORE_NAMESPACE = 'test5595';
|
||||
export const SHINE_CORE_NUMBER_TAG_NAME = 'n';
|
||||
export const SHINE_CORE_LINE_TAG_NAME = 'l';
|
||||
export const SHINE_CORE_LINE_PROFILE = 2147483645;
|
||||
export const SHINE_CORE_LINE_CONNECTION = 2147483646;
|
||||
export const SHINE_CORE_LINE_TECH = 2147483647;
|
||||
export const SHINE_CORE_MAX_BLOCK_NUMBER = 2147482623;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { unpackCoreContent } from './core-content.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
const SNAPSHOT_STORAGE_KEY = 'shine-ui-blockchain-snapshot-v1';
|
||||
|
||||
@@ -77,8 +78,10 @@ export async function buildBlockchainSnapshotFile({
|
||||
throw new Error(t('remaining.blockchain_snapshot.no_blocks_available_on_the_server_for_a_snapshot'));
|
||||
}
|
||||
|
||||
const parts = [];
|
||||
let totalBytes = 0;
|
||||
// Snapshot v2: magic followed by u32 BE container length + original container.
|
||||
const magic = new TextEncoder().encode('SHINECC2');
|
||||
const parts = [magic];
|
||||
let totalBytes = magic.length;
|
||||
for (let blockNumber = 0; blockNumber <= maxBlockNumber; blockNumber += 1) {
|
||||
const response = await authService.ws.request('GetBlockchainBlock', {
|
||||
blockchainName: cleanBlockchainName,
|
||||
@@ -89,8 +92,11 @@ export async function buildBlockchainSnapshotFile({
|
||||
throw new Error(`Не удалось скачать блок ${blockNumber}: ${message}`);
|
||||
}
|
||||
const blockBytes = decodeBase64ToBytes(response?.payload?.blockBytesB64 || '');
|
||||
parts.push(blockBytes);
|
||||
totalBytes += blockBytes.length;
|
||||
unpackCoreContent(blockBytes);
|
||||
const length = new Uint8Array(4);
|
||||
new DataView(length.buffer).setUint32(0, blockBytes.length);
|
||||
parts.push(length, blockBytes);
|
||||
totalBytes += 4 + blockBytes.length;
|
||||
}
|
||||
|
||||
const file = new File(parts, `${cleanBlockchainName}.shine-blockchain`, {
|
||||
|
||||
@@ -1,57 +1,12 @@
|
||||
# SHiNE Arweave Viewer v2 — ANS-104 / Frame v1
|
||||
# SHiNE Arweave Viewer — CORE/CONTENT Minimal (App=test5595)
|
||||
|
||||
Новая версия viewer для формата, где каждый пользовательский блок хранится в Arweave как отдельный ANS-104 DataItem, а `data` DataItem содержит один `SHiNE Frame v1`.
|
||||
Самостоятельный `index.html`, прежний интерфейс. По `?login=<login>` получает ключ через Solana PDA, по `?key=<base58>` читает напрямую. `&channel=<channel>` — локальный фильтр после выборки автора.
|
||||
|
||||
Основной файл: `index.html`.
|
||||
- GraphQL: owner + App=test5595, страницы HEIGHT_DESC; сертификаты t=reg исключаются (нет n).
|
||||
- По каждому CORE скачивает payload и затем CONTENT по подписанному в CORE ID. Проверяет размер CORE, n/l/App из индекса и SHA-256 CONTENT, разбирает смысловое тело, показывает хеши и ссылки CORE. Кэш новой эпохи отделён от Frame.
|
||||
- Как и прежний standalone Viewer, работает с gateway payload, **не** с полным ANS-104. Подписи и SHA-256 подписи (DataItem ID) не проверены локально; индекс owner не является доказательством подписи. Интерфейс это явно сообщает. Для полной проверки использовать серверный импорт или проверку подписанной пары в основном клиенте.
|
||||
- Выборка относится к одному ключу; Viewer не восстанавливает каноническую историю через предыдущие ключи FORK. Отсутствующий предок отмечается как непроверенный. Не использовать Viewer для определения канонической ветки.
|
||||
- При отсутствии CONTENT загрузка сообщает ошибку, а не показывает неполное событие как валидное.
|
||||
- Историческая копия v1 в `history/`; исходная версия текущего Viewer находится в архиве `reference/`.
|
||||
|
||||
## Быстрый запуск
|
||||
|
||||
Через логин (ключ берётся из Solana PDA):
|
||||
|
||||
```text
|
||||
index.html?login=aidarkc&channel=books
|
||||
```
|
||||
|
||||
Напрямую через blockchain public key, без Solana:
|
||||
|
||||
```text
|
||||
index.html?key=<BASE58_BLOCKCHAIN_PUBLIC_KEY>&channel=books
|
||||
```
|
||||
|
||||
Дополнительные параметры:
|
||||
|
||||
```text
|
||||
&arweaveGateway=https://arweave.net
|
||||
&solanaRpc=https://api.mainnet-beta.solana.com
|
||||
```
|
||||
|
||||
`channel` можно не передавать. Тогда viewer ищет все DataItem пользователя с `App=test5592` и строит список каналов из найденных блоков.
|
||||
|
||||
## Что делает viewer
|
||||
|
||||
1. Если передан `login`, вычисляет PDA `user_login=<login>` программы `SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6` и читает `blockchainKey`.
|
||||
2. Если передан `key`, использует его напрямую и не обращается к Solana.
|
||||
3. Из Ed25519/Solana public key вычисляет Arweave owner address как `base64url(SHA-256(pubkey32))`.
|
||||
4. Делает Arweave GraphQL запрос по owner + `App=test5592`; `channel` применяется локально после загрузки авторского блокчейна.
|
||||
5. Загружает payload каждого DataItem через gateway `/<DataItemId>`.
|
||||
6. Разбирает payload как SHiNE Frame v1 (`frameCode=0x0001`, header 88 bytes).
|
||||
7. Дедуплицирует повторно опубликованные одинаковые пользовательские блоки по SHA-256 Frame v1.
|
||||
8. Восстанавливает канал/сообщения тем же body parser, который использовал старый viewer.
|
||||
|
||||
## Важно
|
||||
|
||||
При фильтрации по конкретному `channel` viewer получает только блоки с соответствующим тегом `c`. Поэтому он не заявляет полную проверку глобальной `prevHash`-цепочки пользователя: между двумя блоками одного канала могут существовать блоки других каналов. SHA-256 каждого загруженного Frame вычисляется локально.
|
||||
|
||||
Старый `shine-solana-arweave-viewer/` не изменяется; новая версия лежит отдельно в `shine-solana-arweave-viewer-v2/`.
|
||||
|
||||
|
||||
## Проверка данных (v3.3)
|
||||
Нижняя строка показывает краткий итог доступных проверок. Нажатие на неё или `⋮ → Проверка данных` открывает отдельный экран:
|
||||
- локально вычисленный SHA-256 каждого SHiNE Frame;
|
||||
- `prevHash` общей цепочки, когда предыдущий глобальный блок загружен;
|
||||
- `prevLineHash` канальной цепочки, когда указанный предыдущий блок загружен;
|
||||
- наличие DataItem в выборке Arweave owner соответствующего blockchain key;
|
||||
- разрывы «нет данных» отдельно от доказанных несовпадений;
|
||||
- честный статус ANS-104 signature: gateway payload/GraphQL не содержит сырой подписи, поэтому она не помечается как локально перепроверенная.
|
||||
|
||||
`○ нет данных` не является ошибкой. `⚠` появляется только при фактическом несовпадении доступных хэшей.
|
||||
Локальная проверка: `node --test shine-UI/tests/m6-viewer-pair.test.mjs` из корня проекта. Живая загрузка через gateway и UI вручную — отдельный интеграционный тест.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# SHiNE Arweave Viewer v3
|
||||
|
||||
Viewer нового per-action Arweave формата SHiNE.
|
||||
Viewer CORE/CONTENT, App=test5595. Границы проверки подписей и FORK: [README.md](README.md).
|
||||
|
||||
## URL
|
||||
- `?login=<login>&channel=<channel>` — получает blockchain key через Solana PDA, затем читает Arweave.
|
||||
@@ -15,12 +15,12 @@ Viewer нового per-action Arweave формата SHiNE.
|
||||
- выключение кэша удаляет сохранённые данные каналов;
|
||||
- одна нижняя status bar, по нажатию — подробный журнал;
|
||||
- GraphQL читает от новых Arweave записей к старым (`HEIGHT_DESC`);
|
||||
- до 6 параллельных загрузок Frame;
|
||||
- до 6 параллельных загрузок пар CORE/CONTENT;
|
||||
- отображение известных типов и raw-представление любых неизвестных блоков в режиме `Блоки`;
|
||||
- лайки намеренно не отображаются.
|
||||
|
||||
Кэш использует browser localStorage и сериализует BigInt-поля Frame явно. Тема/RPC/gateway являются настройками и не удаляются при отключении кэша.
|
||||
Кэш использует browser localStorage и сериализует BigInt-поля явно. Тема/RPC/gateway являются настройками и не удаляются при отключении кэша.
|
||||
|
||||
## V3.1 — streaming reverse loading
|
||||
|
||||
Arweave history is now processed page-by-page in `HEIGHT_DESC` order. The first GraphQL page (up to 100 DataItems) is downloaded, parsed and rendered immediately. Older pages are then fetched and merged in the background. The bottom status line shows the currently available block range while history expands toward the beginning. Each completed page is also persisted when cache is enabled.
|
||||
Arweave history is now processed page-by-page in `HEIGHT_DESC` order. The first GraphQL page (up to 100 indexed CORE DataItems) is downloaded, parsed and rendered immediately. Older pages are then fetched and merged in the background. The bottom status line shows the currently available block range while history expands toward the beginning. Each completed page is also persisted when cache is enabled.
|
||||
|
||||
@@ -1097,10 +1097,9 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
const BLOCK_TYPE_SESSIONS = 50;
|
||||
const BLOCK_TYPE_TRUSTED_STATE = 70;
|
||||
const BLOCK_TYPE_ARCHIVE_HEAD = 80;
|
||||
const BCH_FRAME_HEADER_SIZE = 88;
|
||||
const BCH_FRAME_CODE_V1 = 0x0001;
|
||||
const CORE_MAX_NUMBER = 2147482623;
|
||||
// Transport namespace актуального standalone Viewer.
|
||||
const SHINE_PROTOCOL_NAMESPACE = 'test5592';
|
||||
const SHINE_PROTOCOL_NAMESPACE = 'test5595';
|
||||
const SHINE_ARWEAVE_APP_TAG = SHINE_PROTOCOL_NAMESPACE;
|
||||
const SHINE_ARWEAVE_CHANNEL_TAG = 'c';
|
||||
const BCH_TYPE_TECH = 0;
|
||||
@@ -1938,16 +1937,16 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
throw new Error(`HEADER: неожиданный tag ${tag}`);
|
||||
}
|
||||
const login = reader.readUtf8U8();
|
||||
const initialBlockchainKey = base64Url(reader.readBytes(32));
|
||||
reader.ensureDone();
|
||||
return { kind: 'header', login, tag };
|
||||
return { kind: 'header', login, tag, initialBlockchainKey };
|
||||
}
|
||||
|
||||
function parseCreateChannelBody(bodyBytes) {
|
||||
function parseCreateChannelBody(bodyBytes, line) {
|
||||
const reader = makeBigEndianReader(bodyBytes, 'CREATE_CHANNEL');
|
||||
const lineCode = reader.readI32();
|
||||
const prevLineNumber = reader.readI32();
|
||||
const prevLineHashHex = bytesToHex(reader.readBytes(32));
|
||||
const thisLineNumber = reader.readI32();
|
||||
if (!line) throw new Error('Missing CORE line');
|
||||
const { lineCode, prevLineNumber, prevLineHashHex } = line;
|
||||
const thisLineNumber = null; // not a signed field
|
||||
const channelName = reader.readUtf8U8();
|
||||
const channelDescription = reader.readUtf8U16();
|
||||
const channelTypeCode = reader.readU16();
|
||||
@@ -1966,12 +1965,11 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
};
|
||||
}
|
||||
|
||||
function parseTextLineBody(subType, bodyBytes) {
|
||||
function parseTextLineBody(subType, bodyBytes, line) {
|
||||
const reader = makeBigEndianReader(bodyBytes, 'TEXT_LINE');
|
||||
const lineCode = reader.readI32();
|
||||
const prevLineNumber = reader.readI32();
|
||||
const prevLineHashHex = bytesToHex(reader.readBytes(32));
|
||||
const thisLineNumber = reader.readI32();
|
||||
if (!line) throw new Error('Missing CORE line');
|
||||
const { lineCode, prevLineNumber, prevLineHashHex } = line;
|
||||
const thisLineNumber = null; // not a signed field
|
||||
let targetBlockchainName = '';
|
||||
let targetBlockNumber = null;
|
||||
let targetBlockHashHex = '';
|
||||
@@ -1980,7 +1978,10 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
targetBlockNumber = reader.readI32();
|
||||
targetBlockHashHex = bytesToHex(reader.readBytes(32));
|
||||
} else if (subType === BCH_SUBTYPE_TEXT_REPOST) {
|
||||
targetBlockchainName = reader.readUtf8U8();
|
||||
const targetLogin = reader.readUtf8U8();
|
||||
const targetFork = reader.readU16();
|
||||
if(targetFork<1 || targetFork>999) throw new Error('Invalid target fork');
|
||||
targetBlockchainName = `${targetLogin.toLowerCase()}-${String(targetFork).padStart(3,'0')}`;
|
||||
targetBlockNumber = reader.readI32();
|
||||
targetBlockHashHex = bytesToHex(reader.readBytes(32));
|
||||
}
|
||||
@@ -2005,7 +2006,10 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
const reader = makeBigEndianReader(bodyBytes, 'TEXT_REPLY');
|
||||
let targetBlockchainName = '';
|
||||
if (subType === BCH_SUBTYPE_TEXT_REPLY) {
|
||||
targetBlockchainName = reader.readUtf8U8();
|
||||
const targetLogin = reader.readUtf8U8();
|
||||
const targetFork = reader.readU16();
|
||||
if(targetFork<1 || targetFork>999) throw new Error('Invalid target fork');
|
||||
targetBlockchainName = `${targetLogin.toLowerCase()}-${String(targetFork).padStart(3,'0')}`;
|
||||
}
|
||||
const targetBlockNumber = reader.readI32();
|
||||
const targetBlockHashHex = bytesToHex(reader.readBytes(32));
|
||||
@@ -2021,7 +2025,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
};
|
||||
}
|
||||
|
||||
function parseBlockchainBody(type, subType, version, bodyBytes) {
|
||||
function parseBlockchainBody(type, subType, version, bodyBytes, line) {
|
||||
if (version !== 1) {
|
||||
return { kind: 'unsupported', reason: `Неподдерживаемая версия body ${version}` };
|
||||
}
|
||||
@@ -2029,19 +2033,20 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
return parseHeaderBody(bodyBytes);
|
||||
}
|
||||
if (type === BCH_TYPE_TECH && subType === BCH_SUBTYPE_CREATE_CHANNEL) {
|
||||
return parseCreateChannelBody(bodyBytes);
|
||||
return parseCreateChannelBody(bodyBytes, line);
|
||||
}
|
||||
if (type === BCH_TYPE_TEXT && [
|
||||
BCH_SUBTYPE_TEXT_POST,
|
||||
BCH_SUBTYPE_TEXT_EDIT_POST,
|
||||
BCH_SUBTYPE_TEXT_REPOST,
|
||||
BCH_SUBTYPE_TEXT_CHANNEL_META,
|
||||
92, // CHANNEL_DELETE
|
||||
BCH_SUBTYPE_TEXT_ENTRYPOINT,
|
||||
BCH_SUBTYPE_TEXT_EXERCISE,
|
||||
BCH_SUBTYPE_TEXT_SERVICE,
|
||||
BCH_SUBTYPE_TEXT_COURSE,
|
||||
].includes(subType)) {
|
||||
return parseTextLineBody(subType, bodyBytes);
|
||||
return parseTextLineBody(subType, bodyBytes, line);
|
||||
}
|
||||
if (type === BCH_TYPE_TEXT && [BCH_SUBTYPE_TEXT_REPLY, BCH_SUBTYPE_TEXT_EDIT_REPLY].includes(subType)) {
|
||||
return parseTextReplyBody(subType, bodyBytes);
|
||||
@@ -2049,41 +2054,34 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
return { kind: 'unsupported', reason: `Неподдерживаемый блок type=${type} subType=${subType} version=${version}` };
|
||||
}
|
||||
|
||||
async function parseBlockchainBlock(fullBytes) {
|
||||
// New Arweave format: gateway /<DataItemId> returns the DataItem payload,
|
||||
// which is exactly one SHiNE Frame v1. The ANS-104 signature/owner/tags
|
||||
// live around this payload and are indexed by Arweave GraphQL.
|
||||
const bytes = fullBytes instanceof Uint8Array ? fullBytes : new Uint8Array(fullBytes || []);
|
||||
if (bytes.length < BCH_FRAME_HEADER_SIZE) {
|
||||
throw new Error(`SHiNE Frame v1 слишком короткий: ${bytes.length}`);
|
||||
}
|
||||
const frameCode = readUint16BE(bytes, 0);
|
||||
if (frameCode !== BCH_FRAME_CODE_V1) {
|
||||
throw new Error(`Неожиданный frameCode 0x${frameCode.toString(16)} (ожидался 0x0001)`);
|
||||
}
|
||||
const blockSize = readInt32BE(bytes, 66);
|
||||
if (blockSize !== bytes.length || blockSize < BCH_FRAME_HEADER_SIZE) {
|
||||
throw new Error(`Frame size mismatch: blockSize=${blockSize}, actual=${bytes.length}`);
|
||||
}
|
||||
const hashBytes = await digestSha256(bytes);
|
||||
const type = readUint16BE(bytes, 82);
|
||||
const subType = readUint16BE(bytes, 84);
|
||||
const version = readUint16BE(bytes, 86);
|
||||
const bodyBytes = bytes.slice(BCH_FRAME_HEADER_SIZE);
|
||||
const body = parseBlockchainBody(type, subType, version, bodyBytes);
|
||||
return {
|
||||
frameCode,
|
||||
prevHashHex: bytesToHex(bytes.slice(2, 34)),
|
||||
back32HashHex: bytesToHex(bytes.slice(34, 66)),
|
||||
blockSize,
|
||||
blockNumber: readInt32BE(bytes, 70),
|
||||
timestampSec: readInt64BE(bytes, 74),
|
||||
type,
|
||||
subType,
|
||||
version,
|
||||
body,
|
||||
hashHex: bytesToHex(hashBytes),
|
||||
};
|
||||
// Gateway payloads are not raw ANS-104: hash linkage is checked, signatures are NOT.
|
||||
function parseCorePayload(bytes) {
|
||||
if (![109,149].includes(bytes.length) || bytes[0] !== 1) throw new Error('Invalid CORE payload');
|
||||
const blockNumber = readInt32BE(bytes,33), timestampSec = readInt64BE(bytes,37);
|
||||
const prevHashHex = bytesToHex(bytes.slice(1,33));
|
||||
if (blockNumber < 0 || blockNumber > CORE_MAX_NUMBER || timestampSec < 0 || !Number.isSafeInteger(timestampSec)) throw new Error('Invalid CORE number/timestamp');
|
||||
const line = bytes.length === 149 ? {lineCode:readInt32BE(bytes,109),prevLineNumber:readInt32BE(bytes,113),prevLineHashHex:bytesToHex(bytes.slice(117,149))} : null;
|
||||
if (blockNumber === 0 && (line || !/^0{64}$/.test(prevHashHex))) throw new Error('Invalid HEADER CORE');
|
||||
if (line && (line.lineCode < 0 || (line.lineCode > CORE_MAX_NUMBER && ![2147483645,2147483646,2147483647].includes(line.lineCode)) || line.prevLineNumber < 0 || line.prevLineNumber >= blockNumber || (line.lineCode > 0 && line.lineCode <= CORE_MAX_NUMBER && line.prevLineNumber < line.lineCode))) throw new Error('Invalid CORE line');
|
||||
return {blockNumber,timestampSec,prevHashHex,line,contentHashHex:bytesToHex(bytes.slice(45,77)),contentDataItemId:base64Url(bytes.slice(77,109))};
|
||||
}
|
||||
async function parseBlockchainBlock(coreBytes, contentBytes) {
|
||||
const core = parseCorePayload(coreBytes);
|
||||
if (contentBytes.length < 7 || contentBytes.length > 8*1024*1024-117 || contentBytes[0] !== 1 || bytesToHex(await digestSha256(contentBytes)) !== core.contentHashHex) throw new Error('CONTENT hash/format mismatch');
|
||||
const type=readUint16BE(contentBytes,1),subType=readUint16BE(contentBytes,3),version=readUint16BE(contentBytes,5);
|
||||
if (version !== 1 || (type===0 && subType===0)!==(core.blockNumber===0)) throw new Error('Invalid CONTENT version/HEADER');
|
||||
const channelText=type===1 && [10,11,50,90,92,100,110,120,130].includes(subType);
|
||||
const expectedLine=type===0&&subType!==0?2147483647:type===3?2147483646:type===4?2147483645:null;
|
||||
if (channelText ? !core.line||core.line.lineCode>CORE_MAX_NUMBER : expectedLine===null ? !!core.line : core.line?.lineCode!==expectedLine) throw new Error('CONTENT/CORE line mismatch');
|
||||
const body=parseBlockchainBody(type,subType,version,contentBytes.slice(7),core.line);
|
||||
return {...core,type,subType,version,body,blockSize:coreBytes.length+contentBytes.length,hashHex:bytesToHex(await digestSha256(coreBytes)),contentHashChecked:true};
|
||||
}
|
||||
|
||||
function checkIndexedCoreTags(node, core) {
|
||||
const tags=node.tags||[];
|
||||
const expected={App:SHINE_PROTOCOL_NAMESPACE,n:String(core.blockNumber)};
|
||||
if(core.line) expected.l=({2147483645:'P',2147483646:'C',2147483647:'T'})[core.line.lineCode]??String(core.line.lineCode);
|
||||
if(tags.length!==Object.keys(expected).length || Object.entries(expected).some(([name,value])=>tags.filter(t=>t.name===name&&t.value===value).length!==1)) throw new Error('CORE index tags mismatch');
|
||||
}
|
||||
|
||||
function refKey(blockchainName, blockNumber, blockHashHex) {
|
||||
@@ -2360,7 +2358,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
allNodesByKey.set(nodeKey, node);
|
||||
const targetBlockchainName = block.body.targetBlockchainName || blockchainName;
|
||||
const targetKey = refKey(targetBlockchainName, block.body.targetBlockNumber, block.body.targetBlockHashHex);
|
||||
const parentNode = allNodesByKey.get(targetKey);
|
||||
const parentNode = allNodesByKey.get(targetKey) || (blockchainName==='main' && targetBlockchainName.startsWith(ownerLogin.toLowerCase()+'-') ? allNodesByKey.get(refKey(blockchainName,block.body.targetBlockNumber,block.body.targetBlockHashHex)) : null);
|
||||
if (parentNode) {
|
||||
parentNode.replies.push(node);
|
||||
parentNode.repliesCount += 1;
|
||||
@@ -2442,7 +2440,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
const txs = json?.data?.transactions;
|
||||
if (!txs?.edges) throw new Error('Arweave GraphQL не вернул transactions.edges');
|
||||
page += 1;
|
||||
const items = txs.edges.map(edge => edge.node);
|
||||
const items = txs.edges.map(edge => edge.node).filter(node => (node.tags || []).some(tag => tag.name === 'n')); // registration certificates are not CORE
|
||||
const hasNextPage = !!txs.pageInfo?.hasNextPage;
|
||||
after = hasNextPage ? txs.edges.at(-1)?.cursor || null : null;
|
||||
if (hasNextPage && !after) throw new Error('Arweave GraphQL: hasNextPage без cursor');
|
||||
@@ -2460,7 +2458,7 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
return { ownerAddress, items };
|
||||
}
|
||||
|
||||
async function loadArweaveFrames(gatewayBaseUrl, nodes, onProgress) {
|
||||
async function loadArweavePairs(gatewayBaseUrl, nodes, onProgress) {
|
||||
const gateway = baseUrl(gatewayBaseUrl);
|
||||
const blocks = [];
|
||||
let totalBytes = 0;
|
||||
@@ -2473,9 +2471,14 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
const node = nodes[index];
|
||||
const response = await fetch(`${gateway}/${node.id}`, { cache: 'no-store' });
|
||||
if (!response.ok) throw new Error(`Arweave ${node.id}: HTTP ${response.status}`);
|
||||
const frame = new Uint8Array(await response.arrayBuffer());
|
||||
totalBytes += frame.length;
|
||||
const block = await parseBlockchainBlock(frame);
|
||||
const coreBytes = new Uint8Array(await response.arrayBuffer());
|
||||
const core = parseCorePayload(coreBytes);
|
||||
checkIndexedCoreTags(node, core);
|
||||
const contentResponse = await fetch(`${gateway}/${core.contentDataItemId}`, { cache: 'no-store' });
|
||||
if (!contentResponse.ok) throw new Error(`CONTENT ${core.contentDataItemId}: HTTP ${contentResponse.status}`);
|
||||
const contentBytes = new Uint8Array(await contentResponse.arrayBuffer());
|
||||
totalBytes += coreBytes.length + contentBytes.length;
|
||||
const block = await parseBlockchainBlock(coreBytes, contentBytes);
|
||||
block.arweaveId = node.id;
|
||||
block.arweaveHeight = node.block?.height ?? null;
|
||||
block.arweaveOwnerAddress = node.owner?.address || '';
|
||||
@@ -2498,21 +2501,6 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
return { blocks: unique, totalBytes };
|
||||
}
|
||||
|
||||
async function parseBlockchainSnapshotBytes(bytes, blockchainName, fallbackLogin, gatewayBaseUrl) {
|
||||
// Kept for local/debug use: concatenated Frame v1 values can still be inspected.
|
||||
const data = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || []);
|
||||
const blocks = [];
|
||||
let offset = 0;
|
||||
while (offset < data.length) {
|
||||
if (data.length - offset < BCH_FRAME_HEADER_SIZE) throw new Error(`Frame обрывается на смещении ${offset}`);
|
||||
const blockSize = readInt32BE(data, offset + 66);
|
||||
if (blockSize < BCH_FRAME_HEADER_SIZE || offset + blockSize > data.length) throw new Error(`Некорректный blockSize ${blockSize} на смещении ${offset}`);
|
||||
blocks.push(await parseBlockchainBlock(data.slice(offset, offset + blockSize)));
|
||||
offset += blockSize;
|
||||
}
|
||||
return buildChannelSnapshot(blocks, blockchainName, fallbackLogin, gatewayBaseUrl);
|
||||
}
|
||||
|
||||
async function checkSolanaEndpoint(endpoint) {
|
||||
const rpc = normalizeUrl(endpoint);
|
||||
if (!rpc) throw new Error('Не указан Solana RPC');
|
||||
@@ -3179,10 +3167,10 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
ownerAddress = page.ownerAddress;
|
||||
pageCount = page.page;
|
||||
discovered += page.items.length;
|
||||
if (!page.items.length && pageCount === 1) break;
|
||||
if (!page.items.length) continue;
|
||||
|
||||
setContentStatus('loading', `Загрузка · найдено ${discovered} · страница ${pageCount} · скачиваю ${page.items.length}`);
|
||||
const loaded = await loadArweaveFrames(gateway, page.items, function (progress) {
|
||||
const loaded = await loadArweavePairs(gateway, page.items, function (progress) {
|
||||
setContentStatus('loading', `Загрузка · ${allBlocks.length + progress.completed} блоков · страница ${pageCount} · ${formatBytes(totalBytes + progress.totalBytes)}`);
|
||||
});
|
||||
totalBytes += loaded.totalBytes;
|
||||
@@ -3237,9 +3225,9 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
v3SaveCache(blockchainKey, requestedChannel, allBlocks);
|
||||
const minBlock = allBlocks[0]?.blockNumber ?? '?';
|
||||
const maxBlock = allBlocks[allBlocks.length - 1]?.blockNumber ?? '?';
|
||||
setContentStatus('ok', `✓ Загружено ${allBlocks.length} блоков · #${maxBlock} → #${minBlock} · ${formatBytes(totalBytes)}`);
|
||||
setContentStatus('ok', `Загружено ${allBlocks.length} пар (подписи не проверены) · #${maxBlock} → #${minBlock} · ${formatBytes(totalBytes)}`);
|
||||
v3UpdateVerification();
|
||||
v3Log(`Author-first · Arweave owner ${ownerAddress}; GraphQL страниц: ${pageCount}; найдено DataItem: ${discovered}; уникальных Frame: ${allBlocks.length}.`);
|
||||
v3Log(`Author-first · Arweave owner ${ownerAddress}; GraphQL страниц: ${pageCount}; найдено DataItem: ${discovered}; уникальных CORE: ${allBlocks.length}.`);
|
||||
} catch (error) {
|
||||
if (!V3.blocks.length) clearBlockchainBrowser();
|
||||
setContentStatus('error', error.message);
|
||||
@@ -3349,10 +3337,10 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
const oldSetContentStatus = setContentStatus;
|
||||
setContentStatus = function(kind,text){ oldSetContentStatus(kind,text); const el=document.getElementById('v3-status'); if(el) el.textContent=text; v3Log(text); };
|
||||
function v3Theme(theme){ document.documentElement.dataset.theme=theme; localStorage.setItem('shine.viewer.theme',theme); const b=document.getElementById('v3-theme'); if(b)b.textContent=theme==='dark'?'☀':'☾'; }
|
||||
function v3RenderBlocks(){ const host=document.getElementById('v3-block-view'); if(!host)return; host.innerHTML=''; const wrap=document.createElement('div'); wrap.className='v3-blocks'; const blocks=(currentBlockchainView?.rawBlocks||V3.blocks||[]).slice().sort((a,b)=>b.blockNumber-a.blockNumber); blocks.forEach(b=>{ const d=document.createElement('details'); d.className='v3-block'; const sm=document.createElement('summary'); sm.textContent=`#${b.blockNumber} · type ${b.type}/${b.subType} · ${formatTimestamp(Number(b.timestampSec)*1000)}`; const pre=document.createElement('pre'); pre.textContent=JSON.stringify({blockNumber:b.blockNumber,type:b.type,subType:b.subType,version:b.version,hash:b.hashHex,prevHash:b.prevHashHex,back32Hash:b.back32HashHex,arweaveId:b.arweaveId,body:b.body},(k,v)=>typeof v==='bigint'?String(v):v,2); d.append(sm,pre); wrap.appendChild(d); }); if(!blocks.length)wrap.textContent='Блоки ещё не загружены.'; host.appendChild(wrap); }
|
||||
function v3RenderBlocks(){ const host=document.getElementById('v3-block-view'); if(!host)return; host.innerHTML=''; const wrap=document.createElement('div'); wrap.className='v3-blocks'; const blocks=(currentBlockchainView?.rawBlocks||V3.blocks||[]).slice().sort((a,b)=>b.blockNumber-a.blockNumber); blocks.forEach(b=>{ const d=document.createElement('details'); d.className='v3-block'; const sm=document.createElement('summary'); sm.textContent=`#${b.blockNumber} · type ${b.type}/${b.subType} · ${formatTimestamp(Number(b.timestampSec)*1000)}`; const pre=document.createElement('pre'); pre.textContent=JSON.stringify({blockNumber:b.blockNumber,type:b.type,subType:b.subType,version:b.version,hash:b.hashHex,prevHash:b.prevHashHex,contentHash:b.contentHashHex,contentDataItemId:b.contentDataItemId,line:b.line,arweaveId:b.arweaveId,body:b.body},(k,v)=>typeof v==='bigint'?String(v):v,2); d.append(sm,pre); wrap.appendChild(d); }); if(!blocks.length)wrap.textContent='Блоки ещё не загружены.'; host.appendChild(wrap); }
|
||||
function v3SetView(mode){ const bv=document.getElementById('v3-block-view'), cb=document.getElementById('content-browser'); document.getElementById('v3-channel-tab').classList.toggle('is-active',mode==='channel'); document.getElementById('v3-blocks-tab').classList.toggle('is-active',mode==='blocks'); if(bv)bv.hidden=mode!=='blocks'; if(cb)cb.hidden=mode==='blocks'; if(mode==='blocks')v3RenderBlocks(); }
|
||||
async function v3ClearCache(){ try{ const keys=Object.keys(localStorage).filter(k=>k.startsWith('shine.viewer.data.')); keys.forEach(k=>localStorage.removeItem(k)); if('caches' in window){ for(const k of await caches.keys()) if(k.startsWith('shine-viewer-')) await caches.delete(k); } v3Log('Кэш данных очищен'); }catch(e){v3Log('Ошибка очистки кэша: '+e.message);} }
|
||||
function v3CacheKey(key,channel){return 'shine.viewer.author-chain.'+String(key);}
|
||||
async function v3ClearCache(){ try{ const keys=Object.keys(localStorage).filter(k=>k.startsWith('shine.viewer.data.')||k.startsWith('shine.viewer.author-chain.')); keys.forEach(k=>localStorage.removeItem(k)); if('caches' in window){ for(const k of await caches.keys()) if(k.startsWith('shine-viewer-')) await caches.delete(k); } v3Log('Кэш данных очищен'); }catch(e){v3Log('Ошибка очистки кэша: '+e.message);} }
|
||||
function v3CacheKey(key,channel){return 'shine.viewer.author-chain.test5595.'+String(key);}
|
||||
function v3SaveCache(key,channel,blocks){ if(!V3.cacheEnabled)return; try{ localStorage.setItem(v3CacheKey(key,channel),JSON.stringify(blocks,(k,v)=>typeof v==='bigint'?{__bigint:String(v)}:v)); }catch(e){v3Log('Кэш переполнен: '+e.message);} }
|
||||
function v3LoadCache(key,channel){ if(!V3.cacheEnabled)return null; try{return JSON.parse(localStorage.getItem(v3CacheKey(key,channel))||'null',(k,v)=>v&&typeof v==='object'&&v.__bigint!==undefined?BigInt(v.__bigint):v);}catch{return null;} }
|
||||
async function v3RestoreCached(key, channel) {
|
||||
@@ -3375,40 +3363,20 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
function v3ZeroHash(h){return /^0{64}$/i.test(String(h||''));}
|
||||
function v3Verification(blocks){
|
||||
blocks=(blocks||[]).slice().sort((a,b)=>a.blockNumber-b.blockNumber);
|
||||
const byNum=new Map(blocks.map(b=>[Number(b.blockNumber),b]));
|
||||
const result={total:blocks.length,frameHash:{ok:blocks.length,bad:0,na:0},global:{ok:0,bad:0,na:0},back32:{ok:0,bad:0,na:0},channel:{ok:0,bad:0,na:0},owner:{ok:0,bad:0,na:0},signature:{ok:0,bad:0,na:blocks.length},issues:[]};
|
||||
const byHash=new Map(blocks.map(b=>[b.hashHex,b]));
|
||||
const result={total:blocks.length,contentHash:{ok:0,bad:0,na:0},global:{ok:0,bad:0,na:0},channel:{ok:0,bad:0,na:0},owner:{ok:0,bad:0,na:0},signature:{ok:0,bad:0,na:blocks.length},issues:[]};
|
||||
function checkLink(metric,b,num,hash){
|
||||
const target=byHash.get(hash);
|
||||
if(target && target.blockNumber===num) result[metric].ok++;
|
||||
else if(target || v3ZeroHash(hash)){result[metric].bad++;result.issues.push({kind:metric,state:'bad',block:b.blockNumber,text:`Неверная ссылка #${num}`});}
|
||||
else {result[metric].na++;result.issues.push({kind:metric,state:'na',block:b.blockNumber,text:`Нет CORE #${num} с требуемым хешем (возможно предыдущий ключ или ещё не загружен)`});}
|
||||
}
|
||||
for(const b of blocks){
|
||||
// hashHex is SHA-256(Frame) calculated locally by parseBlockchainBlock.
|
||||
if(!b.hashHex){result.frameHash.ok--;result.frameHash.na++;}
|
||||
if(b.arweaveOwnerAddress){result.owner.ok++;} else result.owner.na++;
|
||||
if(Number(b.blockNumber)<=0 || v3ZeroHash(b.prevHashHex)){result.global.ok++;}
|
||||
else{
|
||||
const prev=byNum.get(Number(b.blockNumber)-1);
|
||||
if(!prev){result.global.na++; result.issues.push({kind:'global',state:'na',block:b.blockNumber,text:`Нет блока #${Number(b.blockNumber)-1}; prevHash ${String(b.prevHashHex).slice(0,16)}…`});}
|
||||
else if(String(prev.hashHex).toLowerCase()===String(b.prevHashHex).toLowerCase()) result.global.ok++;
|
||||
else{result.global.bad++;result.issues.push({kind:'global',state:'bad',block:b.blockNumber,text:`prevHash не совпадает с SHA-256 блока #${prev.blockNumber}`});}
|
||||
}
|
||||
const back32=String(b.back32HashHex||'');
|
||||
if(Number(b.blockNumber)<32){
|
||||
if(v3ZeroHash(back32)) result.back32.ok++;
|
||||
else{result.back32.bad++;result.issues.push({kind:'back32',state:'bad',block:b.blockNumber,text:'Для блока <32 back32Hash должен быть нулевым'});}
|
||||
} else {
|
||||
const target=byNum.get(Number(b.blockNumber)-32);
|
||||
if(!target){result.back32.na++;result.issues.push({kind:'back32',state:'na',block:b.blockNumber,text:`Нет блока #${Number(b.blockNumber)-32} для проверки back32Hash`});}
|
||||
else if(String(target.hashHex).toLowerCase()===back32.toLowerCase()) result.back32.ok++;
|
||||
else{result.back32.bad++;result.issues.push({kind:'back32',state:'bad',block:b.blockNumber,text:`back32Hash не совпадает с SHA-256 блока #${Number(b.blockNumber)-32}`});}
|
||||
}
|
||||
const body=b.body||{};
|
||||
if(body.kind==='text_line' || body.kind==='create_channel'){
|
||||
const pn=Number(body.prevLineNumber||0), ph=String(body.prevLineHashHex||'');
|
||||
if(pn<=0 || v3ZeroHash(ph)) result.channel.ok++;
|
||||
else{
|
||||
const prev=byNum.get(pn);
|
||||
if(!prev){result.channel.na++;result.issues.push({kind:'channel',state:'na',block:b.blockNumber,text:`Нет предыдущего блока линии #${pn}; ожидается ${ph.slice(0,16)}…`});}
|
||||
else if(String(prev.hashHex).toLowerCase()===ph.toLowerCase()) result.channel.ok++;
|
||||
else{result.channel.bad++;result.issues.push({kind:'channel',state:'bad',block:b.blockNumber,text:`prevLineHash не совпадает с SHA-256 блока #${pn}`});}
|
||||
}
|
||||
}
|
||||
if(b.contentHashChecked) result.contentHash.ok++; else result.contentHash.na++;
|
||||
if(b.arweaveOwnerAddress) result.owner.ok++; else result.owner.na++;
|
||||
if(b.blockNumber===0 && v3ZeroHash(b.prevHashHex)) result.global.ok++;
|
||||
else checkLink('global',b,b.blockNumber-1,b.prevHashHex);
|
||||
if(b.line) checkLink('channel',b,b.line.prevLineNumber,b.line.prevLineHashHex);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -3416,10 +3384,10 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
function v3UpdateVerification(){
|
||||
const r=v3Verification(currentBlockchainView?.rawBlocks||V3.blocks||[]);
|
||||
V3.verification=r;
|
||||
const bad=r.global.bad+r.back32.bad+r.channel.bad+r.frameHash.bad+r.owner.bad+r.signature.bad;
|
||||
const checked=r.global.ok+r.back32.ok+r.channel.ok;
|
||||
const bad=r.global.bad+r.channel.bad+r.contentHash.bad+r.owner.bad+r.signature.bad;
|
||||
const checked=r.global.ok+r.channel.ok;
|
||||
const el=document.getElementById('v3-status');
|
||||
if(el && r.total) el.textContent=`${bad?'⚠':'✓'} Хэши ${checked} · global ${v3MetricText(r.global)} · канал ${v3MetricText(r.channel)} · owner ${v3MetricText(r.owner)}`;
|
||||
if(el && r.total) el.textContent=`${bad?'⚠':'○'} Хэши ${checked} · global ${v3MetricText(r.global)} · канал ${v3MetricText(r.channel)} · owner ${v3MetricText(r.owner)}`;
|
||||
return r;
|
||||
}
|
||||
function v3VerifyCard(title,m,note){
|
||||
@@ -3428,15 +3396,14 @@ var solanaWeb3=function(exports){"use strict";function getDefaultExportFromCjs(x
|
||||
function v3OpenVerification(){
|
||||
const r=v3UpdateVerification(), view=document.getElementById('v3-verification');
|
||||
document.getElementById('v3-verify-summary').innerHTML=
|
||||
v3VerifyCard('SHA-256 Frame',r.frameHash,'вычислен локально')+
|
||||
v3VerifyCard('SHA-256 CONTENT',r.contentHash,'сверен с CORE')+
|
||||
v3VerifyCard('Общая цепочка',r.global,'prevHash')+
|
||||
v3VerifyCard('Резерв N−32',r.back32,'back32Hash')+
|
||||
v3VerifyCard('Цепочки каналов',r.channel,'prevLineHash')+
|
||||
v3VerifyCard('Arweave owner',r.owner,'совпадение выборки owner');
|
||||
v3VerifyCard('Ссылки линий',r.channel,'prevLineCoreHash')+
|
||||
v3VerifyCard('Arweave owner',r.owner,'только индекс GraphQL');
|
||||
const sig=document.getElementById('v3-signature-note');
|
||||
sig.innerHTML=`<strong>Подписи ANS-104: ○ ${r.signature.na}/${r.total} локально не перепроверены.</strong><br><span class="verify-muted">Gateway отдаёт Viewer содержимое Frame и GraphQL owner/id/tags, но не 64-байтовую подпись DataItem. Это состояние «нет данных», а не ошибка. DataItem при этом найден в Arweave по owner соответствующего blockchain key.</span>`;
|
||||
sig.innerHTML=`<strong>Подписи ANS-104: ○ ${r.signature.na}/${r.total} локально не перепроверены.</strong><br><span class="verify-muted">Gateway отдаёт Viewer payload CORE/CONTENT и GraphQL metadata, но не подписанные ANS-104. Хеш CONTENT проверяется, ID и подписи локально не подтверждены. Это состояние «нет данных», а не ошибка. DataItem при этом найден в Arweave по owner соответствующего blockchain key.</span>`;
|
||||
const issues=document.getElementById('v3-verify-issues'); issues.innerHTML='';
|
||||
if(!r.issues.length) issues.innerHTML='<div class="verify-row"><span class="verify-ok">✓ Хорошо</span><span>Среди доступных блоков противоречий hash-цепочек не найдено.</span></div>';
|
||||
if(!r.issues.length) issues.innerHTML='<div class="verify-row"><span class="verify-ok">✓ Хорошо</span><span>Среди доступных payload противоречий ссылок не найдено. Это не проверка подписей или каноничности истории.</span></div>';
|
||||
r.issues.slice(0,300).forEach(x=>{const row=document.createElement('div');row.className='verify-row';row.innerHTML=`<span class="${x.state==='bad'?'verify-bad':'verify-na'}">${x.state==='bad'?'⚠ Ошибка':'○ Нет данных'} #${x.block}</span><span></span>`;row.lastChild.textContent=x.text;issues.appendChild(row);});
|
||||
document.getElementById('v3-verify-meta').textContent=`Загружено блоков: ${r.total}. «Не проверено» означает, что нужного соседнего блока или сырой подписи нет в текущем наборе; это не считается повреждением. Красный статус появляется только при доказанном несовпадении.`;
|
||||
view.hidden=false; document.getElementById('v3-menu').hidden=true;
|
||||
|
||||
@@ -6,14 +6,16 @@ import path from 'node:path';
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
|
||||
const read = (p) => fs.readFileSync(path.join(root, p), 'utf8');
|
||||
|
||||
test('Тестовая эпоха Arweave одинакова в UI, Server и Viewer', () => {
|
||||
test('CORE эпоха одинакова в UI, Server, discovery и сертификате; viewer', () => {
|
||||
const ui = read('shine-UI/js/services/protocol-tags.js');
|
||||
const server = read('SHiNE-server/shine-server-blockchain/src/main/java/blockchain/ShineProtocolTags.java');
|
||||
const viewer = read('shine-UI/static-sites/arweave-viewer/index.html');
|
||||
const reg = read('SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationCertificateV1.java');
|
||||
assert.match(ui, /SHINE_PROTOCOL_NAMESPACE\s*=\s*'test5592'/);
|
||||
assert.match(server, /NAMESPACE\s*=\s*"test5592"/);
|
||||
assert.match(viewer, /SHINE_PROTOCOL_NAMESPACE\s*=\s*'test5592'/);
|
||||
assert.match(reg, /ShineProtocolTags\.APP_TAG_VALUE/);
|
||||
const archive = read('SHiNE-server/shine-server-archive/src/main/java/server/archive/ArweaveBlocksConfig.java');
|
||||
assert.match(ui, /SHINE_CORE_NAMESPACE\s*=\s*'test5595'/);
|
||||
assert.match(archive, /TEST_TAG_VALUE\s*=\s*ShineProtocolTags\.CORE_NAMESPACE/);
|
||||
assert.match(server, /CORE_NAMESPACE\s*=\s*"test5595"/);
|
||||
assert.match(viewer, /SHINE_PROTOCOL_NAMESPACE\s*=\s*'test5595'/);
|
||||
assert.match(reg, /ShineProtocolTags\.CORE_REGISTRATION_TAGS/);
|
||||
for (const txt of [ui, server, viewer, reg]) assert.doesNotMatch(txt, /test5591/);
|
||||
});
|
||||
|
||||
@@ -27,12 +27,20 @@ test('подмена payload не проходит проверку подпис
|
||||
assert.equal(proof.signatureValid, false);
|
||||
assert.notEqual(Buffer.from(proof.frameHashBytes).toString('hex'), expectedHash);
|
||||
});
|
||||
test('по API нельзя скачать DataItem с подменённым хешем или ID', async () => {
|
||||
const bytes = new Uint8Array(await readFile(signedPath));
|
||||
test('по API проверяется полная пара и отклоняется неверный номер, хеш или ID', async () => {
|
||||
const { packCoreContent } = await import('../js/services/core-content.js');
|
||||
const row = (await readFile(new URL('../../docs/Blockchain/vectors/core-content-v1.tsv', import.meta.url), 'utf8')).trim().split('\n')[1].split('\t');
|
||||
const bytes = packCoreContent(Buffer.from(row[6], 'hex'), Buffer.from(row[8], 'hex'));
|
||||
const id = Buffer.from(row[7], 'hex').toString('base64url');
|
||||
const args = { blockchainName: 'wwwww@shine-001', blockNumber: 0, blockHash: row[3], dataItemId: id };
|
||||
const authService = { ws: { request: async () => ({ status: 200, payload: {
|
||||
blockHash: expectedHash, blockBytesB64: Buffer.from(bytes).toString('base64'),
|
||||
blockHash: row[3], blockBytesB64: Buffer.from(bytes).toString('base64'),
|
||||
} }) } };
|
||||
assert.equal((await readSignedBlock({authService, blockchainName:'wwwww@shine-001',blockNumber:11,blockHash:expectedHash,dataItemId:expectedId})).bytes.length, 412);
|
||||
await assert.rejects(readSignedBlock({authService, blockchainName:'wwwww@shine-001',blockNumber:11,blockHash:expectedHash,dataItemId:'A'.repeat(43)}), /Arweave/);
|
||||
assert.deepEqual((await readSignedBlock({authService, ...args})).bytes, bytes);
|
||||
await assert.rejects(readSignedBlock({authService, ...args, dataItemId:'A'.repeat(43)}), /Arweave/);
|
||||
await assert.rejects(readSignedBlock({authService, ...args, blockNumber:1}), /номер/);
|
||||
await assert.rejects(readSignedBlock({authService, ...args, blockHash:'a'.repeat(64)}), /хеш/);
|
||||
bytes[bytes.length - 1] ^= 1;
|
||||
await assert.rejects(readSignedBlock({authService, ...args}));
|
||||
assert.equal(arweaveBlockUrl('../evil'), '');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { verifyAns104DataItem, createAns104DataItem } from '../js/services/ans104-data-item.js';
|
||||
import { SHINE_CORE_NAMESPACE, SHINE_CORE_LINE_PROFILE, SHINE_CORE_LINE_CONNECTION,
|
||||
SHINE_CORE_LINE_TECH, SHINE_CORE_MAX_BLOCK_NUMBER } from '../js/services/protocol-tags.js';
|
||||
|
||||
const file = new URL('../../docs/Blockchain/vectors/core-content-v1.tsv', import.meta.url);
|
||||
const rows = fs.readFileSync(file,'utf8').trim().split('\n').slice(1).map(r=>r.split('\t'));
|
||||
const hex = b=>Buffer.from(b).toString('hex');
|
||||
const unhex = s=>Buffer.from(s,'hex');
|
||||
const hash = b=>createHash('sha256').update(b).digest('hex');
|
||||
const special = new Map([[SHINE_CORE_LINE_PROFILE,'P'],[SHINE_CORE_LINE_CONNECTION,'C'],[SHINE_CORE_LINE_TECH,'T']]);
|
||||
|
||||
test('CORE v2 namespace и числовые линии согласованы в Java и UI', () => {
|
||||
const server=fs.readFileSync(new URL('../../SHiNE-server/shine-server-blockchain/src/main/java/blockchain/ShineProtocolTags.java',import.meta.url),'utf8');
|
||||
assert.equal(SHINE_CORE_NAMESPACE,'test5595');
|
||||
assert.match(server,/CORE_NAMESPACE\s*=\s*"test5595"/);
|
||||
assert.equal(SHINE_CORE_MAX_BLOCK_NUMBER,2147482623);
|
||||
assert.deepEqual([...special.keys()],[2147483645,2147483646,2147483647]);
|
||||
});
|
||||
|
||||
// Независимые Python fixtures, проверенные также Java. Воссоздание байтов CORE/CONTENT
|
||||
// через Buffer не переключает runtime браузерного клиента (это часть C).
|
||||
test('CORE/CONTENT fixtures: BigEndian, hash, ANS-104 Ed25519 и подписи браузерной библиотеки', async () => {
|
||||
const pkcs8=Buffer.concat([unhex('302e020100300506032b657004220420'),Buffer.from(Array.from({length:32},(_,i)=>i))]);
|
||||
const key=await crypto.subtle.importKey('pkcs8',pkcs8,{name:'Ed25519'},false,['sign']);
|
||||
const history=[];
|
||||
for(const [name,ownerHex,coreHex,coreHash,contentHex,contentHash,coreItemHex,coreId,contentItemHex,contentId] of rows) {
|
||||
const core=unhex(coreHex), content=unhex(contentHex), owner=unhex(ownerHex);
|
||||
assert.ok([109,149].includes(core.length),name);
|
||||
assert.equal(core[0],1); assert.equal(content[0],1);
|
||||
assert.equal(core.readInt32BE(33),history.length);
|
||||
assert.equal(hash(core),coreHash); assert.equal(hash(content),contentHash);
|
||||
assert.equal(hex(core.subarray(45,77)),contentHash); assert.equal(hex(core.subarray(77,109)),contentId);
|
||||
assert.equal(hex(core.subarray(1,33)),history.at(-1)??'00'.repeat(32));
|
||||
const newCore=Buffer.alloc(core.length);
|
||||
newCore[0]=1;
|
||||
unhex(history.at(-1)??'00'.repeat(32)).copy(newCore,1);
|
||||
newCore.writeInt32BE(history.length,33);
|
||||
newCore.writeBigInt64BE(core.readBigInt64BE(37),37);
|
||||
unhex(contentHash).copy(newCore,45); unhex(contentId).copy(newCore,77);
|
||||
const tags=[{name:'App',value:SHINE_CORE_NAMESPACE},{name:'n',value:String(history.length)}];
|
||||
if(core.length===149) {
|
||||
const line=core.readInt32BE(109), prev=core.readInt32BE(113);
|
||||
newCore.writeInt32BE(line,109); newCore.writeInt32BE(prev,113); unhex(history[prev]).copy(newCore,117);
|
||||
tags.push({name:'l',value:special.get(line)??String(line)});
|
||||
}
|
||||
const newContent=Buffer.alloc(content.length); newContent[0]=1;
|
||||
for(const offset of [1,3,5]) newContent.writeUInt16BE(content.readUInt16BE(offset),offset);
|
||||
content.subarray(7).copy(newContent,7);
|
||||
assert.equal(hex(newCore),coreHex); assert.equal(hex(newContent),contentHex);
|
||||
for(const [data,expectedItem,id,expectedTags] of [[newCore,coreItemHex,coreId,tags],[newContent,contentItemHex,contentId,[]]]) {
|
||||
const verified=await verifyAns104DataItem(unhex(expectedItem));
|
||||
assert.ok(verified.signatureValid,name); assert.equal(hex(verified.owner32),ownerHex);
|
||||
assert.equal(hex(verified.dataItemIdBytes),id); assert.equal(hex(verified.data),hex(data));
|
||||
const produced=await createAns104DataItem({owner32:owner,privateKey:key,data,tags:expectedTags});
|
||||
assert.equal(hex(produced),expectedItem,name);
|
||||
}
|
||||
history.push(coreHash);
|
||||
}
|
||||
});
|
||||
|
||||
import { encodeCore, decodeCore, encodeContent, decodeContent, signCoreContentPair, verifyCoreContentPair,
|
||||
packCoreContent, unpackCoreContent, CORE_MAX_CONTAINER_BYTES } from '../js/services/core-content.js';
|
||||
test('Minimal pair codec and container: exact vectors, tampering, unsigned lengths', async () => {
|
||||
const pkcs8=Buffer.concat([unhex('302e020100300506032b657004220420'),Buffer.from(Array.from({length:32},(_,i)=>i))]);
|
||||
const key=await crypto.subtle.importKey('pkcs8',pkcs8,{name:'Ed25519'},false,['sign']);
|
||||
for (const [name,ownerHex,coreHex,coreHash,contentHex,contentHash,coreItemHex,coreId,contentItemHex,contentId] of rows) {
|
||||
const core=decodeCore(unhex(coreHex)), content=decodeContent(unhex(contentHex)), owner=unhex(ownerHex);
|
||||
assert.equal(hex(encodeCore(core)),coreHex); assert.equal(hex(encodeContent(content)),contentHex);
|
||||
const signed=await signCoreContentPair({owner32:owner,privateKey:key,content, ...core});
|
||||
assert.equal(hex(signed.coreDataItem),coreItemHex,name); assert.equal(hex(signed.contentDataItem),contentItemHex,name);
|
||||
const raw=packCoreContent(signed.coreDataItem,signed.contentDataItem);
|
||||
assert.equal(Buffer.from(raw).readUInt32BE(),signed.coreDataItem.length);
|
||||
const pair=unpackCoreContent(raw);
|
||||
assert.equal(hex(pair.coreDataItem),coreItemHex); assert.equal(hex(pair.contentDataItem),contentItemHex);
|
||||
const verified=await verifyCoreContentPair(pair.coreDataItem,pair.contentDataItem,owner);
|
||||
assert.equal(hex(verified.coreHash32),coreHash); assert.equal(hex(verified.coreDataItemId32),coreId);
|
||||
await assert.rejects(verifyCoreContentPair(pair.coreDataItem,pair.contentDataItem,new Uint8Array(32)));
|
||||
const badCore=pair.coreDataItem.slice(); badCore[2]^=1;
|
||||
await assert.rejects(verifyCoreContentPair(badCore,pair.contentDataItem,owner));
|
||||
const badContent=pair.contentDataItem.slice(); badContent[2]^=1;
|
||||
await assert.rejects(verifyCoreContentPair(pair.coreDataItem,badContent,owner));
|
||||
const badLen=raw.slice(); new DataView(badLen.buffer).setUint32(0,0xffffffff);
|
||||
assert.throws(()=>unpackCoreContent(badLen));
|
||||
assert.throws(()=>unpackCoreContent(raw.slice(0,4+pair.coreDataItem.length)));
|
||||
}
|
||||
assert.throws(()=>unpackCoreContent(new Uint8Array(CORE_MAX_CONTAINER_BYTES+1)));
|
||||
});
|
||||
@@ -14,21 +14,20 @@ const encode = vm.runInNewContext(`function makeHeaderBodyBytes(${source}\nmakeH
|
||||
int8Byte: value => Uint8Array.of(value),
|
||||
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
|
||||
Uint8Array,
|
||||
HEADER_LICENSE_FIELD_CC0: 'license:CC0-1.0',
|
||||
});
|
||||
|
||||
test('client writes HEADER v2 as SHiNE → login → literal license → key', () => {
|
||||
test('client writes new HEADER v1 as SHiNE → login → key', () => {
|
||||
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
|
||||
const login = 'Alice@shine';
|
||||
const body = encode({ login, initialBlockchainKey32: key });
|
||||
const loginBytes = utf8(login);
|
||||
const expected = Uint8Array.from([
|
||||
...utf8('SHiNE'), loginBytes.length, ...loginBytes,
|
||||
...utf8('license:CC0-1.0'), ...key,
|
||||
...key,
|
||||
]);
|
||||
assert.deepEqual(Array.from(body), Array.from(expected));
|
||||
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION_CC0/);
|
||||
assert.match(auth, /export const HEADER_VERSION_CC0 = 2/);
|
||||
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION/);
|
||||
assert.match(auth, /export const HEADER_VERSION = 1/);
|
||||
});
|
||||
|
||||
test('inspector decodes both v1 and v2 and rejects invalid v2 license/order', () => {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { KeyRotationClient } from '../js/services/key-rotation-service.js';
|
||||
import { packCoreContent, unpackCoreContent, verifyCoreContentPair, coreHex } from '../js/services/core-content.js';
|
||||
const rows=fs.readFileSync(new URL('../../docs/Blockchain/vectors/core-content-v1.tsv',import.meta.url),'utf8').trim().split('\n').slice(1).map(x=>x.split('\t'));
|
||||
const h=x=>Buffer.from(x,'hex');
|
||||
const b64=x=>Buffer.from(x).toString('base64');
|
||||
const key=await crypto.subtle.importKey('pkcs8',Buffer.concat([h('302e020100300506032b657004220420'),Buffer.alloc(32,42)]),{name:'Ed25519'},true,['sign']);
|
||||
const owner=Buffer.from((await crypto.subtle.exportKey('jwk',key)).x,'base64url');
|
||||
const stored=rows.map(r=>({blockHash:r[3],blockBytesB64:b64(packCoreContent(h(r[6]),h(r[8])))}));
|
||||
for (const cutoff of [0,2,7]) test(`M5 FORK at #${cutoff}: new owner, retained TECH tail, deterministic retry`,async()=>{
|
||||
const calls=[];
|
||||
const client=new KeyRotationClient({ws:{async request(op,p){
|
||||
if(op==='GetBlockchainBlock'){assert.equal(p.blockchainName,'Alice-001');return {status:200,payload:stored[p.blockNumber]};}
|
||||
assert.equal(op,'KeyRotationAddBlock');calls.push(p);return {status:200,payload:{}};
|
||||
}}});
|
||||
const rotation={forkFromBlock:cutoff,sourceBlockchainName:'Alice-001',sourceTipBlock:7,oldBlockchainKey:b64(h(rows[0][1])),newBlockchainKey:b64(owner),forkFromHash:rows[cutoff][3],sourceTipHash:rows[7][3],createdAtMs:1700000010000,reasonCode:3,comment:' test\r\nFORK '};
|
||||
const args={rotation,newBundle:{blockchainPair:{publicKeyB64:b64(owner),privateKey:key}}};
|
||||
await client.copyCandidateChain(args);await client.copyCandidateChain(args);
|
||||
assert.deepEqual(calls[0],calls[1]);
|
||||
const p=unpackCoreContent(Buffer.from(calls[0].blockBytesB64,'base64'));
|
||||
const proof=await verifyCoreContentPair(p.coreDataItem,p.contentDataItem,owner);
|
||||
assert.equal(proof.core.blockNumber,cutoff+1);assert.equal(coreHex(proof.core.prevCoreHash32),rotation.forkFromHash);
|
||||
assert.equal(proof.core.line.lineCode,2147483647);assert.equal(proof.core.line.prevLineBlockNumber,cutoff===0?0:1);assert.equal(coreHex(proof.core.line.prevLineCoreHash32),rows[cutoff===0?0:1][3]);
|
||||
assert.deepEqual([proof.content.type,proof.content.subType,proof.content.version],[0,2,1]);
|
||||
const body=Buffer.from(proof.content.body);assert.deepEqual(body.subarray(0,32),h(rows[0][1]));assert.equal(body.readInt32BE(32),cutoff);assert.equal(body.readBigInt64BE(68),BigInt(1700000000+cutoff)*1000n);assert.equal(body.readInt32BE(76),7);assert.equal(body.readBigInt64BE(112),1700000007000n);assert.equal(body.readInt32BE(120),7-cutoff);assert.equal(body[124],3);assert.equal(body.subarray(127).toString(),'test\nFORK');
|
||||
await assert.rejects(verifyCoreContentPair(p.coreDataItem,p.contentDataItem,h(rows[0][1])));
|
||||
if(process.env.M5_FORK_FIXTURES)fs.appendFileSync(process.env.M5_FORK_FIXTURES,`${cutoff}\t${calls[0].blockBytesB64}\t${b64(owner)}\n`);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
import { webcrypto } from 'node:crypto';
|
||||
const html=fs.readFileSync(new URL('../static-sites/arweave-viewer/index.html',import.meta.url),'utf8');
|
||||
const fixtures=fs.readFileSync(new URL('../../docs/Blockchain/vectors/core-content-v1.tsv',import.meta.url),'utf8').trim().split('\n').slice(1).map(l=>Object.fromEntries(l.split('\t').map((v,i)=>[['name','owner','core','coreHash','content','contentHash','coreItem','coreItemId','contentItem','contentItemId'][i],v])));
|
||||
const source=html.slice(html.indexOf(' const CORE_MAX_NUMBER'),html.indexOf(' const CHANNEL_TYPE_PERSONAL'));
|
||||
const funcs=html.slice(html.indexOf(' async function digestSha256'),html.indexOf(' function refKey('));
|
||||
const b64=html.slice(html.indexOf(' function base64Url('),html.indexOf(' async function arweaveOwnerAddressFromBlockchainKey'));
|
||||
const loader=html.slice(html.indexOf(' async function loadArweavePairs('),html.indexOf(' async function checkSolanaEndpoint('));
|
||||
const checks=html.slice(html.indexOf(' function v3ZeroHash('),html.indexOf(' function v3MetricText('));
|
||||
const ctx=vm.createContext({crypto:webcrypto,Uint8Array,DataView,TextDecoder,TextEncoder,btoa, MAGIC:'SHiNE',bytesToHex:b=>Buffer.from(b).toString('hex'),baseUrl:s=>s,fetch:()=>{throw Error('unexpected fetch')}});
|
||||
vm.runInContext(source+funcs+b64+loader+checks+';globalThis.viewer={parseCorePayload,parseBlockchainBlock,checkIndexedCoreTags,loadArweavePairs,v3Verification}',ctx);
|
||||
const v=ctx.viewer,bytes=s=>Uint8Array.from(Buffer.from(s,'hex'));
|
||||
const itemid=x=>Buffer.from(x,'hex').toString('base64url');
|
||||
const find=n=>fixtures.find(f=>f.name===n);
|
||||
const parse=f=>v.parseBlockchainBlock(bytes(f.core),bytes(f.content));
|
||||
test('viewer: parses all CORE/CONTENT vectors and computes exact hashes',async()=>{
|
||||
for(const f of fixtures){const b=await parse(f);assert.equal(b.hashHex,f.coreHash);assert.equal(b.contentDataItemId,itemid(f.contentItemId));assert.equal(b.contentHashChecked,true);}
|
||||
assert.equal((await parse(find('header'))).body.kind,'header');assert.equal((await parse(find('post'))).body.message,'Hello');
|
||||
});
|
||||
test('viewer: rejects tampered CONTENT, invalid CORE and wrong indexed tags',async()=>{
|
||||
const f=find('post');const bad=bytes(f.content);bad[bad.length-1]^=1;
|
||||
await assert.rejects(v.parseBlockchainBlock(bytes(f.core),bad),/CONTENT hash/);
|
||||
assert.throws(()=>v.parseCorePayload(bytes(f.core).slice(0,108)),/Invalid CORE/);
|
||||
assert.throws(()=>v.checkIndexedCoreTags({tags:[{name:'App',value:'test5592'}]},v.parseCorePayload(bytes(f.core))),/tags mismatch/);
|
||||
});
|
||||
test('viewer: requests CORE then CONTENT by ID and never claims signature verification',async()=>{
|
||||
const f=find('post'),id=itemid(f.coreItemId),cid=itemid(f.contentItemId),calls=[];
|
||||
ctx.fetch=async url=>{calls.push(url);const raw=url.endsWith(cid)?f.content:f.core;return {ok:true,arrayBuffer:async()=>bytes(raw).buffer};};
|
||||
const r=await v.loadArweavePairs('https://mock.invalid',[{id,owner:{address:'indexed'},tags:[{name:'App',value:'test5595'},{name:'n',value:'2'},{name:'l',value:'1'}]}]);
|
||||
assert.deepEqual(calls,[`https://mock.invalid/${id}`,`https://mock.invalid/${cid}`]);assert.equal(r.blocks[0].hashHex,f.coreHash);
|
||||
const checks=v.v3Verification(r.blocks);assert.equal(checks.signature.ok,0);assert.equal(checks.signature.na,1);assert.equal(checks.global.na,1);
|
||||
ctx.fetch=async url=>url.endsWith(cid)?{ok:false,status:404}:{ok:true,arrayBuffer:async()=>bytes(f.core).buffer};
|
||||
await assert.rejects(v.loadArweavePairs('https://mock.invalid',[{id,tags:[{name:'App',value:'test5595'},{name:'n',value:'2'},{name:'l',value:'1'}]}]),/CONTENT.*404/);
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { signEventContainer, unpackCoreContent, packCoreContent, decodeCore, decodeContent, readStoredLineMeta, submitSignedEvent } from '../js/services/core-content.js';
|
||||
import { parseAns104DataItem } from '../js/services/ans104-data-item.js';
|
||||
import { inspectBlockchainDataItem } from '../js/services/blockchain-entry-inspector.js';
|
||||
import { checkArweavePair, readSignedBlock } from '../js/services/blockchain-proof-service.js';
|
||||
import { buildBlockchainSnapshotFile } from '../js/services/shine-blockchain-snapshot-service.js';
|
||||
const rows=fs.readFileSync(new URL('../../docs/Blockchain/vectors/core-content-v1.tsv',import.meta.url),'utf8').trim().split('\n').slice(1).map(r=>r.split('\t'));
|
||||
const unhex=s=>Buffer.from(s,'hex');
|
||||
const fixture=r=>packCoreContent(unhex(r[6]),unhex(r[8]));
|
||||
const base64=b=>Buffer.from(b).toString('base64');
|
||||
const cursor={ blockchainName:'Alice@shine-001', blockNumber:2, prevBlockHash:rows[1][3] };
|
||||
const signed={bytes:fixture(rows[2]),hash:rows[2][3]};
|
||||
function oldFactoryBody(core,content,ordinal=7){
|
||||
if(!core.line) return content.body;
|
||||
const fixed=[3,4].includes(content.type), prefix=Buffer.alloc(fixed?40:44), offset=fixed?0:4;
|
||||
if(!fixed) prefix.writeInt32BE(content.type===0?0:core.line.lineCode,0);
|
||||
prefix.writeInt32BE(core.line.prevLineBlockNumber,offset);
|
||||
Buffer.from(core.line.prevLineCoreHash32).copy(prefix,offset+4);
|
||||
prefix.writeInt32BE(ordinal,offset+36);
|
||||
return Buffer.concat([prefix,content.body]);
|
||||
}
|
||||
test('existing body factories produce exact independent signed pair; ordinal is not signed',async()=>{
|
||||
const key=await crypto.subtle.importKey('pkcs8',Buffer.concat([unhex('302e020100300506032b657004220420'),Buffer.from(Array.from({length:32},(_,i)=>i))]),{name:'Ed25519'},false,['sign']);
|
||||
for(const r of rows){
|
||||
const core=decodeCore(unhex(r[2])),content=decodeContent(unhex(r[4]));
|
||||
const args={owner32:unhex(r[1]),privateKey:key,blockNumber:core.blockNumber,prevBlockHash:Buffer.from(core.prevCoreHash32).toString('hex'),timestamp:core.timestamp,msgType:content.type,msgSubType:content.subType,msgVersion:content.version};
|
||||
const result=await signEventContainer({...args,bodyBytes:oldFactoryBody(core,content)});
|
||||
assert.deepEqual(result.bytes,fixture(r),r[0]);assert.equal(result.hash,r[3]);
|
||||
if(core.line){
|
||||
const again=await signEventContainer({...args,bodyBytes:oldFactoryBody(core,content,42)});
|
||||
assert.deepEqual(again.bytes,result.bytes);
|
||||
const meta=readStoredLineMeta(result.bytes,42);
|
||||
assert.equal(meta.lineSequence,42);assert.equal(meta.lineCode,core.line.lineCode>2147482623?0:core.line.lineCode);
|
||||
assert.throws(()=>readStoredLineMeta(result.bytes,null));assert.throws(()=>readStoredLineMeta(result.bytes,-1));
|
||||
}
|
||||
const inspection=await inspectBlockchainDataItem(base64(result.bytes),42);
|
||||
assert.equal(inspection.frame.blockNumber,core.blockNumber);assert.equal(inspection.frame.type,content.type);
|
||||
assert.deepEqual(Buffer.from(inspection.frame.bodyBytes),Buffer.from(content.body));
|
||||
if(core.line) assert.equal(inspection.frame.body.line.lineSequence,42);
|
||||
if(core.blockNumber===0) assert.equal(inspection.frame.body.license,null);
|
||||
}
|
||||
});
|
||||
test('lost response: retransmit the identical signed container, then confirm canonical bytes',async()=>{
|
||||
const calls=[];
|
||||
const ws={request:async(op,payload)=>{calls.push({op,payload});if(calls.length===1)throw Error('timeout');if(op==='AddBlock')return {status:400,payload:{code:'bad_block_number',serverLastGlobalNumber:3}};return {status:200,payload:{blockHash:signed.hash,blockBytesB64:base64(signed.bytes)}};}};
|
||||
const result=await submitSignedEvent(ws,cursor,signed);
|
||||
assert.equal(result.status,200);assert.equal(result.payload.serverLastGlobalNumber,2);assert.equal(result.payload.serverLastGlobalHash,signed.hash);
|
||||
assert.deepEqual(calls[0],calls[1]);assert.equal(calls[2].op,'GetBlockchainBlock');
|
||||
});
|
||||
test('ambiguous outcome with mismatched bytes never authorizes fresh signing',async()=>{
|
||||
let count=0;
|
||||
const ws={request:async(op)=>{count++;if(op==='AddBlock')throw Error('timeout');return {status:200,payload:{blockHash:signed.hash,blockBytesB64:base64(fixture(rows[3]))}};}};
|
||||
await assert.rejects(submitSignedEvent(ws,cursor,signed),/outcome unknown/);assert.equal(count,3);
|
||||
});
|
||||
test('definite rejection preserves original error for existing line retry',async()=>{
|
||||
const response={status:400,payload:{code:'bad_prev_line_hash',serverLastGlobalNumber:1}};
|
||||
assert.equal(await submitSignedEvent({request:async()=>response},cursor,signed),response);
|
||||
});
|
||||
test('proof checks both archive payloads, not just CORE',async()=>{
|
||||
const r=rows[2];const proof=await readSignedBlock({authService:{ws:{request:async()=>({status:200,payload:{blockHash:r[3],blockBytesB64:base64(fixture(r))}})}},blockchainName:cursor.blockchainName,blockNumber:2,blockHash:r[3]});
|
||||
const original=globalThis.fetch;const calls=[];
|
||||
try{globalThis.fetch=async url=>{calls.push(url);return new Response(url.endsWith(proof.actualId)?proof.data:proof.contentData);};assert.equal((await checkArweavePair(proof)).status,'valid');assert.equal(calls.length,2);
|
||||
globalThis.fetch=async url=>new Response(url.endsWith(proof.actualId)?proof.data:new Uint8Array([0]));assert.equal((await checkArweavePair(proof)).status,'invalid');
|
||||
globalThis.fetch=async url=>url.endsWith(proof.actualId)?new Response(proof.data):new Response(null,{status:404});assert.equal((await checkArweavePair(proof)).status,'unavailable');
|
||||
}finally{globalThis.fetch=original;}
|
||||
});
|
||||
test('snapshot records are independently delimited and retain original bytes',async()=>{
|
||||
const result=await buildBlockchainSnapshotFile({authService:{ws:{request:async(op,{blockNumber})=>({status:200,payload:{blockBytesB64:base64(fixture(rows[blockNumber]))}})}},login:'Alice@shine',blockchainName:cursor.blockchainName,lastBlockNumber:2});
|
||||
const bytes=Buffer.from(await result.file.arrayBuffer());assert.equal(bytes.subarray(0,8).toString(),'SHINECC2');let pos=8;
|
||||
for(const r of rows.slice(0,3)){const n=bytes.readUInt32BE(pos);pos+=4;assert.deepEqual(bytes.subarray(pos,pos+n),Buffer.from(fixture(r)));pos+=n;}
|
||||
assert.equal(pos,bytes.length);assert.equal(result.totalBytes,pos);
|
||||
});
|
||||
@@ -110,3 +110,9 @@ test('V3/V4: вход через нижнюю кнопку очищает исс
|
||||
assert.match(view, /void resetBarrier\.then\(async \(\) =>/);
|
||||
assert.doesNotMatch(switcher, /select\.addEventListener\('change',[\s\S]*resetExplorerOnTabEntry/);
|
||||
});
|
||||
|
||||
test('V4 Canvas открывается по умолчанию, но ранее выбранная версия сохраняется', () => {
|
||||
const switcher = readFileSync(new URL('../js/pages/network-version-switcher.js', import.meta.url), 'utf8');
|
||||
assert.match(switcher, /const DEFAULT_MODE = 'explorer-canvas';/);
|
||||
assert.match(switcher, /MODES\.has\(saved\) \? saved : DEFAULT_MODE/);
|
||||
});
|
||||
|
||||
@@ -21,22 +21,20 @@ const context = {
|
||||
int8Byte: value => Uint8Array.of(value),
|
||||
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
|
||||
Uint8Array,
|
||||
HEADER_LICENSE_FIELD_CC0: 'license:CC0-1.0',
|
||||
};
|
||||
const makeHeaderBodyBytes = vm.runInNewContext(`function makeHeaderBodyBytes(${makeBytesFunction}\nmakeHeaderBodyBytes`, context);
|
||||
|
||||
test('HEADER v2 places literal license:CC0-1.0 before the initial key', () => {
|
||||
test('CORE/CONTENT HEADER v1 contains login and initial key without CC0', () => {
|
||||
const key = Uint8Array.from({ length: 32 }, (_, n) => n + 1);
|
||||
const result = makeHeaderBodyBytes({ login: 'Alice@shine', initialBlockchainKey32: key });
|
||||
const login = new TextEncoder().encode('Alice@shine');
|
||||
assert.equal(new TextDecoder().decode(result.slice(0,5)), 'SHiNE');
|
||||
assert.equal(result[5], login.length);
|
||||
assert.deepEqual(Array.from(result.slice(6, 6+login.length)), Array.from(login));
|
||||
assert.equal(new TextDecoder().decode(result.slice(6+login.length, 6+login.length+15)), 'license:CC0-1.0');
|
||||
assert.deepEqual(Array.from(result.slice(6+login.length+15)), Array.from(key));
|
||||
assert.equal(result.length, 5 + 1 + login.length + 15 + 32);
|
||||
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION_CC0/);
|
||||
assert.match(auth, /export const HEADER_VERSION_CC0 = 2/);
|
||||
assert.deepEqual(Array.from(result.slice(6+login.length)), Array.from(key));
|
||||
assert.equal(result.length, 5 + 1 + login.length + 32);
|
||||
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION/);
|
||||
assert.match(auth, /export const HEADER_VERSION = 1/);
|
||||
});
|
||||
|
||||
test('free and paid registration both require accepted documents before any registration operation', { skip: !hasRegistrationTerms }, () => {
|
||||
|
||||
Reference in New Issue
Block a user