SHA256
Регистрация V2: не проверено end-to-end
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
{
|
||||
"version": 1,
|
||||
"program_id": "SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6",
|
||||
"test_key_notice": "FIXTURES ONLY, never use these deterministic seeds for real accounts",
|
||||
"email_input": " Alice.Example+Tag@Example.COM ",
|
||||
"normalized_email": "alice.example+tag@example.com",
|
||||
"email_sha256_hex": "cbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956",
|
||||
"public_keys_hex": {
|
||||
"root": "03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8",
|
||||
"blockchain": "29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7",
|
||||
"client": "2543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d",
|
||||
"registrar": "174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd5"
|
||||
},
|
||||
"users": [
|
||||
{
|
||||
"login": "alice@shine",
|
||||
"valid": true,
|
||||
"user_seed_hex": "b82963883026329da3289e9f103a3c8883ed8ecfc4c31d9c3118a2650a00342a",
|
||||
"user_pda": "Fj61xHrbqCeWq5LiX3PnUgyuwemVNx1ydo5c7oy99Tzo",
|
||||
"bump": 255
|
||||
},
|
||||
{
|
||||
"login": "bob@free",
|
||||
"valid": true,
|
||||
"user_seed_hex": "316a2f8889e56e583350d02227c14a7ce0d0e9475d05fd11918fb48fdcfa6c4b",
|
||||
"user_pda": "CYQTXWaTiEjBvg9eMcRuJYoRSgEY6YupCKnmqdEAoepD",
|
||||
"bump": 253
|
||||
},
|
||||
{
|
||||
"login": "a_b@shine",
|
||||
"valid": true,
|
||||
"user_seed_hex": "7bb903c31cd612026cf8afde3b26f8124ddb08969349c1c6f8830bf33323b51e",
|
||||
"user_pda": "AJBuEQNYLYJJYn1NLV9CDe1YNyvNrYoGjrr9zzwxFUDr",
|
||||
"bump": 253
|
||||
},
|
||||
{
|
||||
"login": "a@shine",
|
||||
"valid": true,
|
||||
"user_seed_hex": "8ee3fb297bc57ae5669f3b9c94a4d4cc3a97a1c334ecdadd94375dd1a6848190",
|
||||
"user_pda": "Aez41BW2iKLo2DNYQdF4hcx22G2xhtdrU2HnH7Fg4mZx",
|
||||
"bump": 255
|
||||
},
|
||||
{
|
||||
"login": "aaaaaaaaaaaaaaaaaaaaaaaa@shine",
|
||||
"valid": true,
|
||||
"user_seed_hex": "ed5c0130230c3fa9c19bfe133b88ed767bfcbd60cf37461ecb3d65676af97c9f",
|
||||
"user_pda": "HXtFs2maytc7s6w62y7gprGKJvMt3aR7ErWQUqYwzE3X",
|
||||
"bump": 254
|
||||
},
|
||||
{
|
||||
"login": "aaaaaaaaaaaaaaaaaaaaaaaaa@shine",
|
||||
"valid": false,
|
||||
"user_seed_hex": "a0d506d1619b55f61af17454adc138bd0f60d1f667181b456b38c2716b39dd07",
|
||||
"user_pda": "EwMLHtuJJ9bzCFRtu6Y2iBQXPPiN3B8Tnewp1ktjcBS4",
|
||||
"bump": 255
|
||||
}
|
||||
],
|
||||
"namespace": [
|
||||
{
|
||||
"name": "shine",
|
||||
"type": 1,
|
||||
"seed_hex": "bdb6dfbe3ba61f66e177ed92ddd85270cd653ba0b92f31d91bf94877ced616ea",
|
||||
"pda": "G1QwyeTcyqBMitsTpGpbwwbCYMFqGkTiGw6trKr5baLa",
|
||||
"bump": 254,
|
||||
"bytes_hex": "01000103057368696e658096980000000000"
|
||||
},
|
||||
{
|
||||
"name": "free",
|
||||
"type": 2,
|
||||
"seed_hex": "ceb53ebd89ee0b2663831b8a458cc7ac53a507e0a5f7b7a5766311348d829dcb",
|
||||
"pda": "C4W54n5sfJfCQLwQb8bDox6JAf98YA2MMFPU2mfhefJh",
|
||||
"bump": 255,
|
||||
"bytes_hex": "010002030466726565404b4c0000000000174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd50f726567697374726172407368696e65"
|
||||
}
|
||||
],
|
||||
"certificate": {
|
||||
"login": "bob@free",
|
||||
"inner_message_hex": "5348694e455f465245455f5245475f563100010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d",
|
||||
"inner_signature_hex": "e2edfcd8b1b7a1823f56b827ddfa8a3682793e036141b526467ae346e220d08757d0a878a2f722562e6d3132ef9df04b1ab9e2f65d72bb0f48c17b7ada3e5a0a",
|
||||
"payload_hex": "010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559de2edfcd8b1b7a1823f56b827ddfa8a3682793e036141b526467ae346e220d08757d0a878a2f722562e6d3132ef9df04b1ab9e2f65d72bb0f48c17b7ada3e5a0acbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956",
|
||||
"identity_fields_hex": "010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d",
|
||||
"dataitem_sha256_id_hex": "45ef42eda7c7e76d222ecce8a7678edb923ae63f8419ea0899701551c2466770",
|
||||
"dataitem_hex": "0200a9de19b3551ace117973b80d632503bf2a55f0aa2490deb1474a280b675fa01bb2ccb5890faadcb213d3882fb21a7af13702526a569f7807b1c8b6963c0be402174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd500000300000000000000390000000000000006064170701074657374353539310274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d563100010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559de2edfcd8b1b7a1823f56b827ddfa8a3682793e036141b526467ae346e220d08757d0a878a2f722562e6d3132ef9df04b1ab9e2f65d72bb0f48c17b7ada3e5a0acbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956",
|
||||
"dataitem_deep_hash_hex": "45d96dbd7e4e81420f06fb591be56c80f9b5da3df647c460d1ecea37b26e6c2b0fbaaf7531cb9ed5be10d8fe224091c6",
|
||||
"tags": [
|
||||
[
|
||||
"App",
|
||||
"test5591"
|
||||
],
|
||||
[
|
||||
"t",
|
||||
"reg"
|
||||
],
|
||||
[
|
||||
"Protocol",
|
||||
"SHiNE-Free-Registration-V1"
|
||||
]
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
program_id=SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6
|
||||
email_hash_hex=cbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956
|
||||
inner_message_hex=5348694e455f465245455f5245475f563100010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d
|
||||
inner_signature_hex=e2edfcd8b1b7a1823f56b827ddfa8a3682793e036141b526467ae346e220d08757d0a878a2f722562e6d3132ef9df04b1ab9e2f65d72bb0f48c17b7ada3e5a0a
|
||||
registrar_pubkey_hex=174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd5
|
||||
ans104_id_hex=45ef42eda7c7e76d222ecce8a7678edb923ae63f8419ea0899701551c2466770
|
||||
user_alice_shine_seed=b82963883026329da3289e9f103a3c8883ed8ecfc4c31d9c3118a2650a00342a
|
||||
user_alice_shine_pda=Fj61xHrbqCeWq5LiX3PnUgyuwemVNx1ydo5c7oy99Tzo
|
||||
user_alice_shine_bump=255
|
||||
user_bob_free_seed=316a2f8889e56e583350d02227c14a7ce0d0e9475d05fd11918fb48fdcfa6c4b
|
||||
user_bob_free_pda=CYQTXWaTiEjBvg9eMcRuJYoRSgEY6YupCKnmqdEAoepD
|
||||
user_bob_free_bump=253
|
||||
user_a_underscore_b_shine_seed=7bb903c31cd612026cf8afde3b26f8124ddb08969349c1c6f8830bf33323b51e
|
||||
user_a_underscore_b_shine_pda=AJBuEQNYLYJJYn1NLV9CDe1YNyvNrYoGjrr9zzwxFUDr
|
||||
user_a_underscore_b_shine_bump=253
|
||||
user_a_shine_seed=8ee3fb297bc57ae5669f3b9c94a4d4cc3a97a1c334ecdadd94375dd1a6848190
|
||||
user_a_shine_pda=Aez41BW2iKLo2DNYQdF4hcx22G2xhtdrU2HnH7Fg4mZx
|
||||
user_a_shine_bump=255
|
||||
user_aaaaaaaaaaaaaaaaaaaaaaaa_shine_seed=ed5c0130230c3fa9c19bfe133b88ed767bfcbd60cf37461ecb3d65676af97c9f
|
||||
user_aaaaaaaaaaaaaaaaaaaaaaaa_shine_pda=HXtFs2maytc7s6w62y7gprGKJvMt3aR7ErWQUqYwzE3X
|
||||
user_aaaaaaaaaaaaaaaaaaaaaaaa_shine_bump=254
|
||||
user_aaaaaaaaaaaaaaaaaaaaaaaaa_shine_seed=a0d506d1619b55f61af17454adc138bd0f60d1f667181b456b38c2716b39dd07
|
||||
user_aaaaaaaaaaaaaaaaaaaaaaaaa_shine_pda=EwMLHtuJJ9bzCFRtu6Y2iBQXPPiN3B8Tnewp1ktjcBS4
|
||||
user_aaaaaaaaaaaaaaaaaaaaaaaaa_shine_bump=255
|
||||
namespace_shine_seed=bdb6dfbe3ba61f66e177ed92ddd85270cd653ba0b92f31d91bf94877ced616ea
|
||||
namespace_shine_pda=G1QwyeTcyqBMitsTpGpbwwbCYMFqGkTiGw6trKr5baLa
|
||||
namespace_shine_bump=254
|
||||
namespace_shine_bytes_hex=01000103057368696e658096980000000000
|
||||
namespace_free_seed=ceb53ebd89ee0b2663831b8a458cc7ac53a507e0a5f7b7a5766311348d829dcb
|
||||
namespace_free_pda=C4W54n5sfJfCQLwQb8bDox6JAf98YA2MMFPU2mfhefJh
|
||||
namespace_free_bump=255
|
||||
namespace_free_bytes_hex=010002030466726565404b4c0000000000174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd50f726567697374726172407368696e65
|
||||
@@ -0,0 +1,75 @@
|
||||
import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.security.*;
|
||||
import java.security.spec.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Автономная проверка Rust/Java/JS фикстур; не зависит от Solana SDK и сетевого RPC. */
|
||||
public final class RegistrationV2VectorsCheck {
|
||||
private static final BigInteger P=BigInteger.ONE.shiftLeft(255).subtract(BigInteger.valueOf(19));
|
||||
private static final BigInteger D=BigInteger.valueOf(-121665).multiply(BigInteger.valueOf(121666).modInverse(P)).mod(P);
|
||||
private static final String B58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
||||
private static byte[] utf8(String s){return s.getBytes(StandardCharsets.UTF_8);}
|
||||
private static byte[] sha(byte[] b){try{return MessageDigest.getInstance("SHA-256").digest(b);}catch(Exception e){throw new IllegalStateException(e);}}
|
||||
private static byte[] join(byte[]... array){int n=0;for(var a:array)n+=a.length;byte[] out=new byte[n];int i=0;for(var a:array){System.arraycopy(a,0,out,i,a.length);i+=a.length;}return out;}
|
||||
private static String hex(byte[] b){return HexFormat.of().formatHex(b);}
|
||||
private static byte[] fromHex(String s){return HexFormat.of().parseHex(s);}
|
||||
private static byte[] base58decode(String text){
|
||||
BigInteger n=BigInteger.ZERO, b=BigInteger.valueOf(58);
|
||||
for(char c:text.toCharArray()) {int digit=B58.indexOf(c);if(digit<0)throw new IllegalArgumentException();n=n.multiply(b).add(BigInteger.valueOf(digit));}
|
||||
byte[] raw=n.equals(BigInteger.ZERO)?new byte[0]:n.toByteArray();if(raw.length>0 && raw[0]==0)raw=Arrays.copyOfRange(raw,1,raw.length);
|
||||
int zero=0;while(zero<text.length() && text.charAt(zero)=='1')zero++;
|
||||
return join(new byte[zero],raw);
|
||||
}
|
||||
private static String base58encode(byte[] raw){
|
||||
BigInteger n=new BigInteger(1,raw), b=BigInteger.valueOf(58);StringBuilder result=new StringBuilder();
|
||||
while(n.signum()>0){BigInteger[] div=n.divideAndRemainder(b);result.append(B58.charAt(div[1].intValue()));n=div[0];}
|
||||
int zero=0;while(zero<raw.length && raw[zero]==0)zero++;for(int i=0;i<zero;i++)result.append('1');
|
||||
return result.reverse().toString();
|
||||
}
|
||||
private static boolean onCurve(byte[] raw){
|
||||
byte[] ybytes=Arrays.copyOf(raw,32);int sign=(ybytes[31]&0xff)>>7;ybytes[31]&=127;
|
||||
for(int i=0;i<16;i++){byte x=ybytes[i];ybytes[i]=ybytes[31-i];ybytes[31-i]=x;}
|
||||
BigInteger y=new BigInteger(1,ybytes);if(y.compareTo(P)>=0)return false;
|
||||
BigInteger yy=y.multiply(y).mod(P);
|
||||
BigInteger xx=yy.subtract(BigInteger.ONE).multiply(D.multiply(yy).add(BigInteger.ONE).mod(P).modInverse(P)).mod(P);
|
||||
if(xx.equals(BigInteger.ZERO))return sign==0;
|
||||
return xx.modPow(P.subtract(BigInteger.ONE).shiftRight(1),P).equals(BigInteger.ONE);
|
||||
}
|
||||
private static String[] pda(byte[] seed,byte[] program){
|
||||
for(int bump=255;bump>=0;bump--){byte[] bytes=sha(join(seed,new byte[]{(byte)bump},program,utf8("ProgramDerivedAddress")));
|
||||
if(!onCurve(bytes))return new String[]{base58encode(bytes),Integer.toString(bump)};}
|
||||
throw new IllegalStateException("PDA unavailable");
|
||||
}
|
||||
private static void check(boolean condition,String text){if(!condition)throw new AssertionError(text);}
|
||||
public static void main(String[] argv)throws Exception{
|
||||
Path path=argv.length>0?Path.of(argv[0]):Path.of("tests/fixtures/registration-v2.properties");
|
||||
Properties props=new Properties();try(var reader=Files.newBufferedReader(path)){props.load(reader);}
|
||||
byte[] program=base58decode(props.getProperty("program_id"));check(program.length==32,"program id");
|
||||
for(String name:List.of("alice@shine","bob@free","a_b@shine","a@shine","aaaaaaaaaaaaaaaaaaaaaaaa@shine","aaaaaaaaaaaaaaaaaaaaaaaaa@shine")){
|
||||
String key=name.replace("a_b","a_underscore_b").replace('@','_');
|
||||
byte[] seed=sha(utf8("user_login="+name));check(hex(seed).equals(props.getProperty("user_"+key+"_seed")),"seed " + name);
|
||||
String[] result=pda(seed,program);
|
||||
check(result[0].equals(props.getProperty("user_"+key+"_pda")),"user pda " + name);
|
||||
check(result[1].equals(props.getProperty("user_"+key+"_bump")),"user bump " + name);
|
||||
}
|
||||
for(String name:List.of("shine","free")){
|
||||
byte[] seed=sha(utf8("namespace="+name));
|
||||
check(hex(seed).equals(props.getProperty("namespace_"+name+"_seed")),"namespace seed");
|
||||
String[] result=pda(seed,program);
|
||||
check(result[0].equals(props.getProperty("namespace_"+name+"_pda")),"namespace pda");
|
||||
check(result[1].equals(props.getProperty("namespace_"+name+"_bump")),"namespace bump");
|
||||
}
|
||||
byte[] raw=fromHex(props.getProperty("registrar_pubkey_hex"));
|
||||
byte[] der=join(fromHex("302a300506032b6570032100"),raw);
|
||||
PublicKey signer=KeyFactory.getInstance("Ed25519").generatePublic(new X509EncodedKeySpec(der));
|
||||
byte[] msg=fromHex(props.getProperty("inner_message_hex")),signature=fromHex(props.getProperty("inner_signature_hex"));
|
||||
Signature verifier=Signature.getInstance("Ed25519");verifier.initVerify(signer);verifier.update(msg);
|
||||
check(verifier.verify(signature),"inner signature");
|
||||
byte[] bad=msg.clone();bad[bad.length-1]^=1;
|
||||
verifier.initVerify(signer);verifier.update(bad);check(!verifier.verify(signature),"tamper should fail");
|
||||
check(hex(sha(utf8("alice.example+tag@example.com"))).equals(props.getProperty("email_hash_hex")),"email hash");
|
||||
System.out.println("OK: SHA-256 + user/namespace PDA + Ed25519 + email vector");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { decodeNamespace } from '../scripts/registration-v2/decode-namespace.mjs';
|
||||
const vec=JSON.parse(readFileSync(new URL('./fixtures/registration-v2.json',import.meta.url)));
|
||||
function throws(data,msg){assert.throws(()=>decodeNamespace(data),msg);}
|
||||
test('Декодирование paid/free namespaces',()=>{
|
||||
const shine=decodeNamespace(Buffer.from(vec.namespace[0].bytes_hex,'hex'));
|
||||
const free=decodeNamespace(Buffer.from(vec.namespace[1].bytes_hex,'hex'));
|
||||
assert.equal(shine.registrarPubkeyHex,null);
|
||||
assert.equal(shine.serverLogin,null);
|
||||
assert.equal(shine.registrationFeeLamports,'10000000');
|
||||
assert.equal(free.serverLogin,'registrar@shine');
|
||||
assert.equal(free.minLocalLen,3);
|
||||
});
|
||||
test('Некорректный namespace не пройдет строгий декодер',()=>{
|
||||
const canonical=Buffer.from(vec.namespace[1].bytes_hex,'hex');
|
||||
for(const index of [0,1,2,3,4]){
|
||||
const bad=Buffer.from(canonical);bad[index]=index===1?1:0;
|
||||
throws(bad);
|
||||
}
|
||||
throws(canonical.subarray(0,-1));
|
||||
throws(Buffer.concat([canonical,Buffer.from([0])]));
|
||||
const bad=Buffer.from(canonical);
|
||||
bad[5]='F'.charCodeAt(0);
|
||||
throws(bad);
|
||||
});
|
||||
test('Некорректный server login отвергается',()=>{
|
||||
const canonical=Buffer.from(vec.namespace[1].bytes_hex,'hex');
|
||||
const bad=Buffer.from(canonical);bad[bad.length-1]='@'.charCodeAt(0);
|
||||
throws(bad);
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
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);
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
//! Общие зафиксированные Rust/Java/JS фикстуры. Запуск: cargo test --test registration_v2_vectors.
|
||||
use std::str::FromStr;
|
||||
use solana_program::{hash::hash, pubkey::Pubkey};
|
||||
use shine_users::{certificate_inner_message, find_namespace_pda, find_user_pda, serialize_namespace, user_pda_seed, NamespaceState};
|
||||
|
||||
fn fixture(key: &str) -> String {
|
||||
include_str!("fixtures/registration-v2.properties").lines()
|
||||
.find_map(|line| line.split_once('=').filter(|(name,_)| *name==key).map(|(_,value)| value.to_string()))
|
||||
.expect("ключ тест-вектора")
|
||||
}
|
||||
fn decode_hex(text: &str) -> Vec<u8> {
|
||||
assert_eq!(text.len()%2,0);
|
||||
(0..text.len()).step_by(2).map(|i| u8::from_str_radix(&text[i..i+2],16).unwrap()).collect()
|
||||
}
|
||||
fn encode_hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{:02x}",b)).collect()
|
||||
}
|
||||
#[test]
|
||||
fn user_pdas_match_portable_vectors() {
|
||||
let program=Pubkey::from_str(&fixture("program_id")).unwrap();
|
||||
for (login,key) in [
|
||||
("alice@shine","alice_shine"), ("bob@free","bob_free"),
|
||||
("a_b@shine","a_underscore_b_shine"), ("a@shine","a_shine"),
|
||||
("aaaaaaaaaaaaaaaaaaaaaaaa@shine","aaaaaaaaaaaaaaaaaaaaaaaa_shine"),
|
||||
("aaaaaaaaaaaaaaaaaaaaaaaaa@shine","aaaaaaaaaaaaaaaaaaaaaaaaa_shine")
|
||||
] {
|
||||
assert_eq!(encode_hex(&user_pda_seed(login)),fixture(&format!("user_{key}_seed")));
|
||||
let (pda,bump)=find_user_pda(&program,login);
|
||||
assert_eq!(pda.to_string(),fixture(&format!("user_{key}_pda")));
|
||||
assert_eq!(bump.to_string(),fixture(&format!("user_{key}_bump")));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn namespace_pdas_and_binaries_match_vectors() {
|
||||
let program=Pubkey::from_str(&fixture("program_id")).unwrap();
|
||||
for (name,typ,fee) in [("shine",1,10_000_000), ("free",2,5_000_000)] {
|
||||
let (pda,bump)=find_namespace_pda(&program,name);
|
||||
assert_eq!(pda.to_string(),fixture(&format!("namespace_{name}_pda")));
|
||||
assert_eq!(bump.to_string(),fixture(&format!("namespace_{name}_bump")));
|
||||
assert_eq!(encode_hex(hash(format!("namespace={name}").as_bytes()).as_ref()),fixture(&format!("namespace_{name}_seed")));
|
||||
let registrar=if typ==2 {Some(Pubkey::new_from_array(decode_hex(&fixture("registrar_pubkey_hex")).try_into().unwrap()))}else{None};
|
||||
let state=NamespaceState {namespace_type:typ,min_localpart_len:3,namespace:name.to_string(),registration_fee:fee,registrar_pubkey:registrar,server_login:if typ==2{Some("registrar@shine".to_string())}else{None}};
|
||||
assert_eq!(encode_hex(&serialize_namespace(&state)),fixture(&format!("namespace_{name}_bytes_hex")));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn free_certificate_inner_message_matches_vector() {
|
||||
let msg=decode_hex(&fixture("inner_message_hex"));
|
||||
assert!(msg.starts_with(b"SHiNE_FREE_REG_V1\0"));
|
||||
assert_eq!(msg[18],1);
|
||||
assert_eq!(msg[19],0);
|
||||
assert_eq!(msg[20],8);
|
||||
assert_eq!(&msg[21..29],b"bob@free");
|
||||
let message=certificate_inner_message("bob@free",
|
||||
&Pubkey::new_from_array(msg[29..61].try_into().unwrap()),
|
||||
&Pubkey::new_from_array(msg[61..93].try_into().unwrap()),
|
||||
&Pubkey::new_from_array(msg[93..125].try_into().unwrap())).unwrap();
|
||||
assert_eq!(message,msg);
|
||||
}
|
||||
Reference in New Issue
Block a user