CORE/CONTENT test5593 и адаптация UI

This commit is contained in:
AidarKC
2026-11-27 00:47:13 +03:00
parent 205b7ad971
commit 873535654e
1271 changed files with 219621 additions and 1900 deletions
+49 -79
View File
@@ -1,11 +1,10 @@
import { createAns104DataItem, createAns104DataItemWithRawParts, parseAns104DataItem } from './ans104-data-item.js';
import { coreHashBytes, coreHex, readCoreBlock, signCoreContentPair } from './core-content.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, SHINE_CORE_MAX_BLOCK_NUMBER } from './protocol-tags.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 || {}); }
@@ -29,46 +28,22 @@ function concat(...chunks) {
function be16(v) { const a=new Uint8Array(2); new DataView(a.buffer).setUint16(0, Number(v), false); return a; }
function be32(v) { const a=new Uint8Array(4); new DataView(a.buffer).setUint32(0, Number(v), false); return a; }
function be64(v) { const a=new Uint8Array(8); new DataView(a.buffer).setBigInt64(0, BigInt(v), false); return a; }
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 blockNumber(value) {
if (!Number.isInteger(value) || value < 0 || value > SHINE_CORE_MAX_BLOCK_NUMBER) throw new Error('Некорректный номер CORE');
return value;
}
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 timestampMs(core) {
const ms = Number(core.timestamp * 1000n);
if (!Number.isSafeInteger(ms)) throw new Error('Некорректное время CORE');
return ms;
}
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 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);
}
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);
const discarded=blockNumber(parentTipBlock)-blockNumber(forkPointBlock);
if(discarded<0 || ![1,2,3,4].includes(reasonCode)) throw new Error('Некорректная точка fork или причина');
return concat(oldKey,be32(forkPointBlock),coreHashBytes(forkPointHash),be64(forkPointTimestampMs),be32(parentTipBlock),coreHashBytes(parentTipHash),be64(parentTipTimestampMs),be32(discarded),Uint8Array.of(reasonCode),be16(c.length),c);
}
export const KEY_ROTATION_REASONS = Object.freeze([
@@ -87,68 +62,64 @@ export class KeyRotationClient {
async finishChain() { return assertOk(await this.auth.ws.request('KeyRotationFinishChain', {}), 'KeyRotationFinishChain'); }
async notifyPdaRotation(signature) { return assertOk(await this.auth.ws.request('KeyRotationRotatePda', { pdaRotationSignature: signature }), 'KeyRotationRotatePda'); }
async getMyBlockchain({ beforeBlock=null, limit=50, includeBlockBytes=false }={}) {
return assertOk(await this.auth.ws.request('GetMyBlockchain', { beforeBlock, limit, includeBlockBytes }), 'GetMyBlockchain');
const page=assertOk(await this.auth.ws.request('GetMyBlockchain', { beforeBlock, limit, includeBlockBytes }), 'GetMyBlockchain');
// The original cutoff picker needs time and hash, now derived from signed CORE.
return {...page, blocks:await Promise.all((page.blocks||[]).map(async row=>{
const checked=await readCoreBlock(row);
return {...row,blockHash:checked.coreHash,timestampMs:timestampMs(checked.core)};
}))};
}
async getBlock(blockchainName, blockNumber) {
return assertOk(await this.auth.ws.request('GetBlockchainBlock', { blockchainName, blockNumber }), 'GetBlockchainBlock');
async getBlock(blockchainName, number) {
const row=assertOk(await this.auth.ws.request('GetBlockchainBlock', { blockchainName, blockNumber:number }), 'GetBlockchainBlock');
if(row.blockNumber!==number || String(row.blockchainName||'').toLowerCase()!==blockchainName.toLowerCase()) throw new Error('CORE source mismatch');
return readCoreBlock({...row,contentDataItemB64:null});
}
async addCandidate({ blockNumber, prevBlockHash, blockBytesB64 }) {
return assertOk(await this.auth.ws.request('KeyRotationAddBlock', { blockNumber, prevBlockHash, blockBytesB64 }, 30000), 'KeyRotationAddBlock');
async addCandidate({ blockNumber, prevBlockHash, coreDataItemB64, contentDataItemB64 }) {
return assertOk(await this.auth.ws.request('KeyRotationAddBlock', { blockNumber, prevBlockHash, coreDataItemB64, contentDataItemB64 }, 30000), 'KeyRotationAddBlock');
}
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);
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,
};
async #resolveTechLineTail(source, point) {
// Search the frozen source prefix, not the active TECH head (which may be after cutoff).
// The line selector lives in CORE and works even when CONTENT is missing.
let entry=point;
for(;;) {
if(entry.core.blockNumber===0 || entry.core.line?.lineCode===SHINE_CORE_LINE_TECH) {
return {lineCode:SHINE_CORE_LINE_TECH,prevLineBlockNumber:entry.core.blockNumber,prevLineCoreHash32:coreHashBytes(entry.coreHash)};
}
const previous=await this.getBlock(source,entry.core.blockNumber-1);
if(previous.coreHash!==coreHex(entry.core.prevCoreHash32)) throw new Error('Нарушена связь CORE в исходной цепочке');
entry=previous;
}
const header=await this.getBlock(source,0);
return { prevLineNumber:0, prevLineHash:String(header.blockHash||''), lineSequence:1 };
}
async copyCandidateChain({ rotation, newBundle, onProgress=()=>{} }) {
const cutoff=Number(rotation.forkFromBlock); const source=String(rotation.sourceBlockchainName||'');
if(!source || !Number.isInteger(cutoff) || cutoff<0) throw new Error('Некорректное состояние ротации');
const cutoff=blockNumber(rotation.forkFromBlock); const source=String(rotation.sourceBlockchainName||'');
if(!source || cutoff===SHINE_CORE_MAX_BLOCK_NUMBER) throw new Error('Некорректное состояние ротации');
if(String(newBundle?.blockchainPair?.publicKeyB64||'') !== String(rotation.newBlockchainKey||'')) throw new Error('Новый пароль выводит другой blockchain key');
const total=1;
if((Number(rotation.progressCurrent)||0)>=total){onProgress({phase:'copy',current:total,total});return;}
const owner32=base64ToBytes(newBundle.blockchainPair.publicKeyB64);
const privateKey=newBundle.blockchainPair.privateKey;
const tipBlock=blockNumber(rotation.sourceTipBlock);
if(tipBlock<cutoff) throw new Error('Некорректная точка fork');
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 techTail=await this.#resolveTechLineTail(source,cutoff);
if(forkSource.coreHash!==coreHex(coreHashBytes(rotation.forkFromHash)) || tipSource.coreHash!==coreHex(coreHashBytes(rotation.sourceTipHash))) throw new Error('CORE hash исходной цепочки не совпадает с сессией ротации');
const line=await this.#resolveTechLineTail(source,forkSource);
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(forkSource.core), parentTipBlock:tipBlock, parentTipHash:rotation.sourceTipHash,
parentTipTimestampMs:timestampMs(tipSource.core), reasonCode:rotation.reasonCode, comment:rotation.comment,
});
const techTimestampMs=Number(rotation.createdAtMs)||readFrameTimestampMs(tipParsed.data)+1000;
// Fixed session timestamp preserves identical bytes on a retry with the same new key.
const techTimestampMs=Number(rotation.createdAtMs)||timestampMs(tipSource.core)+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'}]});
await this.addCandidate({blockNumber:techBlockNumber,prevBlockHash:rotation.forkFromHash,blockBytesB64:bytesToBase64(techRaw)});
const pair=await signCoreContentPair({owner32,privateKey,content:{type:0,subType:TECH_FORK_SUBTYPE,version:1,body:forkBody},
prevCoreHash32:coreHashBytes(rotation.forkFromHash),blockNumber:techBlockNumber,timestamp:Math.floor(techTimestampMs/1000),line});
await this.addCandidate({blockNumber:techBlockNumber,prevBlockHash:rotation.forkFromHash,coreDataItemB64:bytesToBase64(pair.coreDataItem),contentDataItemB64:bytesToBase64(pair.contentDataItem)});
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) {
@@ -229,4 +200,3 @@ export class KeyRotationClient {
}
}
function nullIfEmpty(value) { const s=String(value||'').trim(); return s || null; }