// Общий бинарный протокол namespace PDA v1; используется платным create и upgrade. import { sha256Bytes } from './crypto-utils.js'; import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js'; import { SHINE_USERS_PROGRAM_ID } from '../solana-programs.js'; const enc = new TextEncoder(); const dec = new TextDecoder('utf-8', { fatal: true }); export function normalizeNamespace(value) { const name = String(value ?? ''); if (!/^[a-z0-9_]+$/.test(name)) throw new Error('Некорректный namespace: разрешены только ASCII lowercase a-z0-9_'); return name; } export function normalizeFullLogin(value) { const login = String(value ?? ''); const parts = login.split('@'); if (parts.length !== 2 || !/^[a-z0-9_]+$/.test(parts[0])) throw new Error('Требуется полный login@namespace без автоматического преобразования'); normalizeNamespace(parts[1]); if (enc.encode(login).length > 30) throw new Error('Полный логин превышает 30 байт'); return login; } export async function userPdaSeed32(fullLogin) { return sha256Bytes(enc.encode('user_login=' + normalizeFullLogin(fullLogin))); } export async function namespacePdaSeed32(namespace) { return sha256Bytes(enc.encode('namespace=' + normalizeNamespace(namespace))); } export function buildFreeCertificateInnerMessage(fullLogin, root32, blockchain32, client32) { const name = enc.encode(normalizeFullLogin(fullLogin)); for (const key of [root32, blockchain32, client32]) { if (!(key instanceof Uint8Array) || key.length !== 32) throw new Error('Ожидается 32-байтовый публичный ключ'); } return new Uint8Array([ ...enc.encode('SHiNE_FREE_REG_V1\0'), 1, 0, name.length, ...name, ...root32, ...blockchain32, ...client32, ]); } export function decodeNamespacePda(data) { const bytes = new Uint8Array(data); if (bytes.length < 13 || bytes[0] !== 1 || bytes[1] !== 0 || (bytes[2] !== 1 && bytes[2] !== 2)) throw new Error('Неподдерживаемый namespace PDA'); const type = bytes[2], minLocalpartLength = bytes[3], len = bytes[4]; if (len === 0 || 5 + len + 8 > bytes.length) throw new Error('Обрезанный namespace PDA'); const namespace = dec.decode(bytes.slice(5, 5 + len)); normalizeNamespace(namespace); if (minLocalpartLength < 1 || minLocalpartLength + len + 1 > 30) throw new Error('Недопустимая минимальная длина'); const fee = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getBigUint64(5 + len, true); let offset = 5 + len + 8, registrarPublicKey32 = null, serverLogin = null; if (type === 2) { if (bytes.length < offset + 33) throw new Error('В namespace типа 2 отсутствует ключ регистратора'); registrarPublicKey32 = bytes.slice(offset, offset + 32); offset += 32; const serverLen = bytes[offset++]; if (serverLen < 1 || bytes.length !== offset + serverLen) throw new Error('Неверная длина серверного логина'); serverLogin = normalizeFullLogin(dec.decode(bytes.slice(offset, offset + serverLen))); offset += serverLen; } if (bytes.length !== offset) throw new Error('Лишние данные namespace PDA'); return { namespace, type, minLocalpartLength, registrationFeeLamports: fee, registrarPublicKey32, serverLogin }; } export function encodeNamespacePda({ namespace, type, minLocalpartLength, registrationFeeLamports, registrarPublicKey32, serverLogin }) { const name = enc.encode(normalizeNamespace(namespace)); if (!Number.isInteger(minLocalpartLength) || minLocalpartLength < 1 || minLocalpartLength + name.length + 1 > 30) throw new Error('Недопустимая длина локального логина'); if (type !== 1 && type !== 2) throw new Error('Недопустимый тип namespace'); const fee = BigInt(registrationFeeLamports); if (fee < 0n || fee > (2n ** 64n - 1n)) throw new Error('Неверная цена регистрации'); const server = type === 2 ? enc.encode(normalizeFullLogin(serverLogin)) : new Uint8Array(); const pub = type === 2 ? new Uint8Array(registrarPublicKey32) : new Uint8Array(); if (type === 2 && pub.length !== 32) throw new Error('Ключ регистратора должен быть 32 байта'); const out = new Uint8Array(5 + name.length + 8 + (type === 2 ? 32 + 1 + server.length : 0)); out.set([1, 0, type, minLocalpartLength, name.length]); out.set(name, 5); let offset = 5 + name.length; new DataView(out.buffer).setBigUint64(offset, fee, true); offset += 8; if (type === 2) { out.set(pub, offset); offset += 32; out[offset++] = server.length; out.set(server, offset); } return out; } export function assertLoginInNamespace(fullLogin, ns) { const login = normalizeFullLogin(fullLogin); if (login.split('@')[1] !== ns.namespace || login.split('@')[0].length < ns.minLocalpartLength) throw new Error('Логин не соответствует namespace'); return login; } export async function deriveUserPda(fullLogin) { const solana = await loadSolanaWeb3(); const program = new solana.PublicKey(SHINE_USERS_PROGRAM_ID); return solana.PublicKey.findProgramAddressSync([await userPdaSeed32(fullLogin)], program)[0]; } export async function deriveNamespacePda(namespace) { const solana = await loadSolanaWeb3(); const program = new solana.PublicKey(SHINE_USERS_PROGRAM_ID); return solana.PublicKey.findProgramAddressSync([await namespacePdaSeed32(namespace)], program)[0]; } export async function getNamespace({ namespace, solanaEndpoint }) { const solana = await loadSolanaWeb3(); const connection = new solana.Connection(String(solanaEndpoint || '').trim(), 'confirmed'); const address = await deriveNamespacePda(namespace); const info = await connection.getAccountInfo(address, 'confirmed'); if (!info || !info.owner.equals(new solana.PublicKey(SHINE_USERS_PROGRAM_ID))) throw new Error('Namespace PDA не найдена в программе shine_users'); const ns = decodeNamespacePda(info.data); if (ns.namespace !== namespace) throw new Error('PDA namespace не совпадает с именем'); return { ...ns, pdaAddress: address.toBase58(), address }; } export async function listNamespaces({ solanaEndpoint }) { const solana = await loadSolanaWeb3(); const conn = new solana.Connection(String(solanaEndpoint || '').trim(), 'confirmed'); const accounts = await conn.getProgramAccounts(new solana.PublicKey(SHINE_USERS_PROGRAM_ID)); const out = []; for (const entry of accounts) { try { const ns = decodeNamespacePda(entry.account.data); const expected = await deriveNamespacePda(ns.namespace); if (!entry.pubkey.equals(expected)) continue; out.push({ ...ns, pdaAddress: entry.pubkey.toBase58(), address: entry.pubkey }); } catch { /* User PDA или неподдерживаемый формат */ } } return out.sort((a, b) => a.namespace.localeCompare(b.namespace)); }