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
+2 -3
View File
@@ -27,12 +27,11 @@ test('подмена payload не проходит проверку подпис
assert.equal(proof.signatureValid, false);
assert.notEqual(Buffer.from(proof.frameHashBytes).toString('hex'), expectedHash);
});
test('по API нельзя скачать DataItem с подменённым хешем или ID', async () => {
test('активный CORE API не принимает старый Frame как пару', async () => {
const bytes = new Uint8Array(await readFile(signedPath));
const authService = { ws: { request: async () => ({ status: 200, payload: {
blockHash: expectedHash, 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/);
await assert.rejects(readSignedBlock({authService, blockchainName:'wwwww@shine-001',blockNumber:11,blockHash:expectedHash,dataItemId:expectedId}));
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 { decodeCore, readCoreBlock } from '../js/services/core-content.js';
import { inspectCoreBlock } from '../js/services/blockchain-entry-inspector.js';
import { readSignedBlock } from '../js/services/blockchain-proof-service.js';
import { AuthService } from '../js/services/auth-service.js';
import { saveEncryptedUserSecrets } from '../js/services/key-vault.js';
import { canonicalReadPosts, readPrefixCount } from '../js/services/channel-message-ordinals.js';
import { buildBlockchainSnapshotFile } from '../js/services/shine-blockchain-snapshot-service.js';
const b64 = hex => Buffer.from(hex,'hex').toString('base64');
const id = hex => Buffer.from(hex,'hex').toString('base64url');
const fixtures = fs.readFileSync(new URL('../../docs/Blockchain/vectors/core-content-v1.tsv', import.meta.url),'utf8').trim().split('\n').slice(1).map(line => line.split('\t'));
const rows = fixtures.map(([name,owner,core,coreHash,content,contentHash,coreItem,coreItemId,contentItem,contentItemId]) => ({name,blockNumber:decodeCore(Uint8Array.from(Buffer.from(core,'hex'))).blockNumber,coreHash,contentHash,coreDataItemId:id(coreItemId),contentDataItemId:id(contentItemId),coreDataItemB64:b64(coreItem),contentDataItemB64:b64(contentItem),contentStatus:'VALID'}));
test('signed CORE reader and existing semantic inspector decode all external vectors', async () => {
for (const row of rows) {
const p = await readCoreBlock(row,{requireContent:true});
const inspection = await inspectCoreBlock(row);
assert.equal(p.actualId,row.coreDataItemId,row.name);
assert.equal(inspection.frame.blockNumber,row.blockNumber,row.name);
assert.equal(inspection.frame.type,p.content.type,row.name);
assert.equal(inspection.contentDataItemId,row.contentDataItemId,row.name);
assert.notEqual(inspection.frame.body.kind,'unknown',row.name);
if (p.core.line) assert.equal(inspection.frame.body.line.lineCode,p.core.line.lineCode,row.name);
}
});
test('CORE can be inspected without CONTENT, but a full proof cannot be claimed',async()=>{
const row={...rows[0],contentDataItemB64:null,contentStatus:'MISSING'};
assert.equal((await inspectCoreBlock(row)).frame.body.kind,'unknown');
await assert.rejects(readCoreBlock(row,{requireContent:true}),/CONTENT unavailable/);
});
test('read rejects altered metadata, substituted content, and invalid signature',async()=>{
const row=rows[0];
for (const change of [{blockNumber:1},{coreHash:'a'.repeat(64)},{contentDataItemId:'A'.repeat(43)},{contentHash:'b'.repeat(64)},{coreDataItemId:'B'.repeat(43)},{contentDataItemB64:rows[1].contentDataItemB64}]) await assert.rejects(readCoreBlock({...row,...change}));
const raw=Buffer.from(row.coreDataItemB64,'base64'); raw[2]^=1;
await assert.rejects(readCoreBlock({...row,coreDataItemB64:raw.toString('base64')}));
assert.equal((await inspectCoreBlock({...row,contentStatus:'INVALID'})).frame.body.kind,'unknown');
});
test('existing proof request verifies both exact DataItems and expected CORE ID',async()=>{
const row=rows[2];
const authService={ws:{request:async(op,payload)=>{assert.equal(op,'GetBlockchainBlock');assert.equal(payload.blockNumber,row.blockNumber);return {status:200,payload:{...row,blockHash:row.coreHash}};}}};
const args={authService,blockchainName:'Alice-001',blockNumber:row.blockNumber,blockHash:row.coreHash,dataItemId:row.coreDataItemId};
const p=await readSignedBlock(args);
assert.equal(Buffer.from(p.bytes).toString('base64'),row.coreDataItemB64);
assert.equal(Buffer.from(p.contentProof.bytes).toString('base64'),row.contentDataItemB64);
await assert.rejects(readSignedBlock({...args,dataItemId:'A'.repeat(43)}),/Arweave/);
await assert.rejects(readSignedBlock({...args,blockHash:'a'.repeat(64)}));
});
const h=x=>x.repeat(64);
const root={blockNumber:5,blockHash:h('a')};
const p1={authorLogin:'Alice',localNumber:2,messageRef:{blockNumber:6,blockHash:h('b')}};
const p2={authorLogin:'Alice',localNumber:1,messageRef:{blockNumber:9,blockHash:h('c')}};
const summary={channel:{ownerLogin:'Alice',channelRoot:root},followHash:h('d'),messagesCount:2,readAnchor:p2.messageRef};
test('read prefix is canonical not display order, and never skips an unseen publication',()=>{
const ordered=canonicalReadPosts([p2,p1],summary);
assert.deepEqual(ordered,[p1,p2]);
assert.equal(readPrefixCount(ordered,0,new Set([1])),0);
assert.equal(readPrefixCount(ordered,0,new Set([2])),1);
assert.equal(readPrefixCount(ordered,1,new Set([1])),2);
assert.equal(canonicalReadPosts([p2],summary),null);
assert.equal(canonicalReadPosts([p2,p1],{...summary,readAnchor:{...p2.messageRef,blockHash:h('e')}}),null);
assert.equal(canonicalReadPosts([p2,{...p1,authorLogin:'Other'}],summary),null);
assert.deepEqual(canonicalReadPosts([],{...summary,messagesCount:0,readAnchor:root}),[]);
});
test('SetChannelReadState signs the exact existing server contract with client key',async()=>{
const seed=Buffer.from(Array.from({length:32},(_,i)=>i));
const pkcs8=Buffer.concat([Buffer.from('302e020100300506032b657004220420','hex'),seed]);
const auth=new AuthService('wss://test.invalid/ws');
await saveEncryptedUserSecrets('Bob','read-test',{clientKey:pkcs8.toString('base64')});
const mark={owner:'Alice',root:5,rootHash:h('a'),followHash:h('d'),anchor:6,anchorHash:h('b'),timeMs:1760000000000};
const result={applied:true,state:{followHash:mark.followHash,initialized:true,readCount:1,unreadCount:1}};
auth.ws.request=async(op,payload)=>{
assert.equal(op,'SetChannelReadState');const {signatureB64,...rest}=payload;
assert.deepEqual(rest,mark);
const pub=await crypto.subtle.importKey('raw',Buffer.from(fixtures[0][1],'hex'),{name:'Ed25519'},false,['verify']);
assert.equal(await crypto.subtle.verify('Ed25519',pub,Buffer.from(signatureB64,'base64'),new TextEncoder().encode(['SHiNE_CORE_READ_V1','test5593','Bob','Alice',5,h('a'),h('d'),6,h('b'),mark.timeMs].join('|'))),true);
return {status:200,payload:{result}};
};
assert.deepEqual(await auth.setChannelReadState({login:'Bob',storagePwd:'read-test',...mark}),result);
await assert.rejects(auth.setChannelReadState({login:'Bob',storagePwd:'read-test',...mark,anchor:4}),/BAD_READ_STATE/);
await assert.rejects(auth.setChannelReadState({login:'Bob',storagePwd:'read-test',ownerBlockchainName:'Alice-001',channelName:'news',readCount:1}),/BAD_READ_STATE/);
});
test('public channel resolution uses original profile API, not another user’s subscriptions',async()=>{
const auth=new AuthService('wss://test.invalid/ws');
auth.ws.request=async(op,payload)=>{assert.equal(op,'ListUserProfileChannels');assert.deepEqual(payload,{login:'Alice',mode:'owned',limit:500,offset:0,includeDeleted:false});return {status:200,payload:{channels:[{ownerLogin:'Alice',ownerBlockchainName:'Alice-001',slug:'news',rootBlockNumber:5,rootBlockHashHex:h('a')}]}};};
const [row]=await auth.listOwnedChannelSummaries('Alice');
assert.equal(row.channel.channelName,'news');assert.deepEqual(row.channel.channelRoot,root);
});
test('snapshot creation is blocked until D rather than generating an empty legacy file',async()=>{
await assert.rejects(buildBlockchainSnapshotFile({authService:{ws:{request:()=>assert.fail('must not fetch legacy blocks')}}}));
});
@@ -0,0 +1,202 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { encodeContent, decodeContent, encodeCore, decodeCore, coreHex, coreHashBytes,
signCoreContentPair, verifyCoreContentPair, splitEventBody, CORE_MAX_CONTENT_BYTES } from '../js/services/core-content.js';
import { AuthService } from '../js/services/auth-service.js';
import { saveEncryptedUserSecrets } from '../js/services/key-vault.js';
import { SHINE_CORE_LINE_PROFILE, SHINE_CORE_LINE_CONNECTION, SHINE_CORE_LINE_TECH } from '../js/services/protocol-tags.js';
const unhex = s=>Uint8Array.from(Buffer.from(s,'hex'));
const b64 = b=>Buffer.from(b).toString('base64');
const unb64 = s=>Uint8Array.from(Buffer.from(s,'base64'));
const seed = Buffer.from(Array.from({length:32},(_,i)=>i));
const pkcs8 = Buffer.concat([Buffer.from('302e020100300506032b657004220420','hex'),seed]);
const key = await crypto.subtle.importKey('pkcs8',pkcs8,{name:'Ed25519'},false,['sign']);
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 owner = unhex(rows[0][1]);
const zero = new Uint8Array(32);
const h = 'ab'.repeat(32);
const head = (blockNumber, coreHash=h)=>({blockNumber,coreHash});
const names = { blockchainName:'Alice-001' };
const headResponse = (global, line=null)=>({status:200,payload:{result:{...names,global,line}}});
// The production codec, not a second Buffer implementation, must reproduce the external fixtures.
test('runtime codec and signer reproduce all eight Java/Python vectors byte for byte', async()=>{
for(const [name,ownerHex,coreHexValue,coreHash,contentHex,contentHash,coreItemHex,coreId,contentItemHex,contentId] of rows){
const core=decodeCore(unhex(coreHexValue)), content=decodeContent(unhex(contentHex));
assert.equal(coreHex(encodeCore(core)),coreHexValue,name);
assert.equal(coreHex(encodeContent(content)),contentHex,name);
const produced=await signCoreContentPair({...core,owner32:unhex(ownerHex),privateKey:key,content});
assert.equal(coreHex(produced.coreDataItem),coreItemHex,name);
assert.equal(coreHex(produced.contentDataItem),contentItemHex,name);
assert.equal(coreHex(produced.coreHash32),coreHash,name);
assert.equal(coreHex(produced.contentHash32),contentHash,name);
assert.equal(coreHex(produced.contentDataItemId32),contentId,name);
const checked=await verifyCoreContentPair(produced.coreDataItem,produced.contentDataItem,owner);
assert.equal(coreHex(checked.coreDataItemId32),coreId,name);
}
});
test('codec rejects malformed sizes, version bytes, indices and bad genesis', ()=>{
const core=decodeCore(unhex(rows[0][2]));
for(const bytes of [new Uint8Array(108),new Uint8Array(150),Uint8Array.of(1)]) assert.throws(()=>decodeCore(bytes));
assert.throws(()=>encodeCore({...core,blockNumber:2147482624}));
assert.throws(()=>encodeCore({...core,timestamp:-1}));
assert.throws(()=>encodeCore({...core,prevCoreHash32:unhex(h)}));
assert.throws(()=>encodeCore({...core,blockNumber:1,line:{lineCode:0,prevLineBlockNumber:1,prevLineCoreHash32:zero}}));
assert.throws(()=>decodeContent(Uint8Array.of(0,0,0,0,0,0,1)));
assert.throws(()=>encodeContent({type:65536,subType:0,version:1,body:zero}));
assert.throws(()=>encodeContent({type:1,subType:10,version:1,body:new Uint8Array(CORE_MAX_CONTENT_BYTES-6)}));
});
test('pair validation rejects wrong owner, swapped valid content and tampering', async()=>{
const c=unhex(rows[0][6]), p=unhex(rows[0][8]);
await assert.rejects(verifyCoreContentPair(c,p,zero));
await assert.rejects(verifyCoreContentPair(c,unhex(rows[1][8]),owner));
const modified=p.slice(); modified[modified.length-1]^=1;
await assert.rejects(verifyCoreContentPair(c,modified,owner));
});
test('adapter moves only predecessor/line code, never old lineSequence, into CORE',()=>{
const fixed=new Uint8Array(42); fixed.set(unhex(h),4); new DataView(fixed.buffer).setInt32(36,123); fixed.set([1,2],40);
for(const [msgType,lineCode] of [[3,SHINE_CORE_LINE_CONNECTION],[4,SHINE_CORE_LINE_PROFILE]]){
const {content,line}=splitEventBody({msgType,msgSubType:1,bodyBytes:fixed});
assert.deepEqual(Array.from(content.body),[1,2]); assert.equal(line.lineCode,lineCode); assert.equal(line.prevLineBlockNumber,0); assert.equal(coreHex(line.prevLineCoreHash32),h);
}
const explicit=new Uint8Array(46); explicit.set(fixed,4);
const tech=splitEventBody({msgType:0,msgSubType:1,bodyBytes:explicit});
assert.equal(tech.line.lineCode,SHINE_CORE_LINE_TECH); assert.deepEqual(Array.from(tech.content.body),[1,2]);
new DataView(explicit.buffer).setInt32(0,9);
const post=splitEventBody({msgType:1,msgSubType:10,bodyBytes:explicit});
assert.equal(post.line.lineCode,9); assert.deepEqual(Array.from(post.content.body),[1,2]);
assert.throws(()=>splitEventBody({msgType:4,msgSubType:1,bodyBytes:zero}));
assert.equal(splitEventBody({msgType:2,msgSubType:1,bodyBytes:zero}).line,null);
});
async function service(request, withKey=true){
const auth=new AuthService('wss://test.invalid/ws');
// Real existing encrypted vault, with in-memory fallback in Node; no network or real keys.
await saveEncryptedUserSecrets('Alice','test-password',withKey?{blockchainKey:b64(pkcs8)}:{});
auth.ws.request=request;
return auth;
}
const args={login:'Alice',storagePwd:'test-password',_skipHeaderEnsure:true};
async function checked(payload){
assert.deepEqual(Object.keys(payload).sort(),['blockNumber','blockchainName','contentDataItemB64','coreDataItemB64','prevBlockHash'].sort());
return verifyCoreContentPair(unb64(payload.coreDataItemB64),unb64(payload.contentDataItemB64),owner);
}
test('original ensureBlockchainHeader uses registered spelling and CreateGenesis, then no duplicate',async()=>{
let exists=false; const writes=[];
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(exists?head(0):null);
assert.equal(op,'CreateGenesis'); const pair=await checked(p); assert.equal(p.prevBlockHash,''); assert.equal(p.blockNumber,0);
assert.equal(pair.content.version,1); assert.equal(pair.core.line,null);
assert.equal(Buffer.from(pair.content.body).toString('hex'),Buffer.concat([Buffer.from('SHiNE'),Buffer.of(5),Buffer.from('Alice'),Buffer.from(owner)]).toString('hex'));
exists=true; writes.push(p);return {status:200,payload:{serverLastGlobalNumber:0,serverLastGlobalHash:coreHex(pair.coreHash32)}};
});
auth.getUser=async()=>({exists:true,login:'Alice',serverLastGlobalNumber:exists?0:-1,blockchainName:'Alice-001'});
await auth.ensureBlockchainHeader('alice','test-password'); await auth.ensureBlockchainHeader('alice','test-password');
assert.equal(writes.length,1);
});
test('ordinary AddBlock signs fresh global + line head; no back32 lookup or legacy payload',async()=>{
const calls=[]; const lineBody=new Uint8Array(47); lineBody.set(unhex(h),8); new DataView(lineBody.buffer).setInt32(4,3); lineBody.set([0,1,65],44);
const auth=await service(async(op,p)=>{
calls.push(op);
if(op==='GetMyCoreHeads'){assert.equal(p.lineCode,0);return headResponse(head(40),head(3));}
assert.equal(op,'AddBlock'); const pair=await checked(p);
assert.equal(p.blockNumber,41);assert.equal(p.prevBlockHash,h);assert.equal(pair.core.line.prevLineBlockNumber,3);assert.equal(pair.core.line.lineCode,0);
assert.deepEqual(Array.from(pair.content.body),[0,1,65]);return {status:200,payload:{serverLastGlobalNumber:41,serverLastGlobalHash:coreHex(pair.coreHash32)}};
});
await auth.addBlockSigned({...args,msgType:1,msgSubType:10,bodyBytes:lineBody});
assert.deepEqual(calls,['GetMyCoreHeads','AddBlock']);
});
test('retry only explicit global conflict; refresh head and re-sign without changing content',async()=>{
let reads=0,writes=0;let original;
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(head(10+reads++,reads===1?h:'cd'.repeat(32)));
const pair=await checked(p);writes++;
if(writes===1){original=p.contentDataItemB64;return {status:409,payload:{code:'GLOBAL_HEAD_CONFLICT'}};}
assert.equal(p.blockNumber,12); assert.equal(p.prevBlockHash,'cd'.repeat(32));assert.equal(p.contentDataItemB64,original);
return {status:200,payload:{serverLastGlobalNumber:12,serverLastGlobalHash:coreHex(pair.coreHash32)}};
});
await auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero});assert.equal(writes,2);
});
test('reject stale line, revoked session, unknown outcome and legacy remote signer without fallback',async()=>{
const body=new Uint8Array(44);body.set(unhex(h),8);
let writes=0;
let auth=await service(async(op)=>{if(op==='GetMyCoreHeads')return headResponse(head(4),head(1));writes++;throw new Error('should not write');});
await assert.rejects(auth.addBlockSigned({...args,msgType:1,msgSubType:10,bodyBytes:body}),e=>e.code==='LINE_HEAD_CONFLICT');assert.equal(writes,0);
auth=await service(async(op)=>{if(op==='GetMyCoreHeads')return headResponse(head(4));writes++;return {status:401,payload:{code:'SESSION_NOT_FOUND'}};});
await assert.rejects(auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero}),e=>e.code==='SESSION_NOT_FOUND');assert.equal(writes,1);
auth=await service(async(op)=>{if(op==='GetMyCoreHeads')return headResponse(head(4));if(op==='GetBlockchainBlock')return {status:404};writes++;throw new Error('timeout');});
await assert.rejects(auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero}),e=>e.code==='CORE_WRITE_OUTCOME_UNKNOWN');assert.equal(writes,3);
auth=await service(async()=>{throw new Error('unexpected network');},false);
await assert.rejects(auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero}),/remote signing is not migrated/);
});
test('existing create-channel, post and profile factories send original semantic body and CORE line',async()=>{
const writes=[];
let global=head(0), channelRoot=null;
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(global,p.lineCode===1?channelRoot:p.lineCode==null?null:head(0));
if(op==='GetBlockchainBlock'){assert.equal(p.blockNumber,1);return {status:200,payload:{blockHash:channelRoot.coreHash}};}
assert.equal(op,'AddBlock'); const pair=await checked(p);writes.push(pair);
global=head(p.blockNumber,coreHex(pair.coreHash32));
if(pair.content.type===0)channelRoot=global;
return {status:200,payload:{serverLastGlobalNumber:global.blockNumber,serverLastGlobalHash:global.coreHash}};
});
auth.getUser=async()=>({exists:true,login:'Alice',blockchainName:'Alice-001',serverLastGlobalNumber:global.blockNumber});
const channel=await auth.addBlockCreateChannel({login:'Alice',storagePwd:'test-password',channelName:'News'});
assert.equal(writes[0].core.line.lineCode,SHINE_CORE_LINE_TECH);
assert.deepEqual(Array.from(writes[0].content.body),[4,78,101,119,115,0,0,0,1,0,1]);
await auth.addBlockTextPost({login:'Alice',storagePwd:'test-password',channel:{...channel.channel,channelName:'News'},text:'Hello'});
assert.equal(writes[1].core.line.lineCode,1);assert.equal(writes[1].core.line.prevLineBlockNumber,1);
assert.equal(coreHex(writes[1].content.body),'000548656c6c6f');
await auth.addBlockUserParam({login:'Alice',storagePwd:'test-password',param:'name',value:'Alice'});
assert.equal(writes[2].core.line.lineCode,SHINE_CORE_LINE_PROFILE);
assert.equal(coreHex(writes[2].content.body),'00046e616d650005416c696365');
});
test('lost AddBlock response retries the identical signed pair even when server head advances',async()=>{
let first, writes=0;
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(head(4));
assert.equal(op,'AddBlock'); writes++;
if(writes===1){first=structuredClone(p);throw new Error('connection closed after commit');}
assert.deepEqual(p,first);
return {status:200,payload:{serverLastGlobalNumber:6,serverLastGlobalHash:'cd'.repeat(32)}};
});
const result=await auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero});
assert.equal(writes,2);assert.equal(result.submittedBlockNumber,5);assert.equal(result.submittedBlockHash,coreHex((await checked(first)).coreHash32));assert.equal(result.serverLastGlobalNumber,6);
});
test('ambiguous 5xx followed by conflict confirms only exact signed bytes in current fork',async()=>{
let first, pair, writes=0, reads=0;
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(head(++reads===1?4:6));
if(op==='GetBlockchainBlock')return {status:200,payload:{blockNumber:5,coreHash:coreHex(pair.coreHash32),contentStatus:'VALID',coreDataItemB64:first.coreDataItemB64,contentDataItemB64:first.contentDataItemB64}};
assert.equal(op,'AddBlock');writes++;
if(writes===1){first=structuredClone(p);pair=await checked(p);return {status:500,payload:{code:'DB_ERROR'}};}
assert.deepEqual(p,first);return {status:409,payload:{code:'GLOBAL_HEAD_CONFLICT'}};
});
const result=await auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero});
assert.equal(writes,2);assert.equal(reads,2);assert.equal(result.submittedBlockNumber,5);
});
test('uncertain write cannot trigger line re-signing on a later explicit conflict',async()=>{
let first,writes=0,builds=0;
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(head(4));
if(op==='GetBlockchainBlock')return {status:404};
writes++;
if(writes===1){first=structuredClone(p);throw new Error('lost response');}
assert.deepEqual(p,first);return {status:409,payload:{code:'GLOBAL_HEAD_CONFLICT'}};
});
await assert.rejects(auth.runLineWriteLocked('test',()=>{builds++;return auth.addBlockSigned({...args,msgType:2,msgSubType:1,bodyBytes:zero});}),e=>e.code==='CORE_WRITE_OUTCOME_UNKNOWN');
assert.equal(builds,1);assert.equal(writes,2);
});
test('CreateGenesis retry preserves exact signed bytes',async()=>{
let first,writes=0;
const auth=await service(async(op,p)=>{
if(op==='GetMyCoreHeads')return headResponse(null);
assert.equal(op,'CreateGenesis');writes++;
if(writes===1){first=structuredClone(p);throw new Error('lost genesis response');}
assert.deepEqual(p,first);return {status:200,payload:{serverLastGlobalNumber:0,serverLastGlobalHash:coreHex((await checked(p)).coreHash32)}};
});
auth.getUser=async()=>({exists:true,login:'Alice',serverLastGlobalNumber:-1,blockchainName:'Alice-001'});
await auth.ensureBlockchainHeader('Alice','test-password');assert.equal(writes,2);
});
@@ -0,0 +1,67 @@
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, Viewer, Python', () => {
const server=fs.readFileSync(new URL('../../SHiNE-server/shine-server-blockchain/src/main/java/blockchain/ShineProtocolTags.java',import.meta.url),'utf8');
const viewer=fs.readFileSync(new URL('../static-sites/arweave-viewer/index.html',import.meta.url),'utf8');
const publisher=fs.readFileSync(new URL('../../tools/test-publisher/protocol_tags.py',import.meta.url),'utf8');
assert.equal(SHINE_CORE_NAMESPACE,'test5593');
assert.match(server,/CORE_NAMESPACE\s*=\s*"test5593"/);
assert.match(viewer,/SHINE_CORE_NAMESPACE\s*=\s*'test5593'/);
assert.match(publisher,/CORE_NAMESPACE\s*=.*SHINE_CORE_NAMESPACE/);
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);
}
});
+60
View File
@@ -0,0 +1,60 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { KeyRotationClient } from '../js/services/key-rotation-service.js';
import { coreHex, coreHashBytes, signCoreContentPair, verifyCoreContentPair } from '../js/services/core-content.js';
import { parseAns104DataItem } from '../js/services/ans104-data-item.js';
import { SHINE_CORE_LINE_TECH } from '../js/services/protocol-tags.js';
const b64=b=>Buffer.from(b).toString('base64');
const unb64=s=>Uint8Array.from(Buffer.from(s,'base64'));
const id=b=>Buffer.from(b).toString('base64url');
const sha=async b=>new Uint8Array(await crypto.subtle.digest('SHA-256',b));
const old=await crypto.subtle.generateKey('Ed25519',true,['sign','verify']);
const next=await crypto.subtle.generateKey('Ed25519',true,['sign','verify']);
const owner= new Uint8Array(await crypto.subtle.exportKey('raw',old.publicKey));
const nextOwner= new Uint8Array(await crypto.subtle.exportKey('raw',next.publicKey));
const bundle={blockchainPair:{publicKeyB64:b64(nextOwner),privateKey:next.privateKey}};
const name='Alice-001', start=1760000000;
const rows=[];
async function append(type,subType,lineCode=null,prevLine=0){
const n=rows.length;
const pair=await signCoreContentPair({owner32:owner,privateKey:old.privateKey,content:{type,subType,version:1,body:new Uint8Array()},prevCoreHash32:n?coreHashBytes(rows[n-1].coreHash):new Uint8Array(32),blockNumber:n,timestamp:start+n,line:lineCode===null?null:{lineCode,prevLineBlockNumber:prevLine,prevLineCoreHash32:coreHashBytes(rows[prevLine].coreHash)}});
rows.push({blockchainName:name,blockNumber:n,coreHash:coreHex(pair.coreHash32),coreDataItemId:id(await sha(parseAns104DataItem(pair.coreDataItem).signature)),contentHash:coreHex(pair.contentHash32),contentDataItemId:id(pair.contentDataItemId32),coreDataItemB64:b64(pair.coreDataItem),contentDataItemB64:b64(pair.contentDataItem),contentStatus:'VALID'});
}
await append(0,0);await append(0,1,SHINE_CORE_LINE_TECH);await append(1,10,1,1);await append(0,1,SHINE_CORE_LINE_TECH,1);
const rotation={sourceBlockchainName:name,forkFromBlock:2,forkFromHash:rows[2].coreHash,sourceTipBlock:3,sourceTipHash:rows[3].coreHash,oldBlockchainKey:b64(owner),newBlockchainKey:b64(nextOwner),createdAtMs:(start+10)*1000,reasonCode:3,comment:' test\r\nrollback ',progressCurrent:0};
function fixture(change={}){
const writes=[],reads=[];
const client=new KeyRotationClient({ws:{request:async(op,payload)=>{
if(op==='GetBlockchainBlock'){reads.push(payload.blockNumber);assert.equal(payload.blockchainName,name);return {status:200,payload:{...rows[payload.blockNumber],...change[payload.blockNumber]}};}
if(op==='GetMyBlockchain'){assert.equal(payload.includeBlockBytes,false);return {status:200,payload:{blocks:rows.map(r=>({...r,contentDataItemB64:null})),tipBlockNumber:3,nextBeforeBlock:null}};}
assert.equal(op,'KeyRotationAddBlock');writes.push(payload);return {status:200,payload:{rotationStatus:'COPYING_CHAIN'}};
}}});
return {client,writes,reads};
}
test('original cutoff picker derives hash and time from signed CORE-only page',async()=>{
const {client}=fixture();const page=await client.getMyBlockchain();assert.equal(page.blocks[2].blockHash,rows[2].coreHash);assert.equal(page.blocks[2].timestampMs,(start+2)*1000);
});
test('rollback FORK preserves body layout and TECH predecessor before cutoff; deterministic retry',async()=>{
const {client,writes,reads}=fixture({1:{contentDataItemB64:null,contentStatus:'MISSING'}});const progress=[];
await client.copyCandidateChain({rotation,newBundle:bundle,onProgress:p=>progress.push(p)});
await client.copyCandidateChain({rotation,newBundle:bundle});assert.deepEqual(writes[0],writes[1]);assert.deepEqual(reads,[2,3,1,2,3,1]);assert.deepEqual(progress,[{phase:'copy',current:1,total:1}]);
const w=writes[0];assert.deepEqual(Object.keys(w).sort(),['blockNumber','contentDataItemB64','coreDataItemB64','prevBlockHash']);
const {core,content}=await verifyCoreContentPair(unb64(w.coreDataItemB64),unb64(w.contentDataItemB64),nextOwner);
assert.equal(core.blockNumber,3);assert.equal(core.timestamp,BigInt(start+10));assert.equal(coreHex(core.prevCoreHash32),rows[2].coreHash);assert.equal(core.line.lineCode,SHINE_CORE_LINE_TECH);assert.equal(core.line.prevLineBlockNumber,1);assert.equal(coreHex(core.line.prevLineCoreHash32),rows[1].coreHash);
assert.deepEqual([content.type,content.subType,content.version],[0,2,1]);
// Independent layout matching ForkContentBody.java, no structural prefix.
const b=Buffer.from(content.body);assert.equal(b.subarray(0,32).toString('base64'),b64(owner));assert.equal(b.readInt32BE(32),2);assert.equal(b.subarray(36,68).toString('hex'),rows[2].coreHash);assert.equal(b.readBigInt64BE(68),BigInt((start+2)*1000));assert.equal(b.readInt32BE(76),3);assert.equal(b.subarray(80,112).toString('hex'),rows[3].coreHash);assert.equal(b.readBigInt64BE(112),BigInt((start+3)*1000));assert.equal(b.readInt32BE(120),1);assert.equal(b[124],3);assert.equal(b.readUInt16BE(125),13);assert.equal(b.subarray(127).toString(),'test\nrollback');
});
test('genesis cutoff uses HEADER as TECH predecessor and preserves old source tip',async()=>{
const {client,writes}=fixture();await client.copyCandidateChain({rotation:{...rotation,forkFromBlock:0,forkFromHash:rows[0].coreHash},newBundle:bundle});const {core}=await verifyCoreContentPair(unb64(writes[0].coreDataItemB64),unb64(writes[0].contentDataItemB64),nextOwner);assert.equal(core.line.prevLineBlockNumber,0);assert.equal(coreHex(core.line.prevLineCoreHash32),rows[0].coreHash);
});
test('wrong source metadata or session hash refuses candidate before write',async()=>{
for(const [overrides,change] of [[{forkFromHash:'ff'.repeat(32)},{}],[{}, {2:{coreHash:'ff'.repeat(32)}}],[{}, {1:{blockchainName:'Bob-001'}}]]){
const {client,writes}=fixture(change);await assert.rejects(client.copyCandidateChain({rotation:{...rotation,...overrides},newBundle:bundle}));assert.equal(writes.length,0);
}
});
test('resume of published candidate does not submit again; invalid key and comment rejected',async()=>{
const {client,writes,reads}=fixture();await client.copyCandidateChain({rotation:{...rotation,progressCurrent:1},newBundle:bundle});assert.equal(writes.length,0);assert.equal(reads.length,0);
await assert.rejects(client.copyCandidateChain({rotation:{...rotation,newBlockchainKey:b64(owner)},newBundle:bundle}));
await assert.rejects(client.copyCandidateChain({rotation:{...rotation,comment:'я'.repeat(513)},newBundle:bundle}));assert.equal(writes.length,0);
});
@@ -0,0 +1,31 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { AuthService } from '../js/services/auth-service.js';
test('профиль читает CORE-проекцию, а не устаревший ListUserParams', async () => {
const calls = [];
const auth = new AuthService('wss://test.invalid/ws');
auth.ws.request = async (op, payload) => {
calls.push([op, payload]);
assert.equal(op, 'GetCoreProfile');
if (!payload.afterKey) {
return { status: 200, payload: { result: {
values: [{ key: 'first_name', value: 'Алиса', timestampSeconds: 100 }], nextAfterKey: 'first_name',
} } };
}
return { status: 200, payload: { result: {
values: [{ key: 'web', value: 'https://example.test', timestampSeconds: 101 }], nextAfterKey: null,
} } };
};
assert.deepEqual(await auth.listUserParams('Alice@shine'), {
params: [
{ param: 'first_name', value: 'Алиса', time_ms: 100000 },
{ param: 'web', value: 'https://example.test', time_ms: 101000 },
],
});
assert.deepEqual(calls, [
['GetCoreProfile', { login: 'Alice@shine', afterKey: '', limit: 20 }],
['GetCoreProfile', { login: 'Alice@shine', afterKey: 'first_name', limit: 20 }],
]);
});
+4 -5
View File
@@ -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 CORE 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_CONTENT_VERSION/);
assert.match(auth, /export const HEADER_CONTENT_VERSION = 1/);
});
test('inspector decodes both v1 and v2 and rejects invalid v2 license/order', () => {
@@ -11,11 +11,10 @@ const api=read('shine-UI/js/services/registration-v2-api.js');
const ops=['GetNamespaces','CheckRegistrationLogin','CheckRegistrationEmail',
'StartFreeRegistration','ConfirmFreeRegistration','GetRegistrationStatus'];
test('в серверном реестре ровно согласованные шесть операций, каждый op имеет request type',()=>{
for(const op of ops) {
assert.ok(registry.includes(`Map.entry("${op}", new Net_Registration_Handler`));
assert.ok(registry.includes(`Map.entry("${op}", Net_Registration_Request.class`));
}
assert.doesNotMatch(registry,/Map\.entry\("CheckRegistrationAvailability"/);
const registrationRoutes = [...registry.matchAll(/add\(handlers,types,"(\w+)",(?:[\w.]+\.)?Net_Registration_Request\.class,new (?:[\w.]+\.)?Net_Registration_Handler\("(\w+)"\)\);/g)];
assert.deepEqual(registrationRoutes.map(m => m[1]).sort(), [...ops].sort());
for (const [, route, handlerOp] of registrationRoutes) assert.equal(route, handlerOp);
assert.doesNotMatch(registry,/add\(handlers,types,"CheckRegistrationAvailability"/);
});
test('проверки login и email независимы и не отправляют лишних данных',()=>{
assert.match(api,/checkRegistrationLogin = .*call\('CheckRegistrationLogin', \{ fullLogin:/);
@@ -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 HEADER v1 preserves registration 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_CONTENT_VERSION/);
assert.match(auth, /export const HEADER_CONTENT_VERSION = 1/);
});
test('free and paid registration both require accepted documents before any registration operation', { skip: !hasRegistrationTerms }, () => {