SHA256
Немного улучшен дизайн и обновлены каналы
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env node
|
||||
// Без --send выполняет проверку и показывает транзакцию, но ничего не записывает.
|
||||
// Работа только localnet/devnet; ключ upgrade authority не выводится в консоль.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createRequire } from 'node:module';
|
||||
import { decodeNamespace } from './decode-namespace.mjs';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { Connection, PublicKey, Keypair, Transaction, TransactionInstruction, SystemProgram, sendAndConfirmTransaction } = require('@solana/web3.js');
|
||||
const PROGRAM_ID = new PublicKey('SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6');
|
||||
const [ECONOMY] = PublicKey.findProgramAddressSync([Buffer.from('shine_users_economy_config')], PROGRAM_ID);
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = {};
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
if (!argv[i].startsWith('--')) throw Error(`Неизвестный аргумент: ${argv[i]}`);
|
||||
const key = argv[i].slice(2);
|
||||
if (key === 'send') { args.send = true; continue; }
|
||||
if (args[key] !== undefined || !argv[i + 1]) throw Error(`Отсутствует либо повторён параметр --${key}`);
|
||||
args[key] = argv[++i];
|
||||
}
|
||||
return args;
|
||||
}
|
||||
function solToLamports(text) {
|
||||
if (!/^(0|[1-9][0-9]*)(?:\.[0-9]{1,9})?$/.test(text || '')) throw Error('Ожидается сумма SOL с точностью не более 9 знаков');
|
||||
const [whole, part = ''] = text.split('.');
|
||||
return BigInt(whole) * 1_000_000_000n + BigInt((part + '000000000').slice(0, 9));
|
||||
}
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
if (!args.rpc || !args.keypair || !args.namespace) throw Error('Нужны --rpc --keypair --namespace и --fee-sol либо --fee-lamports');
|
||||
if (!/^[a-z0-9_]{1,29}$/.test(args.namespace)) throw Error('Недопустимое имя namespace');
|
||||
if (args['fee-sol'] === undefined && args['fee-lamports'] === undefined) throw Error('Укажите стоимость');
|
||||
if (args['fee-sol'] !== undefined && args['fee-lamports'] !== undefined) throw Error('Укажите только один формат цены');
|
||||
const currencyCode = Number(args.currency ?? '1');
|
||||
if (currencyCode !== 1) throw Error('Валюта 2 (USDT) зарезервирована; сейчас разрешена только 1 (SOL)');
|
||||
const fee = args['fee-sol'] !== undefined ? solToLamports(args['fee-sol']) : BigInt(args['fee-lamports']);
|
||||
if (fee < 0n || fee > 0xffff_ffff_ffff_ffffn) throw Error('Стоимость вне диапазона u64');
|
||||
const uri = new URL(args.rpc);
|
||||
if (!(uri.protocol === 'https:' || uri.protocol === 'http:')) throw Error('Требуется RPC URL http/https');
|
||||
if (!(['localhost', '127.0.0.1'].includes(uri.hostname) || uri.hostname.endsWith('.devnet.solana.com')))
|
||||
throw Error('Для админского скрипта разрешены только localhost и публичный RPC *.devnet.solana.com');
|
||||
const wallet = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(args.keypair, 'utf8'))));
|
||||
const connection = new Connection(args.rpc, 'confirmed');
|
||||
const executable = await connection.getAccountInfo(PROGRAM_ID, 'confirmed');
|
||||
const upgradeableLoader = new PublicKey('BPFLoaderUpgradeab1e11111111111111111111111');
|
||||
if (!executable || !executable.executable || !executable.owner.equals(upgradeableLoader) || executable.data.length < 36 || executable.data.readUInt32LE(0) !== 2)
|
||||
throw Error('shine_users не является валидной upgradeable программой');
|
||||
const programdata = new PublicKey(executable.data.subarray(4, 36));
|
||||
const pd = await connection.getAccountInfo(programdata, 'confirmed');
|
||||
if (!pd || !pd.owner.equals(upgradeableLoader) || 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('Подписант не является текущей upgrade authority shine_users');
|
||||
const economy = await connection.getAccountInfo(ECONOMY, 'confirmed');
|
||||
if (!economy || !economy.owner.equals(PROGRAM_ID)) throw Error('Economy PDA не инициализирована');
|
||||
const [namespacePda] = PublicKey.findProgramAddressSync([createHash('sha256').update(`namespace=${args.namespace}`).digest()], PROGRAM_ID);
|
||||
const oldAccount = await connection.getAccountInfo(namespacePda, 'confirmed');
|
||||
if (!oldAccount || !oldAccount.owner.equals(PROGRAM_ID)) throw Error('Namespace не найден');
|
||||
const oldPrice = decodeNamespace(oldAccount.data);
|
||||
if (oldPrice.name !== args.namespace) throw Error('Состояние namespace не соответствует PDA');
|
||||
const name = Buffer.from(args.namespace);
|
||||
const data = Buffer.alloc(1 + 1 + name.length + 1 + 8);
|
||||
let offset = 0;
|
||||
data[offset++] = 8; // IX_UPDATE_NAMESPACE_PRICE
|
||||
data[offset++] = name.length;
|
||||
name.copy(data, offset); offset += name.length;
|
||||
data[offset++] = currencyCode;
|
||||
data.writeBigUInt64LE(fee, offset);
|
||||
const ix = new TransactionInstruction({ programId: PROGRAM_ID, keys: [
|
||||
{pubkey: wallet.publicKey, isSigner: true, isWritable: true},
|
||||
{pubkey: namespacePda, isSigner: false, isWritable: true},
|
||||
{pubkey: SystemProgram.programId, isSigner: false, isWritable: false},
|
||||
{pubkey: ECONOMY, isSigner: false, isWritable: false},
|
||||
{pubkey: PROGRAM_ID, isSigner: false, isWritable: false},
|
||||
{pubkey: programdata, isSigner: false, isWritable: false},
|
||||
], data });
|
||||
console.log(JSON.stringify({ namespace: args.namespace, currencyCode,
|
||||
previousPriceLamports: oldPrice.registrationFeeLamports, newPriceLamports: fee.toString(),
|
||||
newPriceSol: `${fee / 1_000_000_000n}.${(fee % 1_000_000_000n).toString().padStart(9, '0')}`,
|
||||
namespacePda: namespacePda.toBase58(), versionBefore: `${oldPrice.major}.${oldPrice.minor}`,
|
||||
mode: args.send ? 'SEND' : 'DRY-RUN' }, null, 2));
|
||||
if (!args.send) return;
|
||||
const signature = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [wallet], {commitment: 'confirmed'});
|
||||
const updated = await connection.getAccountInfo(namespacePda, 'confirmed');
|
||||
if (!updated) throw Error('После транзакции namespace отсутствует');
|
||||
const after = decodeNamespace(updated.data);
|
||||
if (after.registrationFeeLamports !== fee.toString() || after.currencyCode !== 1 || after.minor !== 1)
|
||||
throw Error('Изменение цены не подтверждено чтением namespace PDA');
|
||||
console.log(`Цена изменена. Signature: ${signature}; namespace PDA подтверждена.`);
|
||||
}
|
||||
main().catch(error => { console.error('Ошибка:', error.message); process.exitCode = 1; });
|
||||
@@ -0,0 +1,31 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {decodeNamespace} from '../scripts/registration-v2/decode-namespace.mjs';
|
||||
const vectors=JSON.parse(readFileSync(new URL('fixtures/registration-v2.json', import.meta.url)));
|
||||
|
||||
test('старые namespace 1.0 читаются как SOL', () => {
|
||||
for (const entry of vectors.namespace) {
|
||||
const parsed=decodeNamespace(Buffer.from(entry.bytes_hex,'hex'));
|
||||
assert.equal(parsed.minor,0);
|
||||
assert.equal(parsed.currencyCode,1);
|
||||
}
|
||||
});
|
||||
test('namespace 1.1 содержит отдельный байт валюты без потери регистратора', () => {
|
||||
for (const entry of vectors.namespace) {
|
||||
const legacy=Buffer.from(entry.bytes_hex,'hex');
|
||||
const offset=5+legacy[4]+8;
|
||||
const current=Buffer.concat([legacy.subarray(0,offset),Buffer.from([1]),legacy.subarray(offset)]);
|
||||
current[1]=1;
|
||||
const old=decodeNamespace(legacy);
|
||||
const parsed=decodeNamespace(current);
|
||||
assert.equal(parsed.minor,1);
|
||||
assert.equal(parsed.currencyCode,1);
|
||||
assert.equal(parsed.registrationFeeLamports,old.registrationFeeLamports);
|
||||
assert.equal(parsed.serverLogin,old.serverLogin);
|
||||
assert.equal(parsed.name,old.name);
|
||||
const unsupported=Buffer.from(current);unsupported[offset]=2;
|
||||
assert.throws(()=>decodeNamespace(unsupported),/неподдерживаемый код валюты/);
|
||||
assert.throws(()=>decodeNamespace(current.subarray(0,-1)));
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user