SHA256
104 lines
5.9 KiB
JavaScript
104 lines
5.9 KiB
JavaScript
#!/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; });
|