SHA256
НЕ ПРОВЕРЕНО: учтены логины с большими и маленькими буквами. Добавлен временный devnet-смарт-контракт для очистки тестового аккаунта от старых логинов; после сброса его необходимо удалить и восстановить штатный контракт.
119 lines
8.4 KiB
JavaScript
119 lines
8.4 KiB
JavaScript
#!/usr/bin/env node
|
|
// Временная очистка PDA shine_users. Только devnet, всегда проверять genesis hash.
|
|
// Никогда не добавляйте приватный ключ или файл keypair в git/архив.
|
|
import { Connection, PublicKey, Keypair, Transaction, TransactionInstruction, sendAndConfirmTransaction, BPF_LOADER_UPGRADEABLE_PROGRAM_ID } from '@solana/web3.js';
|
|
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
|
|
|
|
const PROGRAM_ID = new PublicKey('SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6');
|
|
const DEVNET_GENESIS = 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG';
|
|
const RPC = 'https://api.devnet.solana.com';
|
|
const MAX_ACCOUNTS = 100; // Защита от случайной массовой очистки.
|
|
const usage = `
|
|
Команды:
|
|
node cleaner.mjs inspect --authority <PUBKEY> --manifest <file.json>
|
|
node cleaner.mjs execute --manifest <file.json> --keypair <authority-keypair.json> --confirm <COUNT> --i-understand-irreversible
|
|
node cleaner.mjs verify
|
|
Все команды работают ТОЛЬКО с devnet и с фиксированным Program ID: ${PROGRAM_ID.toBase58()}
|
|
`;
|
|
function arg(name) {
|
|
const i = process.argv.indexOf(name);
|
|
return i < 0 ? undefined : process.argv[i + 1];
|
|
}
|
|
function fatal(msg) { throw new Error(msg); }
|
|
const command = process.argv[2];
|
|
if (!['inspect', 'execute', 'verify'].includes(command)) { console.log(usage); process.exit(2); }
|
|
const c = new Connection(RPC, 'confirmed');
|
|
|
|
async function checkNetworkAndProgram() {
|
|
const genesis = await c.getGenesisHash();
|
|
if (genesis !== DEVNET_GENESIS) fatal(`ОПАСНО: RPC не devnet: ${genesis}`);
|
|
const p = await c.getAccountInfo(PROGRAM_ID, 'confirmed');
|
|
if (!p?.executable || !p.owner.equals(BPF_LOADER_UPGRADEABLE_PROGRAM_ID)) fatal('Программа не является upgradeable loader-v3. Остановка.');
|
|
if (p.data.length < 36 || p.data.readUInt32LE(0) !== 2) fatal('Неверный loader-v3 Program account');
|
|
const programdata = new PublicKey(p.data.subarray(4, 36));
|
|
const pd = await c.getAccountInfo(programdata, 'confirmed');
|
|
if (!pd || !pd.owner.equals(BPF_LOADER_UPGRADEABLE_PROGRAM_ID) || pd.data.length < 45 || pd.data.readUInt32LE(0) !== 3 || pd.data[12] !== 1) {
|
|
fatal('ProgramData не содержит активную upgrade authority');
|
|
}
|
|
const authority = new PublicKey(pd.data.subarray(13, 45));
|
|
return { programdata, authority };
|
|
}
|
|
async function listOwned() {
|
|
// dataSlice устраняет скачивание всех данных PDA, получаем адрес и lamports.
|
|
const a = await c.getProgramAccounts(PROGRAM_ID, { commitment: 'confirmed', dataSlice: { offset: 0, length: 0 } });
|
|
return a.map(x => ({ address: x.pubkey.toBase58(), lamports: x.account.lamports }))
|
|
.sort((x, y) => x.address.localeCompare(y.address));
|
|
}
|
|
async function main() {
|
|
const { programdata, authority } = await checkNetworkAndProgram();
|
|
const rows = await listOwned();
|
|
console.log(`Devnet OK; Program=${PROGRAM_ID}; authority=${authority}; PDA=${rows.length}; SOL=${rows.reduce((s,x)=>s+x.lamports,0)/1e9}`);
|
|
if (rows.length > MAX_ACCOUNTS) fatal(`Найдено больше ${MAX_ACCOUNTS} PDA; скрипт намеренно прекращает работу.`);
|
|
if (command === 'verify') {
|
|
if (rows.length !== 0) fatal(`Осталось ${rows.length} PDA: ${rows.map(x => x.address).join(', ')}`);
|
|
console.log('OK: пользовательских и конфигурационных аккаунтов, принадлежащих программе, нет.');
|
|
return;
|
|
}
|
|
if (command === 'inspect') {
|
|
const ownerString = arg('--authority');
|
|
if (!ownerString) fatal('Укажите --authority с публичным адресом владельца.');
|
|
if (!new PublicKey(ownerString).equals(authority)) fatal('Указанный владелец не является upgrade authority.');
|
|
const manifest = arg('--manifest');
|
|
if (!manifest || existsSync(manifest)) fatal('Укажите новый --manifest путь (не перезаписываем существующий файл).');
|
|
const snapshot = {
|
|
purpose: 'destructive-devnet-shine-users-cleanup', genesis: DEVNET_GENESIS,
|
|
program: PROGRAM_ID.toBase58(), authority: authority.toBase58(), programdata: programdata.toBase58(),
|
|
createdAtUtc: new Date().toISOString(), accounts: rows,
|
|
};
|
|
writeFileSync(manifest, JSON.stringify(snapshot, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
|
console.log('План сохранён:', manifest);
|
|
for (const row of rows) console.log(`${row.address} ${(row.lamports / 1e9).toFixed(9)} SOL`);
|
|
console.log('Проверьте список и суммы перед деплоем временной программы и перед execute.');
|
|
return;
|
|
}
|
|
if (command === 'execute') {
|
|
if (!process.argv.includes('--i-understand-irreversible')) fatal('Требуется --i-understand-irreversible');
|
|
const path = arg('--manifest');
|
|
const keypath = arg('--keypair');
|
|
if (!path || !keypath) fatal('Нужны --manifest и --keypair');
|
|
const m = JSON.parse(readFileSync(path, 'utf8'));
|
|
const wallet = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(keypath, 'utf8'))));
|
|
if (!wallet.publicKey.equals(authority)) fatal('Файл keypair не совпадает с текущей upgrade authority');
|
|
if (m.purpose !== 'destructive-devnet-shine-users-cleanup' || m.genesis !== DEVNET_GENESIS || m.program !== PROGRAM_ID.toBase58() || m.programdata !== programdata.toBase58() || m.authority !== authority.toBase58()) fatal('План создан для другой сети, программы или владельца');
|
|
if (!Array.isArray(m.accounts) || new Set(m.accounts.map(x=>x.address)).size !== m.accounts.length || m.accounts.length > MAX_ACCOUNTS) fatal('Неверный список PDA в плане');
|
|
if (String(m.accounts.length) !== arg('--confirm')) fatal(`Неверный --confirm, должно быть ${m.accounts.length}`);
|
|
const currentByKey = new Map(rows.map(x => [x.address, x.lamports]));
|
|
const expectedByKey = new Map(m.accounts.map(x => [x.address, x.lamports]));
|
|
for (const row of rows) {
|
|
if (!expectedByKey.has(row.address) || row.lamports !== expectedByKey.get(row.address)) fatal('Состояние devnet отличается от плана: ' + row.address);
|
|
}
|
|
// Часть PDA может быть уже закрыта после сбоя связи: пропускаем только исчезнувшие.
|
|
const pending = m.accounts.filter(x => currentByKey.has(x.address));
|
|
console.log(`Подтверждено ${m.accounts.length} PDA, осталось закрыть ${pending.length}.`);
|
|
for (const [i, item] of pending.entries()) {
|
|
const target = new PublicKey(item.address);
|
|
const ix = new TransactionInstruction({
|
|
programId: PROGRAM_ID,
|
|
keys: [
|
|
{ pubkey: authority, isSigner: true, isWritable: true },
|
|
{ pubkey: PROGRAM_ID, isSigner: false, isWritable: false },
|
|
{ pubkey: programdata, isSigner: false, isWritable: false },
|
|
{ pubkey: target, isSigner: false, isWritable: true },
|
|
],
|
|
data: Buffer.from([1]),
|
|
});
|
|
const tx = new Transaction().add(ix);
|
|
const sim = await c.simulateTransaction(tx, [wallet]);
|
|
if (sim.value.err) fatal(`Симуляция НЕ прошла для ${item.address}: ${JSON.stringify(sim.value.err)} ${JSON.stringify(sim.value.logs)}`);
|
|
const signature = await sendAndConfirmTransaction(c, tx, [wallet], { commitment: 'confirmed', maxRetries: 3 });
|
|
const after = await c.getAccountInfo(target, 'confirmed');
|
|
if (after) fatal(`Транзакция ${signature} подтверждена, но ${item.address} ещё существует. Остановка.`);
|
|
console.log(`[${i+1}/${pending.length}] ЗАКРЫТО ${item.address}; +${item.lamports/1e9} SOL → ${authority.toBase58()}; tx=${signature}`);
|
|
}
|
|
const remaining = await listOwned();
|
|
if (remaining.length) fatal(`После очистки осталось ${remaining.length} аккаунтов`);
|
|
console.log('УСПЕХ: PDA shine_users отсутствуют. СРОЧНО ВОССТАНОВИТЕ ШТАТНЫЙ СМАРТ-КОНТРАКТ.');
|
|
}
|
|
}
|
|
main().catch(e => { console.error('ОШИБКА:', e.message); process.exitCode = 1; });
|