SHA256
Новый формат блоков CORE/CONTENT test5595
This commit is contained in:
@@ -6,14 +6,16 @@ import path from 'node:path';
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
|
||||
const read = (p) => fs.readFileSync(path.join(root, p), 'utf8');
|
||||
|
||||
test('Тестовая эпоха Arweave одинакова в UI, Server и Viewer', () => {
|
||||
test('CORE эпоха одинакова в UI, Server, discovery и сертификате; viewer', () => {
|
||||
const ui = read('shine-UI/js/services/protocol-tags.js');
|
||||
const server = read('SHiNE-server/shine-server-blockchain/src/main/java/blockchain/ShineProtocolTags.java');
|
||||
const viewer = read('shine-UI/static-sites/arweave-viewer/index.html');
|
||||
const reg = read('SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/FreeRegistrationCertificateV1.java');
|
||||
assert.match(ui, /SHINE_PROTOCOL_NAMESPACE\s*=\s*'test5592'/);
|
||||
assert.match(server, /NAMESPACE\s*=\s*"test5592"/);
|
||||
assert.match(viewer, /SHINE_PROTOCOL_NAMESPACE\s*=\s*'test5592'/);
|
||||
assert.match(reg, /ShineProtocolTags\.APP_TAG_VALUE/);
|
||||
const archive = read('SHiNE-server/shine-server-archive/src/main/java/server/archive/ArweaveBlocksConfig.java');
|
||||
assert.match(ui, /SHINE_CORE_NAMESPACE\s*=\s*'test5595'/);
|
||||
assert.match(archive, /TEST_TAG_VALUE\s*=\s*ShineProtocolTags\.CORE_NAMESPACE/);
|
||||
assert.match(server, /CORE_NAMESPACE\s*=\s*"test5595"/);
|
||||
assert.match(viewer, /SHINE_PROTOCOL_NAMESPACE\s*=\s*'test5595'/);
|
||||
assert.match(reg, /ShineProtocolTags\.CORE_REGISTRATION_TAGS/);
|
||||
for (const txt of [ui, server, viewer, reg]) assert.doesNotMatch(txt, /test5591/);
|
||||
});
|
||||
|
||||
@@ -27,12 +27,20 @@ test('подмена payload не проходит проверку подпис
|
||||
assert.equal(proof.signatureValid, false);
|
||||
assert.notEqual(Buffer.from(proof.frameHashBytes).toString('hex'), expectedHash);
|
||||
});
|
||||
test('по API нельзя скачать DataItem с подменённым хешем или ID', async () => {
|
||||
const bytes = new Uint8Array(await readFile(signedPath));
|
||||
test('по API проверяется полная пара и отклоняется неверный номер, хеш или ID', async () => {
|
||||
const { packCoreContent } = await import('../js/services/core-content.js');
|
||||
const row = (await readFile(new URL('../../docs/Blockchain/vectors/core-content-v1.tsv', import.meta.url), 'utf8')).trim().split('\n')[1].split('\t');
|
||||
const bytes = packCoreContent(Buffer.from(row[6], 'hex'), Buffer.from(row[8], 'hex'));
|
||||
const id = Buffer.from(row[7], 'hex').toString('base64url');
|
||||
const args = { blockchainName: 'wwwww@shine-001', blockNumber: 0, blockHash: row[3], dataItemId: id };
|
||||
const authService = { ws: { request: async () => ({ status: 200, payload: {
|
||||
blockHash: expectedHash, blockBytesB64: Buffer.from(bytes).toString('base64'),
|
||||
blockHash: row[3], blockBytesB64: Buffer.from(bytes).toString('base64'),
|
||||
} }) } };
|
||||
assert.equal((await readSignedBlock({authService, blockchainName:'wwwww@shine-001',blockNumber:11,blockHash:expectedHash,dataItemId:expectedId})).bytes.length, 412);
|
||||
await assert.rejects(readSignedBlock({authService, blockchainName:'wwwww@shine-001',blockNumber:11,blockHash:expectedHash,dataItemId:'A'.repeat(43)}), /Arweave/);
|
||||
assert.deepEqual((await readSignedBlock({authService, ...args})).bytes, bytes);
|
||||
await assert.rejects(readSignedBlock({authService, ...args, dataItemId:'A'.repeat(43)}), /Arweave/);
|
||||
await assert.rejects(readSignedBlock({authService, ...args, blockNumber:1}), /номер/);
|
||||
await assert.rejects(readSignedBlock({authService, ...args, blockHash:'a'.repeat(64)}), /хеш/);
|
||||
bytes[bytes.length - 1] ^= 1;
|
||||
await assert.rejects(readSignedBlock({authService, ...args}));
|
||||
assert.equal(arweaveBlockUrl('../evil'), '');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { verifyAns104DataItem, createAns104DataItem } from '../js/services/ans104-data-item.js';
|
||||
import { SHINE_CORE_NAMESPACE, SHINE_CORE_LINE_PROFILE, SHINE_CORE_LINE_CONNECTION,
|
||||
SHINE_CORE_LINE_TECH, SHINE_CORE_MAX_BLOCK_NUMBER } from '../js/services/protocol-tags.js';
|
||||
|
||||
const file = new URL('../../docs/Blockchain/vectors/core-content-v1.tsv', import.meta.url);
|
||||
const rows = fs.readFileSync(file,'utf8').trim().split('\n').slice(1).map(r=>r.split('\t'));
|
||||
const hex = b=>Buffer.from(b).toString('hex');
|
||||
const unhex = s=>Buffer.from(s,'hex');
|
||||
const hash = b=>createHash('sha256').update(b).digest('hex');
|
||||
const special = new Map([[SHINE_CORE_LINE_PROFILE,'P'],[SHINE_CORE_LINE_CONNECTION,'C'],[SHINE_CORE_LINE_TECH,'T']]);
|
||||
|
||||
test('CORE v2 namespace и числовые линии согласованы в Java и UI', () => {
|
||||
const server=fs.readFileSync(new URL('../../SHiNE-server/shine-server-blockchain/src/main/java/blockchain/ShineProtocolTags.java',import.meta.url),'utf8');
|
||||
assert.equal(SHINE_CORE_NAMESPACE,'test5595');
|
||||
assert.match(server,/CORE_NAMESPACE\s*=\s*"test5595"/);
|
||||
assert.equal(SHINE_CORE_MAX_BLOCK_NUMBER,2147482623);
|
||||
assert.deepEqual([...special.keys()],[2147483645,2147483646,2147483647]);
|
||||
});
|
||||
|
||||
// Независимые Python fixtures, проверенные также Java. Воссоздание байтов CORE/CONTENT
|
||||
// через Buffer не переключает runtime браузерного клиента (это часть C).
|
||||
test('CORE/CONTENT fixtures: BigEndian, hash, ANS-104 Ed25519 и подписи браузерной библиотеки', async () => {
|
||||
const pkcs8=Buffer.concat([unhex('302e020100300506032b657004220420'),Buffer.from(Array.from({length:32},(_,i)=>i))]);
|
||||
const key=await crypto.subtle.importKey('pkcs8',pkcs8,{name:'Ed25519'},false,['sign']);
|
||||
const history=[];
|
||||
for(const [name,ownerHex,coreHex,coreHash,contentHex,contentHash,coreItemHex,coreId,contentItemHex,contentId] of rows) {
|
||||
const core=unhex(coreHex), content=unhex(contentHex), owner=unhex(ownerHex);
|
||||
assert.ok([109,149].includes(core.length),name);
|
||||
assert.equal(core[0],1); assert.equal(content[0],1);
|
||||
assert.equal(core.readInt32BE(33),history.length);
|
||||
assert.equal(hash(core),coreHash); assert.equal(hash(content),contentHash);
|
||||
assert.equal(hex(core.subarray(45,77)),contentHash); assert.equal(hex(core.subarray(77,109)),contentId);
|
||||
assert.equal(hex(core.subarray(1,33)),history.at(-1)??'00'.repeat(32));
|
||||
const newCore=Buffer.alloc(core.length);
|
||||
newCore[0]=1;
|
||||
unhex(history.at(-1)??'00'.repeat(32)).copy(newCore,1);
|
||||
newCore.writeInt32BE(history.length,33);
|
||||
newCore.writeBigInt64BE(core.readBigInt64BE(37),37);
|
||||
unhex(contentHash).copy(newCore,45); unhex(contentId).copy(newCore,77);
|
||||
const tags=[{name:'App',value:SHINE_CORE_NAMESPACE},{name:'n',value:String(history.length)}];
|
||||
if(core.length===149) {
|
||||
const line=core.readInt32BE(109), prev=core.readInt32BE(113);
|
||||
newCore.writeInt32BE(line,109); newCore.writeInt32BE(prev,113); unhex(history[prev]).copy(newCore,117);
|
||||
tags.push({name:'l',value:special.get(line)??String(line)});
|
||||
}
|
||||
const newContent=Buffer.alloc(content.length); newContent[0]=1;
|
||||
for(const offset of [1,3,5]) newContent.writeUInt16BE(content.readUInt16BE(offset),offset);
|
||||
content.subarray(7).copy(newContent,7);
|
||||
assert.equal(hex(newCore),coreHex); assert.equal(hex(newContent),contentHex);
|
||||
for(const [data,expectedItem,id,expectedTags] of [[newCore,coreItemHex,coreId,tags],[newContent,contentItemHex,contentId,[]]]) {
|
||||
const verified=await verifyAns104DataItem(unhex(expectedItem));
|
||||
assert.ok(verified.signatureValid,name); assert.equal(hex(verified.owner32),ownerHex);
|
||||
assert.equal(hex(verified.dataItemIdBytes),id); assert.equal(hex(verified.data),hex(data));
|
||||
const produced=await createAns104DataItem({owner32:owner,privateKey:key,data,tags:expectedTags});
|
||||
assert.equal(hex(produced),expectedItem,name);
|
||||
}
|
||||
history.push(coreHash);
|
||||
}
|
||||
});
|
||||
|
||||
import { encodeCore, decodeCore, encodeContent, decodeContent, signCoreContentPair, verifyCoreContentPair,
|
||||
packCoreContent, unpackCoreContent, CORE_MAX_CONTAINER_BYTES } from '../js/services/core-content.js';
|
||||
test('Minimal pair codec and container: exact vectors, tampering, unsigned lengths', async () => {
|
||||
const pkcs8=Buffer.concat([unhex('302e020100300506032b657004220420'),Buffer.from(Array.from({length:32},(_,i)=>i))]);
|
||||
const key=await crypto.subtle.importKey('pkcs8',pkcs8,{name:'Ed25519'},false,['sign']);
|
||||
for (const [name,ownerHex,coreHex,coreHash,contentHex,contentHash,coreItemHex,coreId,contentItemHex,contentId] of rows) {
|
||||
const core=decodeCore(unhex(coreHex)), content=decodeContent(unhex(contentHex)), owner=unhex(ownerHex);
|
||||
assert.equal(hex(encodeCore(core)),coreHex); assert.equal(hex(encodeContent(content)),contentHex);
|
||||
const signed=await signCoreContentPair({owner32:owner,privateKey:key,content, ...core});
|
||||
assert.equal(hex(signed.coreDataItem),coreItemHex,name); assert.equal(hex(signed.contentDataItem),contentItemHex,name);
|
||||
const raw=packCoreContent(signed.coreDataItem,signed.contentDataItem);
|
||||
assert.equal(Buffer.from(raw).readUInt32BE(),signed.coreDataItem.length);
|
||||
const pair=unpackCoreContent(raw);
|
||||
assert.equal(hex(pair.coreDataItem),coreItemHex); assert.equal(hex(pair.contentDataItem),contentItemHex);
|
||||
const verified=await verifyCoreContentPair(pair.coreDataItem,pair.contentDataItem,owner);
|
||||
assert.equal(hex(verified.coreHash32),coreHash); assert.equal(hex(verified.coreDataItemId32),coreId);
|
||||
await assert.rejects(verifyCoreContentPair(pair.coreDataItem,pair.contentDataItem,new Uint8Array(32)));
|
||||
const badCore=pair.coreDataItem.slice(); badCore[2]^=1;
|
||||
await assert.rejects(verifyCoreContentPair(badCore,pair.contentDataItem,owner));
|
||||
const badContent=pair.contentDataItem.slice(); badContent[2]^=1;
|
||||
await assert.rejects(verifyCoreContentPair(pair.coreDataItem,badContent,owner));
|
||||
const badLen=raw.slice(); new DataView(badLen.buffer).setUint32(0,0xffffffff);
|
||||
assert.throws(()=>unpackCoreContent(badLen));
|
||||
assert.throws(()=>unpackCoreContent(raw.slice(0,4+pair.coreDataItem.length)));
|
||||
}
|
||||
assert.throws(()=>unpackCoreContent(new Uint8Array(CORE_MAX_CONTAINER_BYTES+1)));
|
||||
});
|
||||
@@ -14,21 +14,20 @@ const encode = vm.runInNewContext(`function makeHeaderBodyBytes(${source}\nmakeH
|
||||
int8Byte: value => Uint8Array.of(value),
|
||||
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
|
||||
Uint8Array,
|
||||
HEADER_LICENSE_FIELD_CC0: 'license:CC0-1.0',
|
||||
});
|
||||
|
||||
test('client writes HEADER v2 as SHiNE → login → literal license → key', () => {
|
||||
test('client writes new HEADER v1 as SHiNE → login → key', () => {
|
||||
const key = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
|
||||
const login = 'Alice@shine';
|
||||
const body = encode({ login, initialBlockchainKey32: key });
|
||||
const loginBytes = utf8(login);
|
||||
const expected = Uint8Array.from([
|
||||
...utf8('SHiNE'), loginBytes.length, ...loginBytes,
|
||||
...utf8('license:CC0-1.0'), ...key,
|
||||
...key,
|
||||
]);
|
||||
assert.deepEqual(Array.from(body), Array.from(expected));
|
||||
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION_CC0/);
|
||||
assert.match(auth, /export const HEADER_VERSION_CC0 = 2/);
|
||||
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION/);
|
||||
assert.match(auth, /export const HEADER_VERSION = 1/);
|
||||
});
|
||||
|
||||
test('inspector decodes both v1 and v2 and rejects invalid v2 license/order', () => {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { KeyRotationClient } from '../js/services/key-rotation-service.js';
|
||||
import { packCoreContent, unpackCoreContent, verifyCoreContentPair, coreHex } from '../js/services/core-content.js';
|
||||
const rows=fs.readFileSync(new URL('../../docs/Blockchain/vectors/core-content-v1.tsv',import.meta.url),'utf8').trim().split('\n').slice(1).map(x=>x.split('\t'));
|
||||
const h=x=>Buffer.from(x,'hex');
|
||||
const b64=x=>Buffer.from(x).toString('base64');
|
||||
const key=await crypto.subtle.importKey('pkcs8',Buffer.concat([h('302e020100300506032b657004220420'),Buffer.alloc(32,42)]),{name:'Ed25519'},true,['sign']);
|
||||
const owner=Buffer.from((await crypto.subtle.exportKey('jwk',key)).x,'base64url');
|
||||
const stored=rows.map(r=>({blockHash:r[3],blockBytesB64:b64(packCoreContent(h(r[6]),h(r[8])))}));
|
||||
for (const cutoff of [0,2,7]) test(`M5 FORK at #${cutoff}: new owner, retained TECH tail, deterministic retry`,async()=>{
|
||||
const calls=[];
|
||||
const client=new KeyRotationClient({ws:{async request(op,p){
|
||||
if(op==='GetBlockchainBlock'){assert.equal(p.blockchainName,'Alice-001');return {status:200,payload:stored[p.blockNumber]};}
|
||||
assert.equal(op,'KeyRotationAddBlock');calls.push(p);return {status:200,payload:{}};
|
||||
}}});
|
||||
const rotation={forkFromBlock:cutoff,sourceBlockchainName:'Alice-001',sourceTipBlock:7,oldBlockchainKey:b64(h(rows[0][1])),newBlockchainKey:b64(owner),forkFromHash:rows[cutoff][3],sourceTipHash:rows[7][3],createdAtMs:1700000010000,reasonCode:3,comment:' test\r\nFORK '};
|
||||
const args={rotation,newBundle:{blockchainPair:{publicKeyB64:b64(owner),privateKey:key}}};
|
||||
await client.copyCandidateChain(args);await client.copyCandidateChain(args);
|
||||
assert.deepEqual(calls[0],calls[1]);
|
||||
const p=unpackCoreContent(Buffer.from(calls[0].blockBytesB64,'base64'));
|
||||
const proof=await verifyCoreContentPair(p.coreDataItem,p.contentDataItem,owner);
|
||||
assert.equal(proof.core.blockNumber,cutoff+1);assert.equal(coreHex(proof.core.prevCoreHash32),rotation.forkFromHash);
|
||||
assert.equal(proof.core.line.lineCode,2147483647);assert.equal(proof.core.line.prevLineBlockNumber,cutoff===0?0:1);assert.equal(coreHex(proof.core.line.prevLineCoreHash32),rows[cutoff===0?0:1][3]);
|
||||
assert.deepEqual([proof.content.type,proof.content.subType,proof.content.version],[0,2,1]);
|
||||
const body=Buffer.from(proof.content.body);assert.deepEqual(body.subarray(0,32),h(rows[0][1]));assert.equal(body.readInt32BE(32),cutoff);assert.equal(body.readBigInt64BE(68),BigInt(1700000000+cutoff)*1000n);assert.equal(body.readInt32BE(76),7);assert.equal(body.readBigInt64BE(112),1700000007000n);assert.equal(body.readInt32BE(120),7-cutoff);assert.equal(body[124],3);assert.equal(body.subarray(127).toString(),'test\nFORK');
|
||||
await assert.rejects(verifyCoreContentPair(p.coreDataItem,p.contentDataItem,h(rows[0][1])));
|
||||
if(process.env.M5_FORK_FIXTURES)fs.appendFileSync(process.env.M5_FORK_FIXTURES,`${cutoff}\t${calls[0].blockBytesB64}\t${b64(owner)}\n`);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
import { webcrypto } from 'node:crypto';
|
||||
const html=fs.readFileSync(new URL('../static-sites/arweave-viewer/index.html',import.meta.url),'utf8');
|
||||
const fixtures=fs.readFileSync(new URL('../../docs/Blockchain/vectors/core-content-v1.tsv',import.meta.url),'utf8').trim().split('\n').slice(1).map(l=>Object.fromEntries(l.split('\t').map((v,i)=>[['name','owner','core','coreHash','content','contentHash','coreItem','coreItemId','contentItem','contentItemId'][i],v])));
|
||||
const source=html.slice(html.indexOf(' const CORE_MAX_NUMBER'),html.indexOf(' const CHANNEL_TYPE_PERSONAL'));
|
||||
const funcs=html.slice(html.indexOf(' async function digestSha256'),html.indexOf(' function refKey('));
|
||||
const b64=html.slice(html.indexOf(' function base64Url('),html.indexOf(' async function arweaveOwnerAddressFromBlockchainKey'));
|
||||
const loader=html.slice(html.indexOf(' async function loadArweavePairs('),html.indexOf(' async function checkSolanaEndpoint('));
|
||||
const checks=html.slice(html.indexOf(' function v3ZeroHash('),html.indexOf(' function v3MetricText('));
|
||||
const ctx=vm.createContext({crypto:webcrypto,Uint8Array,DataView,TextDecoder,TextEncoder,btoa, MAGIC:'SHiNE',bytesToHex:b=>Buffer.from(b).toString('hex'),baseUrl:s=>s,fetch:()=>{throw Error('unexpected fetch')}});
|
||||
vm.runInContext(source+funcs+b64+loader+checks+';globalThis.viewer={parseCorePayload,parseBlockchainBlock,checkIndexedCoreTags,loadArweavePairs,v3Verification}',ctx);
|
||||
const v=ctx.viewer,bytes=s=>Uint8Array.from(Buffer.from(s,'hex'));
|
||||
const itemid=x=>Buffer.from(x,'hex').toString('base64url');
|
||||
const find=n=>fixtures.find(f=>f.name===n);
|
||||
const parse=f=>v.parseBlockchainBlock(bytes(f.core),bytes(f.content));
|
||||
test('viewer: parses all CORE/CONTENT vectors and computes exact hashes',async()=>{
|
||||
for(const f of fixtures){const b=await parse(f);assert.equal(b.hashHex,f.coreHash);assert.equal(b.contentDataItemId,itemid(f.contentItemId));assert.equal(b.contentHashChecked,true);}
|
||||
assert.equal((await parse(find('header'))).body.kind,'header');assert.equal((await parse(find('post'))).body.message,'Hello');
|
||||
});
|
||||
test('viewer: rejects tampered CONTENT, invalid CORE and wrong indexed tags',async()=>{
|
||||
const f=find('post');const bad=bytes(f.content);bad[bad.length-1]^=1;
|
||||
await assert.rejects(v.parseBlockchainBlock(bytes(f.core),bad),/CONTENT hash/);
|
||||
assert.throws(()=>v.parseCorePayload(bytes(f.core).slice(0,108)),/Invalid CORE/);
|
||||
assert.throws(()=>v.checkIndexedCoreTags({tags:[{name:'App',value:'test5592'}]},v.parseCorePayload(bytes(f.core))),/tags mismatch/);
|
||||
});
|
||||
test('viewer: requests CORE then CONTENT by ID and never claims signature verification',async()=>{
|
||||
const f=find('post'),id=itemid(f.coreItemId),cid=itemid(f.contentItemId),calls=[];
|
||||
ctx.fetch=async url=>{calls.push(url);const raw=url.endsWith(cid)?f.content:f.core;return {ok:true,arrayBuffer:async()=>bytes(raw).buffer};};
|
||||
const r=await v.loadArweavePairs('https://mock.invalid',[{id,owner:{address:'indexed'},tags:[{name:'App',value:'test5595'},{name:'n',value:'2'},{name:'l',value:'1'}]}]);
|
||||
assert.deepEqual(calls,[`https://mock.invalid/${id}`,`https://mock.invalid/${cid}`]);assert.equal(r.blocks[0].hashHex,f.coreHash);
|
||||
const checks=v.v3Verification(r.blocks);assert.equal(checks.signature.ok,0);assert.equal(checks.signature.na,1);assert.equal(checks.global.na,1);
|
||||
ctx.fetch=async url=>url.endsWith(cid)?{ok:false,status:404}:{ok:true,arrayBuffer:async()=>bytes(f.core).buffer};
|
||||
await assert.rejects(v.loadArweavePairs('https://mock.invalid',[{id,tags:[{name:'App',value:'test5595'},{name:'n',value:'2'},{name:'l',value:'1'}]}]),/CONTENT.*404/);
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { signEventContainer, unpackCoreContent, packCoreContent, decodeCore, decodeContent, readStoredLineMeta, submitSignedEvent } from '../js/services/core-content.js';
|
||||
import { parseAns104DataItem } from '../js/services/ans104-data-item.js';
|
||||
import { inspectBlockchainDataItem } from '../js/services/blockchain-entry-inspector.js';
|
||||
import { checkArweavePair, readSignedBlock } from '../js/services/blockchain-proof-service.js';
|
||||
import { buildBlockchainSnapshotFile } from '../js/services/shine-blockchain-snapshot-service.js';
|
||||
const rows=fs.readFileSync(new URL('../../docs/Blockchain/vectors/core-content-v1.tsv',import.meta.url),'utf8').trim().split('\n').slice(1).map(r=>r.split('\t'));
|
||||
const unhex=s=>Buffer.from(s,'hex');
|
||||
const fixture=r=>packCoreContent(unhex(r[6]),unhex(r[8]));
|
||||
const base64=b=>Buffer.from(b).toString('base64');
|
||||
const cursor={ blockchainName:'Alice@shine-001', blockNumber:2, prevBlockHash:rows[1][3] };
|
||||
const signed={bytes:fixture(rows[2]),hash:rows[2][3]};
|
||||
function oldFactoryBody(core,content,ordinal=7){
|
||||
if(!core.line) return content.body;
|
||||
const fixed=[3,4].includes(content.type), prefix=Buffer.alloc(fixed?40:44), offset=fixed?0:4;
|
||||
if(!fixed) prefix.writeInt32BE(content.type===0?0:core.line.lineCode,0);
|
||||
prefix.writeInt32BE(core.line.prevLineBlockNumber,offset);
|
||||
Buffer.from(core.line.prevLineCoreHash32).copy(prefix,offset+4);
|
||||
prefix.writeInt32BE(ordinal,offset+36);
|
||||
return Buffer.concat([prefix,content.body]);
|
||||
}
|
||||
test('existing body factories produce exact independent signed pair; ordinal is not signed',async()=>{
|
||||
const key=await crypto.subtle.importKey('pkcs8',Buffer.concat([unhex('302e020100300506032b657004220420'),Buffer.from(Array.from({length:32},(_,i)=>i))]),{name:'Ed25519'},false,['sign']);
|
||||
for(const r of rows){
|
||||
const core=decodeCore(unhex(r[2])),content=decodeContent(unhex(r[4]));
|
||||
const args={owner32:unhex(r[1]),privateKey:key,blockNumber:core.blockNumber,prevBlockHash:Buffer.from(core.prevCoreHash32).toString('hex'),timestamp:core.timestamp,msgType:content.type,msgSubType:content.subType,msgVersion:content.version};
|
||||
const result=await signEventContainer({...args,bodyBytes:oldFactoryBody(core,content)});
|
||||
assert.deepEqual(result.bytes,fixture(r),r[0]);assert.equal(result.hash,r[3]);
|
||||
if(core.line){
|
||||
const again=await signEventContainer({...args,bodyBytes:oldFactoryBody(core,content,42)});
|
||||
assert.deepEqual(again.bytes,result.bytes);
|
||||
const meta=readStoredLineMeta(result.bytes,42);
|
||||
assert.equal(meta.lineSequence,42);assert.equal(meta.lineCode,core.line.lineCode>2147482623?0:core.line.lineCode);
|
||||
assert.throws(()=>readStoredLineMeta(result.bytes,null));assert.throws(()=>readStoredLineMeta(result.bytes,-1));
|
||||
}
|
||||
const inspection=await inspectBlockchainDataItem(base64(result.bytes),42);
|
||||
assert.equal(inspection.frame.blockNumber,core.blockNumber);assert.equal(inspection.frame.type,content.type);
|
||||
assert.deepEqual(Buffer.from(inspection.frame.bodyBytes),Buffer.from(content.body));
|
||||
if(core.line) assert.equal(inspection.frame.body.line.lineSequence,42);
|
||||
if(core.blockNumber===0) assert.equal(inspection.frame.body.license,null);
|
||||
}
|
||||
});
|
||||
test('lost response: retransmit the identical signed container, then confirm canonical bytes',async()=>{
|
||||
const calls=[];
|
||||
const ws={request:async(op,payload)=>{calls.push({op,payload});if(calls.length===1)throw Error('timeout');if(op==='AddBlock')return {status:400,payload:{code:'bad_block_number',serverLastGlobalNumber:3}};return {status:200,payload:{blockHash:signed.hash,blockBytesB64:base64(signed.bytes)}};}};
|
||||
const result=await submitSignedEvent(ws,cursor,signed);
|
||||
assert.equal(result.status,200);assert.equal(result.payload.serverLastGlobalNumber,2);assert.equal(result.payload.serverLastGlobalHash,signed.hash);
|
||||
assert.deepEqual(calls[0],calls[1]);assert.equal(calls[2].op,'GetBlockchainBlock');
|
||||
});
|
||||
test('ambiguous outcome with mismatched bytes never authorizes fresh signing',async()=>{
|
||||
let count=0;
|
||||
const ws={request:async(op)=>{count++;if(op==='AddBlock')throw Error('timeout');return {status:200,payload:{blockHash:signed.hash,blockBytesB64:base64(fixture(rows[3]))}};}};
|
||||
await assert.rejects(submitSignedEvent(ws,cursor,signed),/outcome unknown/);assert.equal(count,3);
|
||||
});
|
||||
test('definite rejection preserves original error for existing line retry',async()=>{
|
||||
const response={status:400,payload:{code:'bad_prev_line_hash',serverLastGlobalNumber:1}};
|
||||
assert.equal(await submitSignedEvent({request:async()=>response},cursor,signed),response);
|
||||
});
|
||||
test('proof checks both archive payloads, not just CORE',async()=>{
|
||||
const r=rows[2];const proof=await readSignedBlock({authService:{ws:{request:async()=>({status:200,payload:{blockHash:r[3],blockBytesB64:base64(fixture(r))}})}},blockchainName:cursor.blockchainName,blockNumber:2,blockHash:r[3]});
|
||||
const original=globalThis.fetch;const calls=[];
|
||||
try{globalThis.fetch=async url=>{calls.push(url);return new Response(url.endsWith(proof.actualId)?proof.data:proof.contentData);};assert.equal((await checkArweavePair(proof)).status,'valid');assert.equal(calls.length,2);
|
||||
globalThis.fetch=async url=>new Response(url.endsWith(proof.actualId)?proof.data:new Uint8Array([0]));assert.equal((await checkArweavePair(proof)).status,'invalid');
|
||||
globalThis.fetch=async url=>url.endsWith(proof.actualId)?new Response(proof.data):new Response(null,{status:404});assert.equal((await checkArweavePair(proof)).status,'unavailable');
|
||||
}finally{globalThis.fetch=original;}
|
||||
});
|
||||
test('snapshot records are independently delimited and retain original bytes',async()=>{
|
||||
const result=await buildBlockchainSnapshotFile({authService:{ws:{request:async(op,{blockNumber})=>({status:200,payload:{blockBytesB64:base64(fixture(rows[blockNumber]))}})}},login:'Alice@shine',blockchainName:cursor.blockchainName,lastBlockNumber:2});
|
||||
const bytes=Buffer.from(await result.file.arrayBuffer());assert.equal(bytes.subarray(0,8).toString(),'SHINECC2');let pos=8;
|
||||
for(const r of rows.slice(0,3)){const n=bytes.readUInt32BE(pos);pos+=4;assert.deepEqual(bytes.subarray(pos,pos+n),Buffer.from(fixture(r)));pos+=n;}
|
||||
assert.equal(pos,bytes.length);assert.equal(result.totalBytes,pos);
|
||||
});
|
||||
@@ -110,3 +110,9 @@ test('V3/V4: вход через нижнюю кнопку очищает исс
|
||||
assert.match(view, /void resetBarrier\.then\(async \(\) =>/);
|
||||
assert.doesNotMatch(switcher, /select\.addEventListener\('change',[\s\S]*resetExplorerOnTabEntry/);
|
||||
});
|
||||
|
||||
test('V4 Canvas открывается по умолчанию, но ранее выбранная версия сохраняется', () => {
|
||||
const switcher = readFileSync(new URL('../js/pages/network-version-switcher.js', import.meta.url), 'utf8');
|
||||
assert.match(switcher, /const DEFAULT_MODE = 'explorer-canvas';/);
|
||||
assert.match(switcher, /MODES\.has\(saved\) \? saved : DEFAULT_MODE/);
|
||||
});
|
||||
|
||||
@@ -21,22 +21,20 @@ const context = {
|
||||
int8Byte: value => Uint8Array.of(value),
|
||||
concatBytes: (...parts) => Uint8Array.from(parts.flatMap(part => Array.from(part))),
|
||||
Uint8Array,
|
||||
HEADER_LICENSE_FIELD_CC0: 'license:CC0-1.0',
|
||||
};
|
||||
const makeHeaderBodyBytes = vm.runInNewContext(`function makeHeaderBodyBytes(${makeBytesFunction}\nmakeHeaderBodyBytes`, context);
|
||||
|
||||
test('HEADER v2 places literal license:CC0-1.0 before the initial key', () => {
|
||||
test('CORE/CONTENT HEADER v1 contains login and initial key without CC0', () => {
|
||||
const key = Uint8Array.from({ length: 32 }, (_, n) => n + 1);
|
||||
const result = makeHeaderBodyBytes({ login: 'Alice@shine', initialBlockchainKey32: key });
|
||||
const login = new TextEncoder().encode('Alice@shine');
|
||||
assert.equal(new TextDecoder().decode(result.slice(0,5)), 'SHiNE');
|
||||
assert.equal(result[5], login.length);
|
||||
assert.deepEqual(Array.from(result.slice(6, 6+login.length)), Array.from(login));
|
||||
assert.equal(new TextDecoder().decode(result.slice(6+login.length, 6+login.length+15)), 'license:CC0-1.0');
|
||||
assert.deepEqual(Array.from(result.slice(6+login.length+15)), Array.from(key));
|
||||
assert.equal(result.length, 5 + 1 + login.length + 15 + 32);
|
||||
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION_CC0/);
|
||||
assert.match(auth, /export const HEADER_VERSION_CC0 = 2/);
|
||||
assert.deepEqual(Array.from(result.slice(6+login.length)), Array.from(key));
|
||||
assert.equal(result.length, 5 + 1 + login.length + 32);
|
||||
assert.match(auth, /msgSubType: MSG_SUBTYPE_TECH_HEADER,\s*msgVersion: HEADER_VERSION/);
|
||||
assert.match(auth, /export const HEADER_VERSION = 1/);
|
||||
});
|
||||
|
||||
test('free and paid registration both require accepted documents before any registration operation', { skip: !hasRegistrationTerms }, () => {
|
||||
|
||||
Reference in New Issue
Block a user