Добавить безопасную очистку user PDA перед запуском 1.0

This commit is contained in:
AidarKC
2026-12-02 15:06:27 +03:00
parent d8ef68836d
commit ad4949d2ac
4 changed files with 270 additions and 0 deletions
@@ -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; });