SHA256
Новый формат блоков CORE/CONTENT test5595
This commit is contained in:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user