SHA256
Добавить безопасную очистку user PDA перед запуском 1.0
This commit is contained in:
@@ -1,5 +1,9 @@
|
||||
# Программа `shine_users`
|
||||
|
||||
> Переходный релиз перед публичным `1.0.0`: этот код остаётся совместимым с
|
||||
> форматами 1.2/1.3 только чтобы разово очистить ранее созданные user PDA.
|
||||
> Финальный релиз после очистки удалит эту совместимость и opcode 11.
|
||||
|
||||
Актуальный пользовательский формат — `user_pda 1.3`; [нормативные изменения](../../../../docs/Solana/SHINE_USER_PDA_V13_ROOT_LIMITS.md).
|
||||
Физический layout: `doc/formats/shine-user-pda-format-v.1.2.md` с изменениями 1.3.
|
||||
Legacy 1.0 считается тестовым и не мигрируется.
|
||||
@@ -115,6 +119,33 @@ Accounts:
|
||||
|
||||
Программа проверяет PDA seed/owner и `format=1.0`, переводит все lamports PDA вызывающему и обнуляет account data. PDA 1.2/1.3 этой инструкцией закрыть нельзя.
|
||||
|
||||
### `11 reset_user_pda` — только переходный релиз
|
||||
|
||||
```text
|
||||
tag:u8 = 11
|
||||
login:string_u8
|
||||
```
|
||||
|
||||
Accounts: `upgrade_authority signer+writable`, `user_pda writable`, исполняемый
|
||||
`shine_users program`, связанный `ProgramData`. Программа проверяет реальную
|
||||
upgrade authority из ProgramData, выводит user PDA из `login` (допустимы оба
|
||||
исторических seed-формата), проверяет заголовок `SHiNE/1.*`, возвращает все
|
||||
lamports только authority, очищает data и назначает владельцем System Program.
|
||||
Поэтому по тому же адресу может быть создана новая PDA финального формата.
|
||||
|
||||
Инструкция не принимает произвольный адрес и не может удалить namespace,
|
||||
economy config, vault или иной PDA. Перед отправкой необходимо сформировать и
|
||||
проверить инвентарь командой:
|
||||
|
||||
```bash
|
||||
node scripts/registration-v2/list-user-pdas-for-reset.mjs \
|
||||
--rpc https://api.devnet.solana.com --output /tmp/shine-users-devnet.json
|
||||
```
|
||||
|
||||
`reset-user-pdas.mjs` по умолчанию работает как dry-run; отправка требует
|
||||
`--send`, а для mainnet — ещё и явный `--mainnet`. Mainnet-очистка выполняется
|
||||
только после отдельного решения владельца программы и проверки полного списка.
|
||||
|
||||
### `7 create_namespace`
|
||||
|
||||
```text
|
||||
|
||||
@@ -51,6 +51,9 @@ const IX_CREATE_NAMESPACE: u8 = 7;
|
||||
const IX_UPDATE_NAMESPACE_PRICE: u8 = 8;
|
||||
const IX_SUPPORT_USER: u8 = 9;
|
||||
const IX_SUPPORT_DAO: u8 = 10;
|
||||
/// Одноразовая административная инструкция промежуточного релиза reset.
|
||||
/// В финальную публичную 1.0 она не войдёт.
|
||||
const IX_RESET_USER_PDA: u8 = 11;
|
||||
const SUPPORT_STATS_VERSION: u8 = 2; // ONLY Stars cents, old SOL stats rejected
|
||||
const SUPPORT_STATS_LEN: usize = 25;
|
||||
const SUPPORT_TARGET_USER: u8 = 0;
|
||||
@@ -228,6 +231,13 @@ pub struct CloseLegacyUserPdaArgs {
|
||||
pub login: String,
|
||||
}
|
||||
|
||||
/// Логин нужен не для поиска по данным аккаунта, а чтобы программа сама вывела
|
||||
/// допустимый PDA. Это исключает закрытие произвольного PDA программы.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ResetUserPdaArgs {
|
||||
pub login: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct UpdateUsersEconomyConfigArgs {
|
||||
pub update_fee_lamports: u64,
|
||||
@@ -343,6 +353,7 @@ fn process_instruction<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'a>],
|
||||
process_update_namespace_price(program_id, accounts, &namespace_name, currency_code, registration_fee)
|
||||
},
|
||||
IX_CLOSE_LEGACY_USER_PDA => dispatch_close_legacy_user_pda(program_id, accounts, r),
|
||||
IX_RESET_USER_PDA => dispatch_reset_user_pda(program_id, accounts, r),
|
||||
_ => Err(ProgramError::from(ShineUsersError::InvalidInstruction)),
|
||||
}
|
||||
}
|
||||
@@ -469,6 +480,12 @@ fn dispatch_close_legacy_user_pda(program_id: &Pubkey, accounts: &[AccountInfo],
|
||||
process_close_legacy_user_pda(program_id, accounts, args)
|
||||
}
|
||||
|
||||
fn dispatch_reset_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], mut r: Reader<'_>) -> ProgramResult {
|
||||
let args = ResetUserPdaArgs { login: r.read_string_u8()? };
|
||||
r.finish()?;
|
||||
process_reset_user_pda(program_id, accounts, args)
|
||||
}
|
||||
|
||||
fn process_init_users_economy_config(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult {
|
||||
let mut it = accounts.iter();
|
||||
let signer = next_account_info(&mut it)?;
|
||||
@@ -976,6 +993,60 @@ fn process_close_legacy_user_pda(program_id: &Pubkey, accounts: &[AccountInfo],
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Служебная инструкция только для планового запуска публичного формата 1.0.
|
||||
///
|
||||
/// Accounts:
|
||||
/// 0. `[signer, writable]` текущая upgrade authority; ей возвращается рента;
|
||||
/// 1. `[writable]` пользовательский PDA;
|
||||
/// 2. `[]` executable Program аккаунт `shine_users`;
|
||||
/// 3. `[]` связанный ProgramData аккаунт Upgradeable Loader.
|
||||
///
|
||||
/// Эта инструкция не умеет трогать namespace, economy config или иной PDA:
|
||||
/// адрес обязательно выводится из переданного login по одному из двух
|
||||
/// исторических user-seed форматов, а содержимое обязано быть user-записью SHiNE.
|
||||
fn process_reset_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args: ResetUserPdaArgs) -> ProgramResult {
|
||||
let mut it = accounts.iter();
|
||||
let authority = next_account_info(&mut it)?;
|
||||
let user_pda = next_account_info(&mut it)?;
|
||||
let program_ai = next_account_info(&mut it)?;
|
||||
let programdata_ai = next_account_info(&mut it)?;
|
||||
require!(it.next().is_none(), ShineUsersError::InvalidInstruction);
|
||||
require!(authority.is_writable && user_pda.is_writable, ShineUsersError::InvalidAccountData);
|
||||
validate_upgrade_authority(program_id, authority, program_ai, programdata_ai)?;
|
||||
|
||||
let expected_pda = if args.login.contains('@') {
|
||||
validate_full_login(&args.login)?;
|
||||
find_user_pda(program_id, &args.login).0
|
||||
} else {
|
||||
validate_legacy_login(&args.login)?;
|
||||
find_legacy_user_pda(program_id, &args.login.to_ascii_lowercase()).0
|
||||
};
|
||||
require_keys_eq!(expected_pda, *user_pda.key, ShineUsersError::InvalidPdaAddress);
|
||||
require!(user_pda.owner == program_id, ShineUsersError::InvalidAccountOwner);
|
||||
// Проверяем заголовок, но намеренно принимаем любой исторический minor:
|
||||
// это переходная утилита для удаления всех форматов перед чистым запуском.
|
||||
record_format_minor(&read_pda_all(user_pda)?)?;
|
||||
|
||||
let lamports = user_pda.lamports();
|
||||
{
|
||||
let mut authority_lamports = authority.try_borrow_mut_lamports()
|
||||
.map_err(|_| ProgramError::from(ShineUsersError::InvalidAccountData))?;
|
||||
**authority_lamports = (**authority_lamports)
|
||||
.checked_add(lamports)
|
||||
.ok_or(ProgramError::from(ShineUsersError::MathOverflow))?;
|
||||
}
|
||||
{
|
||||
let mut pda_lamports = user_pda.try_borrow_mut_lamports()
|
||||
.map_err(|_| ProgramError::from(ShineUsersError::InvalidAccountData))?;
|
||||
**pda_lamports = 0;
|
||||
}
|
||||
// realloc сам по себе оставит владельцем программу. Возвращаем System
|
||||
// Program, чтобы финальная 1.0 могла создать новую запись по тому же PDA.
|
||||
user_pda.realloc(0, false)?;
|
||||
user_pda.assign(&system_program::id());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_users_economy_config(state: &UsersEconomyConfigState) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(1 + 8);
|
||||
out.push(state.version);
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Creates a reviewable inventory of every SHiNE user record PDA currently
|
||||
* owned by shine_users. It never sends a transaction.
|
||||
*
|
||||
* node scripts/registration-v2/list-user-pdas-for-reset.mjs \
|
||||
* --rpc https://api.devnet.solana.com --output /tmp/shine-users-devnet.json
|
||||
*/
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { Connection, PublicKey } = require('@solana/web3.js');
|
||||
|
||||
const PROGRAM_ID = new PublicKey('SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6');
|
||||
const MAGIC = Buffer.from('SHiNE');
|
||||
|
||||
function argsOf(argv) {
|
||||
const out = {};
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const key = argv[i];
|
||||
if (!key.startsWith('--') || !argv[i + 1] || argv[i + 1].startsWith('--')) throw Error('Expected --rpc and --output');
|
||||
const name = key.slice(2);
|
||||
if (out[name] !== undefined) throw Error('Repeated --' + name);
|
||||
out[name] = argv[++i];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function readLogin(raw) {
|
||||
// All historical user records that can be reset have this signed prefix:
|
||||
// header(9), created(8), updated(8), number(4), previous hash(32), login.
|
||||
const loginLengthOffset = 9 + 8 + 8 + 4 + 32;
|
||||
if (raw.length <= loginLengthOffset) return null;
|
||||
const length = raw[loginLengthOffset];
|
||||
const start = loginLengthOffset + 1;
|
||||
const end = start + length;
|
||||
if (end > raw.length || length === 0) return null;
|
||||
const login = raw.subarray(start, end).toString('utf8');
|
||||
return Buffer.from(login, 'utf8').equals(raw.subarray(start, end)) ? login : null;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const a = argsOf(process.argv.slice(2));
|
||||
if (!a.rpc || !a.output) throw Error('Specify --rpc and --output');
|
||||
const url = new URL(a.rpc);
|
||||
if (!['http:', 'https:'].includes(url.protocol)) throw Error('RPC must use HTTP(S)');
|
||||
const conn = new Connection(a.rpc, 'confirmed');
|
||||
const accounts = await conn.getProgramAccounts(PROGRAM_ID, { commitment: 'confirmed' });
|
||||
const records = accounts
|
||||
.filter(({ account }) => account.data.length >= 9 && account.data.subarray(0, 5).equals(MAGIC) && account.data[5] === 1)
|
||||
.map(({ pubkey, account }) => ({
|
||||
pda: pubkey.toBase58(),
|
||||
login: readLogin(account.data),
|
||||
format: `${account.data[5]}.${account.data[6]}`,
|
||||
lamports: account.lamports.toString(),
|
||||
dataLength: account.data.length,
|
||||
}))
|
||||
.sort((a, b) => a.pda.localeCompare(b.pda));
|
||||
const unreadable = records.filter(({ login }) => login === null);
|
||||
const output = { programId: PROGRAM_ID.toBase58(), generatedAt: new Date().toISOString(), records };
|
||||
writeFileSync(a.output, JSON.stringify(output, null, 2) + '\n', { encoding: 'utf8', flag: 'wx' });
|
||||
console.log(JSON.stringify({ output: a.output, candidates: records.length, unreadable: unreadable.length }, null, 2));
|
||||
if (unreadable.length) process.exitCode = 2;
|
||||
}
|
||||
main().catch((e) => { console.error('Error:', e.message); process.exitCode = 1; });
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Executes the one-time reset instruction from the intermediate shine_users
|
||||
* release. Input must be an inventory reviewed by a human first.
|
||||
*
|
||||
* Dry run (default):
|
||||
* node scripts/registration-v2/reset-user-pdas.mjs --rpc https://api.devnet.solana.com \
|
||||
* --keypair ~/.config/solana/id.json --input /tmp/shine-users-devnet.json
|
||||
*
|
||||
* Sending needs an explicit --send. Mainnet additionally needs --mainnet.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { Connection, PublicKey, Keypair, Transaction, TransactionInstruction, sendAndConfirmTransaction, SystemProgram } = require('@solana/web3.js');
|
||||
const { createHash } = require('node:crypto');
|
||||
|
||||
const PROGRAM_ID = new PublicKey('SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6');
|
||||
const LOADER = new PublicKey('BPFLoaderUpgradeab1e11111111111111111111111');
|
||||
const MAGIC = Buffer.from('SHiNE');
|
||||
const IX_RESET_USER_PDA = 11;
|
||||
|
||||
function argsOf(argv) {
|
||||
const out = {};
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const item = argv[i];
|
||||
if (!item.startsWith('--')) throw Error('Unknown argument: ' + item);
|
||||
const key = item.slice(2);
|
||||
if (key === 'send' || key === 'mainnet') { if (out[key]) throw Error('Repeated --' + key); out[key] = true; continue; }
|
||||
if (!argv[i + 1] || argv[i + 1].startsWith('--') || out[key] !== undefined) throw Error('Missing/repeated --' + key);
|
||||
out[key] = argv[++i];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function deriveUserPda(login) {
|
||||
const normalized = login.toLowerCase();
|
||||
if (login.includes('@')) {
|
||||
const seed = createHash('sha256').update('user_login=' + normalized, 'utf8').digest();
|
||||
return PublicKey.findProgramAddressSync([seed], PROGRAM_ID)[0];
|
||||
}
|
||||
return PublicKey.findProgramAddressSync([Buffer.from('user_login='), Buffer.from(normalized)], PROGRAM_ID)[0];
|
||||
}
|
||||
function resetData(login) {
|
||||
const text = Buffer.from(login, 'utf8');
|
||||
if (text.length === 0 || text.length > 255) throw Error('Invalid login length: ' + login);
|
||||
return Buffer.concat([Buffer.from([IX_RESET_USER_PDA, text.length]), text]);
|
||||
}
|
||||
function loadInventory(path) {
|
||||
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
||||
if (!parsed || parsed.programId !== PROGRAM_ID.toBase58() || !Array.isArray(parsed.records)) throw Error('Input is not a shine_users reset inventory');
|
||||
const seen = new Set();
|
||||
return parsed.records.map((entry) => {
|
||||
if (!entry || typeof entry.login !== 'string' || typeof entry.pda !== 'string') throw Error('Every inventory record needs login and pda');
|
||||
const pda = new PublicKey(entry.pda);
|
||||
if (!deriveUserPda(entry.login).equals(pda)) throw Error('PDA does not match login: ' + entry.login);
|
||||
if (seen.has(pda.toBase58())) throw Error('Duplicate PDA: ' + pda.toBase58());
|
||||
seen.add(pda.toBase58());
|
||||
return { login: entry.login, pda };
|
||||
});
|
||||
}
|
||||
async function currentProgramdata(conn, wallet) {
|
||||
const executable = await conn.getAccountInfo(PROGRAM_ID, 'confirmed');
|
||||
if (!executable?.executable || !executable.owner.equals(LOADER) || executable.data.length < 36 || executable.data.readUInt32LE(0) !== 2)
|
||||
throw Error('Program is not an upgradeable shine_users program');
|
||||
const programdata = new PublicKey(executable.data.subarray(4, 36));
|
||||
const pd = await conn.getAccountInfo(programdata, 'confirmed');
|
||||
if (!pd || !pd.owner.equals(LOADER) || pd.data.length < 45 || pd.data.readUInt32LE(0) !== 3 || pd.data[12] !== 1 ||
|
||||
!new PublicKey(pd.data.subarray(13, 45)).equals(wallet.publicKey)) throw Error('Wallet is not current shine_users upgrade authority');
|
||||
return programdata;
|
||||
}
|
||||
async function main() {
|
||||
const a = argsOf(process.argv.slice(2));
|
||||
if (!a.rpc || !a.keypair || !a.input) throw Error('Specify --rpc, --keypair and --input');
|
||||
const url = new URL(a.rpc);
|
||||
if (!['http:', 'https:'].includes(url.protocol)) throw Error('RPC must use HTTP(S)');
|
||||
const mainnet = url.hostname.includes('mainnet');
|
||||
if (a.send && mainnet && !a.mainnet) throw Error('Mainnet requires --mainnet in addition to --send');
|
||||
if (a.mainnet && !mainnet) throw Error('--mainnet is only valid for a mainnet RPC');
|
||||
const wallet = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(a.keypair.replace(/^~\//, process.env.HOME + '/'), 'utf8'))));
|
||||
const records = loadInventory(a.input);
|
||||
const conn = new Connection(a.rpc, 'confirmed');
|
||||
const programdata = await currentProgramdata(conn, wallet);
|
||||
console.log(JSON.stringify({ mode: a.send ? 'SEND' : 'DRY RUN', programId: PROGRAM_ID.toBase58(), authority: wallet.publicKey.toBase58(), records: records.length }, null, 2));
|
||||
for (const { login, pda } of records) {
|
||||
const before = await conn.getAccountInfo(pda, 'confirmed');
|
||||
if (!before || !before.owner.equals(PROGRAM_ID) || before.data.length < 9 || !before.data.subarray(0, 5).equals(MAGIC) || before.data[5] !== 1)
|
||||
throw Error('Not a resettable user PDA: ' + pda.toBase58());
|
||||
console.log(JSON.stringify({ login, pda: pda.toBase58(), format: `${before.data[5]}.${before.data[6]}`, refundLamports: before.lamports.toString() }));
|
||||
if (!a.send) continue;
|
||||
const ix = new TransactionInstruction({ programId: PROGRAM_ID, keys: [
|
||||
{ pubkey: wallet.publicKey, isSigner: true, isWritable: true },
|
||||
{ pubkey: pda, isSigner: false, isWritable: true },
|
||||
{ pubkey: PROGRAM_ID, isSigner: false, isWritable: false },
|
||||
{ pubkey: programdata, isSigner: false, isWritable: false },
|
||||
], data: resetData(login) });
|
||||
const signature = await sendAndConfirmTransaction(conn, new Transaction().add(ix), [wallet], { commitment: 'confirmed' });
|
||||
const after = await conn.getAccountInfo(pda, 'confirmed');
|
||||
if (after && (!after.owner.equals(SystemProgram.programId) || after.lamports !== 0 || after.data.length !== 0))
|
||||
throw Error('Reset did not leave an empty system account: ' + pda.toBase58());
|
||||
console.log('Reset ' + login + ': ' + signature);
|
||||
}
|
||||
}
|
||||
main().catch((e) => { console.error('Error:', e.message); process.exitCode = 1; });
|
||||
Reference in New Issue
Block a user