Обновить shine-users и синхронизацию пользователей

This commit is contained in:
AidarKC
2026-11-18 15:28:07 +03:00
parent 780ca53931
commit 76bbc9d023
24 changed files with 503 additions and 278 deletions
+95 -76
View File
@@ -13,11 +13,11 @@ import { getNamespace, assertLoginInNamespace, normalizeFullLogin, userPdaSeed32
const MAGIC = 'SHiNE';
const FORMAT_MAJOR = 1;
const FORMAT_MINOR_LEGACY = 0;
const FORMAT_MINOR_CURRENT = 2;
const FORMAT_MINOR_CURRENT = 3;
const FORMAT_MINOR_PREVIOUS = 2;
const SHINE_PAYMENTS_INFLOW_VAULT_SEED = 'shine_payments_inflow_vault';
const SHINE_USERS_USER_PDA_SEED_PREFIX = 'user_login=';
const SHINE_USERS_PROMO_SELLER_PDA_SEED_PREFIX = 'promo_seller=';
const LIMIT_STEP = 10_000n;
const ED25519_PROGRAM_ID = 'Ed25519SigVerify111111111111111111111111111';
const SYSVAR_INSTRUCTIONS_ID = 'Sysvar1nstructions1111111111111111111111111';
const PROMO_SIGN_PREFIX = 'shine_promo_v1:';
@@ -56,7 +56,7 @@ function normalizeAccessServers(values) {
const login = normalizeLogin(value);
if (!login || seen.has(login)) continue;
if (result.length >= MAX_EFFECTIVE_ACCESS_SERVERS) {
throw new Error('PDA 1.2 поддерживает максимум один сервер доступа');
throw new Error('PDA 1.3 поддерживает максимум один сервер доступа');
}
seen.add(login);
result.push(login);
@@ -122,13 +122,11 @@ function makeReader(bytes) {
function parseUsersEconomyConfig(dataBytes) {
const view = new DataView(dataBytes.buffer, dataBytes.byteOffset, dataBytes.byteLength);
if (dataBytes.byteLength < 25) throw new Error('Некорректный economy config');
return {
version: view.getUint8(0),
registrationFeeLamports: view.getBigUint64(1, true),
lamportsPerLimitStep: view.getBigUint64(9, true),
startBonusLimit: view.getBigUint64(17, true),
};
if (dataBytes.byteLength < 9) throw new Error('Некорректный economy config');
const version = view.getUint8(0);
if (version === 2) return { version, updateFeeLamports: view.getBigUint64(1, true) };
if (version === 1 && dataBytes.byteLength >= 25) return { version, updateFeeLamports: 20_000n };
throw new Error('Неподдерживаемая версия economy config');
}
function buildEd25519IxData(sig64, pubkey32, messageBytes) {
@@ -157,7 +155,7 @@ function buildEd25519IxData(sig64, pubkey32, messageBytes) {
function normalizeServerAddresses(values, fallback = null) {
const src = Array.isArray(values) && values.length ? values : (fallback ? [fallback] : []);
if (src.length > 1) throw new Error('PDA 1.2 поддерживает только один адрес сервера');
if (src.length > 1) throw new Error('PDA 1.3 поддерживает только один адрес сервера');
return src.map((item) => {
const address = String(item?.address ?? item?.serverAddress ?? '').trim();
const bytes = new TextEncoder().encode(address);
@@ -225,7 +223,7 @@ function parseV12Pda(bytes, header) {
if (payload.remaining !== 0) throw new Error('Повреждённый BlockchainRegistry');
} else if (blockType === BLOCK_TYPE_SERVER_PROFILE) {
const count = payload.readU8();
if (count !== 1) throw new Error('PDA 1.2 допускает ровно один адрес в ServerProfileBlock');
if (count !== 1) throw new Error('PDA 1.3 допускает ровно один адрес в ServerProfileBlock');
serverAddresses = [];
for (let j = 0; j < count; j += 1) {
serverAddresses.push({
@@ -237,13 +235,13 @@ function parseV12Pda(bytes, header) {
if (payload.remaining !== 0) throw new Error('Повреждённый ServerProfileBlock');
} else if (blockType === BLOCK_TYPE_ACCESS_SERVERS) {
const count = payload.readU8();
if (count > 1) throw new Error('PDA 1.2 допускает максимум один access server');
if (count > 1) throw new Error('PDA 1.3 допускает максимум один access server');
accessServers = [];
for (let j = 0; j < count; j += 1) accessServers.push(payload.readStrU8());
if (payload.remaining !== 0) throw new Error('Повреждённый AccessServersBlock');
}
}
if (!rootKey || !clientKey || !forks) throw new Error('PDA 1.2 не содержит обязательные блоки');
if (!rootKey || !clientKey || !forks) throw new Error('PDA не содержит обязательные блоки');
const firstAddress = serverAddresses[0] || null;
const blockchain = activeBlockchainCompatibility(header.login, forks);
return {
@@ -279,7 +277,7 @@ export function parseShineUserPda(dataBytes) {
const formatMajor = reader.readU8();
const formatMinor = reader.readU8();
const recordLen = reader.readU16();
if (formatMajor !== FORMAT_MAJOR || formatMinor !== FORMAT_MINOR_CURRENT) throw new Error(`Неподдерживаемый формат PDA ${formatMajor}.${formatMinor}`);
if (formatMajor !== FORMAT_MAJOR || ![FORMAT_MINOR_PREVIOUS, FORMAT_MINOR_CURRENT].includes(formatMinor)) throw new Error(`Неподдерживаемый формат PDA ${formatMajor}.${formatMinor}`);
if (recordLen < 9 + 64 || recordLen > bytes.length) throw new Error('Некорректный record_len');
const createdAtMs = reader.readU64();
const updatedAtMs = reader.readU64();
@@ -313,6 +311,58 @@ function writeVariableBlock(out, blockType, writer) {
out[lenPos + 1] = (len >>> 8) & 0xff;
}
/** PDA 1.3 canonical signing message. Only the four limit bytes per fork are skipped.
* All physical length fields remain unchanged, so changing a limit preserves signatures.
*/
export function canonicalPdaSigningBytes(unsignedBytes) {
const bytes = toUint8Array(unsignedBytes);
if (bytes.length < 64 || new TextDecoder().decode(bytes.slice(0, 5)) !== MAGIC || bytes[5] !== 1 || bytes[6] !== 3) {
throw new Error('Ожидается unsigned PDA v1.3');
}
const rd16 = (i) => bytes[i] | (bytes[i + 1] << 8);
if (rd16(7) !== bytes.length + 64) throw new Error('Неверный record_len');
let c = 9 + 8 + 8 + 4 + 32;
c += 1 + bytes[c];
const blocks = bytes[c++];
const chunks = [bytes.slice(0, c)];
let registry = false;
for (let i = 0; i < blocks; i++) {
const start = c;
if (c + 2 > bytes.length) throw new Error('Обрезан PDA');
const type = bytes[c], ver = bytes[c + 1];
c += 2;
if (type === 1 || type === 2) {
c += 32;
if (c > bytes.length) throw new Error('Обрезан PDA');
chunks.push(bytes.slice(start, c));
continue;
}
if (c + 2 > bytes.length) throw new Error('Обрезан блок PDA');
const len = rd16(c); c += 2;
const end = c + len;
if (end > bytes.length) throw new Error('Обрезан payload PDA');
if (type === 3 && ver === 0) {
if (registry || c + 2 > end) throw new Error('Некорректный реестр fork');
registry = true;
const count = rd16(c);
if (!count || len !== 2 + count * 44) throw new Error('Некорректная длина реестра fork');
chunks.push(bytes.slice(start, c + 2));
c += 2;
for (let k = 0; k < count; k++) {
chunks.push(bytes.slice(c, c + 40)); // never sign these four limit bytes
c += 44;
}
if (c !== end) throw new Error('Некорректная длина fork');
} else chunks.push(bytes.slice(start, end));
c = end;
}
if (!registry || c !== bytes.length) throw new Error('Некорректная структура PDA');
const out = new Uint8Array(chunks.reduce((n, b) => n + b.length, 0));
let at = 0;
for (const chunk of chunks) { out.set(chunk, at); at += chunk.length; }
return out;
}
export function serializeUnsignedRecordFromState(stateLike) {
const state = stateLike || {};
const login = String(state.login || '');
@@ -379,7 +429,6 @@ export function serializeCreateUserPdaArgs(args) {
pushStrU8(out, args.login);
pushBytes(out, toUint8Array(args.rootKey32, 32));
pushU64LE(out, args.createdAtMs);
pushU64LE(out, BigInt(args.additionalLimitBytes || 0));
pushBytes(out, toUint8Array(args.clientKey32, 32));
pushBytes(out, toUint8Array(args.blockchainKey32, 32));
const addresses = normalizeServerAddresses(args.serverAddresses || []);
@@ -403,7 +452,6 @@ function serializeUpdateUserPdaArgs(args) {
pushStrU8(out, args.login);
pushBytes(out, toUint8Array(args.rootKey32, 32));
pushU64LE(out, args.updatedAtMs);
pushU64LE(out, BigInt(args.additionalLimitBytes || 0));
pushBytes(out, toUint8Array(args.clientKey32, 32));
out.push(Number(args.authMode) & 0xff);
if (args.newBlockchainKey32) {
@@ -570,7 +618,6 @@ async function createShineUserPdaOnSolana({
const blockchainKey32 = base64ToBytes(keyBundle.blockchainPair.publicKeyB64);
const clientKey32 = base64ToBytes(keyBundle.clientPair.publicKeyB64);
const rootPriv = await importPkcs8Ed25519(keyBundle.rootPair.privatePkcs8B64);
const bchPriv = await importPkcs8Ed25519(keyBundle.blockchainPair.privatePkcs8B64);
const ctx = await buildCommonContext({
login: cleanLogin,
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
@@ -587,8 +634,7 @@ async function createShineUserPdaOnSolana({
? [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;
if (startBonusLimit > 0xffffffffn) throw new Error('Стартовый лимит не помещается в PDA 1.2 u32');
parseUsersEconomyConfig(new Uint8Array(ecoInfo.data)); // economy PDA presence/version
const createdAtMs = BigInt(Date.now());
const addresses = normalizeServerAddresses(serverAddresses, isServer ? { addressFormatType, addressFormatVersion, address: serverAddress } : null);
const initial = {
@@ -599,14 +645,13 @@ async function createShineUserPdaOnSolana({
prevRecordHash: new Uint8Array(32),
rootKey: rootKey32,
clientKey: clientKey32,
forks: [{ blockchainKey: blockchainKey32, createdAtMs, paidLimitBytes: startBonusLimit }],
forks: [{ blockchainKey: blockchainKey32, createdAtMs, paidLimitBytes: 0n }],
serverAddresses: addresses,
accessServers: effectiveAccessServers,
};
const unsigned = serializeUnsignedRecordFromState(initial);
const hash = await sha256Bytes(unsigned);
const hash = await sha256Bytes(canonicalPdaSigningBytes(unsigned));
const rootSig = await signBytes(rootPriv, hash);
const recordSig = await signBytes(bchPriv, hash);
// Namespace читается из цепи, комиссия никогда не берётся из старого economy.registrationFee.
const certMessage = registrar
@@ -617,9 +662,8 @@ async function createShineUserPdaOnSolana({
data: buildEd25519IxData(registrar, namespace.registrarPublicKey32, certMessage),
}) : null;
const ixData = serializeCreateUserPdaArgs({ login: rawLogin, rootKey32, createdAtMs, additionalLimitBytes: 0n, clientKey32, blockchainKey32, serverAddresses: addresses, accessServers: effectiveAccessServers, recordSignature64: recordSig, registrarSignature64: registrar });
const ixData = serializeCreateUserPdaArgs({ login: rawLogin, rootKey32, createdAtMs, clientKey32, blockchainKey32, serverAddresses: addresses, accessServers: effectiveAccessServers, recordSignature64: rootSig, 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({
programId: ctx.usersProgram,
keys: [
@@ -636,7 +680,7 @@ async function createShineUserPdaOnSolana({
try {
const tx = new ctx.solana.Transaction();
if (registrarIx) tx.add(registrarIx);
tx.add(rootIx, recordIx, createIx);
tx.add(rootIx, createIx);
const signature = await sendAndConfirmSolanaHttp(ctx.connection, tx, [ctx.payerKeypair]);
return { signature, userPda: ctx.userPda.toBase58(), pdaAddress: ctx.userPda.toBase58(), blockchainName: `${cleanLogin}-001`, registrationFeeLamports: namespace.registrationFeeLamports };
} catch (error) { throw await attachSolanaLogs(error, ctx.connection); }
@@ -692,7 +736,6 @@ export async function updateShineUserPdaOnSolana({
payerPrivatePkcs8B64 = '',
blockchainPrivatePkcs8B64,
authorityMode,
additionalLimitBytes = 0n,
newRootPublicKey32 = null,
newRootPrivatePkcs8B64 = '',
nextClientPublicKey32 = null,
@@ -709,8 +752,6 @@ export async function updateShineUserPdaOnSolana({
payerPrivatePkcs8B64: String(payerPrivatePkcs8B64 || blockchainPrivatePkcs8B64 || ''),
solanaEndpoint,
});
const addLimit = BigInt(additionalLimitBytes || 0);
if (addLimit < 0n || addLimit % LIMIT_STEP !== 0n) throw new Error(`Лимит можно увеличивать только шагом ${LIMIT_STEP}`);
const rootKey = newRootPublicKey32 ? toUint8Array(newRootPublicKey32, 32) : current.rootKey;
const clientKey = nextClientPublicKey32 ? toUint8Array(nextClientPublicKey32, 32) : current.clientKey;
const rootChanged = bytesToBase58(rootKey) !== bytesToBase58(current.rootKey);
@@ -719,10 +760,9 @@ export async function updateShineUserPdaOnSolana({
if ((rootChanged || clientChanged) && !fullKeyRotation) {
throw new Error('Root/client keys меняются только как полная ротация: новый root + новый client + новый blockchain fork');
}
const authMode = fullKeyRotation ? AUTH_MODE_ROOT : AUTH_MODE_BLOCKCHAIN;
if (authorityMode != null) {
const requestedMode = authorityMode === 'root' || authorityMode === AUTH_MODE_ROOT ? AUTH_MODE_ROOT : AUTH_MODE_BLOCKCHAIN;
if (requestedMode !== authMode) throw new Error(fullKeyRotation ? 'Полная ротация требует root authority' : 'Обычное обновление PDA выполняется blockchain authority');
const authMode = AUTH_MODE_ROOT; // Root is the sole user PDA authority in v1.3.
if (authorityMode != null && authorityMode !== 'root' && authorityMode !== 'blockchain' && authorityMode !== AUTH_MODE_ROOT && authorityMode !== AUTH_MODE_BLOCKCHAIN) {
throw new Error('Неподдерживаемый режим authority');
}
const updatedAtMs = BigInt(Date.now());
@@ -733,13 +773,8 @@ export async function updateShineUserPdaOnSolana({
if (forks.some((f) => bytesToBase58(f.blockchainKey) === bytesToBase58(appendedKey))) throw new Error('Этот blockchain key уже был в истории fork');
const lastForkAt = BigInt(forks.at(-1).createdAtMs);
if (!fullKeyRotation && updatedAtMs - lastForkAt < FORK_COOLDOWN_MS) throw new Error('Новый fork обычным blockchain authority можно создавать не чаще одного раза в 72 часа');
const newLimit = forks.at(-1).paidLimitBytes + addLimit;
if (newLimit > 0xffffffffn) throw new Error('paid_limit_bytes превышает u32');
forks.push({ blockchainKey: appendedKey, createdAtMs: updatedAtMs, paidLimitBytes: newLimit });
} else if (addLimit > 0n) {
const active = forks.at(-1);
active.paidLimitBytes += addLimit;
if (active.paidLimitBytes > 0xffffffffn) throw new Error('paid_limit_bytes превышает u32');
// Each new fork starts at 0 (unlimited); older forks keep their own limits.
forks.push({ blockchainKey: appendedKey, createdAtMs: updatedAtMs, paidLimitBytes: 0n });
}
let addresses = current.serverAddresses;
@@ -755,7 +790,8 @@ export async function updateShineUserPdaOnSolana({
createdAtMs: current.createdAtMs,
updatedAtMs,
recordNumber: current.recordNumber + 1,
prevRecordHash: await sha256Bytes(current.unsignedBytes),
prevRecordHash: await sha256Bytes(current.formatMinor === FORMAT_MINOR_CURRENT
? canonicalPdaSigningBytes(current.unsignedBytes) : current.unsignedBytes),
rootKey,
clientKey,
forks,
@@ -763,29 +799,21 @@ export async function updateShineUserPdaOnSolana({
accessServers: nextAccess,
};
const unsigned = serializeUnsignedRecordFromState(next);
const hash = await sha256Bytes(unsigned);
const oldAuthorityPub = fullKeyRotation ? current.rootKey : current.forks.at(-1).blockchainKey;
const oldAuthorityPrivB64 = fullKeyRotation ? rootPrivatePkcs8B64 : blockchainPrivatePkcs8B64;
if (!oldAuthorityPrivB64) throw new Error(fullKeyRotation ? 'Для полной ротации нужен старый root private key' : 'Для обновления PDA нужен blockchain private key');
const oldAuthorityPriv = await importPkcs8Ed25519(oldAuthorityPrivB64);
const authSig = await signBytes(oldAuthorityPriv, hash);
let recordSignerPub;
let recordSignerPrivB64;
if (appendedKey) {
recordSignerPub = appendedKey;
recordSignerPrivB64 = newBlockchainPrivatePkcs8B64;
} else {
recordSignerPub = current.forks.at(-1).blockchainKey;
recordSignerPrivB64 = blockchainPrivatePkcs8B64;
}
if (!recordSignerPrivB64) throw new Error('Нет приватного ключа нового authority для подписи новой PDA');
const recordSignerPriv = await importPkcs8Ed25519(recordSignerPrivB64);
const recordSig = await signBytes(recordSignerPriv, hash);
const authIx = new ctx.solana.TransactionInstruction({ programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(authSig, oldAuthorityPub, hash) });
const recordIx = new ctx.solana.TransactionInstruction({ programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(recordSig, recordSignerPub, hash) });
const hash = await sha256Bytes(canonicalPdaSigningBytes(unsigned));
if (!rootPrivatePkcs8B64) throw new Error('Для изменения PDA нужен приватный Root Key');
const oldRootPriv = await importPkcs8Ed25519(rootPrivatePkcs8B64);
// Never allow an old root to authorize replacing itself without a new root signature.
const oldRootSig = await signBytes(oldRootPriv, hash);
const nextRootPriv = rootChanged
? await importPkcs8Ed25519(newRootPrivatePkcs8B64)
: oldRootPriv;
const recordSig = rootChanged ? await signBytes(nextRootPriv, hash) : oldRootSig;
const authIx = rootChanged ? new ctx.solana.TransactionInstruction({
programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(oldRootSig, current.rootKey, hash),
}) : null;
const recordIx = new ctx.solana.TransactionInstruction({
programId: ctx.ed25519Program, keys: [], data: buildEd25519IxData(recordSig, rootKey, hash),
});
const updateIx = new ctx.solana.TransactionInstruction({
programId: ctx.usersProgram,
keys: [
@@ -796,10 +824,10 @@ export async function updateShineUserPdaOnSolana({
{ pubkey: ctx.sysvarInstructions, isSigner: false, isWritable: false },
{ pubkey: ctx.economyConfigPda, isSigner: false, isWritable: false },
],
data: serializeUpdateUserPdaArgs({ login: current.login, rootKey32: rootKey, updatedAtMs, additionalLimitBytes: addLimit, clientKey32: clientKey, authMode, newBlockchainKey32: appendedKey, serverAddresses: addresses, accessServers: nextAccess, recordSignature64: recordSig }),
data: serializeUpdateUserPdaArgs({ login: current.login, rootKey32: rootKey, updatedAtMs, clientKey32: clientKey, authMode, newBlockchainKey32: appendedKey, serverAddresses: addresses, accessServers: nextAccess, recordSignature64: recordSig }),
});
try {
const signature = await sendAndConfirmSolanaHttp(ctx.connection, new ctx.solana.Transaction().add(authIx, recordIx, updateIx), [ctx.payerKeypair]);
const signature = await sendAndConfirmSolanaHttp(ctx.connection, new ctx.solana.Transaction().add(...(authIx ? [authIx] : []), recordIx, updateIx), [ctx.payerKeypair]);
return { signature, userPda: ctx.userPda.toBase58(), pdaAddress: ctx.userPda.toBase58(), paidLimitBytes: forks.at(-1).paidLimitBytes, forkCount: forks.length };
} catch (error) { throw await attachSolanaLogs(error, ctx.connection); }
}
@@ -811,20 +839,11 @@ export async function updateServerOnSolana({ login, keyBundle, serverAddress, se
rootPrivatePkcs8B64: keyBundle.rootPair.privatePkcs8B64,
blockchainPrivatePkcs8B64: keyBundle.blockchainPair.privatePkcs8B64,
clientPrivatePkcs8B64: keyBundle.clientPair.privatePkcs8B64,
authorityMode: 'blockchain',
authorityMode: 'root',
serverAddresses: serverAddresses || [{ addressFormatType, addressFormatVersion, address: serverAddress }],
});
}
export function calcLimitTopupPriceLamports(additionalLimitBytes, lamportsPerLimitStep) {
const add = BigInt(additionalLimitBytes || 0);
const pricePerStep = BigInt(lamportsPerLimitStep || 0);
if (add < 0n || add % LIMIT_STEP !== 0n) throw new Error(`Увеличение лимита должно быть кратно ${LIMIT_STEP} байт`);
return (add / LIMIT_STEP) * pricePerStep;
}
export function getLimitStepBytes() { return LIMIT_STEP; }
function supportData(tag, senderLogin, recipientLogin, amountLamports, starCents, target) {
const out = [tag];
const putString = (value) => { const bytes = new TextEncoder().encode(String(value)); if (bytes.length > 255) throw new Error('Слишком длинный login'); out.push(bytes.length, ...bytes); };