SHA256
Добавить promo-регистрацию и оффлайн генератор промокодов
This commit is contained in:
@@ -0,0 +1,20 @@
|
|||||||
|
# Promo-логины через продавцов в Solana
|
||||||
|
|
||||||
|
- краткое описание:
|
||||||
|
- в `shine_users` добавлена поддержка PDA продавцов красивых логинов, promo-подписи `shine_promo_v1:<login>` и отдельная автономная страница `shine-UI/promo-code-generator.html` для генерации promo-кода через браузерный кошелёк или через ручной ввод Base58 seed 32 bytes;
|
||||||
|
- что проверять:
|
||||||
|
- admin-транзакцией создать или обновить `promo_seller_pda`;
|
||||||
|
- сгенерировать promo-код на странице `promo-code-generator.html` в режиме wallet extension;
|
||||||
|
- сгенерировать promo-код на той же странице в режиме ручного Base58 seed;
|
||||||
|
- открыть HTML локально как отдельный файл без сервера и убедиться, что генерация в режиме Base58 seed продолжает работать;
|
||||||
|
- зарегистрировать короткий/premium логин по promo-коду;
|
||||||
|
- убедиться, что без promo-кода тот же логин не проходит `shine_login_guard`;
|
||||||
|
- убедиться, что после успешной регистрации `remaining_sales` уменьшается на 1;
|
||||||
|
- проверить отказ при исчерпанной квоте, неверной подписи и логине короче `min_login_length`;
|
||||||
|
- ожидаемый результат:
|
||||||
|
- promo-регистрация проходит только при валидной подписи продавца и соблюдении лимитов;
|
||||||
|
- обычная регистрация без promo-кода продолжает работать как раньше;
|
||||||
|
- страница генерации выдаёт строку формата `1seller-signatureBase58` в обоих режимах;
|
||||||
|
- single-file HTML работает локально оффлайн минимум в режиме ручного Base58 seed;
|
||||||
|
- статус:
|
||||||
|
- `pending`
|
||||||
+2
-2
@@ -1,2 +1,2 @@
|
|||||||
client.version=1.2.290
|
client.version=1.2.291
|
||||||
server.version=1.2.270
|
server.version=1.2.271
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ export function render({ navigate }) {
|
|||||||
|
|
||||||
let passwordMode = String(state.registrationDraft.passwordMode || 'single') === 'words' ? 'words' : 'single';
|
let passwordMode = String(state.registrationDraft.passwordMode || 'single') === 'words' ? 'words' : 'single';
|
||||||
let passwordWords = normalizePasswordWords(state.registrationDraft.passwordWords);
|
let passwordWords = normalizePasswordWords(state.registrationDraft.passwordWords);
|
||||||
|
let usePromoCode = Boolean(state.registrationDraft.usePromoCode);
|
||||||
|
|
||||||
const loginInput = document.createElement('input');
|
const loginInput = document.createElement('input');
|
||||||
loginInput.className = 'input';
|
loginInput.className = 'input';
|
||||||
@@ -117,6 +118,40 @@ export function render({ navigate }) {
|
|||||||
|
|
||||||
passwordModeToggle.append(passwordModeCheckbox, passwordModeLabel);
|
passwordModeToggle.append(passwordModeCheckbox, passwordModeLabel);
|
||||||
|
|
||||||
|
const promoToggle = document.createElement('label');
|
||||||
|
promoToggle.className = 'registration-toggle';
|
||||||
|
|
||||||
|
const promoCheckbox = document.createElement('input');
|
||||||
|
promoCheckbox.type = 'checkbox';
|
||||||
|
promoCheckbox.checked = usePromoCode;
|
||||||
|
|
||||||
|
const promoToggleLabel = document.createElement('span');
|
||||||
|
promoToggleLabel.textContent = 'У меня есть промокод';
|
||||||
|
|
||||||
|
promoToggle.append(promoCheckbox, promoToggleLabel);
|
||||||
|
|
||||||
|
const promoField = document.createElement('label');
|
||||||
|
promoField.className = 'stack';
|
||||||
|
|
||||||
|
const promoFieldLabel = document.createElement('span');
|
||||||
|
promoFieldLabel.className = 'field-label';
|
||||||
|
promoFieldLabel.textContent = 'Промокод';
|
||||||
|
|
||||||
|
const promoInput = document.createElement('input');
|
||||||
|
promoInput.className = 'input';
|
||||||
|
promoInput.type = 'text';
|
||||||
|
promoInput.autocomplete = 'off';
|
||||||
|
promoInput.autocapitalize = 'off';
|
||||||
|
promoInput.spellcheck = false;
|
||||||
|
promoInput.value = String(state.registrationDraft.promoCode || '');
|
||||||
|
promoInput.placeholder = 'Вставьте промокод';
|
||||||
|
|
||||||
|
const promoHint = document.createElement('p');
|
||||||
|
promoHint.className = 'meta-muted';
|
||||||
|
promoHint.textContent = 'Если промокод включён, обычная проверка premium/trademark логина пропускается.';
|
||||||
|
|
||||||
|
promoField.append(promoFieldLabel, promoInput, promoHint);
|
||||||
|
|
||||||
const statusText = document.createElement('p');
|
const statusText = document.createElement('p');
|
||||||
statusText.className = 'meta-muted';
|
statusText.className = 'meta-muted';
|
||||||
statusText.textContent = 'Проверка логина: не выполнена';
|
statusText.textContent = 'Проверка логина: не выполнена';
|
||||||
@@ -202,6 +237,12 @@ export function render({ navigate }) {
|
|||||||
state.registrationDraft.passwordMode = passwordMode;
|
state.registrationDraft.passwordMode = passwordMode;
|
||||||
state.registrationDraft.passwordWords = normalizePasswordWords(passwordWords);
|
state.registrationDraft.passwordWords = normalizePasswordWords(passwordWords);
|
||||||
state.registrationDraft.password = getCurrentPassword();
|
state.registrationDraft.password = getCurrentPassword();
|
||||||
|
state.registrationDraft.usePromoCode = usePromoCode;
|
||||||
|
state.registrationDraft.promoCode = String(promoInput.value || '').trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function updatePromoVisibility() {
|
||||||
|
promoField.style.display = usePromoCode ? 'grid' : 'none';
|
||||||
}
|
}
|
||||||
|
|
||||||
async function runAvailabilityCheck() {
|
async function runAvailabilityCheck() {
|
||||||
@@ -212,6 +253,16 @@ export function render({ navigate }) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (usePromoCode) {
|
||||||
|
lastCheckedLogin = login;
|
||||||
|
lastCheckedFree = true;
|
||||||
|
lastCheckedClassName = 'promo';
|
||||||
|
statusText.textContent = 'Промокод включён: обычная проверка premium/trademark логина пропущена';
|
||||||
|
statusText.className = 'status-line is-available';
|
||||||
|
formError.style.display = 'none';
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
if (login === lastCheckedLogin) {
|
if (login === lastCheckedLogin) {
|
||||||
if (!lastCheckedFree) {
|
if (!lastCheckedFree) {
|
||||||
statusText.textContent = 'Логин уже занят ❌';
|
statusText.textContent = 'Логин уже занят ❌';
|
||||||
@@ -320,8 +371,34 @@ export function render({ navigate }) {
|
|||||||
syncDraftState();
|
syncDraftState();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
promoCheckbox.addEventListener('change', () => {
|
||||||
|
usePromoCode = promoCheckbox.checked;
|
||||||
|
lastCheckedLogin = '';
|
||||||
|
lastCheckedFree = false;
|
||||||
|
lastCheckedClassName = '';
|
||||||
|
updatePromoVisibility();
|
||||||
|
syncDraftState();
|
||||||
|
if (usePromoCode) {
|
||||||
|
statusText.textContent = 'Промокод включён: проверка логина будет пропущена';
|
||||||
|
statusText.className = 'status-line is-available';
|
||||||
|
} else {
|
||||||
|
statusText.textContent = 'Проверка логина: не выполнена';
|
||||||
|
statusText.className = 'meta-muted';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
promoInput.addEventListener('input', () => {
|
||||||
|
syncDraftState();
|
||||||
|
});
|
||||||
|
|
||||||
nextButton.addEventListener('click', async () => {
|
nextButton.addEventListener('click', async () => {
|
||||||
formError.style.display = 'none';
|
formError.style.display = 'none';
|
||||||
|
const promoCode = String(promoInput.value || '').trim();
|
||||||
|
if (usePromoCode && !promoCode) {
|
||||||
|
formError.textContent = 'Если включён промокод, поле промокода должно быть заполнено.';
|
||||||
|
formError.style.display = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
const isFree = await runAvailabilityCheck();
|
const isFree = await runAvailabilityCheck();
|
||||||
if (!isFree) return;
|
if (!isFree) return;
|
||||||
|
|
||||||
@@ -345,6 +422,8 @@ export function render({ navigate }) {
|
|||||||
state.registrationDraft.password = nextPassword;
|
state.registrationDraft.password = nextPassword;
|
||||||
state.registrationDraft.passwordMode = passwordMode;
|
state.registrationDraft.passwordMode = passwordMode;
|
||||||
state.registrationDraft.passwordWords = normalizePasswordWords(passwordWords);
|
state.registrationDraft.passwordWords = normalizePasswordWords(passwordWords);
|
||||||
|
state.registrationDraft.usePromoCode = usePromoCode;
|
||||||
|
state.registrationDraft.promoCode = promoCode;
|
||||||
if (credsChanged) {
|
if (credsChanged) {
|
||||||
state.registrationDraft.preGeneratedKeyBundle = null;
|
state.registrationDraft.preGeneratedKeyBundle = null;
|
||||||
}
|
}
|
||||||
@@ -363,10 +442,11 @@ export function render({ navigate }) {
|
|||||||
passwordField = form.children[1];
|
passwordField = form.children[1];
|
||||||
loginField.append(loginInput);
|
loginField.append(loginInput);
|
||||||
passwordField.append(passwordInput);
|
passwordField.append(passwordInput);
|
||||||
form.append(passwordModeToggle, passwordLengthText, wordsSection, statusText, checkButton, formError);
|
form.append(passwordModeToggle, promoToggle, promoField, passwordLengthText, wordsSection, statusText, checkButton, formError);
|
||||||
actions.innerHTML = '';
|
actions.innerHTML = '';
|
||||||
actions.append(backButton, nextButton);
|
actions.append(backButton, nextButton);
|
||||||
updatePasswordModeVisibility();
|
updatePasswordModeVisibility();
|
||||||
|
updatePromoVisibility();
|
||||||
syncDraftState();
|
syncDraftState();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -155,6 +155,8 @@ export function render({ navigate }) {
|
|||||||
state.registrationDraft.password = '';
|
state.registrationDraft.password = '';
|
||||||
state.registrationDraft.passwordMode = 'single';
|
state.registrationDraft.passwordMode = 'single';
|
||||||
state.registrationDraft.passwordWords = EMPTY_PASSWORD_WORDS.slice();
|
state.registrationDraft.passwordWords = EMPTY_PASSWORD_WORDS.slice();
|
||||||
|
state.registrationDraft.usePromoCode = false;
|
||||||
|
state.registrationDraft.promoCode = '';
|
||||||
state.registrationDraft.storagePwd = '';
|
state.registrationDraft.storagePwd = '';
|
||||||
state.registrationDraft.sessionId = '';
|
state.registrationDraft.sessionId = '';
|
||||||
state.registrationDraft.pendingKeyBundle = null;
|
state.registrationDraft.pendingKeyBundle = null;
|
||||||
|
|||||||
@@ -82,6 +82,8 @@ async function completeRegistrationLogin({ navigate, keyBundle }) {
|
|||||||
state.registrationDraft.password = '';
|
state.registrationDraft.password = '';
|
||||||
state.registrationDraft.passwordMode = 'single';
|
state.registrationDraft.passwordMode = 'single';
|
||||||
state.registrationDraft.passwordWords = EMPTY_PASSWORD_WORDS.slice();
|
state.registrationDraft.passwordWords = EMPTY_PASSWORD_WORDS.slice();
|
||||||
|
state.registrationDraft.usePromoCode = false;
|
||||||
|
state.registrationDraft.promoCode = '';
|
||||||
state.registrationDraft.storagePwd = '';
|
state.registrationDraft.storagePwd = '';
|
||||||
state.registrationDraft.sessionId = '';
|
state.registrationDraft.sessionId = '';
|
||||||
state.registrationDraft.pendingKeyBundle = null;
|
state.registrationDraft.pendingKeyBundle = null;
|
||||||
@@ -264,6 +266,7 @@ export function render({ navigate }) {
|
|||||||
keyBundle,
|
keyBundle,
|
||||||
solanaEndpoint: state.entrySettings.solanaServer,
|
solanaEndpoint: state.entrySettings.solanaServer,
|
||||||
accessServers: [state.entrySettings.shineServerLogin || defaultServerLogin],
|
accessServers: [state.entrySettings.shineServerLogin || defaultServerLogin],
|
||||||
|
promoCode: state.registrationDraft.usePromoCode ? state.registrationDraft.promoCode : '',
|
||||||
});
|
});
|
||||||
} catch (solanaError) {
|
} catch (solanaError) {
|
||||||
const solanaMsg = formatSolanaErrorDetails(solanaError);
|
const solanaMsg = formatSolanaErrorDetails(solanaError);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { base64ToBytes, importPkcs8Ed25519, sha256Bytes, signBytes } from './crypto-utils.js';
|
import { base64ToBytes, bytesToBase58, importPkcs8Ed25519, sha256Bytes, signBytes } from './crypto-utils.js';
|
||||||
import { extractSeed32FromPkcs8B64 } from './client-key-utils.js';
|
import { extractSeed32FromPkcs8B64 } from './client-key-utils.js';
|
||||||
import {
|
import {
|
||||||
SHINE_LOGIN_GUARD_PROGRAM_ID,
|
SHINE_LOGIN_GUARD_PROGRAM_ID,
|
||||||
@@ -12,10 +12,12 @@ const MAGIC = 'SHiNE';
|
|||||||
const LAST_BLOCK_STATE_PREFIX = 'SHiNE_LAST_BLOCK';
|
const LAST_BLOCK_STATE_PREFIX = 'SHiNE_LAST_BLOCK';
|
||||||
const SHINE_PAYMENTS_INFLOW_VAULT_SEED = 'shine_payments_inflow_vault';
|
const SHINE_PAYMENTS_INFLOW_VAULT_SEED = 'shine_payments_inflow_vault';
|
||||||
const SHINE_USERS_USER_PDA_SEED_PREFIX = 'user_login=';
|
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 LIMIT_STEP = 10_000n;
|
||||||
const BLOCKCHAIN_TYPE_MAIN_USER = 1;
|
const BLOCKCHAIN_TYPE_MAIN_USER = 1;
|
||||||
const ED25519_PROGRAM_ID = 'Ed25519SigVerify111111111111111111111111111';
|
const ED25519_PROGRAM_ID = 'Ed25519SigVerify111111111111111111111111111';
|
||||||
const SYSVAR_INSTRUCTIONS_ID = 'Sysvar1nstructions1111111111111111111111111';
|
const SYSVAR_INSTRUCTIONS_ID = 'Sysvar1nstructions1111111111111111111111111';
|
||||||
|
const PROMO_SIGN_PREFIX = 'shine_promo_v1:';
|
||||||
|
|
||||||
const BLOCK_TYPE_RECOVERY_KEY = 0;
|
const BLOCK_TYPE_RECOVERY_KEY = 0;
|
||||||
const BLOCK_TYPE_ROOT_KEY = 1;
|
const BLOCK_TYPE_ROOT_KEY = 1;
|
||||||
@@ -214,6 +216,10 @@ function serializeCreateUserPdaArgs(args) {
|
|||||||
}
|
}
|
||||||
buf.push(Number(args.trustedCount || 0) & 0xff);
|
buf.push(Number(args.trustedCount || 0) & 0xff);
|
||||||
for (const x of args.rootSignature64) buf.push(x);
|
for (const x of args.rootSignature64) buf.push(x);
|
||||||
|
const promoCode = String(args.promoCode || '').trim();
|
||||||
|
if (promoCode) {
|
||||||
|
pushStrU8(buf, promoCode);
|
||||||
|
}
|
||||||
return new Uint8Array(buf);
|
return new Uint8Array(buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -363,6 +369,37 @@ export function buildLastBlockStateBytes(login, blockchainName, lastBlockNumber
|
|||||||
return new Uint8Array(buf);
|
return new Uint8Array(buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function buildPromoMessageBytes(login) {
|
||||||
|
return new TextEncoder().encode(`${PROMO_SIGN_PREFIX}${normalizeLogin(login)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildPromoCodeString(sellerLogin, signatureBytes) {
|
||||||
|
const cleanSellerLogin = normalizeLogin(sellerLogin);
|
||||||
|
if (!cleanSellerLogin) {
|
||||||
|
throw new Error('Не указан логин продавца');
|
||||||
|
}
|
||||||
|
const sig = signatureBytes instanceof Uint8Array ? signatureBytes : new Uint8Array(signatureBytes || []);
|
||||||
|
if (sig.length !== 64) {
|
||||||
|
throw new Error('Подпись промокода должна быть ровно 64 байта');
|
||||||
|
}
|
||||||
|
return `1${cleanSellerLogin}-${bytesToBase58(sig)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function findPromoSellerPda({ sellerLogin }) {
|
||||||
|
const cleanSellerLogin = normalizeLogin(sellerLogin);
|
||||||
|
if (!cleanSellerLogin) throw new Error('Не указан логин продавца');
|
||||||
|
const solana = await loadSolanaLib();
|
||||||
|
const usersProgram = new solana.PublicKey(SHINE_USERS_PROGRAM_ID);
|
||||||
|
const [promoSellerPda] = solana.PublicKey.findProgramAddressSync(
|
||||||
|
[new TextEncoder().encode(SHINE_USERS_PROMO_SELLER_PDA_SEED_PREFIX), new TextEncoder().encode(cleanSellerLogin)],
|
||||||
|
usersProgram,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
sellerLogin: cleanSellerLogin,
|
||||||
|
promoSellerPda: promoSellerPda.toBase58(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function parseShineUserPda(dataBytes) {
|
export function parseShineUserPda(dataBytes) {
|
||||||
const bytes = dataBytes instanceof Uint8Array ? dataBytes : new Uint8Array(dataBytes || []);
|
const bytes = dataBytes instanceof Uint8Array ? dataBytes : new Uint8Array(dataBytes || []);
|
||||||
const reader = makeReader(bytes);
|
const reader = makeReader(bytes);
|
||||||
@@ -770,6 +807,7 @@ async function createShineUserPdaOnSolana({
|
|||||||
serverAddress = '',
|
serverAddress = '',
|
||||||
syncServers = [],
|
syncServers = [],
|
||||||
accessServers = [],
|
accessServers = [],
|
||||||
|
promoCode = '',
|
||||||
}) {
|
}) {
|
||||||
const ctx = await buildCreateContext({ login, keyBundle, solanaEndpoint });
|
const ctx = await buildCreateContext({ login, keyBundle, solanaEndpoint });
|
||||||
const ecoAccount = await ctx.connection.getAccountInfo(ctx.economyConfigPda);
|
const ecoAccount = await ctx.connection.getAccountInfo(ctx.economyConfigPda);
|
||||||
@@ -778,6 +816,7 @@ async function createShineUserPdaOnSolana({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const cleanLogin = ctx.cleanLogin;
|
const cleanLogin = ctx.cleanLogin;
|
||||||
|
const cleanPromoCode = String(promoCode || '').trim();
|
||||||
const blockchainName = `${cleanLogin}-001`;
|
const blockchainName = `${cleanLogin}-001`;
|
||||||
const zeroHash32 = new Uint8Array(32);
|
const zeroHash32 = new Uint8Array(32);
|
||||||
const createdAtMs = BigInt(Date.now());
|
const createdAtMs = BigInt(Date.now());
|
||||||
@@ -845,8 +884,41 @@ async function createShineUserPdaOnSolana({
|
|||||||
sessions: [],
|
sessions: [],
|
||||||
trustedCount: 0,
|
trustedCount: 0,
|
||||||
rootSignature64: rootSig64,
|
rootSignature64: rootSig64,
|
||||||
|
promoCode: cleanPromoCode,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let promoSellerPda = null;
|
||||||
|
let promoEd25519Ix = null;
|
||||||
|
if (cleanPromoCode) {
|
||||||
|
const dashPos = cleanPromoCode.indexOf('-');
|
||||||
|
if (!cleanPromoCode.startsWith('1') || dashPos <= 1 || dashPos === cleanPromoCode.length - 1) {
|
||||||
|
throw new Error('Некорректный формат промокода');
|
||||||
|
}
|
||||||
|
const sellerLogin = normalizeLogin(cleanPromoCode.slice(1, dashPos));
|
||||||
|
const signatureBase58 = cleanPromoCode.slice(dashPos + 1);
|
||||||
|
const [promoSellerAddress] = ctx.solana.PublicKey.findProgramAddressSync(
|
||||||
|
[new TextEncoder().encode(SHINE_USERS_PROMO_SELLER_PDA_SEED_PREFIX), new TextEncoder().encode(sellerLogin)],
|
||||||
|
ctx.usersProgram,
|
||||||
|
);
|
||||||
|
promoSellerPda = promoSellerAddress;
|
||||||
|
|
||||||
|
const promoMessage = buildPromoMessageBytes(cleanLogin);
|
||||||
|
const signatureBytes = ctx.solana.bs58.decode(signatureBase58);
|
||||||
|
if (signatureBytes.length !== 64) {
|
||||||
|
throw new Error('Подпись промокода должна быть 64 байта в Base58');
|
||||||
|
}
|
||||||
|
const sellerAccount = await ctx.connection.getAccountInfo(promoSellerAddress, 'confirmed');
|
||||||
|
if (!sellerAccount?.data || sellerAccount.data.length < 42) {
|
||||||
|
throw new Error('Promo seller PDA не найдена или повреждена');
|
||||||
|
}
|
||||||
|
const signerPubkey = new Uint8Array(sellerAccount.data.slice(10, 42));
|
||||||
|
promoEd25519Ix = new ctx.solana.TransactionInstruction({
|
||||||
|
programId: ctx.ed25519Program,
|
||||||
|
keys: [],
|
||||||
|
data: buildEd25519IxData(signatureBytes, signerPubkey, promoMessage),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const ed25519RootIx = new ctx.solana.TransactionInstruction({
|
const ed25519RootIx = new ctx.solana.TransactionInstruction({
|
||||||
programId: ctx.ed25519Program,
|
programId: ctx.ed25519Program,
|
||||||
keys: [],
|
keys: [],
|
||||||
@@ -867,15 +939,19 @@ async function createShineUserPdaOnSolana({
|
|||||||
{ pubkey: ctx.sysvarInstructions, isSigner: false, isWritable: false },
|
{ pubkey: ctx.sysvarInstructions, isSigner: false, isWritable: false },
|
||||||
{ pubkey: ctx.economyConfigPda, isSigner: false, isWritable: false },
|
{ pubkey: ctx.economyConfigPda, isSigner: false, isWritable: false },
|
||||||
{ pubkey: ctx.loginGuardProgram, isSigner: false, isWritable: false },
|
{ pubkey: ctx.loginGuardProgram, isSigner: false, isWritable: false },
|
||||||
|
...(promoSellerPda ? [{ pubkey: promoSellerPda, isSigner: false, isWritable: true }] : []),
|
||||||
],
|
],
|
||||||
data: ixData,
|
data: ixData,
|
||||||
});
|
});
|
||||||
|
|
||||||
let signature;
|
let signature;
|
||||||
try {
|
try {
|
||||||
|
const tx = new ctx.solana.Transaction();
|
||||||
|
if (promoEd25519Ix) tx.add(promoEd25519Ix);
|
||||||
|
tx.add(ed25519RootIx, ed25519BchIx, createIx);
|
||||||
signature = await ctx.solana.sendAndConfirmTransaction(
|
signature = await ctx.solana.sendAndConfirmTransaction(
|
||||||
ctx.connection,
|
ctx.connection,
|
||||||
new ctx.solana.Transaction().add(ed25519RootIx, ed25519BchIx, createIx),
|
tx,
|
||||||
[ctx.clientKeypair],
|
[ctx.clientKeypair],
|
||||||
{ commitment: 'confirmed' },
|
{ commitment: 'confirmed' },
|
||||||
);
|
);
|
||||||
@@ -891,13 +967,14 @@ async function createShineUserPdaOnSolana({
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function registerUserOnSolana({ login, keyBundle, solanaEndpoint, accessServers = [] }) {
|
export async function registerUserOnSolana({ login, keyBundle, solanaEndpoint, accessServers = [], promoCode = '' }) {
|
||||||
return createShineUserPdaOnSolana({
|
return createShineUserPdaOnSolana({
|
||||||
login,
|
login,
|
||||||
keyBundle,
|
keyBundle,
|
||||||
solanaEndpoint,
|
solanaEndpoint,
|
||||||
isServer: false,
|
isServer: false,
|
||||||
accessServers: Array.isArray(accessServers) ? accessServers : [],
|
accessServers: Array.isArray(accessServers) ? accessServers : [],
|
||||||
|
promoCode,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -139,6 +139,6 @@ export async function checkLoginExistsOnSolana({ login, solanaEndpoint }) {
|
|||||||
return { exists: !!ai, userPda: userPda.toBase58() };
|
return { exists: !!ai, userPda: userPda.toBase58() };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function registerUserOnSolana({ login, keyBundle, solanaEndpoint, accessServers }) {
|
export async function registerUserOnSolana({ login, keyBundle, solanaEndpoint, accessServers, promoCode = '' }) {
|
||||||
return registerUserOnSolanaShared({ login, keyBundle, solanaEndpoint, accessServers });
|
return registerUserOnSolanaShared({ login, keyBundle, solanaEndpoint, accessServers, promoCode });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -269,6 +269,8 @@ function createInitialState({ withStoredSession = true } = {}) {
|
|||||||
password: '',
|
password: '',
|
||||||
passwordMode: 'single',
|
passwordMode: 'single',
|
||||||
passwordWords: emptyPasswordWords(),
|
passwordWords: emptyPasswordWords(),
|
||||||
|
usePromoCode: false,
|
||||||
|
promoCode: '',
|
||||||
sessionId: '',
|
sessionId: '',
|
||||||
storagePwd: '',
|
storagePwd: '',
|
||||||
pendingKeyBundle: null,
|
pendingKeyBundle: null,
|
||||||
|
|||||||
@@ -0,0 +1,555 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>SHiNE Promo Code Generator</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
color-scheme: dark;
|
||||||
|
--bg: #091019;
|
||||||
|
--card: rgba(18, 29, 42, 0.95);
|
||||||
|
--card-2: rgba(11, 18, 28, 0.98);
|
||||||
|
--line: rgba(116, 146, 189, 0.22);
|
||||||
|
--text: #edf4ff;
|
||||||
|
--muted: #95a8c4;
|
||||||
|
--accent: #61d3a7;
|
||||||
|
--accent-2: #58a8ff;
|
||||||
|
--danger: #ff7f97;
|
||||||
|
--shadow: 0 26px 90px rgba(0, 0, 0, 0.34);
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
min-height: 100vh;
|
||||||
|
font-family: "Segoe UI", "Inter", sans-serif;
|
||||||
|
color: var(--text);
|
||||||
|
background:
|
||||||
|
radial-gradient(circle at top left, rgba(88, 168, 255, 0.22), transparent 28%),
|
||||||
|
radial-gradient(circle at bottom right, rgba(97, 211, 167, 0.16), transparent 36%),
|
||||||
|
linear-gradient(180deg, #060b12 0%, var(--bg) 100%);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
.panel {
|
||||||
|
width: min(840px, 100%);
|
||||||
|
background: linear-gradient(180deg, var(--card) 0%, var(--card-2) 100%);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 24px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
padding: 28px;
|
||||||
|
backdrop-filter: blur(14px);
|
||||||
|
}
|
||||||
|
h1 {
|
||||||
|
margin: 0 0 10px;
|
||||||
|
font-size: clamp(28px, 4vw, 40px);
|
||||||
|
line-height: 1.06;
|
||||||
|
letter-spacing: -0.03em;
|
||||||
|
}
|
||||||
|
.lead, .hint {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--muted);
|
||||||
|
line-height: 1.55;
|
||||||
|
}
|
||||||
|
.layout {
|
||||||
|
display: grid;
|
||||||
|
gap: 16px;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
margin-top: 24px;
|
||||||
|
}
|
||||||
|
.block {
|
||||||
|
background: rgba(8, 14, 21, 0.72);
|
||||||
|
border: 1px solid rgba(116, 146, 189, 0.16);
|
||||||
|
border-radius: 18px;
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
.full { grid-column: 1 / -1; }
|
||||||
|
.field-label, .block strong {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
color: #dce9ff;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
input, textarea {
|
||||||
|
width: 100%;
|
||||||
|
border: 1px solid rgba(116, 146, 189, 0.18);
|
||||||
|
background: rgba(5, 11, 17, 0.92);
|
||||||
|
color: var(--text);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 13px 14px;
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
textarea {
|
||||||
|
min-height: 124px;
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
.mode-switch {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.mode-switch label {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
border: 1px solid rgba(116, 146, 189, 0.18);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 10px 14px;
|
||||||
|
cursor: pointer;
|
||||||
|
color: var(--text);
|
||||||
|
background: rgba(8, 14, 21, 0.82);
|
||||||
|
}
|
||||||
|
.mode-switch input { width: auto; }
|
||||||
|
.actions, .seed-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
border: 0;
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 13px 18px;
|
||||||
|
font: inherit;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: transform 0.16s ease, opacity 0.16s ease;
|
||||||
|
}
|
||||||
|
button:hover { transform: translateY(-1px); }
|
||||||
|
button:disabled {
|
||||||
|
cursor: default;
|
||||||
|
opacity: 0.55;
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
.primary {
|
||||||
|
background: linear-gradient(135deg, var(--accent) 0%, var(--accent-2) 100%);
|
||||||
|
color: #041219;
|
||||||
|
}
|
||||||
|
.secondary {
|
||||||
|
background: rgba(76, 108, 149, 0.18);
|
||||||
|
color: var(--text);
|
||||||
|
border: 1px solid rgba(116, 146, 189, 0.18);
|
||||||
|
}
|
||||||
|
.status {
|
||||||
|
margin-top: 16px;
|
||||||
|
padding: 14px 16px;
|
||||||
|
border-radius: 16px;
|
||||||
|
border: 1px solid rgba(116, 146, 189, 0.18);
|
||||||
|
background: rgba(6, 11, 17, 0.74);
|
||||||
|
color: var(--muted);
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
.status.error {
|
||||||
|
color: #ffd7df;
|
||||||
|
border-color: rgba(255, 127, 151, 0.36);
|
||||||
|
background: rgba(54, 12, 22, 0.52);
|
||||||
|
}
|
||||||
|
.status.success {
|
||||||
|
color: #defff3;
|
||||||
|
border-color: rgba(97, 211, 167, 0.36);
|
||||||
|
background: rgba(8, 38, 29, 0.52);
|
||||||
|
}
|
||||||
|
.muted-text {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.5;
|
||||||
|
margin: 8px 0 0;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
.hidden { display: none !important; }
|
||||||
|
code {
|
||||||
|
padding: 2px 5px;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: rgba(255, 255, 255, 0.06);
|
||||||
|
}
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.panel {
|
||||||
|
padding: 20px;
|
||||||
|
border-radius: 20px;
|
||||||
|
}
|
||||||
|
.layout {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
.full { grid-column: auto; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="panel">
|
||||||
|
<h1>Генератор promo-кодов</h1>
|
||||||
|
<p class="lead">
|
||||||
|
Полностью автономный HTML-файл. Можно открыть локально без сервера и без внешних зависимостей.
|
||||||
|
Подписывается строка <code>shine_promo_v1:<login></code>, а на выходе получается promo-код
|
||||||
|
формата <code>1seller-signatureBase58</code>.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<section class="layout">
|
||||||
|
<div class="block full">
|
||||||
|
<strong>Режим подписи</strong>
|
||||||
|
<div class="mode-switch">
|
||||||
|
<label><input type="radio" name="signMode" value="extension" checked> Wallet extension</label>
|
||||||
|
<label><input type="radio" name="signMode" value="private"> Приватный ключ Base58</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="block">
|
||||||
|
<label class="field-label" for="sellerLogin">Логин продавца</label>
|
||||||
|
<input id="sellerLogin" type="text" autocomplete="off" placeholder="например promo_master">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="block">
|
||||||
|
<label class="field-label" for="targetLogin">Новый логин</label>
|
||||||
|
<input id="targetLogin" type="text" autocomplete="off" placeholder="например SuperName">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="block full" id="extensionBlock">
|
||||||
|
<strong>Подключённый кошелёк</strong>
|
||||||
|
<div class="muted-text" id="walletAddress">не подключен</div>
|
||||||
|
<div class="actions" style="margin-top: 14px;">
|
||||||
|
<button class="secondary" type="button" id="connectBtn">Подключить кошелёк</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="block full hidden" id="privateKeyBlock">
|
||||||
|
<label class="field-label" for="privateSeed">Приватный ключ продавца</label>
|
||||||
|
<input id="privateSeed" type="text" autocomplete="off" placeholder="Base58 seed 32 bytes">
|
||||||
|
<div class="seed-actions" style="margin-top: 14px;">
|
||||||
|
<button class="secondary" type="button" id="generateSeedBtn">Сгенерировать новый Base58 seed</button>
|
||||||
|
<button class="secondary" type="button" id="copySeedBtn">Скопировать seed</button>
|
||||||
|
</div>
|
||||||
|
<p class="muted-text" id="privateSeedHint">
|
||||||
|
Формат: Base58 seed длиной 32 байта. Страница импортирует его в Ed25519 и локально подписывает сообщение через WebCrypto.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="block full">
|
||||||
|
<strong>Подписываемое сообщение</strong>
|
||||||
|
<div class="muted-text" id="messagePreview">—</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="block full">
|
||||||
|
<div class="actions">
|
||||||
|
<button class="primary" type="button" id="generateBtn">Сгенерировать promo-код</button>
|
||||||
|
<button class="secondary" type="button" id="copyCodeBtn" disabled>Скопировать promo-код</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="block full">
|
||||||
|
<label class="field-label" for="promoCode">Готовый promo-код</label>
|
||||||
|
<textarea id="promoCode" readonly placeholder="Здесь появится готовая строка promo-кода"></textarea>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<p class="status" id="status">Готово. Можно работать полностью локально.</p>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
(() => {
|
||||||
|
const LOGIN_RE = /^[0-9A-Za-z_]{1,20}$/;
|
||||||
|
const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
|
||||||
|
const ED25519_PKCS8_PREFIX = new Uint8Array([
|
||||||
|
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
|
||||||
|
]);
|
||||||
|
const PROMO_PREFIX = 'shine_promo_v1:';
|
||||||
|
|
||||||
|
const $ = (id) => document.getElementById(id);
|
||||||
|
const sellerLoginInput = $('sellerLogin');
|
||||||
|
const targetLoginInput = $('targetLogin');
|
||||||
|
const walletAddressNode = $('walletAddress');
|
||||||
|
const privateSeedInput = $('privateSeed');
|
||||||
|
const privateSeedHint = $('privateSeedHint');
|
||||||
|
const messagePreviewNode = $('messagePreview');
|
||||||
|
const promoCodeNode = $('promoCode');
|
||||||
|
const statusNode = $('status');
|
||||||
|
const generateBtn = $('generateBtn');
|
||||||
|
const copyCodeBtn = $('copyCodeBtn');
|
||||||
|
const connectBtn = $('connectBtn');
|
||||||
|
const generateSeedBtn = $('generateSeedBtn');
|
||||||
|
const copySeedBtn = $('copySeedBtn');
|
||||||
|
const extensionBlock = $('extensionBlock');
|
||||||
|
const privateKeyBlock = $('privateKeyBlock');
|
||||||
|
|
||||||
|
let currentMode = 'extension';
|
||||||
|
let provider = null;
|
||||||
|
let walletAddress = '';
|
||||||
|
|
||||||
|
function setStatus(text, kind = '') {
|
||||||
|
statusNode.className = `status ${kind}`.trim();
|
||||||
|
statusNode.textContent = String(text || '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLogin(value) {
|
||||||
|
return String(value || '').trim().toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateLogin(label, raw) {
|
||||||
|
const clean = normalizeLogin(raw);
|
||||||
|
if (!LOGIN_RE.test(clean)) {
|
||||||
|
throw new Error(`${label}: разрешены только 0..9, a..z, A..Z, _ и длина 1..20`);
|
||||||
|
}
|
||||||
|
return clean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bytesToBase58(bytes) {
|
||||||
|
const input = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || []);
|
||||||
|
if (input.length === 0) return '';
|
||||||
|
const digits = [0];
|
||||||
|
for (const byte of input) {
|
||||||
|
let carry = byte;
|
||||||
|
for (let i = 0; i < digits.length; i += 1) {
|
||||||
|
const value = (digits[i] * 256) + carry;
|
||||||
|
digits[i] = value % 58;
|
||||||
|
carry = Math.floor(value / 58);
|
||||||
|
}
|
||||||
|
while (carry > 0) {
|
||||||
|
digits.push(carry % 58);
|
||||||
|
carry = Math.floor(carry / 58);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let out = '';
|
||||||
|
for (const byte of input) {
|
||||||
|
if (byte === 0) out += '1';
|
||||||
|
else break;
|
||||||
|
}
|
||||||
|
for (let i = digits.length - 1; i >= 0; i -= 1) {
|
||||||
|
out += BASE58_ALPHABET[digits[i]];
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function base58ToBytes(value) {
|
||||||
|
const text = String(value || '').trim();
|
||||||
|
if (!text) return new Uint8Array(0);
|
||||||
|
const bytes = [0];
|
||||||
|
for (let i = 0; i < text.length; i += 1) {
|
||||||
|
const ch = text[i];
|
||||||
|
const digit = BASE58_ALPHABET.indexOf(ch);
|
||||||
|
if (digit < 0) throw new Error('Недопустимый символ Base58');
|
||||||
|
let carry = digit;
|
||||||
|
for (let j = 0; j < bytes.length; j += 1) {
|
||||||
|
const x = (bytes[j] * 58) + carry;
|
||||||
|
bytes[j] = x & 0xff;
|
||||||
|
carry = x >> 8;
|
||||||
|
}
|
||||||
|
while (carry > 0) {
|
||||||
|
bytes.push(carry & 0xff);
|
||||||
|
carry >>= 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let i = 0; i < text.length && text[i] === '1'; i += 1) {
|
||||||
|
bytes.push(0);
|
||||||
|
}
|
||||||
|
bytes.reverse();
|
||||||
|
return Uint8Array.from(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pkcs8FromSeed32(seed32) {
|
||||||
|
const out = new Uint8Array(ED25519_PKCS8_PREFIX.length + seed32.length);
|
||||||
|
out.set(ED25519_PKCS8_PREFIX, 0);
|
||||||
|
out.set(seed32, ED25519_PKCS8_PREFIX.length);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signWithSeed32(seed32, messageBytes) {
|
||||||
|
if (!globalThis.crypto?.subtle) {
|
||||||
|
throw new Error('В браузере нет WebCrypto subtle. Для локальной подписи нужен современный браузер.');
|
||||||
|
}
|
||||||
|
const privateKey = await crypto.subtle.importKey(
|
||||||
|
'pkcs8',
|
||||||
|
pkcs8FromSeed32(seed32),
|
||||||
|
{ name: 'Ed25519' },
|
||||||
|
false,
|
||||||
|
['sign'],
|
||||||
|
);
|
||||||
|
const signature = await crypto.subtle.sign('Ed25519', privateKey, messageBytes);
|
||||||
|
return new Uint8Array(signature);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPromoMessageBytes(login) {
|
||||||
|
return new TextEncoder().encode(`${PROMO_PREFIX}${login}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPromoCodeString(sellerLogin, signatureBytes) {
|
||||||
|
if (!(signatureBytes instanceof Uint8Array) || signatureBytes.length !== 64) {
|
||||||
|
throw new Error('Подпись промокода должна быть ровно 64 байта');
|
||||||
|
}
|
||||||
|
return `1${sellerLogin}-${bytesToBase58(signatureBytes)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectWalletProvider() {
|
||||||
|
const injected = [];
|
||||||
|
if (globalThis.shineSolana) injected.push(globalThis.shineSolana);
|
||||||
|
if (globalThis.shineWallet?.solana) injected.push(globalThis.shineWallet.solana);
|
||||||
|
if (globalThis.solana?.providers && Array.isArray(globalThis.solana.providers)) {
|
||||||
|
injected.push(...globalThis.solana.providers);
|
||||||
|
}
|
||||||
|
if (globalThis.solana) injected.push(globalThis.solana);
|
||||||
|
if (globalThis.phantom?.solana) injected.push(globalThis.phantom.solana);
|
||||||
|
|
||||||
|
const seen = new Set();
|
||||||
|
return injected.find((candidate) => {
|
||||||
|
if (!candidate || seen.has(candidate)) return false;
|
||||||
|
seen.add(candidate);
|
||||||
|
return typeof candidate.connect === 'function' && typeof candidate.signMessage === 'function';
|
||||||
|
}) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateMessagePreview() {
|
||||||
|
const login = normalizeLogin(targetLoginInput.value);
|
||||||
|
if (!login) {
|
||||||
|
messagePreviewNode.textContent = '—';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
messagePreviewNode.textContent = new TextDecoder().decode(buildPromoMessageBytes(login));
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateModeUi() {
|
||||||
|
extensionBlock.classList.toggle('hidden', currentMode !== 'extension');
|
||||||
|
privateKeyBlock.classList.toggle('hidden', currentMode !== 'private');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function connectWallet() {
|
||||||
|
provider = detectWalletProvider();
|
||||||
|
if (!provider) {
|
||||||
|
throw new Error('Не найдено wallet extension с connect/signMessage');
|
||||||
|
}
|
||||||
|
const result = await provider.connect();
|
||||||
|
const publicKey = result?.publicKey || provider.publicKey;
|
||||||
|
if (!publicKey) {
|
||||||
|
throw new Error('Кошелёк не вернул public key');
|
||||||
|
}
|
||||||
|
walletAddress = typeof publicKey.toBase58 === 'function' ? publicKey.toBase58() : String(publicKey || '');
|
||||||
|
walletAddressNode.textContent = walletAddress || 'подключен, но адрес не распознан';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getSignatureBytesForCurrentMode(messageBytes) {
|
||||||
|
if (currentMode === 'extension') {
|
||||||
|
if (!provider) {
|
||||||
|
throw new Error('Сначала подключите wallet extension');
|
||||||
|
}
|
||||||
|
const signed = await provider.signMessage(messageBytes, 'utf8');
|
||||||
|
const signature = signed?.signature || signed;
|
||||||
|
const bytes = signature instanceof Uint8Array ? signature : new Uint8Array(signature || []);
|
||||||
|
if (bytes.length !== 64) {
|
||||||
|
throw new Error('Wallet extension вернул подпись некорректной длины');
|
||||||
|
}
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
const seed32 = base58ToBytes(privateSeedInput.value);
|
||||||
|
if (seed32.length !== 32) {
|
||||||
|
throw new Error('Приватный ключ должен быть Base58 seed ровно 32 байта');
|
||||||
|
}
|
||||||
|
return signWithSeed32(seed32, messageBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function generatePromoCode() {
|
||||||
|
const sellerLogin = validateLogin('Логин продавца', sellerLoginInput.value);
|
||||||
|
const targetLogin = validateLogin('Новый логин', targetLoginInput.value);
|
||||||
|
const messageBytes = buildPromoMessageBytes(targetLogin);
|
||||||
|
const signatureBytes = await getSignatureBytesForCurrentMode(messageBytes);
|
||||||
|
const promoCode = buildPromoCodeString(sellerLogin, signatureBytes);
|
||||||
|
promoCodeNode.value = promoCode;
|
||||||
|
copyCodeBtn.disabled = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function randomSeed32Base58() {
|
||||||
|
if (!globalThis.crypto?.getRandomValues) {
|
||||||
|
throw new Error('В браузере нет crypto.getRandomValues');
|
||||||
|
}
|
||||||
|
const seed = new Uint8Array(32);
|
||||||
|
crypto.getRandomValues(seed);
|
||||||
|
return bytesToBase58(seed);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyText(text, errorMessage) {
|
||||||
|
if (!navigator.clipboard?.writeText) {
|
||||||
|
throw new Error(errorMessage);
|
||||||
|
}
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.querySelectorAll('input[name="signMode"]').forEach((node) => {
|
||||||
|
node.addEventListener('change', () => {
|
||||||
|
if (!node.checked) return;
|
||||||
|
currentMode = node.value;
|
||||||
|
updateModeUi();
|
||||||
|
setStatus(
|
||||||
|
currentMode === 'extension'
|
||||||
|
? 'Режим wallet extension активен.'
|
||||||
|
: 'Режим ручного Base58 seed активен. Страница может работать полностью оффлайн.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
connectBtn.addEventListener('click', async () => {
|
||||||
|
connectBtn.disabled = true;
|
||||||
|
try {
|
||||||
|
setStatus('Подключение wallet extension...');
|
||||||
|
await connectWallet();
|
||||||
|
setStatus(`Кошелёк подключён: ${walletAddress}`, 'success');
|
||||||
|
} catch (error) {
|
||||||
|
setStatus(`Ошибка подключения: ${error?.message || 'unknown'}`, 'error');
|
||||||
|
} finally {
|
||||||
|
connectBtn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
generateSeedBtn.addEventListener('click', () => {
|
||||||
|
try {
|
||||||
|
const seed = randomSeed32Base58();
|
||||||
|
privateSeedInput.value = seed;
|
||||||
|
privateSeedHint.textContent = 'Новый Base58 seed сгенерирован локально в браузере. Храните его как приватный ключ.';
|
||||||
|
setStatus('Сгенерирован новый Base58 seed 32 bytes.', 'success');
|
||||||
|
} catch (error) {
|
||||||
|
setStatus(`Ошибка генерации seed: ${error?.message || 'unknown'}`, 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
copySeedBtn.addEventListener('click', async () => {
|
||||||
|
try {
|
||||||
|
const text = String(privateSeedInput.value || '').trim();
|
||||||
|
if (!text) throw new Error('Сначала сгенерируйте или вставьте seed');
|
||||||
|
await copyText(text, 'Clipboard API недоступен');
|
||||||
|
setStatus('Base58 seed скопирован.', 'success');
|
||||||
|
} catch (error) {
|
||||||
|
setStatus(`Ошибка копирования seed: ${error?.message || 'unknown'}`, 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
copyCodeBtn.addEventListener('click', async () => {
|
||||||
|
try {
|
||||||
|
const text = String(promoCodeNode.value || '').trim();
|
||||||
|
if (!text) throw new Error('Сначала сгенерируйте promo-код');
|
||||||
|
await copyText(text, 'Clipboard API недоступен');
|
||||||
|
setStatus('Promo-код скопирован.', 'success');
|
||||||
|
} catch (error) {
|
||||||
|
setStatus(`Ошибка копирования promo-кода: ${error?.message || 'unknown'}`, 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
generateBtn.addEventListener('click', async () => {
|
||||||
|
generateBtn.disabled = true;
|
||||||
|
try {
|
||||||
|
updateMessagePreview();
|
||||||
|
setStatus('Генерация promo-кода...');
|
||||||
|
await generatePromoCode();
|
||||||
|
const modeTitle = currentMode === 'extension' ? 'wallet extension' : 'Base58 seed';
|
||||||
|
setStatus(`Promo-код готов. Режим: ${modeTitle}.`, 'success');
|
||||||
|
} catch (error) {
|
||||||
|
setStatus(`Ошибка генерации: ${error?.message || 'unknown'}`, 'error');
|
||||||
|
} finally {
|
||||||
|
generateBtn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
sellerLoginInput.addEventListener('input', updateMessagePreview);
|
||||||
|
targetLoginInput.addEventListener('input', updateMessagePreview);
|
||||||
|
|
||||||
|
updateModeUi();
|
||||||
|
updateMessagePreview();
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -19,8 +19,10 @@
|
|||||||
- создание `user_pda` по логину;
|
- создание `user_pda` по логину;
|
||||||
- обновление `user_pda` без смены логина и root key;
|
- обновление `user_pda` без смены логина и root key;
|
||||||
- хранение economy-конфига регистрации;
|
- хранение economy-конфига регистрации;
|
||||||
|
- хранение PDA продавцов promo-логинов;
|
||||||
- взимание комиссии за регистрацию и увеличение лимита;
|
- взимание комиссии за регистрацию и увеличение лимита;
|
||||||
- проверку Ed25519-подписей `root_key` и `blockchain_public_key`;
|
- проверку Ed25519-подписей `root_key` и `blockchain_public_key`;
|
||||||
|
- проверку promo-подписей продавца для обхода premium/trademark login guard;
|
||||||
- проверку связности новой версии записи с предыдущей через `prev_record_hash`.
|
- проверку связности новой версии записи с предыдущей через `prev_record_hash`.
|
||||||
|
|
||||||
Программа не отвечает за:
|
Программа не отвечает за:
|
||||||
@@ -91,7 +93,22 @@ system-переводом. Если бы создание шло строго ч
|
|||||||
Проверки повторной инициализации (`owner == System Program` и пустые данные) остаются и
|
Проверки повторной инициализации (`owner == System Program` и пустые данные) остаются и
|
||||||
не зависят от баланса аккаунта.
|
не зависят от баланса аккаунта.
|
||||||
|
|
||||||
### 3.4. Строгий список аккаунтов (нет «лишних» аккаунтов)
|
### 3.4. PDA продавца promo-логинов
|
||||||
|
|
||||||
|
PDA продавца строится так:
|
||||||
|
|
||||||
|
- seed prefix: `promo_seller=`
|
||||||
|
- второй seed: логин продавца в нижнем регистре
|
||||||
|
|
||||||
|
Формула:
|
||||||
|
|
||||||
|
```text
|
||||||
|
promo_seller_pda = PDA(["promo_seller=", lower(seller_login)], shine_users_program_id)
|
||||||
|
```
|
||||||
|
|
||||||
|
В программе может существовать сколько угодно таких PDA, по одному на каждого продавца.
|
||||||
|
|
||||||
|
### 3.5. Строгий список аккаунтов (нет «лишних» аккаунтов)
|
||||||
|
|
||||||
Все инструкции `shine_users` читают строго фиксированный набор аккаунтов и после этого
|
Все инструкции `shine_users` читают строго фиксированный набор аккаунтов и после этого
|
||||||
явно требуют, чтобы в переданном списке больше ничего не было
|
явно требуют, чтобы в переданном списке больше ничего не было
|
||||||
@@ -130,17 +147,35 @@ system-переводом. Если бы создание шло строго ч
|
|||||||
|
|
||||||
Этот документ описывает именно логику программы, а не байтовую структуру блока.
|
Этот документ описывает именно логику программы, а не байтовую структуру блока.
|
||||||
|
|
||||||
|
### 4.3. `promo_seller_pda`
|
||||||
|
|
||||||
|
PDA продавца красивых логинов хранит:
|
||||||
|
|
||||||
|
- `version: u8`
|
||||||
|
- `remaining_sales: u64`
|
||||||
|
- `min_login_length: u8`
|
||||||
|
- `signer_pubkey: [u8; 32]`
|
||||||
|
|
||||||
|
Смысл:
|
||||||
|
|
||||||
|
- `remaining_sales` — сколько ещё красивых логинов продавец может выдать;
|
||||||
|
- `min_login_length` — минимальная длина логина, которую продавец имеет право раздавать;
|
||||||
|
- `signer_pubkey` — публичный Ed25519-ключ, которым off-chain подписываются promo-коды.
|
||||||
|
|
||||||
## 5. Константы и базовые правила
|
## 5. Константы и базовые правила
|
||||||
|
|
||||||
Базовые значения из текущей логики:
|
Базовые значения из текущей логики:
|
||||||
|
|
||||||
- seed `user_pda`: `user_login=`
|
- seed `user_pda`: `user_login=`
|
||||||
- seed economy config: `shine_users_economy_config`
|
- seed economy config: `shine_users_economy_config`
|
||||||
|
- seed promo seller PDA: `promo_seller=`
|
||||||
- стартовый размер `user_pda`: `768` байт
|
- стартовый размер `user_pda`: `768` байт
|
||||||
|
- размер `promo_seller_pda`: `64` байта
|
||||||
- `LIMIT_STEP = 10_000`
|
- `LIMIT_STEP = 10_000`
|
||||||
- `START_REGISTRATION_FEE_LAMPORTS = 10_000_000`
|
- `START_REGISTRATION_FEE_LAMPORTS = 10_000_000`
|
||||||
- `START_LAMPORTS_PER_LIMIT_STEP = 100_000`
|
- `START_LAMPORTS_PER_LIMIT_STEP = 100_000`
|
||||||
- `START_BONUS_LIMIT = 100_000`
|
- `START_BONUS_LIMIT = 100_000`
|
||||||
|
- префикс promo-сообщения: `shine_promo_v1:`
|
||||||
|
|
||||||
Правила:
|
Правила:
|
||||||
|
|
||||||
@@ -230,6 +265,35 @@ On-chain инвариант только один:
|
|||||||
|
|
||||||
Если `shine_login_guard` вернул что-то иное или return_data некорректны, это ошибка.
|
Если `shine_login_guard` вернул что-то иное или return_data некорректны, это ошибка.
|
||||||
|
|
||||||
|
### 7.3. Promo-обход login guard
|
||||||
|
|
||||||
|
При создании пользователя допускается опциональный `promo_code`.
|
||||||
|
|
||||||
|
Формат строки:
|
||||||
|
|
||||||
|
```text
|
||||||
|
1<seller_login>-<signature_base58>
|
||||||
|
```
|
||||||
|
|
||||||
|
Где:
|
||||||
|
|
||||||
|
- первый символ `1` — версия формата promo-кода;
|
||||||
|
- `seller_login` — логин продавца, по которому ищется `promo_seller_pda`;
|
||||||
|
- `signature_base58` — Ed25519-подпись по сообщению:
|
||||||
|
|
||||||
|
```text
|
||||||
|
shine_promo_v1:<login_из_запроса_create_user_pda>
|
||||||
|
```
|
||||||
|
|
||||||
|
Если promo-код валиден, то:
|
||||||
|
|
||||||
|
- premium/trademark-проверка через `shine_login_guard` не выполняется;
|
||||||
|
- базовая синтаксическая проверка логина всё равно остаётся обязательной;
|
||||||
|
- `remaining_sales` уменьшается на `1`;
|
||||||
|
- длина логина должна быть не меньше `min_login_length`.
|
||||||
|
|
||||||
|
Если promo-код не передан, обычная CPI-проверка через `shine_login_guard` обязательна.
|
||||||
|
|
||||||
## 8. Инструкция `init_users_economy_config`
|
## 8. Инструкция `init_users_economy_config`
|
||||||
|
|
||||||
### Назначение
|
### Назначение
|
||||||
@@ -310,6 +374,7 @@ On-chain инвариант только один:
|
|||||||
- sysvar `instructions`
|
- sysvar `instructions`
|
||||||
- `users_economy_config_pda`
|
- `users_economy_config_pda`
|
||||||
- `shine_login_guard_program`
|
- `shine_login_guard_program`
|
||||||
|
- опционально: `promo_seller_pda`, если регистрация идёт по promo-коду
|
||||||
|
|
||||||
### Входные данные
|
### Входные данные
|
||||||
|
|
||||||
@@ -320,6 +385,7 @@ On-chain инвариант только один:
|
|||||||
- `additional_limit`
|
- `additional_limit`
|
||||||
- mutable fields записи
|
- mutable fields записи
|
||||||
- `root` signature по unsigned части
|
- `root` signature по unsigned части
|
||||||
|
- опционально `promo_code`
|
||||||
|
|
||||||
### Бинарный ABI
|
### Бинарный ABI
|
||||||
|
|
||||||
@@ -332,20 +398,27 @@ On-chain инвариант только один:
|
|||||||
- additional_limit: u64 LE
|
- additional_limit: u64 LE
|
||||||
- fields: UserMutableFieldsV1
|
- fields: UserMutableFieldsV1
|
||||||
- root_signature: [u8; 64]
|
- root_signature: [u8; 64]
|
||||||
|
- optional trailing promo_code: string_u8
|
||||||
```
|
```
|
||||||
|
|
||||||
### Обязательные проверки
|
### Обязательные проверки
|
||||||
|
|
||||||
1. Логин валиден по синтаксису.
|
1. Логин валиден по синтаксису.
|
||||||
2. Логин разрешён `shine_login_guard`.
|
2. Если promo-код не передан, логин разрешён `shine_login_guard`.
|
||||||
3. `additional_limit % LIMIT_STEP == 0`.
|
3. Если promo-код передан, он должен:
|
||||||
4. inflow vault совпадает с PDA программы `shine_payments`.
|
- иметь формат `1<seller_login>-<signature_base58>`;
|
||||||
5. `user_pda` вычислена правильно и ещё не существует.
|
- ссылаться на существующий `promo_seller_pda`;
|
||||||
6. Поля блокчейна валидны.
|
- проходить Ed25519-проверку через `signer_pubkey` продавца;
|
||||||
7. Поля server/session/trusted валидны по формату.
|
- иметь `remaining_sales > 0`;
|
||||||
8. `last_block_signature` соответствует `LastBlockState`.
|
- удовлетворять правилу `login.len() >= min_login_length`.
|
||||||
9. `root signature` соответствует unsigned части записи.
|
4. `additional_limit % LIMIT_STEP == 0`.
|
||||||
10. Размер сериализованной записи не превышает допустимый стартовый размер PDA или иные ограничения реализации.
|
5. inflow vault совпадает с PDA программы `shine_payments`.
|
||||||
|
6. `user_pda` вычислена правильно и ещё не существует.
|
||||||
|
7. Поля блокчейна валидны.
|
||||||
|
8. Поля server/session/trusted валидны по формату.
|
||||||
|
9. `last_block_signature` соответствует `LastBlockState`.
|
||||||
|
10. `root signature` соответствует unsigned части записи.
|
||||||
|
11. Размер сериализованной записи не превышает допустимый стартовый размер PDA или иные ограничения реализации.
|
||||||
|
|
||||||
### Экономика
|
### Экономика
|
||||||
|
|
||||||
@@ -375,9 +448,52 @@ limit_fee(additional_limit) = (additional_limit / LIMIT_STEP) * lamports_per_lim
|
|||||||
|
|
||||||
- создаётся PDA;
|
- создаётся PDA;
|
||||||
- в неё записывается полная запись `user_pda`;
|
- в неё записывается полная запись `user_pda`;
|
||||||
|
- если используется promo-код, в `promo_seller_pda` уменьшается `remaining_sales`;
|
||||||
- средства переводятся в inflow vault `shine_payments`.
|
- средства переводятся в inflow vault `shine_payments`.
|
||||||
|
|
||||||
## 11. Инструкция `update_user_pda`
|
## 11. Инструкция `upsert_promo_seller`
|
||||||
|
|
||||||
|
### Назначение
|
||||||
|
|
||||||
|
Создать нового продавца promo-логинов или полностью перезаписать настройки уже существующего продавца.
|
||||||
|
|
||||||
|
### Авторизация
|
||||||
|
|
||||||
|
Только `DAO_AUTHORITY`.
|
||||||
|
|
||||||
|
### Аккаунты
|
||||||
|
|
||||||
|
- signer
|
||||||
|
- `promo_seller_pda`
|
||||||
|
- system program
|
||||||
|
|
||||||
|
### Входные данные
|
||||||
|
|
||||||
|
- `seller_login`
|
||||||
|
- `remaining_sales`
|
||||||
|
- `min_login_length`
|
||||||
|
- `signer_pubkey`
|
||||||
|
|
||||||
|
### Бинарный ABI
|
||||||
|
|
||||||
|
```text
|
||||||
|
- tag: u8 = 5
|
||||||
|
- seller_login: string_u8
|
||||||
|
- remaining_sales: u64 LE
|
||||||
|
- min_login_length: u8
|
||||||
|
- signer_pubkey: [u8; 32]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Правила
|
||||||
|
|
||||||
|
- signer должен совпадать с `DAO_AUTHORITY`;
|
||||||
|
- `seller_login` проходит ту же базовую проверку логина;
|
||||||
|
- `min_login_length` лежит в диапазоне `1..20`;
|
||||||
|
- адрес PDA обязан совпадать с `promo_seller=` + `lower(seller_login)`;
|
||||||
|
- если PDA ещё нет, она создаётся;
|
||||||
|
- если PDA уже есть, её состояние полностью перезаписывается.
|
||||||
|
|
||||||
|
## 12. Инструкция `update_user_pda`
|
||||||
|
|
||||||
### Назначение
|
### Назначение
|
||||||
|
|
||||||
@@ -445,9 +561,9 @@ topup_fee = limit_fee(additional_limit)
|
|||||||
- root_signature: [u8; 64]
|
- root_signature: [u8; 64]
|
||||||
```
|
```
|
||||||
|
|
||||||
## 12. Ed25519-проверки и порядок инструкций
|
## 13. Ed25519-проверки и порядок инструкций
|
||||||
|
|
||||||
В транзакции должны стоять две встроенные Ed25519-инструкции прямо перед вызовом `shine_users`:
|
В обычной транзакции `create/update` должны стоять две встроенные Ed25519-инструкции прямо перед вызовом `shine_users`:
|
||||||
|
|
||||||
1. подпись `root_key` по unsigned записи;
|
1. подпись `root_key` по unsigned записи;
|
||||||
2. подпись `blockchain_public_key` по `LastBlockState`.
|
2. подпись `blockchain_public_key` по `LastBlockState`.
|
||||||
@@ -459,7 +575,19 @@ topup_fee = limit_fee(additional_limit)
|
|||||||
|
|
||||||
Это правило порядка является частью контракта между off-chain клиентом и программой.
|
Это правило порядка является частью контракта между off-chain клиентом и программой.
|
||||||
|
|
||||||
## 13. LastBlockState
|
Если `create_user_pda` вызывается с promo-кодом, то перед ними добавляется ещё одна Ed25519-инструкция:
|
||||||
|
|
||||||
|
1. подпись продавца promo-логина по строке `shine_promo_v1:<login>`;
|
||||||
|
2. подпись `root_key` по unsigned записи;
|
||||||
|
3. подпись `blockchain_public_key` по `LastBlockState`.
|
||||||
|
|
||||||
|
Тогда программа читает:
|
||||||
|
|
||||||
|
- `-3` — promo-подпись;
|
||||||
|
- `-2` — `root_key`;
|
||||||
|
- `-1` — `blockchain_public_key`.
|
||||||
|
|
||||||
|
## 14. LastBlockState
|
||||||
|
|
||||||
Сообщение для подписи `blockchain_public_key`:
|
Сообщение для подписи `blockchain_public_key`:
|
||||||
|
|
||||||
@@ -479,7 +607,7 @@ message_hash = SHA-256(LastBlockState bytes)
|
|||||||
signature = Ed25519(blockchain_private_key, message_hash)
|
signature = Ed25519(blockchain_private_key, message_hash)
|
||||||
```
|
```
|
||||||
|
|
||||||
## 14. Валидируемые mutable-поля записи
|
## 15. Валидируемые mutable-поля записи
|
||||||
|
|
||||||
Программа допускает обновление:
|
Программа допускает обновление:
|
||||||
|
|
||||||
@@ -507,7 +635,7 @@ signature = Ed25519(blockchain_private_key, message_hash)
|
|||||||
- `blockchain_public_key`
|
- `blockchain_public_key`
|
||||||
- `blockchain_type`
|
- `blockchain_type`
|
||||||
|
|
||||||
## 15. Правила серверных и сессионных полей
|
## 16. Правила серверных и сессионных полей
|
||||||
|
|
||||||
### UserMutableFieldsV1
|
### UserMutableFieldsV1
|
||||||
|
|
||||||
@@ -567,7 +695,7 @@ signature = Ed25519(blockchain_private_key, message_hash)
|
|||||||
- `sessions_mode = 1`
|
- `sessions_mode = 1`
|
||||||
- `sessions = []`
|
- `sessions = []`
|
||||||
|
|
||||||
## 16. Realloc поведения PDA
|
## 17. Realloc поведения PDA
|
||||||
|
|
||||||
Запись может расти. Если новая сериализованная запись длиннее текущего размера PDA:
|
Запись может расти. Если новая сериализованная запись длиннее текущего размера PDA:
|
||||||
|
|
||||||
@@ -575,7 +703,7 @@ signature = Ed25519(blockchain_private_key, message_hash)
|
|||||||
- нельзя делать чрезмерный рост одним шагом выше внутреннего лимита реализации;
|
- нельзя делать чрезмерный рост одним шагом выше внутреннего лимита реализации;
|
||||||
- перед realloc нужно обеспечить rent для нового размера.
|
- перед realloc нужно обеспечить rent для нового размера.
|
||||||
|
|
||||||
## 17. Ошибки и классы отказа
|
## 18. Ошибки и классы отказа
|
||||||
|
|
||||||
Программа должна различать как минимум такие классы ошибок:
|
Программа должна различать как минимум такие классы ошибок:
|
||||||
|
|
||||||
@@ -592,9 +720,14 @@ signature = Ed25519(blockchain_private_key, message_hash)
|
|||||||
- попытка уменьшить лимит/used_bytes/block number;
|
- попытка уменьшить лимит/used_bytes/block number;
|
||||||
- overflow;
|
- overflow;
|
||||||
- неверный inflow vault;
|
- неверный inflow vault;
|
||||||
- неверный DAO authority для economy config.
|
- неверный DAO authority для economy config и promo seller update;
|
||||||
|
- неверный promo-код;
|
||||||
|
- несуществующий или повреждённый `promo_seller_pda`;
|
||||||
|
- исчерпанная promo-квота;
|
||||||
|
- promo-подпись не совпадает;
|
||||||
|
- логин короче `min_login_length`.
|
||||||
|
|
||||||
## 18. Что должно сохраниться при переписи без Anchor
|
## 19. Что должно сохраниться при переписи без Anchor
|
||||||
|
|
||||||
В текущей чисто-rust реализации уже сохранены:
|
В текущей чисто-rust реализации уже сохранены:
|
||||||
|
|
||||||
@@ -604,6 +737,7 @@ signature = Ed25519(blockchain_private_key, message_hash)
|
|||||||
- тот же порядок Ed25519-инструкций;
|
- тот же порядок Ed25519-инструкций;
|
||||||
- те же immutable/mutable правила;
|
- те же immutable/mutable правила;
|
||||||
- ту же валидацию логина и CPI в `shine_login_guard`;
|
- ту же валидацию логина и CPI в `shine_login_guard`;
|
||||||
|
- ту же promo-механику с PDA продавцов и подписью `shine_promo_v1:<login>`;
|
||||||
- ту же зависимость от inflow vault программы `shine_payments`.
|
- ту же зависимость от inflow vault программы `shine_payments`.
|
||||||
|
|
||||||
Сознательно не сохранялись:
|
Сознательно не сохранялись:
|
||||||
|
|||||||
@@ -48,7 +48,9 @@ const IX_INIT_USERS_ECONOMY_CONFIG: u8 = 1;
|
|||||||
const IX_UPDATE_USERS_ECONOMY_CONFIG: u8 = 2;
|
const IX_UPDATE_USERS_ECONOMY_CONFIG: u8 = 2;
|
||||||
const IX_CREATE_USER_PDA: u8 = 3;
|
const IX_CREATE_USER_PDA: u8 = 3;
|
||||||
const IX_UPDATE_USER_PDA: u8 = 4;
|
const IX_UPDATE_USER_PDA: u8 = 4;
|
||||||
|
const IX_UPSERT_PROMO_SELLER: u8 = 5;
|
||||||
const LOGIN_GUARD_IX_CLASSIFY_LOGIN: u8 = 1;
|
const LOGIN_GUARD_IX_CLASSIFY_LOGIN: u8 = 1;
|
||||||
|
const PROMO_CODE_VERSION_PREFIX: char = '1';
|
||||||
|
|
||||||
#[repr(u32)]
|
#[repr(u32)]
|
||||||
#[derive(Clone, Copy, Debug)]
|
#[derive(Clone, Copy, Debug)]
|
||||||
@@ -80,6 +82,12 @@ enum ShineUsersError {
|
|||||||
InvalidSystemProgram = 25,
|
InvalidSystemProgram = 25,
|
||||||
InvalidAccountOwner = 26,
|
InvalidAccountOwner = 26,
|
||||||
InvalidAccountData = 27,
|
InvalidAccountData = 27,
|
||||||
|
InvalidPromoCode = 28,
|
||||||
|
PromoSellerNotFound = 29,
|
||||||
|
PromoSalesExhausted = 30,
|
||||||
|
PromoLoginTooShort = 31,
|
||||||
|
InvalidPromoSellerState = 32,
|
||||||
|
PromoSignatureMismatch = 33,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<ShineUsersError> for ProgramError {
|
impl From<ShineUsersError> for ProgramError {
|
||||||
@@ -142,6 +150,7 @@ pub struct CreateUserPdaArgs {
|
|||||||
pub additional_limit: u64,
|
pub additional_limit: u64,
|
||||||
pub fields: UserMutableFields,
|
pub fields: UserMutableFields,
|
||||||
pub signature: [u8; 64],
|
pub signature: [u8; 64],
|
||||||
|
pub promo_code: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
@@ -173,6 +182,22 @@ pub struct UsersEconomyConfigState {
|
|||||||
pub start_bonus_limit: u64,
|
pub start_bonus_limit: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct UpsertPromoSellerArgs {
|
||||||
|
pub seller_login: String,
|
||||||
|
pub remaining_sales: u64,
|
||||||
|
pub min_login_length: u8,
|
||||||
|
pub signer_pubkey: Pubkey,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct PromoSellerState {
|
||||||
|
pub version: u8,
|
||||||
|
pub remaining_sales: u64,
|
||||||
|
pub min_login_length: u8,
|
||||||
|
pub signer_pubkey: Pubkey,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct BlockchainRecord {
|
pub struct BlockchainRecord {
|
||||||
pub blockchain_type: u8,
|
pub blockchain_type: u8,
|
||||||
@@ -255,13 +280,16 @@ impl<'a> Reader<'a> {
|
|||||||
self.cursor = end;
|
self.cursor = end;
|
||||||
std::str::from_utf8(s).map(|v| v.to_string()).map_err(|_| ProgramError::from(ShineUsersError::InvalidInstruction))
|
std::str::from_utf8(s).map(|v| v.to_string()).map_err(|_| ProgramError::from(ShineUsersError::InvalidInstruction))
|
||||||
}
|
}
|
||||||
|
fn remaining(&self) -> usize {
|
||||||
|
self.data.len().saturating_sub(self.cursor)
|
||||||
|
}
|
||||||
fn finish(self) -> Result<(), ProgramError> {
|
fn finish(self) -> Result<(), ProgramError> {
|
||||||
require!(self.cursor == self.data.len(), ShineUsersError::InvalidInstruction);
|
require!(self.cursor == self.data.len(), ShineUsersError::InvalidInstruction);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn process_instruction(program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8]) -> ProgramResult {
|
fn process_instruction<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'a>], instruction_data: &[u8]) -> ProgramResult {
|
||||||
let mut r = Reader::new(instruction_data);
|
let mut r = Reader::new(instruction_data);
|
||||||
let tag = r.read_u8()?;
|
let tag = r.read_u8()?;
|
||||||
match tag {
|
match tag {
|
||||||
@@ -278,18 +306,34 @@ fn process_instruction(program_id: &Pubkey, accounts: &[AccountInfo], instructio
|
|||||||
r.finish()?;
|
r.finish()?;
|
||||||
process_update_users_economy_config(program_id, accounts, args)
|
process_update_users_economy_config(program_id, accounts, args)
|
||||||
}
|
}
|
||||||
IX_CREATE_USER_PDA => {
|
IX_CREATE_USER_PDA => dispatch_create_user_pda(program_id, accounts, r),
|
||||||
let args = parse_create_args(&mut r)?;
|
IX_UPDATE_USER_PDA => dispatch_update_user_pda(program_id, accounts, r),
|
||||||
|
IX_UPSERT_PROMO_SELLER => dispatch_upsert_promo_seller(program_id, accounts, r),
|
||||||
|
_ => Err(ProgramError::from(ShineUsersError::InvalidInstruction)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dispatch_create_user_pda<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'a>], mut r: Reader<'_>) -> ProgramResult {
|
||||||
|
let args = Box::new(parse_create_args(&mut r)?);
|
||||||
r.finish()?;
|
r.finish()?;
|
||||||
process_create_user_pda(program_id, accounts, args)
|
process_create_user_pda(program_id, accounts, args)
|
||||||
}
|
}
|
||||||
IX_UPDATE_USER_PDA => {
|
|
||||||
let args = parse_update_args(&mut r)?;
|
fn dispatch_update_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], mut r: Reader<'_>) -> ProgramResult {
|
||||||
|
let args = Box::new(parse_update_args(&mut r)?);
|
||||||
r.finish()?;
|
r.finish()?;
|
||||||
process_update_user_pda(program_id, accounts, args)
|
process_update_user_pda(program_id, accounts, args)
|
||||||
}
|
}
|
||||||
_ => Err(ProgramError::from(ShineUsersError::InvalidInstruction)),
|
|
||||||
}
|
fn dispatch_upsert_promo_seller(program_id: &Pubkey, accounts: &[AccountInfo], mut r: Reader<'_>) -> ProgramResult {
|
||||||
|
let args = UpsertPromoSellerArgs {
|
||||||
|
seller_login: r.read_string_u8()?,
|
||||||
|
remaining_sales: r.read_u64()?,
|
||||||
|
min_login_length: r.read_u8()?,
|
||||||
|
signer_pubkey: r.read_pubkey()?,
|
||||||
|
};
|
||||||
|
r.finish()?;
|
||||||
|
process_upsert_promo_seller(program_id, accounts, args)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_create_args(r: &mut Reader<'_>) -> Result<CreateUserPdaArgs, ProgramError> {
|
fn parse_create_args(r: &mut Reader<'_>) -> Result<CreateUserPdaArgs, ProgramError> {
|
||||||
@@ -301,6 +345,7 @@ fn parse_create_args(r: &mut Reader<'_>) -> Result<CreateUserPdaArgs, ProgramErr
|
|||||||
additional_limit: r.read_u64()?,
|
additional_limit: r.read_u64()?,
|
||||||
fields: parse_fields(r)?,
|
fields: parse_fields(r)?,
|
||||||
signature: r.read_fixed_64()?,
|
signature: r.read_fixed_64()?,
|
||||||
|
promo_code: if r.remaining() > 0 { Some(r.read_string_u8()?) } else { None },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -432,7 +477,50 @@ fn process_update_users_economy_config(program_id: &Pubkey, accounts: &[AccountI
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn process_create_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args: CreateUserPdaArgs) -> ProgramResult {
|
fn process_upsert_promo_seller(program_id: &Pubkey, accounts: &[AccountInfo], args: UpsertPromoSellerArgs) -> ProgramResult {
|
||||||
|
let mut it = accounts.iter();
|
||||||
|
let signer = next_account_info(&mut it)?;
|
||||||
|
let promo_seller_pda = next_account_info(&mut it)?;
|
||||||
|
let system_program_ai = next_account_info(&mut it)?;
|
||||||
|
require!(it.next().is_none(), ShineUsersError::InvalidInstruction);
|
||||||
|
|
||||||
|
require!(signer.is_signer, ShineUsersError::InvalidSigner);
|
||||||
|
require_keys_eq!(*system_program_ai.key, system_program::id(), ShineUsersError::InvalidSystemProgram);
|
||||||
|
validate_login(&args.seller_login)?;
|
||||||
|
require!((1..=20).contains(&args.min_login_length), ShineUsersError::InvalidPromoSellerState);
|
||||||
|
|
||||||
|
let dao_authority = Pubkey::from_str(settings::DAO_AUTHORITY).map_err(|_| ProgramError::from(ShineUsersError::InvalidSigner))?;
|
||||||
|
require_keys_eq!(dao_authority, *signer.key, ShineUsersError::InvalidSigner);
|
||||||
|
|
||||||
|
let seller_seed = login_seed_normalized(&args.seller_login);
|
||||||
|
let (expected_pda, bump) = find_promo_seller_pda(program_id, &seller_seed);
|
||||||
|
require_keys_eq!(expected_pda, *promo_seller_pda.key, ShineUsersError::InvalidPdaAddress);
|
||||||
|
|
||||||
|
if promo_seller_pda.owner == &system_program::id() {
|
||||||
|
create_pda_account(
|
||||||
|
signer,
|
||||||
|
promo_seller_pda,
|
||||||
|
system_program_ai,
|
||||||
|
program_id,
|
||||||
|
&[settings::PROMO_SELLER_PDA_SEED_PREFIX.as_bytes(), seller_seed.as_bytes(), &[bump]],
|
||||||
|
settings::PROMO_SELLER_PDA_SPACE,
|
||||||
|
)?;
|
||||||
|
} else {
|
||||||
|
require!(promo_seller_pda.owner == program_id, ShineUsersError::InvalidPdaAddress);
|
||||||
|
ensure_pda_size_and_rent(promo_seller_pda, signer, system_program_ai, settings::PROMO_SELLER_PDA_SPACE)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let state = PromoSellerState {
|
||||||
|
version: 1,
|
||||||
|
remaining_sales: args.remaining_sales,
|
||||||
|
min_login_length: args.min_login_length,
|
||||||
|
signer_pubkey: args.signer_pubkey,
|
||||||
|
};
|
||||||
|
write_pda_exact(promo_seller_pda, &serialize_promo_seller_state(&state))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn process_create_user_pda<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'a>], args: Box<CreateUserPdaArgs>) -> ProgramResult {
|
||||||
let mut it = accounts.iter();
|
let mut it = accounts.iter();
|
||||||
let signer = next_account_info(&mut it)?;
|
let signer = next_account_info(&mut it)?;
|
||||||
let user_pda = next_account_info(&mut it)?;
|
let user_pda = next_account_info(&mut it)?;
|
||||||
@@ -441,6 +529,7 @@ fn process_create_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args:
|
|||||||
let instructions_sysvar = next_account_info(&mut it)?;
|
let instructions_sysvar = next_account_info(&mut it)?;
|
||||||
let users_economy_config_pda = next_account_info(&mut it)?;
|
let users_economy_config_pda = next_account_info(&mut it)?;
|
||||||
let login_guard_program = next_account_info(&mut it)?;
|
let login_guard_program = next_account_info(&mut it)?;
|
||||||
|
let promo_seller_pda = it.next();
|
||||||
require!(it.next().is_none(), ShineUsersError::InvalidInstruction);
|
require!(it.next().is_none(), ShineUsersError::InvalidInstruction);
|
||||||
|
|
||||||
require!(signer.is_signer, ShineUsersError::InvalidSigner);
|
require!(signer.is_signer, ShineUsersError::InvalidSigner);
|
||||||
@@ -452,9 +541,19 @@ fn process_create_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args:
|
|||||||
validate_inflow_vault(inflow_vault)?;
|
validate_inflow_vault(inflow_vault)?;
|
||||||
require!(args.additional_limit % settings::LIMIT_STEP == 0, ShineUsersError::InvalidLimitIncrement);
|
require!(args.additional_limit % settings::LIMIT_STEP == 0, ShineUsersError::InvalidLimitIncrement);
|
||||||
require_keys_eq!(*login_guard_program.key, Pubkey::from_str(settings::SHINE_LOGIN_GUARD_PROGRAM_ID).map_err(|_| ProgramError::from(ShineUsersError::InvalidLoginGuardResponse))?, ShineUsersError::InvalidLoginGuardResponse);
|
require_keys_eq!(*login_guard_program.key, Pubkey::from_str(settings::SHINE_LOGIN_GUARD_PROGRAM_ID).map_err(|_| ProgramError::from(ShineUsersError::InvalidLoginGuardResponse))?, ShineUsersError::InvalidLoginGuardResponse);
|
||||||
classify_login_or_fail(login_guard_program, &args.login)?;
|
|
||||||
validate_users_economy_config_pda(program_id, users_economy_config_pda)?;
|
validate_users_economy_config_pda(program_id, users_economy_config_pda)?;
|
||||||
|
|
||||||
|
let promo_context = if let Some(promo_code) = args.promo_code.as_deref().filter(|value| !value.trim().is_empty()) {
|
||||||
|
let seller_pda = promo_seller_pda.ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?;
|
||||||
|
Some(verify_promo_registration(program_id, instructions_sysvar, seller_pda, &args.login, promo_code)?)
|
||||||
|
} else {
|
||||||
|
require!(promo_seller_pda.is_none(), ShineUsersError::InvalidInstruction);
|
||||||
|
None
|
||||||
|
};
|
||||||
|
if promo_context.is_none() {
|
||||||
|
classify_login_or_fail(login_guard_program, &args.login)?;
|
||||||
|
}
|
||||||
|
|
||||||
let economy = read_users_economy_config(users_economy_config_pda)?;
|
let economy = read_users_economy_config(users_economy_config_pda)?;
|
||||||
let login_seed = login_seed_normalized(&args.login);
|
let login_seed = login_seed_normalized(&args.login);
|
||||||
let (expected_pda, bump) = find_user_pda(program_id, &login_seed);
|
let (expected_pda, bump) = find_user_pda(program_id, &login_seed);
|
||||||
@@ -511,12 +610,16 @@ fn process_create_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args:
|
|||||||
)?;
|
)?;
|
||||||
write_pda_exact(user_pda, &serialized)?;
|
write_pda_exact(user_pda, &serialized)?;
|
||||||
|
|
||||||
|
if let Some(promo) = promo_context {
|
||||||
|
write_pda_exact(promo.promo_seller_pda, &serialize_promo_seller_state(&promo.updated_state))?;
|
||||||
|
}
|
||||||
|
|
||||||
let total_fee = economy.registration_fee_lamports.checked_add(limit_fee_lamports(args.additional_limit, economy.lamports_per_limit_step)?).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?;
|
let total_fee = economy.registration_fee_lamports.checked_add(limit_fee_lamports(args.additional_limit, economy.lamports_per_limit_step)?).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?;
|
||||||
transfer_lamports(signer, inflow_vault, system_program_ai, total_fee)?;
|
transfer_lamports(signer, inflow_vault, system_program_ai, total_fee)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn process_update_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args: UpdateUserPdaArgs) -> ProgramResult {
|
fn process_update_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args: Box<UpdateUserPdaArgs>) -> ProgramResult {
|
||||||
let mut it = accounts.iter();
|
let mut it = accounts.iter();
|
||||||
let signer = next_account_info(&mut it)?;
|
let signer = next_account_info(&mut it)?;
|
||||||
let user_pda = next_account_info(&mut it)?;
|
let user_pda = next_account_info(&mut it)?;
|
||||||
@@ -615,6 +718,45 @@ fn build_update_record(old_record: &UserRecord, args: &UpdateUserPdaArgs, new_ba
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct PromoRegistrationContext<'a> {
|
||||||
|
promo_seller_pda: &'a AccountInfo<'a>,
|
||||||
|
updated_state: PromoSellerState,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_promo_registration<'a>(
|
||||||
|
program_id: &Pubkey,
|
||||||
|
instructions_sysvar: &AccountInfo<'a>,
|
||||||
|
promo_seller_pda: &'a AccountInfo<'a>,
|
||||||
|
target_login: &str,
|
||||||
|
promo_code: &str,
|
||||||
|
) -> Result<PromoRegistrationContext<'a>, ProgramError> {
|
||||||
|
let (seller_login, signature58) = parse_promo_code(promo_code)?;
|
||||||
|
let normalized_seller_login = login_seed_normalized(&seller_login);
|
||||||
|
let expected_pda = find_promo_seller_pda(program_id, &normalized_seller_login).0;
|
||||||
|
require_keys_eq!(expected_pda, *promo_seller_pda.key, ShineUsersError::InvalidPdaAddress);
|
||||||
|
require!(promo_seller_pda.owner == program_id, ShineUsersError::PromoSellerNotFound);
|
||||||
|
|
||||||
|
let state = read_promo_seller_state(promo_seller_pda)?;
|
||||||
|
require!(state.remaining_sales > 0, ShineUsersError::PromoSalesExhausted);
|
||||||
|
require!(target_login.len() >= state.min_login_length as usize, ShineUsersError::PromoLoginTooShort);
|
||||||
|
|
||||||
|
let signature = decode_base58_fixed_64(&signature58)?;
|
||||||
|
let message = build_promo_sign_message(target_login);
|
||||||
|
verify_ed25519_signature_instruction(instructions_sysvar, -3, &state.signer_pubkey, &signature, message.as_bytes())
|
||||||
|
.map_err(|_| ProgramError::from(ShineUsersError::PromoSignatureMismatch))?;
|
||||||
|
|
||||||
|
let updated_state = PromoSellerState {
|
||||||
|
version: state.version,
|
||||||
|
remaining_sales: state.remaining_sales.saturating_sub(1),
|
||||||
|
min_login_length: state.min_login_length,
|
||||||
|
signer_pubkey: state.signer_pubkey,
|
||||||
|
};
|
||||||
|
Ok(PromoRegistrationContext {
|
||||||
|
promo_seller_pda,
|
||||||
|
updated_state,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
fn classify_login_or_fail(login_guard_program: &AccountInfo, login: &str) -> ProgramResult {
|
fn classify_login_or_fail(login_guard_program: &AccountInfo, login: &str) -> ProgramResult {
|
||||||
let login_guard_program_id = Pubkey::from_str(settings::SHINE_LOGIN_GUARD_PROGRAM_ID)
|
let login_guard_program_id = Pubkey::from_str(settings::SHINE_LOGIN_GUARD_PROGRAM_ID)
|
||||||
.map_err(|_| ProgramError::from(ShineUsersError::InvalidLoginGuardResponse))?;
|
.map_err(|_| ProgramError::from(ShineUsersError::InvalidLoginGuardResponse))?;
|
||||||
@@ -646,6 +788,15 @@ fn serialize_users_economy_config(state: &UsersEconomyConfigState) -> Vec<u8> {
|
|||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn serialize_promo_seller_state(state: &PromoSellerState) -> Vec<u8> {
|
||||||
|
let mut out = Vec::with_capacity(1 + 8 + 1 + 32);
|
||||||
|
out.push(state.version);
|
||||||
|
out.extend_from_slice(&state.remaining_sales.to_le_bytes());
|
||||||
|
out.push(state.min_login_length);
|
||||||
|
out.extend_from_slice(state.signer_pubkey.as_ref());
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
fn validate_users_economy_config_pda(program_id: &Pubkey, pda: &AccountInfo) -> ProgramResult {
|
fn validate_users_economy_config_pda(program_id: &Pubkey, pda: &AccountInfo) -> ProgramResult {
|
||||||
let (expected_pda, _) = find_users_economy_config_pda(program_id);
|
let (expected_pda, _) = find_users_economy_config_pda(program_id);
|
||||||
require_keys_eq!(expected_pda, *pda.key, ShineUsersError::InvalidPdaAddress);
|
require_keys_eq!(expected_pda, *pda.key, ShineUsersError::InvalidPdaAddress);
|
||||||
@@ -665,6 +816,19 @@ fn read_users_economy_config(pda: &AccountInfo) -> Result<UsersEconomyConfigStat
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn read_promo_seller_state(pda: &AccountInfo) -> Result<PromoSellerState, ProgramError> {
|
||||||
|
let raw = read_pda_all(pda)?;
|
||||||
|
require!(!raw.is_empty(), ShineUsersError::PromoSellerNotFound);
|
||||||
|
require!(raw.len() >= 42, ShineUsersError::InvalidPromoSellerState);
|
||||||
|
let signer_pubkey = Pubkey::new_from_array(raw[10..42].try_into().map_err(|_| ProgramError::from(ShineUsersError::InvalidPromoSellerState))?);
|
||||||
|
Ok(PromoSellerState {
|
||||||
|
version: raw[0],
|
||||||
|
remaining_sales: u64::from_le_bytes(raw[1..9].try_into().unwrap()),
|
||||||
|
min_login_length: raw[9],
|
||||||
|
signer_pubkey,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
fn deserialize_record_from_pda(raw: &[u8]) -> Result<UserRecord, ProgramError> {
|
fn deserialize_record_from_pda(raw: &[u8]) -> Result<UserRecord, ProgramError> {
|
||||||
require!(raw.len() >= 9, ShineUsersError::InvalidRecordData);
|
require!(raw.len() >= 9, ShineUsersError::InvalidRecordData);
|
||||||
require!(sol_memcmp(&raw[0..5], MAGIC, 5) == 0, ShineUsersError::InvalidRecordMagic);
|
require!(sol_memcmp(&raw[0..5], MAGIC, 5) == 0, ShineUsersError::InvalidRecordMagic);
|
||||||
@@ -958,6 +1122,74 @@ fn le_u16(data: &[u8], offset: usize) -> Result<u16, ProgramError> {
|
|||||||
Ok(u16::from_le_bytes([s[0], s[1]]))
|
Ok(u16::from_le_bytes([s[0], s[1]]))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn parse_promo_code(value: &str) -> Result<(String, String), ProgramError> {
|
||||||
|
let trimmed = value.trim();
|
||||||
|
let mut chars = trimmed.chars();
|
||||||
|
require!(chars.next() == Some(PROMO_CODE_VERSION_PREFIX), ShineUsersError::InvalidPromoCode);
|
||||||
|
let rest: String = chars.collect();
|
||||||
|
let dash_pos = rest.find('-').ok_or(ProgramError::from(ShineUsersError::InvalidPromoCode))?;
|
||||||
|
let seller_login = rest[..dash_pos].to_string();
|
||||||
|
let signature58 = rest[dash_pos + 1..].to_string();
|
||||||
|
require!(!seller_login.is_empty() && !signature58.is_empty(), ShineUsersError::InvalidPromoCode);
|
||||||
|
validate_login(&seller_login)?;
|
||||||
|
Ok((seller_login, signature58))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_promo_sign_message(login: &str) -> String {
|
||||||
|
let mut message = String::with_capacity(settings::PROMO_SIGN_PREFIX.len() + login.len());
|
||||||
|
message.push_str(settings::PROMO_SIGN_PREFIX);
|
||||||
|
message.push_str(login);
|
||||||
|
message
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode_base58_fixed_64(value: &str) -> Result<[u8; 64], ProgramError> {
|
||||||
|
let decoded = decode_base58(value)?;
|
||||||
|
<[u8; 64]>::try_from(decoded.as_slice()).map_err(|_| ProgramError::from(ShineUsersError::InvalidPromoCode))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode_base58(value: &str) -> Result<Vec<u8>, ProgramError> {
|
||||||
|
let text = value.trim();
|
||||||
|
require!(!text.is_empty(), ShineUsersError::InvalidPromoCode);
|
||||||
|
|
||||||
|
let mut bytes = vec![0u8];
|
||||||
|
for ch in text.bytes() {
|
||||||
|
let digit = base58_value(ch).ok_or(ProgramError::from(ShineUsersError::InvalidPromoCode))? as u32;
|
||||||
|
let mut carry = digit;
|
||||||
|
for byte in &mut bytes {
|
||||||
|
let x = (*byte as u32).checked_mul(58).and_then(|v| v.checked_add(carry)).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?;
|
||||||
|
*byte = (x & 0xff) as u8;
|
||||||
|
carry = x >> 8;
|
||||||
|
}
|
||||||
|
while carry > 0 {
|
||||||
|
bytes.push((carry & 0xff) as u8);
|
||||||
|
carry >>= 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for ch in text.bytes() {
|
||||||
|
if ch == b'1' {
|
||||||
|
bytes.push(0);
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bytes.reverse();
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn base58_value(ch: u8) -> Option<u8> {
|
||||||
|
match ch {
|
||||||
|
b'1'..=b'9' => Some(ch - b'1'),
|
||||||
|
b'A'..=b'H' => Some(9 + (ch - b'A')),
|
||||||
|
b'J'..=b'N' => Some(17 + (ch - b'J')),
|
||||||
|
b'P'..=b'Z' => Some(22 + (ch - b'P')),
|
||||||
|
b'a'..=b'k' => Some(33 + (ch - b'a')),
|
||||||
|
b'm'..=b'z' => Some(44 + (ch - b'm')),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn validate_login(login: &str) -> ProgramResult {
|
fn validate_login(login: &str) -> ProgramResult {
|
||||||
require!(!login.is_empty(), ShineUsersError::InvalidLogin);
|
require!(!login.is_empty(), ShineUsersError::InvalidLogin);
|
||||||
require!(login.len() <= 20, ShineUsersError::InvalidLogin);
|
require!(login.len() <= 20, ShineUsersError::InvalidLogin);
|
||||||
@@ -1075,6 +1307,7 @@ fn ensure_pda_size_and_rent<'a>(pda: &AccountInfo<'a>, payer: &AccountInfo<'a>,
|
|||||||
|
|
||||||
fn find_user_pda(program_id: &Pubkey, login: &str) -> (Pubkey, u8) { Pubkey::find_program_address(&[settings::USER_PDA_SEED_PREFIX.as_bytes(), login.as_bytes()], program_id) }
|
fn find_user_pda(program_id: &Pubkey, login: &str) -> (Pubkey, u8) { Pubkey::find_program_address(&[settings::USER_PDA_SEED_PREFIX.as_bytes(), login.as_bytes()], program_id) }
|
||||||
fn find_users_economy_config_pda(program_id: &Pubkey) -> (Pubkey, u8) { Pubkey::find_program_address(&[settings::USERS_ECONOMY_CONFIG_SEED], program_id) }
|
fn find_users_economy_config_pda(program_id: &Pubkey) -> (Pubkey, u8) { Pubkey::find_program_address(&[settings::USERS_ECONOMY_CONFIG_SEED], program_id) }
|
||||||
|
fn find_promo_seller_pda(program_id: &Pubkey, seller_login: &str) -> (Pubkey, u8) { Pubkey::find_program_address(&[settings::PROMO_SELLER_PDA_SEED_PREFIX.as_bytes(), seller_login.as_bytes()], program_id) }
|
||||||
fn limit_fee_lamports(limit_delta: u64, lamports_per_limit_step: u64) -> Result<u64, ProgramError> { (limit_delta / settings::LIMIT_STEP).checked_mul(lamports_per_limit_step).ok_or(ProgramError::from(ShineUsersError::MathOverflow)) }
|
fn limit_fee_lamports(limit_delta: u64, lamports_per_limit_step: u64) -> Result<u64, ProgramError> { (limit_delta / settings::LIMIT_STEP).checked_mul(lamports_per_limit_step).ok_or(ProgramError::from(ShineUsersError::MathOverflow)) }
|
||||||
fn pad_to_fixed_size(mut bytes: Vec<u8>, target_size: usize) -> Result<Vec<u8>, ProgramError> { require!(bytes.len() <= target_size, ShineUsersError::RecordTooLarge); bytes.resize(target_size, 0); Ok(bytes) }
|
fn pad_to_fixed_size(mut bytes: Vec<u8>, target_size: usize) -> Result<Vec<u8>, ProgramError> { require!(bytes.len() <= target_size, ShineUsersError::RecordTooLarge); bytes.resize(target_size, 0); Ok(bytes) }
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,14 @@
|
|||||||
pub const USER_PDA_SEED_PREFIX: &str = "user_login=";
|
pub const USER_PDA_SEED_PREFIX: &str = "user_login=";
|
||||||
/// Seed PDA с экономическими параметрами программы `shine_users`.
|
/// Seed PDA с экономическими параметрами программы `shine_users`.
|
||||||
pub const USERS_ECONOMY_CONFIG_SEED: &[u8] = b"shine_users_economy_config";
|
pub const USERS_ECONOMY_CONFIG_SEED: &[u8] = b"shine_users_economy_config";
|
||||||
|
/// Префикс seed для PDA продавца promo-логинов.
|
||||||
|
pub const PROMO_SELLER_PDA_SEED_PREFIX: &str = "promo_seller=";
|
||||||
/// Стартовый размер PDA пользователя, дальше запись может расширяться через realloc.
|
/// Стартовый размер PDA пользователя, дальше запись может расширяться через realloc.
|
||||||
pub const USER_PDA_SPACE: usize = 768;
|
pub const USER_PDA_SPACE: usize = 768;
|
||||||
/// Размер PDA с экономическими параметрами `shine_users`.
|
/// Размер PDA с экономическими параметрами `shine_users`.
|
||||||
pub const USERS_ECONOMY_CONFIG_SPACE: usize = 32;
|
pub const USERS_ECONOMY_CONFIG_SPACE: usize = 32;
|
||||||
|
/// Размер PDA продавца promo-логинов.
|
||||||
|
pub const PROMO_SELLER_PDA_SPACE: usize = 64;
|
||||||
|
|
||||||
/// Адрес DAO authority, который имеет право обновлять economy-конфиг.
|
/// Адрес DAO authority, который имеет право обновлять economy-конфиг.
|
||||||
pub const DAO_AUTHORITY: &str = "FUc28vNixp7F3nnkpGVt6nuJbgvJ4429v4B5wS52Df6P";
|
pub const DAO_AUTHORITY: &str = "FUc28vNixp7F3nnkpGVt6nuJbgvJ4429v4B5wS52Df6P";
|
||||||
@@ -16,6 +20,8 @@ pub const SHINE_PAYMENTS_PROGRAM_ID: &str = "c4yTa4JT9EtQDCBX9LmWFK6T2gp4JGsuymF
|
|||||||
pub const SHINE_PAYMENTS_INFLOW_VAULT_SEED: &[u8] = b"shine_payments_inflow_vault";
|
pub const SHINE_PAYMENTS_INFLOW_VAULT_SEED: &[u8] = b"shine_payments_inflow_vault";
|
||||||
/// Адрес отдельной программы проверки премиальности логина.
|
/// Адрес отдельной программы проверки премиальности логина.
|
||||||
pub const SHINE_LOGIN_GUARD_PROGRAM_ID: &str = "3xkopA7cXagxzMFrKdv3NCBfV6BKiRJCk69kr27M2sRo";
|
pub const SHINE_LOGIN_GUARD_PROGRAM_ID: &str = "3xkopA7cXagxzMFrKdv3NCBfV6BKiRJCk69kr27M2sRo";
|
||||||
|
/// Доменный префикс для подписи promo-кода.
|
||||||
|
pub const PROMO_SIGN_PREFIX: &str = "shine_promo_v1:";
|
||||||
|
|
||||||
/// Стартовая комиссия регистрации (0.01 SOL) для initial economy-конфига.
|
/// Стартовая комиссия регистрации (0.01 SOL) для initial economy-конфига.
|
||||||
pub const START_REGISTRATION_FEE_LAMPORTS: u64 = 10_000_000;
|
pub const START_REGISTRATION_FEE_LAMPORTS: u64 = 10_000_000;
|
||||||
|
|||||||
Reference in New Issue
Block a user