SHA256
Регистрация V2: не проверено end-to-end
This commit is contained in:
@@ -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 }) {
|
||||
|
||||
Reference in New Issue
Block a user