Новый формат блоков CORE/CONTENT test5595

This commit is contained in:
AidarKC
2026-11-27 10:04:22 +03:00
parent d3a84dd451
commit f9e7c4ef94
180 changed files with 15365 additions and 1301 deletions
@@ -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 }),
]);
+2 -2
View File
@@ -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",
+2 -2
View File
@@ -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": "Подписанный блок",
+4 -3
View File
@@ -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');
});
+31 -207
View File
@@ -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('; ') };
}
+199
View File
@@ -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;
}
+23 -59
View File
@@ -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) {
+9
View File
@@ -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`, {