import test from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { createHash, createPublicKey, verify } from 'node:crypto'; // Полностью автономные тесты: не требуют RPC, приватных ключей и npm install. const vectors = JSON.parse(readFileSync(new URL('./fixtures/registration-v2.json', import.meta.url), 'utf8')); const hash = data => createHash('sha256').update(data).digest(); const hash384 = data => createHash('sha384').update(data).digest(); const pubkeyFromRaw = hex => createPublicKey({key: Buffer.concat([Buffer.from('302a300506032b6570032100','hex'),Buffer.from(hex,'hex')]),format:'der',type:'spki'}); const b58abc = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; function decode58(text) { let v=0n; for (const char of text) { const n=b58abc.indexOf(char);assert.ok(n>=0);v=v*58n+BigInt(n); } let b=[]; while(v>0n){b.unshift(Number(v%256n));v/=256n;} return Buffer.concat([Buffer.alloc((text.match(/^1*/)?.[0]||'').length),Buffer.from(b)]); } function encode58(bytes) { let value=BigInt('0x'+bytes.toString('hex'));let result=''; while(value>0n){result=b58abc[Number(value%58n)]+result;value/=58n;} return '1'.repeat(bytes.findIndex(byte=>byte!==0)<0?bytes.length:bytes.findIndex(byte=>byte!==0))+result; } const p=(1n<<255n)-19n; function mod(a){return (a%p+p)%p;} function pow(a,n){let result=1n;while(n>0n){if(n&1n)result=mod(result*a);a=mod(a*a);n>>=1n;}return result;} const d=mod(-121665n*pow(121666n,p-2n)); function onCurve(bytes) { const copy=Buffer.from(bytes),sign=copy[31]>>7;copy[31]&=127; let y=0n;for(let i=31;i>=0;i--)y=y*256n+BigInt(copy[i]); if(y>=p)return false; const yy=mod(y*y), xx=mod((yy-1n)*pow(d*yy+1n,p-2n)); return xx===0n ? sign===0 : pow(xx,(p-1n)/2n)===1n; } function address(prefix, name) { const seed=hash(Buffer.from(prefix+name)); const program=decode58(vectors.program_id); assert.equal(program.length,32); for(let bump=255;bump>=0;bump--){ const a=hash(Buffer.concat([seed,Buffer.from([bump]),program,Buffer.from('ProgramDerivedAddress')])); if(!onCurve(a))return {seed:seed.toString('hex'),pda:encode58(a),bump}; } throw Error('PDA was not found'); } function deepHash(item){ if(Buffer.isBuffer(item))return hash384(Buffer.concat([hash384(Buffer.from('blob'+item.length)),hash384(item)])); let acc=hash384(Buffer.from('list'+item.length)); for(const child of item)acc=hash384(Buffer.concat([acc,deepHash(child)])); return acc; } test('Одинаковые SHA-256 и PDA для всех пользователей',()=>{ for(const u of vectors.users){ const actual=address('user_login=',u.login); assert.deepEqual(actual,{seed:u.user_seed_hex,pda:u.user_pda,bump:u.bump}); assert.equal(u.valid,u.login.length<=30); } }); test('Два PDA namespace отличаются от пользовательских',()=>{ for(const ns of vectors.namespace){ assert.deepEqual(address('namespace=',ns.name),{seed:ns.seed_hex,pda:ns.pda,bump:ns.bump}); assert.notEqual(ns.pda,address('user_login=',ns.name).pda); } }); test('namespace-PDA строгая раскладка и округления нет',()=>{ for(const ns of vectors.namespace){ const b=Buffer.from(ns.bytes_hex,'hex'),name=b.subarray(5,5+b[4]).toString(); assert.equal(b[0],1);assert.equal(b[1],0);assert.equal(b[2],ns.type);assert.equal(name,ns.name); const offset=5+b[4],fee=b.readBigUInt64LE(offset); assert.equal(fee,BigInt(ns.type===1?10_000_000:5_000_000)); if(ns.type===2){assert.equal(b.subarray(offset+8,offset+40).toString('hex'),vectors.public_keys_hex.registrar);} assert.equal(b.length,ns.type===1?5+ns.name.length+8:5+ns.name.length+8+32+1+'registrar@shine'.length); } }); test('Внутренняя подпись защищает имя и все три публичных ключа',()=>{ const c=vectors.certificate,msg=Buffer.from(c.inner_message_hex,'hex'),sign=Buffer.from(c.inner_signature_hex,'hex'); const key=pubkeyFromRaw(vectors.public_keys_hex.registrar); assert.ok(verify(null,msg,key,sign)); assert.equal(msg.subarray(0,18).toString('hex'),Buffer.from('SHiNE_FREE_REG_V1\0').toString('hex')); for(const idx of [18,21,21+c.login.length,21+c.login.length+32,21+c.login.length+64]){ const bad=Buffer.from(msg);bad[idx]^=1; assert.equal(verify(null,bad,key,sign),false); } }); test('Email-хеш стоит после внутренней подписи',()=>{ const c=vectors.certificate,payload=Buffer.from(c.payload_hex,'hex'); assert.equal(hash(Buffer.from(vectors.normalized_email)).toString('hex'),vectors.email_sha256_hex); assert.equal(payload.subarray(-32).toString('hex'),vectors.email_sha256_hex); assert.equal(payload.subarray(0,-96).toString('hex'),c.identity_fields_hex); assert.equal(payload.subarray(-96,-32).toString('hex'),c.inner_signature_hex); }); test('ANS-104 подпись защищает email и теги, ID фиксирован',()=>{ const item=Buffer.from(vectors.certificate.dataitem_hex,'hex'),key=pubkeyFromRaw(vectors.public_keys_hex.registrar); assert.equal(item.readUInt16LE(0),2); const sign=item.subarray(2,66),owner=item.subarray(66,98); assert.equal(owner.toString('hex'),vectors.public_keys_hex.registrar); assert.equal(item[98],0);assert.equal(item[99],0); const count=Number(item.readBigUInt64LE(100)),size=Number(item.readBigUInt64LE(108)); assert.equal(count,3); const tags=item.subarray(116,116+size),data=item.subarray(116+size); assert.equal(data.toString('hex'),vectors.certificate.payload_hex); const msg=deepHash([Buffer.from('dataitem'),Buffer.from('1'),Buffer.from('2'),owner,Buffer.alloc(0),Buffer.alloc(0),tags,data]); assert.equal(msg.toString('hex'),vectors.certificate.dataitem_deep_hash_hex); assert.equal(hash(sign).toString('hex'),vectors.certificate.dataitem_sha256_id_hex); assert.ok(verify(null,msg,key,sign)); let changed=Buffer.from(data);changed[changed.length-1]^=1; assert.equal(verify(null,deepHash([Buffer.from('dataitem'),Buffer.from('1'),Buffer.from('2'),owner,Buffer.alloc(0),Buffer.alloc(0),tags,changed]),key,sign),false); changed=Buffer.from(tags);changed[0]^=1; assert.equal(verify(null,deepHash([Buffer.from('dataitem'),Buffer.from('1'),Buffer.from('2'),owner,Buffer.alloc(0),Buffer.alloc(0),changed,data]),key,sign),false); });