SHA256
Регистрация V2: не проверено end-to-end
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
/** Разделённые шаги V2: независимая проверка логина, затем email. */
|
||||
import { authService } from '../state.js';
|
||||
import { normalizeFullLogin } from './shine-namespace-service.js';
|
||||
|
||||
async function call(op, payload = {}) {
|
||||
const response = await authService.ws.request(op, payload, op==='ConfirmFreeRegistration'?150000:18000);
|
||||
if (response.status !== 200 || response.ok === false) {
|
||||
const error=new Error(response.message || response.error || `${op}: ошибка сервера`);
|
||||
error.code=response.error || 'REGISTRATION_REQUEST_FAILED';
|
||||
throw error;
|
||||
}
|
||||
return response.payload || {};
|
||||
}
|
||||
export const getRegistrationNamespaces = () => call('GetNamespaces');
|
||||
export const checkRegistrationLogin = (fullLogin) => call('CheckRegistrationLogin', { fullLogin: normalizeFullLogin(fullLogin) });
|
||||
export const checkRegistrationEmail = (email) => call('CheckRegistrationEmail', { email });
|
||||
export const startFreeRegistration = ({ fullLogin, keyBundle, email }) => call('StartFreeRegistration', {
|
||||
fullLogin: normalizeFullLogin(fullLogin), email,
|
||||
rootPublicKeyB64: keyBundle.rootPair.publicKeyB64,
|
||||
blockchainPublicKeyB64: keyBundle.blockchainPair.publicKeyB64,
|
||||
clientPublicKeyB64: keyBundle.clientPair.publicKeyB64,
|
||||
});
|
||||
export const confirmFreeRegistration = (challengeId, code) => call('ConfirmFreeRegistration',{challengeId,code});
|
||||
export const getRegistrationStatus = (fullLogin) => call('GetRegistrationStatus',{fullLogin: normalizeFullLogin(fullLogin)});
|
||||
@@ -0,0 +1,112 @@
|
||||
// Общий бинарный протокол 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));
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
SHINE_USERS_PROGRAM_ID,
|
||||
} from '../solana-programs.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
import { getNamespace, assertLoginInNamespace, normalizeFullLogin, userPdaSeed32, buildFreeCertificateInnerMessage } from './shine-namespace-service.js';
|
||||
|
||||
const MAGIC = 'SHiNE';
|
||||
const FORMAT_MAJOR = 1;
|
||||
@@ -364,7 +365,7 @@ export function serializeUnsignedRecordFromState(stateLike) {
|
||||
return new Uint8Array(out);
|
||||
}
|
||||
|
||||
function serializeCreateUserPdaArgs(args) {
|
||||
export function serializeCreateUserPdaArgs(args) {
|
||||
const out = [IX_CREATE_USER_PDA];
|
||||
pushStrU8(out, args.login);
|
||||
pushBytes(out, toUint8Array(args.rootKey32, 32));
|
||||
@@ -382,8 +383,9 @@ function serializeCreateUserPdaArgs(args) {
|
||||
out.push(access.length);
|
||||
for (const value of access) pushStrU8(out, value);
|
||||
pushBytes(out, toUint8Array(args.recordSignature64, 64));
|
||||
const promo = normalizeLogin(args.promoSellerLogin || '');
|
||||
if (promo) pushStrU8(out, promo);
|
||||
const registrar = args.registrarSignature64 == null ? null : toUint8Array(args.registrarSignature64, 64);
|
||||
out.push(registrar ? 1 : 0);
|
||||
if (registrar) pushBytes(out, registrar);
|
||||
return new Uint8Array(out);
|
||||
}
|
||||
|
||||
@@ -468,7 +470,8 @@ export async function readShineUserPda({ login, solanaEndpoint }) {
|
||||
const endpoint = String(solanaEndpoint || '').trim();
|
||||
const connection = new solana.Connection(endpoint, 'confirmed');
|
||||
const usersProgram = new solana.PublicKey(SHINE_USERS_PROGRAM_ID);
|
||||
const [pda] = solana.PublicKey.findProgramAddressSync([new TextEncoder().encode(SHINE_USERS_USER_PDA_SEED_PREFIX), new TextEncoder().encode(cleanLogin)], usersProgram);
|
||||
const [pda] = solana.PublicKey.findProgramAddressSync(
|
||||
cleanLogin.includes('@') ? [await userPdaSeed32(cleanLogin)] : [new TextEncoder().encode(SHINE_USERS_USER_PDA_SEED_PREFIX), new TextEncoder().encode(cleanLogin)], usersProgram);
|
||||
const info = await connection.getAccountInfo(pda, 'confirmed');
|
||||
if (!info?.data) throw new Error(`PDA пользователя @${cleanLogin} не найдена`);
|
||||
return { ...parseShineUserPda(new Uint8Array(info.data)), userPda: pda.toBase58(), pdaAddress: pda.toBase58(), endpoint };
|
||||
@@ -523,11 +526,11 @@ async function buildCommonContext({ login, clientPrivatePkcs8B64, payerPrivatePk
|
||||
const connection = new solana.Connection(endpoint, 'confirmed');
|
||||
const usersProgram = new solana.PublicKey(SHINE_USERS_PROGRAM_ID);
|
||||
const paymentsProgram = new solana.PublicKey(SHINE_PAYMENTS_PROGRAM_ID);
|
||||
const loginGuardProgram = new solana.PublicKey(SHINE_LOGIN_GUARD_PROGRAM_ID);
|
||||
const ed25519Program = new solana.PublicKey(ED25519_PROGRAM_ID);
|
||||
const sysvarInstructions = new solana.PublicKey(SYSVAR_INSTRUCTIONS_ID);
|
||||
const enc = new TextEncoder();
|
||||
const [userPda] = solana.PublicKey.findProgramAddressSync([enc.encode(SHINE_USERS_USER_PDA_SEED_PREFIX), enc.encode(cleanLogin)], usersProgram);
|
||||
const [userPda] = solana.PublicKey.findProgramAddressSync(
|
||||
cleanLogin.includes('@') ? [await userPdaSeed32(cleanLogin)] : [enc.encode(SHINE_USERS_USER_PDA_SEED_PREFIX), enc.encode(cleanLogin)], usersProgram);
|
||||
const [economyConfigPda] = solana.PublicKey.findProgramAddressSync([enc.encode(SHINE_USERS_ECONOMY_CONFIG_SEED)], usersProgram);
|
||||
const [inflowVault] = solana.PublicKey.findProgramAddressSync([enc.encode(SHINE_PAYMENTS_INFLOW_VAULT_SEED)], paymentsProgram);
|
||||
const payerPkcs8 = String(payerPrivatePkcs8B64 || clientPrivatePkcs8B64 || '');
|
||||
@@ -536,7 +539,7 @@ async function buildCommonContext({ login, clientPrivatePkcs8B64, payerPrivatePk
|
||||
const payerKeypair = solana.Keypair.fromSeed(payerSeed32);
|
||||
// Имя clientKeypair сохранено в возвращаемом объекте для совместимости текущих UI-callers;
|
||||
// фактически это произвольный fee payer и он не обязан совпадать с ClientKeyBlock.
|
||||
return { cleanLogin, endpoint, solana, connection, usersProgram, paymentsProgram, loginGuardProgram, ed25519Program, sysvarInstructions, userPda, economyConfigPda, inflowVault, clientKeypair: payerKeypair, payerKeypair };
|
||||
return { cleanLogin, endpoint, solana, connection, usersProgram, paymentsProgram, ed25519Program, sysvarInstructions, userPda, economyConfigPda, inflowVault, clientKeypair: payerKeypair, payerKeypair };
|
||||
}
|
||||
|
||||
async function createShineUserPdaOnSolana({
|
||||
@@ -549,10 +552,11 @@ async function createShineUserPdaOnSolana({
|
||||
addressFormatVersion = 0,
|
||||
serverAddress = '',
|
||||
accessServers = [],
|
||||
promoCode = '',
|
||||
registrarSignature64 = null,
|
||||
feePayerPrivatePkcs8B64 = '',
|
||||
}) {
|
||||
const rawLogin = String(login || '').trim();
|
||||
const cleanLogin = normalizeLogin(rawLogin);
|
||||
const rawLogin = normalizeFullLogin(login);
|
||||
const cleanLogin = rawLogin;
|
||||
const rootKey32 = base64ToBytes(keyBundle.rootPair.publicKeyB64);
|
||||
const blockchainKey32 = base64ToBytes(keyBundle.blockchainPair.publicKeyB64);
|
||||
const clientKey32 = base64ToBytes(keyBundle.clientPair.publicKeyB64);
|
||||
@@ -561,9 +565,17 @@ async function createShineUserPdaOnSolana({
|
||||
const ctx = await buildCommonContext({
|
||||
login: cleanLogin,
|
||||
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
|
||||
payerPrivatePkcs8B64: keyBundle.blockchainPair.privatePkcs8B64,
|
||||
payerPrivatePkcs8B64: feePayerPrivatePkcs8B64 || keyBundle.blockchainPair.privatePkcs8B64,
|
||||
solanaEndpoint,
|
||||
});
|
||||
const namespaceName = cleanLogin.split('@')[1];
|
||||
const namespace = await getNamespace({ namespace: namespaceName, solanaEndpoint });
|
||||
assertLoginInNamespace(cleanLogin, namespace);
|
||||
const registrar = registrarSignature64 == null ? null : toUint8Array(registrarSignature64, 64);
|
||||
if ((namespace.type === 2) !== Boolean(registrar)) throw new Error('Тип 2 требует сертификат, тип 1 не принимает его');
|
||||
// При upgrade сохраняется исходный сервер доступа; после on-chain create его можно сменить.
|
||||
const effectiveAccessServers = (namespace.type === 2 && accessServers.length === 0)
|
||||
? [namespace.serverLogin] : accessServers;
|
||||
const ecoInfo = await ctx.connection.getAccountInfo(ctx.economyConfigPda, 'confirmed');
|
||||
if (!ecoInfo?.data) throw new Error('Economy config не инициализирован.');
|
||||
const startBonusLimit = parseUsersEconomyConfig(new Uint8Array(ecoInfo.data)).startBonusLimit;
|
||||
@@ -580,30 +592,23 @@ async function createShineUserPdaOnSolana({
|
||||
clientKey: clientKey32,
|
||||
forks: [{ blockchainKey: blockchainKey32, createdAtMs, paidLimitBytes: startBonusLimit }],
|
||||
serverAddresses: addresses,
|
||||
accessServers,
|
||||
accessServers: effectiveAccessServers,
|
||||
};
|
||||
const unsigned = serializeUnsignedRecordFromState(initial);
|
||||
const hash = await sha256Bytes(unsigned);
|
||||
const rootSig = await signBytes(rootPriv, hash);
|
||||
const recordSig = await signBytes(bchPriv, hash);
|
||||
|
||||
let promoSellerPda = null;
|
||||
let promoEdIx = null;
|
||||
let promoSellerLogin = '';
|
||||
const cleanPromoCode = String(promoCode || '').trim();
|
||||
if (cleanPromoCode) {
|
||||
const dash = cleanPromoCode.indexOf('-');
|
||||
if (!cleanPromoCode.startsWith('1') || dash <= 1 || dash === cleanPromoCode.length - 1) throw new Error('Некорректный формат промокода');
|
||||
promoSellerLogin = normalizeLogin(cleanPromoCode.slice(1, dash));
|
||||
const sig = base58ToBytes(cleanPromoCode.slice(dash + 1));
|
||||
const [sellerPda] = ctx.solana.PublicKey.findProgramAddressSync([new TextEncoder().encode(SHINE_USERS_PROMO_SELLER_PDA_SEED_PREFIX), new TextEncoder().encode(promoSellerLogin)], ctx.usersProgram);
|
||||
promoSellerPda = sellerPda;
|
||||
const sellerInfo = await ctx.connection.getAccountInfo(sellerPda, 'confirmed');
|
||||
if (!sellerInfo?.data || sellerInfo.data.length < 42) throw new Error('Promo seller PDA не найдена');
|
||||
promoEdIx = new ctx.solana.TransactionInstruction({ programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(sig, new Uint8Array(sellerInfo.data.slice(10, 42)), buildPromoMessageBytes(cleanLogin)) });
|
||||
}
|
||||
// Namespace читается из цепи, комиссия никогда не берётся из старого economy.registrationFee.
|
||||
const certMessage = registrar
|
||||
? buildFreeCertificateInnerMessage(cleanLogin, rootKey32, blockchainKey32, clientKey32)
|
||||
: null;
|
||||
const registrarIx = registrar ? new ctx.solana.TransactionInstruction({
|
||||
programId: ctx.ed25519Program, keys: [],
|
||||
data: buildEd25519IxData(registrar, namespace.registrarPublicKey32, certMessage),
|
||||
}) : null;
|
||||
|
||||
const ixData = serializeCreateUserPdaArgs({ login: rawLogin, rootKey32, createdAtMs, additionalLimitBytes: 0n, clientKey32, blockchainKey32, serverAddresses: addresses, accessServers, recordSignature64: recordSig, promoSellerLogin });
|
||||
const ixData = serializeCreateUserPdaArgs({ login: rawLogin, rootKey32, createdAtMs, additionalLimitBytes: 0n, clientKey32, blockchainKey32, serverAddresses: addresses, accessServers: effectiveAccessServers, recordSignature64: recordSig, registrarSignature64: registrar });
|
||||
const rootIx = new ctx.solana.TransactionInstruction({ programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(rootSig, rootKey32, hash) });
|
||||
const recordIx = new ctx.solana.TransactionInstruction({ programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(recordSig, blockchainKey32, hash) });
|
||||
const createIx = new ctx.solana.TransactionInstruction({
|
||||
@@ -615,26 +620,31 @@ async function createShineUserPdaOnSolana({
|
||||
{ pubkey: ctx.inflowVault, isSigner: false, isWritable: true },
|
||||
{ pubkey: ctx.sysvarInstructions, isSigner: false, isWritable: false },
|
||||
{ pubkey: ctx.economyConfigPda, isSigner: false, isWritable: false },
|
||||
{ pubkey: ctx.loginGuardProgram, isSigner: false, isWritable: false },
|
||||
...(promoSellerPda ? [{ pubkey: promoSellerPda, isSigner: false, isWritable: true }] : []),
|
||||
{ pubkey: namespace.address, isSigner: false, isWritable: false },
|
||||
],
|
||||
data: ixData,
|
||||
});
|
||||
try {
|
||||
const tx = new ctx.solana.Transaction();
|
||||
if (promoEdIx) tx.add(promoEdIx);
|
||||
if (registrarIx) tx.add(registrarIx);
|
||||
tx.add(rootIx, recordIx, createIx);
|
||||
const signature = await sendAndConfirmSolanaHttp(ctx.connection, tx, [ctx.payerKeypair]);
|
||||
return { signature, userPda: ctx.userPda.toBase58(), pdaAddress: ctx.userPda.toBase58(), blockchainName: `${cleanLogin}-001` };
|
||||
return { signature, userPda: ctx.userPda.toBase58(), pdaAddress: ctx.userPda.toBase58(), blockchainName: `${cleanLogin}-001`, registrationFeeLamports: namespace.registrationFeeLamports };
|
||||
} catch (error) { throw await attachSolanaLogs(error, ctx.connection); }
|
||||
}
|
||||
|
||||
export async function registerUserOnSolana({ login, keyBundle, solanaEndpoint, accessServers = [], promoCode = '' }) {
|
||||
return createShineUserPdaOnSolana({ login, keyBundle, solanaEndpoint, accessServers, promoCode });
|
||||
export async function registerUserOnSolana({ login, keyBundle, solanaEndpoint, accessServers = [], registrarSignature64 = null }) {
|
||||
return createShineUserPdaOnSolana({ login, keyBundle, solanaEndpoint, accessServers, registrarSignature64 });
|
||||
}
|
||||
|
||||
export async function upgradeFreeUserOnSolana({ login, keyBundle, solanaEndpoint, innerSignature64, accessServers = [] }) {
|
||||
if (!innerSignature64) throw new Error('Необходима внутренняя подпись исходного сертификата');
|
||||
return createShineUserPdaOnSolana({ login, keyBundle, solanaEndpoint, accessServers, registrarSignature64: innerSignature64 });
|
||||
}
|
||||
|
||||
export async function registerServerOnSolana({ login, keyBundle, serverAddress, serverAddresses = null, addressFormatType = 1, addressFormatVersion = 0, accessServers = [], solanaEndpoint }) {
|
||||
return createShineUserPdaOnSolana({ login, keyBundle, solanaEndpoint, isServer: true, serverAddress, serverAddresses: serverAddresses || [], addressFormatType, addressFormatVersion, accessServers });
|
||||
// Серверная админка показывает баланс client/device-кошелька; именно он оплачивает создание PDA.
|
||||
return createShineUserPdaOnSolana({ login, keyBundle, solanaEndpoint, isServer: true, serverAddress, serverAddresses: serverAddresses || [], addressFormatType, addressFormatVersion, accessServers, feePayerPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64 });
|
||||
}
|
||||
|
||||
export async function closeLegacyShineUserPdaOnSolana({ login, solanaEndpoint, callerPrivatePkcs8B64 }) {
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
import { registerUserOnSolana as registerUserOnSolanaShared } from './shine-user-pda-service.js';
|
||||
import {
|
||||
SHINE_USERS_PROGRAM_ID,
|
||||
SHINE_LOGIN_GUARD_PROGRAM_ID,
|
||||
} from '../solana-programs.js';
|
||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||
|
||||
const CLASSIFY_LOGIN_INSTRUCTION_TAG = 1;
|
||||
const SHINE_USERS_USER_PDA_SEED_PREFIX = 'user_login=';
|
||||
import { deriveUserPda, normalizeFullLogin } from './shine-namespace-service.js';
|
||||
|
||||
let solanaLibPromise = null;
|
||||
function loadSolanaLib() {
|
||||
@@ -14,37 +8,6 @@ function loadSolanaLib() {
|
||||
return solanaLibPromise;
|
||||
}
|
||||
|
||||
function pushU32LE(buf, v) {
|
||||
const n = v >>> 0;
|
||||
buf.push(n & 0xFF, (n >> 8) & 0xFF, (n >> 16) & 0xFF, (n >> 24) & 0xFF);
|
||||
}
|
||||
|
||||
class BorshBuf {
|
||||
constructor() { this._b = []; }
|
||||
u8(v) { this._b.push(v & 0xFF); }
|
||||
u32(v) { pushU32LE(this._b, v); }
|
||||
str(s) {
|
||||
const enc = new TextEncoder().encode(s);
|
||||
this.u32(enc.length);
|
||||
for (const x of enc) this._b.push(x);
|
||||
}
|
||||
raw(bytes) { for (const x of bytes) this._b.push(x); }
|
||||
result() { return new Uint8Array(this._b); }
|
||||
}
|
||||
|
||||
function serializeClassifyLoginArgs(login) {
|
||||
const b = new BorshBuf();
|
||||
b.u8(CLASSIFY_LOGIN_INSTRUCTION_TAG);
|
||||
b.str(String(login || ''));
|
||||
return b.result();
|
||||
}
|
||||
|
||||
function decodeU32FromB64(rawB64) {
|
||||
const bytes = Uint8Array.from(atob(rawB64), (ch) => ch.charCodeAt(0));
|
||||
if (bytes.length < 4) throw new Error('LOGIN_GUARD_BAD_RETURN_DATA');
|
||||
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0, true);
|
||||
}
|
||||
|
||||
function safeJson(value) {
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
@@ -94,64 +57,21 @@ export function isUserAlreadyExistsSolanaError(error) {
|
||||
|| details.includes('Instruction 2: custom program error: 0x4');
|
||||
}
|
||||
|
||||
export async function precheckLoginClassOnSolana({ login, solanaEndpoint }) {
|
||||
const solana = await loadSolanaLib();
|
||||
const connection = new solana.Connection(String(solanaEndpoint || ''), 'confirmed');
|
||||
const loginGuardProgram = new solana.PublicKey(SHINE_LOGIN_GUARD_PROGRAM_ID);
|
||||
const ix = new solana.TransactionInstruction({
|
||||
programId: loginGuardProgram,
|
||||
keys: [],
|
||||
data: serializeClassifyLoginArgs(String(login || '').toLowerCase()),
|
||||
});
|
||||
const { blockhash } = await connection.getLatestBlockhash('confirmed');
|
||||
const v0Message = new solana.TransactionMessage({
|
||||
// Для simulateTransaction нужен существующий аккаунт payer.
|
||||
// Используем сам program id, чтобы не зависеть от внешнего тестового адреса.
|
||||
payerKey: loginGuardProgram,
|
||||
recentBlockhash: blockhash,
|
||||
instructions: [ix],
|
||||
}).compileToV0Message();
|
||||
const tx = new solana.VersionedTransaction(v0Message);
|
||||
|
||||
const sim = await connection.simulateTransaction(tx, {
|
||||
commitment: 'confirmed',
|
||||
sigVerify: false,
|
||||
replaceRecentBlockhash: true,
|
||||
});
|
||||
if (sim?.value?.err) {
|
||||
const simErr = new Error(`LOGIN_GUARD_SIMULATION_FAILED: ${safeJson(sim.value.err)}`);
|
||||
simErr.logs = sim?.value?.logs || [];
|
||||
simErr.err = sim?.value?.err;
|
||||
throw simErr;
|
||||
}
|
||||
const returnData = sim?.value?.returnData;
|
||||
if (!returnData || returnData.programId !== SHINE_LOGIN_GUARD_PROGRAM_ID) {
|
||||
throw new Error('LOGIN_GUARD_BAD_RETURN_DATA');
|
||||
}
|
||||
const classValue = decodeU32FromB64(returnData.data?.[0] || '');
|
||||
if (classValue === 0) return { classCode: 0, className: 'free' };
|
||||
if (classValue === 1) return { classCode: 1, className: 'premium' };
|
||||
if (classValue === 2) return { classCode: 2, className: 'company' };
|
||||
return { classCode: classValue, className: 'unknown' };
|
||||
export async function precheckLoginClassOnSolana() {
|
||||
throw new Error('CLASSIFY_LOGIN_DEPRECATED: новая регистрация использует namespace PDA; UI требуется обновить на этапе 10');
|
||||
}
|
||||
|
||||
export async function checkLoginExistsOnSolana({ login, solanaEndpoint }) {
|
||||
const full = normalizeFullLogin(login);
|
||||
const solana = await loadSolanaLib();
|
||||
const connection = new solana.Connection(String(solanaEndpoint || ''), 'confirmed');
|
||||
const usersProgram = new solana.PublicKey(SHINE_USERS_PROGRAM_ID);
|
||||
const enc = new TextEncoder();
|
||||
const loginNorm = String(login || '').trim().toLowerCase();
|
||||
if (!loginNorm) {
|
||||
throw new Error('EMPTY_LOGIN');
|
||||
}
|
||||
const [userPda] = solana.PublicKey.findProgramAddressSync(
|
||||
[enc.encode(SHINE_USERS_USER_PDA_SEED_PREFIX), enc.encode(loginNorm)],
|
||||
usersProgram,
|
||||
);
|
||||
const userPda = await deriveUserPda(full);
|
||||
const ai = await connection.getAccountInfo(userPda, 'confirmed');
|
||||
return { exists: !!ai, userPda: userPda.toBase58() };
|
||||
// Для type2 нужно также сверяться с отдельным серверным индексом free сертификатов;
|
||||
// отсутствие PDA НЕ является доказательством свободы логина.
|
||||
return { exists: Boolean(ai), userPda: userPda.toBase58(), solanaPdaExists: Boolean(ai) };
|
||||
}
|
||||
|
||||
export async function registerUserOnSolana({ login, keyBundle, solanaEndpoint, accessServers, promoCode = '' }) {
|
||||
return registerUserOnSolanaShared({ login, keyBundle, solanaEndpoint, accessServers, promoCode });
|
||||
export async function registerUserOnSolana({ login, keyBundle, solanaEndpoint, accessServers, registrarSignature64 = null }) {
|
||||
return registerUserOnSolanaShared({ login, keyBundle, solanaEndpoint, accessServers, registrarSignature64 });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user