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