Новый формат блоков 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
+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,
});