Регистрация V2: не проверено end-to-end

This commit is contained in:
AidarKC
2026-10-23 19:21:52 +03:00
parent 6c8159c5f7
commit cab26bbf41
95 changed files with 4469 additions and 1088 deletions
@@ -0,0 +1,41 @@
# SHiNE — Namespace PDA, бинарный формат 1.0
Статус: **черновая реализация в объединённом патче этапов 1–3**, не развёрнута; формат предложен как протокол V1. Перед деплоем обязательна компиляция Rust и тесты localnet/devnet.
## Идентичность и адреса
- `login@namespace`: строго ASCII lowercase, обе части `[a-z0-9_]+`, ровно один `@`.
- Полная длина имени — не более **30 байт**; `min_localpart_len` из namespace. Никаких обрезаний, удаления `_`, автоматических преобразований регистра; некорректный ввод отвергается.
- Пользовательский PDA: `seed=SHA256(UTF8("user_login=" + fullLogin))`, **один seed из 32 сырых байт**; `findProgramAddress([seed], shine_users_program_id)`.
- Namespace PDA: `seed=SHA256(UTF8("namespace=" + namespace))`, **один seed из 32 сырых байт**; `findProgramAddress([seed], shine_users_program_id)`.
- `program_id` из тестовых векторов: `SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6`. При другой программе адреса PDA изменятся.
## NamespaceState 1.0, байтовая раскладка
| Смещение | Значение | Байты |
|---|---|---:|
| 0 | major=1 | 1 |
| 1 | minor=0 | 1 |
| 2 | namespace_type: 1 платный; 2 бесплатный сертификат | 1 |
| 3 | min_localpart_len: u8, не менее 1, вместе с названием укладывается в 30 байт | 1 |
| 4 | namespace_len: u8 | 1 |
| 5 | namespace: lowercase ASCII | namespace_len |
| следующий | registration_fee: u64 little-endian (lamports) | 8 |
| только type=2 | registrar_pubkey: Ed25519 | 32 |
| только type=2 | server_login_len: u8; server_login в формате `login@namespace` | 1+N |
**Размер аккаунта ровно соответствует сериализованному размеру. Padding в namespace-PDA отсутствует.** Десериализатор отвергает лишние/недостающие байты, неверные версии, неизвестные типы, пустые/невалидные имена, несоответствие PDA, owner, namespace. В type=1 НЕ существует дополнительных нулевых полей. В type=2 оба поля обязательны. Цена допускает `0` для тестового namespace; защищённый signer authority выбирает значение до создания аккаунта. Изменение или удаление namespace пока отсутствует.
## Полномочия и создание
Создавать namespaces может только **текущая upgrade authority именно этой программы**. Программа читает аккаунт самой программы (`UpgradeableLoaderState::Program`) и связанный с ним ProgramData, проверяет владельца upgradeable loader, совпадение programData address и `Some(upgrade_authority)` с фактическим подписантом. При immutable программе — отказ. Для type=2 обязательная дополнительная read-only мета с **настоящим PDA v1.2** указанного `server_login`, у записи должен быть ServerProfile адрес; сначала регистрируется сервер в платном namespace. Economy PDA должен существовать, передаётся read-only, чтобы транзакция находилась через его историю `getSignaturesForAddress`. Уведомление `accountSubscribe` только из-за read-only меты не гарантировано.
## Векторы и воспроизводимость
- `tests/fixtures/registration-v2.json` — полный вектор, включая реальные синтетические ANS-104 bytes.
- `tests/fixtures/registration-v2.properties` — общий простой формат для Rust/Java/JS.
- `node --test tests/registration-v2-vectors.test.mjs` — проверка в Node без npm.
- `javac --release 17 -d /tmp/shine-reg-v2 tests/java/RegistrationV2VectorsCheck.java && java -cp /tmp/shine-reg-v2 RegistrationV2VectorsCheck tests/fixtures/registration-v2.properties`.
- `cargo test --test registration_v2_vectors` — в Rust окружении с toolchain (здесь недоступно).
Детерминированные приватные ключи, которыми построены фикстуры, **никогда не использовать** как настоящие ключи пользователей/регистратора.
@@ -183,3 +183,10 @@ Root доказывает владение recovery-key отдельной Ed255
- переводит его lamports вызывающему signer.
Legacy migration в 1.2 отсутствует. После удаления тестовых PDA временную close-инструкцию можно удалить из программы.
## Изменение адресации регистрации V2 (этапы 1–3, dev-only)
Бинарный user-PDA 1.2 **не изменён**. Меняется seed новых PDA на `SHA256(UTF8("user_login="+normalizedFullLogin))` (32 сырых байта), а полная строка `login@namespace` входит в поле `login` и в существующую подпись. Ограничение полного имени — 30 байт. `created_at_ms` в новой PDA при free→paid соответствует дате on-chain создания и не является датой первого Arweave сертификата. Историческая идентичность и потраченные лимиты остаются за логическим пользователем, их сохраняет сервер/БД последующих этапов.
Существующие PDA старых логинов без namespace продолжают принимать `update_user_pda` по старому seed `user_login=` + lowercase login; новых аккаунтов такого типа создать V2 больше нельзя. Новая регистрация **не будет совместима со старым клиентом** до обновления JS/сервера.
+51 -21
View File
@@ -21,41 +21,55 @@ Legacy 1.0 считается тестовым и не мигрируется.
Без изменений.
### `2 update_users_economy_config`
Без изменений.
### `3 create_user_pda`
Меняется **только** право доступа: текущая upgrade authority из ProgramData данного `shine_users`, а не статическая DAO-константа. Accounts: `signer writable?` (signer), `users_economy_config_pda writable`, `program read-only executable`, `programdata read-only`. `init` (opcode 1) остаётся доступным любому подписанту один раз.
### `3 create_user_pda` — новая V2-инструкция
**Внимание:** wire и account metas здесь уже несовместимы со старым UI. До завершения клиентского этапа №4 **НЕ DEPLOY** программу. Клиентский JS ещё не переписан.
```text
tag:u8 = 3
login:string_u8
login:string_u8 // полный lowercase login@namespace, <= 30 байт
root_key:[32]
created_at_ms:u64
additional_limit:u64
created_at_ms:u64 LE // новая Solana дата в пределах +-5 мин
additional_limit:u64 LE // кратно LIMIT_STEP
client_key:[32]
blockchain_key:[32]
address_count:u8 // 0 или 1
[address]
[address] // type:u8, version:u8, address:string_u8
access_server_count:u8 // 0 или 1
[access_server]
record_signature:[64]
[promo_seller_login:string_u8]
[access_server:string_u8]
record_signature:[64] // подпись текущего blockchain-key, сохраняется в PDA
registrar_signature_present:u8 // 0 для type 1, 1 для type 2
[registrar_signature:[64]] // только type 2, внутренняя подпись сертификата
```
Server address:
Accounts в неизменном порядке:
```text
address_format_type:u8
address_format_version:u8
address:string_u8
```
1. `payer` — signer, writable;
2. `user_pda` — writable (SHA-256 полного логина);
3. `system_program` — read-only;
4. `shine_payments` inflow vault — writable;
5. `sysvar::instructions` — read-only;
6. `users_economy_config_pda` — **read-only**;
7. `namespace_pda` — read-only, owner `shine_users`.
Fee payer — любой переданный signer; он не обязан совпадать с client key.
`created_at_ms` должен быть в пределах ±5 минут от Solana Clock.
Root даёт proof-of-possession, а initial blockchain key подписывает саму новую PDA.
Проверки: namespace реально существует в программе, `localPart >= min_localpart_len`, общая длина <= 30, обе части ASCII lowercase `[a-z0-9_]+`, PDA соответствует `SHA256("user_login="+fullLogin)`, схема v1.2, root и blockchain Ed25519 proof-of-possession. Цена = `namespace.registration_fee + additional_limit/LIMIT_STEP * economy.lamports_per_limit_step` в существующий `shine_payments` vault. На create сохраняется существующая схема starter quota из economy-PDA: при переходе free→paid внешняя БД обязана учесть уже использованный бонус и не выдать его снова.
**Ed25519 инструкции перед opcode 3 (строго непосредственно):**
- Тип 1: `[root_verify(unsigned_hash), blockchain_verify(unsigned_hash), create_user]`; смещения `-2`, `-1`.
- Тип 2: `[registrar_verify(inner_message), root_verify(unsigned_hash), blockchain_verify(unsigned_hash), create_user]`; смещения `-3`, `-2`, `-1`.
Всем проверкам нужны именно требуемые `pubkey`, `message`, а blockchain также сопоставляется с `record_signature`. Проверка сертификата использует `registrar_pubkey` **из указанного namespace-PDA**, а не ключ клиента. Порядок байтов inner message см. `docs/Протоколы/SHINE_FREE_REGISTRATION_CERTIFICATE_V1.md`. Solana подтверждает право создать PDA, но не утверждает успешную публикацию сертификата в Arweave.
**Upgrade free→paid** — тот же opcode 3 на том же полном логине и публичных ключах. Старые приватные ключи клиента не раскрываются; сохранение исходных публикаций обеспечивают синхронизатор/сервер (не Solana). Дата создания on-chain PDA может быть новой. Повторное создание PDA отвергается.
### `4 update_user_pda`
Работает только с PDA 1.2.
Работает только с PDA 1.2. Для нового `login@namespace` ищет SHA-256 PDA; для существующего старого логина без `@` сохраняет прежнюю схему `[b"user_login=", lowercase_login]`, чтобы не блокировать прежние аккаунты. Оплата дополнительных лимитов и авторизация обновлений не меняются.
```text
tag:u8 = 4
@@ -101,8 +115,9 @@ Root-mode:
Обе Ed25519-подписи проверяются по одному и тому же hash нового unsigned PDA state, поэтому новые root/client/blockchain public keys входят в подписываемое состояние.
### `5 upsert_promo_seller`
Без изменений.
### `5` — зарезервированная старая promo instruction
В V2 диспетчер не исполняет opcode 5. Новая регистрация не обращается в `shine_login_guard`, не использует promo seller и premium классы. Исторические standalone программы не удалялись.
### `6 close_legacy_pda`
@@ -120,6 +135,21 @@ Accounts:
Программа проверяет PDA seed/owner и `format=1.0`, переводит все lamports PDA вызывающему и обнуляет account data. PDA 1.2 этой инструкцией закрыть нельзя.
### `7 create_namespace`
```text
tag:u8=7
namespace_type:u8 // 1 paid-direct / 2 free-cert
min_localpart_len:u8
namespace:string_u8
registration_fee:u64 LE
[if type=2: registrar_pubkey:[32]; server_login:string_u8]
```
Accounts: `payer signer writable`, `namespace_pda writable`, `system_program read-only`, `economy_pda read-only`, `shine_users program executable read-only`, `shine_users ProgramData read-only`; **только type=2** — `registered_access_server_user_pda` (read-only) настоящего зарегистрированного сервера с ServerProfile.
Проверки: точный PDA по 32-байтному SHA-256 seed `namespace=NAME`, owner, пустой system PDA, версия 1.0, длина имени, тип, поля регистратора; economy валиден и read-only; `ProgramData` строго относится к этому исполняемому program ID и `upgrade_authority=Some(signer)`. У immutable программы создание запрещено; изменить/удалить namespace нельзя. Отдельная документация: `doc/formats/shine-namespace-pda-format-v1.md`.
## BlockchainRegistry 1.2
```text
+206 -193
View File
@@ -3,9 +3,9 @@ use solana_program::{
clock::Clock,
entrypoint,
entrypoint::ProgramResult,
hash::hashv,
instruction::Instruction,
program::{get_return_data, invoke, invoke_signed},
hash::{hash, hashv},
bpf_loader_upgradeable,
program::{invoke, invoke_signed},
program_error::ProgramError,
program_memory::sol_memcmp,
pubkey::Pubkey,
@@ -44,9 +44,9 @@ const IX_INIT_USERS_ECONOMY_CONFIG: u8 = 1;
const IX_UPDATE_USERS_ECONOMY_CONFIG: u8 = 2;
const IX_CREATE_USER_PDA: u8 = 3;
const IX_UPDATE_USER_PDA: u8 = 4;
const IX_UPSERT_PROMO_SELLER: u8 = 5;
const IX_CLOSE_LEGACY_USER_PDA: u8 = 6;
const LOGIN_GUARD_IX_CLASSIFY_LOGIN: u8 = 1;
const IX_CREATE_NAMESPACE: u8 = 7;
const CERTIFICATE_DOMAIN: &[u8] = b"SHiNE_FREE_REG_V1\0";
#[repr(u32)]
#[derive(Clone, Copy, Debug)]
@@ -91,6 +91,10 @@ enum ShineUsersError {
RootChangeRequiresRoot = 38,
AmbiguousAuthorityRotation = 39,
RootModeRequiresFullRotation = 40,
InvalidNamespace = 41,
InvalidUpgradeAuthority = 42,
NamespaceAlreadyExists = 43,
CertificateRequired = 44,
}
impl From<ShineUsersError> for ProgramError {
@@ -161,7 +165,7 @@ pub struct CreateUserPdaArgs {
pub server_addresses: Vec<ServerAddressRecordV12>,
pub access_servers: Vec<String>,
pub signature: [u8; 64],
pub promo_seller_login: Option<String>,
pub registrar_signature: Option<[u8; 64]>,
}
#[derive(Clone, Debug)]
@@ -198,20 +202,14 @@ pub struct UsersEconomyConfigState {
pub start_bonus_limit: u64,
}
#[derive(Clone, Debug)]
pub struct UpsertPromoSellerArgs {
pub seller_login: String,
pub remaining_sales: u64,
pub min_login_length: u8,
pub signer_pubkey: Pubkey,
}
#[derive(Clone, Debug)]
pub struct PromoSellerState {
pub version: u8,
pub remaining_sales: u64,
pub min_login_length: u8,
pub signer_pubkey: Pubkey,
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NamespaceState {
pub namespace_type: u8,
pub min_localpart_len: u8,
pub namespace: String,
pub registration_fee: u64,
pub registrar_pubkey: Option<Pubkey>,
pub server_login: Option<String>,
}
struct Reader<'a> {
@@ -294,7 +292,11 @@ fn process_instruction<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'a>],
}
IX_CREATE_USER_PDA => dispatch_create_user_pda(program_id, accounts, r),
IX_UPDATE_USER_PDA => dispatch_update_user_pda(program_id, accounts, r),
IX_UPSERT_PROMO_SELLER => dispatch_upsert_promo_seller(program_id, accounts, r),
IX_CREATE_NAMESPACE => {
let args = parse_namespace_args(&mut r)?;
r.finish()?;
process_create_namespace(program_id, accounts, args)
},
IX_CLOSE_LEGACY_USER_PDA => dispatch_close_legacy_user_pda(program_id, accounts, r),
_ => Err(ProgramError::from(ShineUsersError::InvalidInstruction)),
}
@@ -312,15 +314,19 @@ fn dispatch_update_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], mut r
process_update_user_pda(program_id, accounts, args)
}
fn dispatch_upsert_promo_seller(program_id: &Pubkey, accounts: &[AccountInfo], mut r: Reader<'_>) -> ProgramResult {
let args = UpsertPromoSellerArgs {
seller_login: r.read_string_u8()?,
remaining_sales: r.read_u64()?,
min_login_length: r.read_u8()?,
signer_pubkey: r.read_pubkey()?,
fn parse_namespace_args(r: &mut Reader<'_>) -> Result<NamespaceState, ProgramError> {
let namespace_type = r.read_u8()?;
let min_localpart_len = r.read_u8()?;
let namespace = r.read_string_u8()?;
let registration_fee = r.read_u64()?;
let (registrar_pubkey, server_login) = match namespace_type {
1 => (None, None),
2 => (Some(r.read_pubkey()?), Some(r.read_string_u8()?)),
_ => return Err(ShineUsersError::InvalidNamespace.into()),
};
r.finish()?;
process_upsert_promo_seller(program_id, accounts, args)
let state = NamespaceState { namespace_type, min_localpart_len, namespace, registration_fee, registrar_pubkey, server_login };
validate_namespace_state(&state)?;
Ok(state)
}
fn parse_server_addresses(r: &mut Reader<'_>) -> Result<Vec<ServerAddressRecordV12>, ProgramError> {
@@ -356,7 +362,11 @@ fn parse_create_args(r: &mut Reader<'_>) -> Result<CreateUserPdaArgs, ProgramErr
server_addresses: parse_server_addresses(r)?,
access_servers: parse_access_servers(r)?,
signature: r.read_fixed_64()?,
promo_seller_login: if r.remaining() > 0 { Some(r.read_string_u8()?) } else { None },
registrar_signature: match r.read_u8()? {
0 => None,
1 => Some(r.read_fixed_64()?),
_ => return Err(ShineUsersError::InvalidInstruction.into()),
},
})
}
@@ -433,11 +443,11 @@ fn process_update_users_economy_config(program_id: &Pubkey, accounts: &[AccountI
let mut it = accounts.iter();
let signer = next_account_info(&mut it)?;
let users_economy_config_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!(signer.is_signer, ShineUsersError::InvalidSigner);
let dao_authority = Pubkey::from_str(settings::DAO_AUTHORITY).map_err(|_| ProgramError::from(ShineUsersError::InvalidSigner))?;
require_keys_eq!(dao_authority, *signer.key, ShineUsersError::InvalidSigner);
validate_upgrade_authority(program_id, signer, program_ai, programdata_ai)?;
let (expected_pda, _) = find_users_economy_config_pda(program_id);
require_keys_eq!(expected_pda, *users_economy_config_pda.key, ShineUsersError::InvalidPdaAddress);
require!(users_economy_config_pda.owner == program_id, ShineUsersError::InvalidPdaAddress);
@@ -451,46 +461,55 @@ fn process_update_users_economy_config(program_id: &Pubkey, accounts: &[AccountI
Ok(())
}
fn process_upsert_promo_seller(program_id: &Pubkey, accounts: &[AccountInfo], args: UpsertPromoSellerArgs) -> ProgramResult {
fn process_create_namespace(program_id: &Pubkey, accounts: &[AccountInfo], state: NamespaceState) -> ProgramResult {
let mut it = accounts.iter();
let signer = next_account_info(&mut it)?;
let promo_seller_pda = next_account_info(&mut it)?;
let namespace_pda = next_account_info(&mut it)?;
let system_program_ai = next_account_info(&mut it)?;
let economy_pda = next_account_info(&mut it)?;
let program_ai = next_account_info(&mut it)?;
let programdata_ai = next_account_info(&mut it)?;
// Для free namespace сервер обязан иметь уже созданную настоящую PDA 1.2.
let registered_server = if state.namespace_type == 2 { Some(next_account_info(&mut it)?) } else { None };
require!(it.next().is_none(), ShineUsersError::InvalidInstruction);
require!(signer.is_signer, ShineUsersError::InvalidSigner);
require_keys_eq!(*system_program_ai.key, system_program::id(), ShineUsersError::InvalidSystemProgram);
validate_login(&args.seller_login)?;
require!((1..=20).contains(&args.min_login_length), ShineUsersError::InvalidPromoSellerState);
let dao_authority = Pubkey::from_str(settings::DAO_AUTHORITY).map_err(|_| ProgramError::from(ShineUsersError::InvalidSigner))?;
require_keys_eq!(dao_authority, *signer.key, ShineUsersError::InvalidSigner);
let seller_seed = login_seed_normalized(&args.seller_login);
let (expected_pda, bump) = find_promo_seller_pda(program_id, &seller_seed);
require_keys_eq!(expected_pda, *promo_seller_pda.key, ShineUsersError::InvalidPdaAddress);
if promo_seller_pda.owner == &system_program::id() {
create_pda_account(
signer,
promo_seller_pda,
system_program_ai,
program_id,
&[settings::PROMO_SELLER_PDA_SEED_PREFIX.as_bytes(), seller_seed.as_bytes(), &[bump]],
settings::PROMO_SELLER_PDA_SPACE,
)?;
} else {
require!(promo_seller_pda.owner == program_id, ShineUsersError::InvalidPdaAddress);
ensure_pda_size_and_rent(promo_seller_pda, signer, system_program_ai, settings::PROMO_SELLER_PDA_SPACE)?;
validate_upgrade_authority(program_id, signer, program_ai, programdata_ai)?;
if let Some(server_ai) = registered_server {
let login = state.server_login.as_deref().ok_or(ShineUsersError::InvalidNamespace)?;
require_keys_eq!(*server_ai.key, find_user_pda(program_id, login).0, ShineUsersError::InvalidPdaAddress);
require!(server_ai.owner == program_id, ShineUsersError::InvalidAccountOwner);
let server_record = deserialize_record_v12_from_pda(&read_pda_all(server_ai)?)?;
require!(server_record.login == login && !server_record.server_addresses.is_empty(), ShineUsersError::InvalidNamespace);
}
validate_users_economy_config_pda(program_id, economy_pda)?;
read_users_economy_config(economy_pda)?;
require!(!economy_pda.is_writable, ShineUsersError::InvalidAccountData);
validate_namespace_state(&state)?;
let (expected, bump) = find_namespace_pda(program_id, &state.namespace);
require_keys_eq!(*namespace_pda.key, expected, ShineUsersError::InvalidPdaAddress);
require!(namespace_pda.owner == &system_program::id() && namespace_pda.data_is_empty(), ShineUsersError::NamespaceAlreadyExists);
let data = serialize_namespace(&state);
let seed = hash(format!("{}{}", settings::NAMESPACE_PDA_SEED_PREFIX, state.namespace).as_bytes()).to_bytes();
create_pda_account(signer, namespace_pda, system_program_ai, program_id, &[&seed, &[bump]], data.len())?;
write_pda_exact(namespace_pda, &data)
}
let state = PromoSellerState {
version: 1,
remaining_sales: args.remaining_sales,
min_login_length: args.min_login_length,
signer_pubkey: args.signer_pubkey,
};
write_pda_exact(promo_seller_pda, &serialize_promo_seller_state(&state))?;
/// Проверяем не просто подписанта, а актуальную authority ProgramData ИМЕННО этой программы.
/// Bincode layout UpgradeableLoaderState: Program = [2:u32LE, programdata:32],
/// ProgramData = [3:u32LE, slot:u64LE, Option<Pubkey>:1+32].
fn validate_upgrade_authority(program_id: &Pubkey, signer: &AccountInfo, program_ai: &AccountInfo, programdata_ai: &AccountInfo) -> ProgramResult {
require!(signer.is_signer, ShineUsersError::InvalidSigner);
require_keys_eq!(*program_ai.key, *program_id, ShineUsersError::InvalidUpgradeAuthority);
require!(program_ai.executable && *program_ai.owner == bpf_loader_upgradeable::id(), ShineUsersError::InvalidUpgradeAuthority);
let program_data = program_ai.try_borrow_data()?;
require!(program_data.len() >= 36 && program_data[0..4] == 2u32.to_le_bytes(), ShineUsersError::InvalidUpgradeAuthority);
require!(program_data[4..36] == programdata_ai.key.to_bytes(), ShineUsersError::InvalidUpgradeAuthority);
require!(*programdata_ai.owner == bpf_loader_upgradeable::id(), ShineUsersError::InvalidUpgradeAuthority);
let pd = programdata_ai.try_borrow_data()?;
require!(pd.len() >= 45 && pd[0..4] == 3u32.to_le_bytes(), ShineUsersError::InvalidUpgradeAuthority);
require!(pd[12] == 1 && pd[13..45] == signer.key.to_bytes(), ShineUsersError::InvalidUpgradeAuthority);
Ok(())
}
@@ -502,38 +521,38 @@ fn process_create_user_pda<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'
let inflow_vault = next_account_info(&mut it)?;
let instructions_sysvar = next_account_info(&mut it)?;
let users_economy_config_pda = next_account_info(&mut it)?;
let login_guard_program = next_account_info(&mut it)?;
let promo_seller_pda = it.next();
let namespace_pda = next_account_info(&mut it)?;
require!(it.next().is_none(), ShineUsersError::InvalidInstruction);
require!(signer.is_signer, ShineUsersError::InvalidSigner);
require_keys_eq!(*system_program_ai.key, system_program::id(), ShineUsersError::InvalidSystemProgram);
validate_login(&args.login)?;
let namespace_name = validate_full_login(&args.login)?;
require!(!namespace_pda.is_writable, ShineUsersError::InvalidAccountData);
let namespace = read_namespace(program_id, namespace_pda, namespace_name)?;
let local_len = args.login.split('@').next().unwrap().len();
require!(local_len >= namespace.min_localpart_len as usize, ShineUsersError::InvalidLogin);
validate_server_addresses(&args.server_addresses)?;
validate_access_servers(&args.access_servers)?;
for server in &args.access_servers { validate_full_login(server)?; }
validate_inflow_vault(inflow_vault)?;
require!(args.additional_limit % settings::LIMIT_STEP == 0, ShineUsersError::InvalidLimitIncrement);
require_keys_eq!(*login_guard_program.key, Pubkey::from_str(settings::SHINE_LOGIN_GUARD_PROGRAM_ID).map_err(|_| ProgramError::from(ShineUsersError::InvalidLoginGuardResponse))?, ShineUsersError::InvalidLoginGuardResponse);
validate_users_economy_config_pda(program_id, users_economy_config_pda)?;
let promo_context = if let Some(seller_login) = args.promo_seller_login.as_deref().filter(|value| !value.trim().is_empty()) {
let seller_pda = promo_seller_pda.ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?;
Some(verify_promo_registration(program_id, instructions_sysvar, seller_pda, &args.login, seller_login)?)
} else {
require!(promo_seller_pda.is_none(), ShineUsersError::InvalidInstruction);
None
};
if promo_context.is_none() {
classify_login_or_fail(login_guard_program, &args.login)?;
}
require!(!users_economy_config_pda.is_writable, ShineUsersError::InvalidAccountData);
let economy = read_users_economy_config(users_economy_config_pda)?;
let login_seed = login_seed_normalized(&args.login);
let (expected_pda, bump) = find_user_pda(program_id, &login_seed);
let (expected_pda, bump) = find_user_pda(program_id, &args.login);
require_keys_eq!(expected_pda, *user_pda.key, ShineUsersError::InvalidPdaAddress);
require!(user_pda.owner == &system_program::id(), ShineUsersError::UserAlreadyExists);
require!(user_pda.data_is_empty(), ShineUsersError::UserAlreadyExists);
match namespace.namespace_type {
1 => require!(args.registrar_signature.is_none(), ShineUsersError::InvalidInstruction),
2 => {
let signature = args.registrar_signature.as_ref().ok_or(ShineUsersError::CertificateRequired)?;
let registrar = namespace.registrar_pubkey.ok_or(ShineUsersError::InvalidNamespace)?;
let message = certificate_inner_message(&args.login, &args.root_key, &args.blockchain_key, &args.client_key)?;
verify_ed25519_signature_instruction(instructions_sysvar, -3, &registrar, signature, &message)?;
},
_ => return Err(ShineUsersError::InvalidNamespace.into()),
}
let start_balance_u64 = economy.start_bonus_limit.checked_add(args.additional_limit).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?;
let start_balance = u32::try_from(start_balance_u64).map_err(|_| ProgramError::from(ShineUsersError::PaidLimitTooLarge))?;
@@ -572,16 +591,12 @@ fn process_create_user_pda<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'
user_pda,
system_program_ai,
program_id,
&[settings::USER_PDA_SEED_PREFIX.as_bytes(), login_seed.as_bytes(), &[bump]],
&[&user_pda_seed(&record.login), &[bump]],
settings::USER_PDA_SPACE,
)?;
write_pda_exact(user_pda, &serialized)?;
if let Some(promo) = promo_context {
write_pda_exact(promo.promo_seller_pda, &serialize_promo_seller_state(&promo.updated_state))?;
}
let total_fee = economy.registration_fee_lamports.checked_add(limit_fee_lamports(args.additional_limit, economy.lamports_per_limit_step)?).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?;
let total_fee = namespace.registration_fee.checked_add(limit_fee_lamports(args.additional_limit, economy.lamports_per_limit_step)?).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?;
transfer_lamports(signer, inflow_vault, system_program_ai, total_fee)?;
Ok(())
}
@@ -598,7 +613,10 @@ fn process_update_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args:
require!(signer.is_signer, ShineUsersError::InvalidSigner);
require_keys_eq!(*system_program_ai.key, system_program::id(), ShineUsersError::InvalidSystemProgram);
validate_login(&args.login)?;
// Старые аккаунты без namespace сохраняют прежнюю возможность update.
// Новый create всегда требует полный login@namespace.
if args.login.contains('@') { validate_full_login(&args.login)?; }
else { validate_legacy_login(&args.login)?; }
validate_server_addresses(&args.server_addresses)?;
validate_access_servers(&args.access_servers)?;
validate_inflow_vault(inflow_vault)?;
@@ -606,8 +624,12 @@ fn process_update_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args:
validate_users_economy_config_pda(program_id, users_economy_config_pda)?;
let economy = read_users_economy_config(users_economy_config_pda)?;
let normalized_login = login_seed_normalized(&args.login);
require_keys_eq!(find_user_pda(program_id, &normalized_login).0, *user_pda.key, ShineUsersError::InvalidPdaAddress);
let expected_pda = if args.login.contains('@') {
find_user_pda(program_id, &args.login).0
} else {
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::InvalidPdaAddress);
let raw = read_pda_all(user_pda)?;
@@ -703,9 +725,8 @@ fn process_close_legacy_user_pda(program_id: &Pubkey, accounts: &[AccountInfo],
require!(caller.is_writable, ShineUsersError::InvalidAccountData);
require!(user_pda.is_writable, ShineUsersError::InvalidAccountData);
validate_login(&args.login)?;
let normalized_login = login_seed_normalized(&args.login);
require_keys_eq!(find_user_pda(program_id, &normalized_login).0, *user_pda.key, ShineUsersError::InvalidPdaAddress);
validate_legacy_login(&args.login)?;
require_keys_eq!(find_legacy_user_pda(program_id, &args.login.to_ascii_lowercase()).0, *user_pda.key, ShineUsersError::InvalidPdaAddress);
require!(user_pda.owner == program_id, ShineUsersError::InvalidPdaAddress);
let raw = read_pda_all(user_pda)?;
@@ -724,66 +745,6 @@ fn process_close_legacy_user_pda(program_id: &Pubkey, accounts: &[AccountInfo],
Ok(())
}
struct PromoRegistrationContext<'a> {
promo_seller_pda: &'a AccountInfo<'a>,
updated_state: PromoSellerState,
}
fn verify_promo_registration<'a>(
program_id: &Pubkey,
instructions_sysvar: &AccountInfo<'a>,
promo_seller_pda: &'a AccountInfo<'a>,
target_login: &str,
seller_login: &str,
) -> Result<PromoRegistrationContext<'a>, ProgramError> {
validate_login(seller_login)?;
let normalized_seller_login = login_seed_normalized(&seller_login);
let expected_pda = find_promo_seller_pda(program_id, &normalized_seller_login).0;
require_keys_eq!(expected_pda, *promo_seller_pda.key, ShineUsersError::InvalidPdaAddress);
require!(promo_seller_pda.owner == program_id, ShineUsersError::PromoSellerNotFound);
let state = read_promo_seller_state(promo_seller_pda)?;
require!(state.remaining_sales > 0, ShineUsersError::PromoSalesExhausted);
require!(target_login.len() >= state.min_login_length as usize, ShineUsersError::PromoLoginTooShort);
let message = build_promo_sign_message(target_login);
verify_ed25519_instruction_pubkey_message(instructions_sysvar, -3, &state.signer_pubkey, message.as_bytes())
.map_err(|_| ProgramError::from(ShineUsersError::PromoSignatureMismatch))?;
let updated_state = PromoSellerState {
version: state.version,
remaining_sales: state.remaining_sales.saturating_sub(1),
min_login_length: state.min_login_length,
signer_pubkey: state.signer_pubkey,
};
Ok(PromoRegistrationContext {
promo_seller_pda,
updated_state,
})
}
fn classify_login_or_fail(login_guard_program: &AccountInfo, login: &str) -> ProgramResult {
let login_guard_program_id = Pubkey::from_str(settings::SHINE_LOGIN_GUARD_PROGRAM_ID)
.map_err(|_| ProgramError::from(ShineUsersError::InvalidLoginGuardResponse))?;
require_keys_eq!(*login_guard_program.key, login_guard_program_id, ShineUsersError::InvalidLoginGuardResponse);
let mut data = Vec::with_capacity(1 + 4 + login.len());
data.push(LOGIN_GUARD_IX_CLASSIFY_LOGIN);
data.extend_from_slice(&(login.len() as u32).to_le_bytes());
data.extend_from_slice(login.as_bytes());
let ix = Instruction { program_id: login_guard_program_id, accounts: vec![], data };
invoke(&ix, &[login_guard_program.clone()])?;
let (program_id, raw) = get_return_data().ok_or(ProgramError::from(ShineUsersError::InvalidLoginGuardResponse))?;
require_keys_eq!(program_id, login_guard_program_id, ShineUsersError::InvalidLoginGuardResponse);
require!(raw.len() == 4, ShineUsersError::InvalidLoginGuardResponse);
let class = u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]);
match class {
0 => Ok(()),
1 => Err(ProgramError::from(ShineUsersError::PremiumLogin)),
2 => Err(ProgramError::from(ShineUsersError::TrademarkLoginRequiresReview)),
_ => Err(ProgramError::from(ShineUsersError::InvalidLoginGuardResponse)),
}
}
fn serialize_users_economy_config(state: &UsersEconomyConfigState) -> Vec<u8> {
let mut out = Vec::with_capacity(1 + 8 + 8 + 8);
out.push(state.version);
@@ -793,15 +754,6 @@ fn serialize_users_economy_config(state: &UsersEconomyConfigState) -> Vec<u8> {
out
}
fn serialize_promo_seller_state(state: &PromoSellerState) -> Vec<u8> {
let mut out = Vec::with_capacity(1 + 8 + 1 + 32);
out.push(state.version);
out.extend_from_slice(&state.remaining_sales.to_le_bytes());
out.push(state.min_login_length);
out.extend_from_slice(state.signer_pubkey.as_ref());
out
}
fn validate_users_economy_config_pda(program_id: &Pubkey, pda: &AccountInfo) -> ProgramResult {
let (expected_pda, _) = find_users_economy_config_pda(program_id);
require_keys_eq!(expected_pda, *pda.key, ShineUsersError::InvalidPdaAddress);
@@ -812,7 +764,7 @@ fn validate_users_economy_config_pda(program_id: &Pubkey, pda: &AccountInfo) ->
fn read_users_economy_config(pda: &AccountInfo) -> Result<UsersEconomyConfigState, ProgramError> {
let raw = read_pda_all(pda)?;
require!(!raw.is_empty(), ShineUsersError::EmptyPdaData);
require!(raw.len() >= 25, ShineUsersError::InvalidAccountData);
require!(raw.len() >= 25 && raw[0] == 1, ShineUsersError::InvalidAccountData);
Ok(UsersEconomyConfigState {
version: raw[0],
registration_fee_lamports: u64::from_le_bytes(raw[1..9].try_into().unwrap()),
@@ -821,19 +773,6 @@ fn read_users_economy_config(pda: &AccountInfo) -> Result<UsersEconomyConfigStat
})
}
fn read_promo_seller_state(pda: &AccountInfo) -> Result<PromoSellerState, ProgramError> {
let raw = read_pda_all(pda)?;
require!(!raw.is_empty(), ShineUsersError::PromoSellerNotFound);
require!(raw.len() >= 42, ShineUsersError::InvalidPromoSellerState);
let signer_pubkey = Pubkey::new_from_array(raw[10..42].try_into().map_err(|_| ProgramError::from(ShineUsersError::InvalidPromoSellerState))?);
Ok(PromoSellerState {
version: raw[0],
remaining_sales: u64::from_le_bytes(raw[1..9].try_into().unwrap()),
min_login_length: raw[9],
signer_pubkey,
})
}
fn record_format_minor(raw: &[u8]) -> Result<u8, ProgramError> {
require!(raw.len() >= 9, ShineUsersError::InvalidRecordData);
require!(sol_memcmp(&raw[0..5], MAGIC, 5) == 0, ShineUsersError::InvalidRecordMagic);
@@ -1131,20 +1070,89 @@ fn le_u16(data: &[u8], offset: usize) -> Result<u16, ProgramError> {
Ok(u16::from_le_bytes([s[0], s[1]]))
}
fn build_promo_sign_message(login: &str) -> String {
let mut message = String::with_capacity(settings::PROMO_SIGN_PREFIX.len() + login.len());
message.push_str(settings::PROMO_SIGN_PREFIX);
message.push_str(login);
message
}
fn validate_login(login: &str) -> ProgramResult {
require!(!login.is_empty(), ShineUsersError::InvalidLogin);
require!(login.len() <= 20, ShineUsersError::InvalidLogin);
for ch in login.chars() { if !(ch.is_ascii_alphabetic() || ch.is_ascii_digit() || ch == '_') { return Err(ProgramError::from(ShineUsersError::InvalidLogin)); } }
fn validate_legacy_login(value: &str) -> ProgramResult {
require!(!value.is_empty() && value.len() <= 20 && value.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_'), ShineUsersError::InvalidLogin);
Ok(())
}
fn login_seed_normalized(login: &str) -> String { login.to_ascii_lowercase() }
fn validate_namespace_name(value: &str) -> ProgramResult {
require!(!value.is_empty() && value.len() <= 29, ShineUsersError::InvalidNamespace);
require!(value.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'), ShineUsersError::InvalidNamespace);
Ok(())
}
fn validate_full_login(login: &str) -> Result<&str, ProgramError> {
require!(login.len() <= 30, ShineUsersError::InvalidLogin);
let (local, namespace) = login.split_once('@').ok_or(ShineUsersError::InvalidLogin)?;
validate_namespace_name(namespace)?;
require!(!local.is_empty(), ShineUsersError::InvalidLogin);
require!(local.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'), ShineUsersError::InvalidLogin);
Ok(namespace)
}
pub fn validate_namespace_state(state: &NamespaceState) -> ProgramResult {
validate_namespace_name(&state.namespace)?;
require!(state.namespace.len() + 1 + state.min_localpart_len as usize <= 30 && state.min_localpart_len > 0, ShineUsersError::InvalidNamespace);
match state.namespace_type {
1 => require!(state.registrar_pubkey.is_none() && state.server_login.is_none(), ShineUsersError::InvalidNamespace),
2 => {
require!(state.registrar_pubkey.is_some(), ShineUsersError::InvalidNamespace);
validate_full_login(state.server_login.as_deref().ok_or(ShineUsersError::InvalidNamespace)?)?;
},
_ => return Err(ShineUsersError::InvalidNamespace.into()),
}
Ok(())
}
pub fn serialize_namespace(state: &NamespaceState) -> Vec<u8> {
let mut out = vec![1, 0, state.namespace_type, state.min_localpart_len, state.namespace.len() as u8];
out.extend_from_slice(state.namespace.as_bytes());
out.extend_from_slice(&state.registration_fee.to_le_bytes());
if let (Some(registrar), Some(server)) = (state.registrar_pubkey, state.server_login.as_ref()) {
out.extend_from_slice(registrar.as_ref());
out.push(server.len() as u8);
out.extend_from_slice(server.as_bytes());
}
out
}
fn read_namespace(program_id: &Pubkey, ai: &AccountInfo, name: &str) -> Result<NamespaceState, ProgramError> {
let expected = find_namespace_pda(program_id, name).0;
require_keys_eq!(expected, *ai.key, ShineUsersError::InvalidPdaAddress);
require!(ai.owner == program_id, ShineUsersError::InvalidAccountOwner);
let data = ai.try_borrow_data()?;
let mut r = Reader::new(&data);
require!(r.read_u8()? == 1 && r.read_u8()? == 0, ShineUsersError::InvalidNamespace);
let namespace_type = r.read_u8()?;
let min_localpart_len = r.read_u8()?;
let namespace = r.read_string_u8()?;
let registration_fee = r.read_u64()?;
let (registrar_pubkey, server_login) = match namespace_type {
1 => (None, None),
2 => (Some(r.read_pubkey()?), Some(r.read_string_u8()?)),
_ => return Err(ShineUsersError::InvalidNamespace.into()),
};
r.finish()?;
let state = NamespaceState { namespace_type, min_localpart_len, namespace, registration_fee, registrar_pubkey, server_login };
require!(state.namespace == name, ShineUsersError::InvalidNamespace);
validate_namespace_state(&state)?;
Ok(state)
}
pub fn certificate_inner_message(login: &str, root: &Pubkey, blockchain: &Pubkey, client: &Pubkey) -> Result<Vec<u8>, ProgramError> {
validate_full_login(login)?;
let mut msg = CERTIFICATE_DOMAIN.to_vec();
msg.extend_from_slice(&[1, 0, login.len() as u8]);
msg.extend_from_slice(login.as_bytes());
msg.extend_from_slice(root.as_ref());
msg.extend_from_slice(blockchain.as_ref());
msg.extend_from_slice(client.as_ref());
Ok(msg)
}
pub fn user_pda_seed(login: &str) -> [u8; 32] {
hash(format!("{}{}", settings::USER_PDA_SEED_PREFIX, login).as_bytes()).to_bytes()
}
fn validate_server_addresses(addresses: &[ServerAddressRecordV12]) -> ProgramResult {
require!(addresses.len() <= 1, ShineUsersError::InvalidRecordData);
@@ -1158,7 +1166,8 @@ fn validate_server_addresses(addresses: &[ServerAddressRecordV12]) -> ProgramRes
fn validate_access_servers(servers: &[String]) -> ProgramResult {
require!(servers.len() <= 1, ShineUsersError::InvalidRecordData);
for login in servers {
validate_login(login)?;
if login.contains('@') { validate_full_login(login)?; }
else { validate_legacy_login(login)?; }
}
Ok(())
}
@@ -1238,9 +1247,13 @@ fn ensure_pda_size_and_rent<'a>(pda: &AccountInfo<'a>, payer: &AccountInfo<'a>,
pda.realloc(required_len, false)
}
fn find_user_pda(program_id: &Pubkey, login: &str) -> (Pubkey, u8) { Pubkey::find_program_address(&[settings::USER_PDA_SEED_PREFIX.as_bytes(), login.as_bytes()], program_id) }
pub fn find_user_pda(program_id: &Pubkey, login: &str) -> (Pubkey, u8) { Pubkey::find_program_address(&[&user_pda_seed(login)], program_id) }
fn find_legacy_user_pda(program_id: &Pubkey, login: &str) -> (Pubkey, u8) { Pubkey::find_program_address(&[settings::USER_PDA_SEED_PREFIX.as_bytes(), login.as_bytes()], program_id) }
pub fn find_namespace_pda(program_id: &Pubkey, name: &str) -> (Pubkey, u8) {
let seed = hash(format!("{}{}", settings::NAMESPACE_PDA_SEED_PREFIX, name).as_bytes()).to_bytes();
Pubkey::find_program_address(&[&seed], program_id)
}
fn find_users_economy_config_pda(program_id: &Pubkey) -> (Pubkey, u8) { Pubkey::find_program_address(&[settings::USERS_ECONOMY_CONFIG_SEED], program_id) }
fn find_promo_seller_pda(program_id: &Pubkey, seller_login: &str) -> (Pubkey, u8) { Pubkey::find_program_address(&[settings::PROMO_SELLER_PDA_SEED_PREFIX.as_bytes(), seller_login.as_bytes()], program_id) }
fn limit_fee_lamports(limit_delta: u64, lamports_per_limit_step: u64) -> Result<u64, ProgramError> { (limit_delta / settings::LIMIT_STEP).checked_mul(lamports_per_limit_step).ok_or(ProgramError::from(ShineUsersError::MathOverflow)) }
fn pad_to_fixed_size(mut bytes: Vec<u8>, target_size: usize) -> Result<Vec<u8>, ProgramError> { require!(bytes.len() <= target_size, ShineUsersError::RecordTooLarge); bytes.resize(target_size, 0); Ok(bytes) }
@@ -2,27 +2,17 @@
pub const USER_PDA_SEED_PREFIX: &str = "user_login=";
/// Seed PDA с экономическими параметрами программы `shine_users`.
pub const USERS_ECONOMY_CONFIG_SEED: &[u8] = b"shine_users_economy_config";
/// Префикс seed для PDA продавца promo-логинов.
pub const PROMO_SELLER_PDA_SEED_PREFIX: &str = "promo_seller=";
/// Префикс хешируемого namespace PDA seed.
pub const NAMESPACE_PDA_SEED_PREFIX: &str = "namespace=";
/// Стартовый размер PDA пользователя, дальше запись может расширяться через realloc.
pub const USER_PDA_SPACE: usize = 768;
/// Размер PDA с экономическими параметрами `shine_users`.
pub const USERS_ECONOMY_CONFIG_SPACE: usize = 32;
/// Размер PDA продавца promo-логинов.
pub const PROMO_SELLER_PDA_SPACE: usize = 64;
/// Адрес DAO authority, который имеет право обновлять economy-конфиг.
pub const DAO_AUTHORITY: &str = "aiShm43fZjm3YkMs22sYL1bpXaL3bVxv7SSraPHzVgq";
/// Адрес программы `shine_payments`, от которой вычисляется PDA inflow-вольта.
pub const SHINE_PAYMENTS_PROGRAM_ID: &str = "SHiPmXbM9Fs9khzRUW3TGKsS2W84aqaXTxs3ZkajW9v";
/// Seed inflow-вольта в программе `shine_payments`.
pub const SHINE_PAYMENTS_INFLOW_VAULT_SEED: &[u8] = b"shine_payments_inflow_vault";
/// Адрес отдельной программы проверки премиальности логина.
pub const SHINE_LOGIN_GUARD_PROGRAM_ID: &str = "SHiGxGsXGioQYCYhchQ5R7KWoxN5UjFAFsucPf6sfnh";
/// Доменный префикс для подписи promo-кода.
pub const PROMO_SIGN_PREFIX: &str = "shine_promo_v1:";
/// Стартовая комиссия регистрации (0.01 SOL) для initial economy-конфига.
pub const START_REGISTRATION_FEE_LAMPORTS: u64 = 10_000_000;
/// Шаг пополнения лимита.
@@ -0,0 +1,82 @@
#!/usr/bin/env node
// Сборщик транзакции администратора namespace. Никаких сетевых действий без --send.
// Требует npm install в shine-solana/shine; не запускайте с mainnet до проверки.
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_SEED=Buffer.from('shine_users_economy_config');
const options={};
for(let i=2;i<process.argv.length;i++){
if(!process.argv[i].startsWith('--'))throw Error('Неожиданный аргумент');
const name=process.argv[i].slice(2);
if(name==='send'){options[name]=true;continue;}
if(i+1>=process.argv.length)throw Error(`Отсутствует значение --${name}`);
options[name]=process.argv[++i];
}
function str(s){if(!s || Buffer.byteLength(s)>255)throw Error('Пустая или слишком длинная строка');return Buffer.concat([Buffer.from([Buffer.byteLength(s)]),Buffer.from(s)]);}
function key(raw){const b=new PublicKey(raw);return b;}
function accountData(type,name,minLocalLen,fee,registrar,serverLogin){
const n=Buffer.from(name);
const output=[Buffer.from([7,type,minLocalLen]),str(name),Buffer.alloc(8)];
output[2].writeBigUInt64LE(fee);
if(type===2)output.push(key(registrar).toBuffer(),str(serverLogin));
return Buffer.concat(output);
}
async function run(){
const rpc=options.rpc,secret=options.keypair,namespace=options.namespace;
if(!rpc || !secret || !namespace)throw Error('Обязательные параметры: --rpc --keypair --namespace --type --min-length --fee-lamports');
// Выбранный сценарий создаёт только localnet/devnet; никакого скрытого доступа к mainnet.
const endpoint=new URL(rpc);
if(!(['localhost','127.0.0.1'].includes(endpoint.hostname)||endpoint.hostname.endsWith('.devnet.solana.com')))
throw Error('Разрешены только localhost/127.0.0.1 и *.devnet.solana.com; production запрещён');
const type=Number(options.type),minimum=Number(options['min-length']);
const fee=BigInt(options['fee-lamports']);
if(![1,2].includes(type) || !Number.isInteger(minimum) || minimum<1 || minimum+1+namespace.length>30 || fee<0n || fee>0xffffffffffffffffn)
throw Error('Некорректные тип, длина или цена');
if(!/^[a-z0-9_]+$/.test(namespace))throw Error('namespace может содержать только lowercase a-z0-9_');
if(type===2 && (!options.registrar || !/^[a-z0-9_]+@[a-z0-9_]+$/.test(options.server)))throw Error('Для type=2 нужны --registrar и --server');
if(type===1 && (options.registrar || options.server))throw Error('type=1 не поддерживает регистратор/сервер');
const bytes=JSON.parse(readFileSync(secret,'utf8'));
const wallet=Keypair.fromSecretKey(Uint8Array.from(bytes));
const seed=createHash('sha256').update('namespace='+namespace).digest();
const [pda,bump]=PublicKey.findProgramAddressSync([seed],PROGRAM_ID);
const [economy]=PublicKey.findProgramAddressSync([ECONOMY_SEED],PROGRAM_ID);
const connection=new Connection(rpc,'confirmed');
const executable=await connection.getAccountInfo(PROGRAM_ID,'confirmed');
if(!executable || !executable.executable || !executable.owner.equals(new PublicKey('BPFLoaderUpgradeab1e11111111111111111111111')))
throw Error('Программа не является upgradeable Program');
const programdata=new PublicKey(executable.data.subarray(4,36));
const pd=await connection.getAccountInfo(programdata,'confirmed');
if(!pd || 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('Указанный signer не является текущей upgrade authority');
const economyInfo=await connection.getAccountInfo(economy,'confirmed');
if(!economyInfo || !economyInfo.owner.equals(PROGRAM_ID))throw Error('Сначала инициализируйте economy PDA');
const payload=accountData(type,namespace,minimum,fee,options.registrar,options.server);
const serverPda=type===2?PublicKey.findProgramAddressSync([
createHash('sha256').update('user_login='+options.server).digest()],PROGRAM_ID)[0]:null;
if(serverPda){
const registered=await connection.getAccountInfo(serverPda,'confirmed');
if(!registered || !registered.owner.equals(PROGRAM_ID))throw Error('У сервера доступа отсутствует реальный PDA 1.2');
}
const instruction=new TransactionInstruction({programId:PROGRAM_ID,keys:[
{pubkey:wallet.publicKey,isSigner:true,isWritable:true},
{pubkey:pda,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},
...(serverPda?[{pubkey:serverPda,isSigner:false,isWritable:false}]:[]),
],data:payload});
console.log(JSON.stringify({namespace,type,minimum,fee:fee.toString(),pda:pda.toBase58(),bump,economy:economy.toBase58(),programdata:programdata.toBase58(),mode:options.send?'SEND':'DRY-RUN'},null,2));
if(!options.send)return;
const signature=await sendAndConfirmTransaction(connection,new Transaction().add(instruction),[wallet],{commitment:'confirmed'});
console.log('Подтверждённая devnet/localnet транзакция:',signature);
const state=await connection.getAccountInfo(pda,'confirmed');
if(!state)throw Error('После транзакции namespace отсутствует');
console.log('Считанный PDA:',decodeNamespace(state.data));
}
run().catch(err=>{console.error('Ошибка создания namespace:',err.message);process.exitCode=1;});
@@ -0,0 +1,36 @@
#!/usr/bin/env node
import { readFileSync } from 'node:fs';
// Автономный декодер namespace 1.0 (без RPC и внешних пакетов).
export function decodeNamespace(data) {
const b=Buffer.from(data);
if(b.length<13) throw Error('namespace: payload слишком короткий');
if(b[0]!==1 || b[1]!==0) throw Error('namespace: неизвестная версия');
const type=b[2],minLocalLen=b[3],len=b[4];
if(type!==1 && type!==2)throw Error('namespace: неверный тип');
if(!len || !minLocalLen || len+1+minLocalLen>30) throw Error('namespace: некорректная длина');
let p=5;
if(p+len+8>b.length)throw Error('namespace: обрезанные поля');
const name=b.subarray(p,p+len).toString('utf8');p+=len;
if(!/^[a-z0-9_]+$/.test(name) || Buffer.byteLength(name)!==len) throw Error('namespace: некорректное название');
const fee=b.readBigUInt64LE(p).toString();p+=8;
let registrar=null,serverLogin=null;
if(type===2){
if(p+33>b.length)throw Error('namespace: отсутствуют ключ и логин сервера');
registrar=b.subarray(p,p+32).toString('hex');p+=32;
const serverLen=b[p++];
if(p+serverLen>b.length)throw Error('namespace: обрезан логин сервера');
serverLogin=b.subarray(p,p+serverLen).toString('utf8');p+=serverLen;
if(!/^[a-z0-9_]+@[a-z0-9_]+$/.test(serverLogin) || Buffer.byteLength(serverLogin)>30)throw Error('namespace: неверный логин сервера');
}
if(p!==b.length) throw Error('namespace: лишние байты запрещены');
return {major:1,minor:0,type,minLocalLen,name,registrationFeeLamports:fee,registrarPubkeyHex:registrar,serverLogin};
}
if(process.argv[1]?.endsWith('decode-namespace.mjs')){
const data=process.argv[2];
if(!data || !/^(?:[\da-fA-F]{2})+$/.test(data)){
console.error('Использование: node decode-namespace.mjs <hex-данные-аккаунта>');process.exit(2);
}
try{console.log(JSON.stringify(decodeNamespace(Buffer.from(data,'hex')),null,2));}
catch(e){console.error(e.message);process.exit(1);}
}
+100
View File
@@ -0,0 +1,100 @@
{
"version": 1,
"program_id": "SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6",
"test_key_notice": "FIXTURES ONLY, never use these deterministic seeds for real accounts",
"email_input": " Alice.Example+Tag@Example.COM ",
"normalized_email": "alice.example+tag@example.com",
"email_sha256_hex": "cbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956",
"public_keys_hex": {
"root": "03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8",
"blockchain": "29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7",
"client": "2543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d",
"registrar": "174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd5"
},
"users": [
{
"login": "alice@shine",
"valid": true,
"user_seed_hex": "b82963883026329da3289e9f103a3c8883ed8ecfc4c31d9c3118a2650a00342a",
"user_pda": "Fj61xHrbqCeWq5LiX3PnUgyuwemVNx1ydo5c7oy99Tzo",
"bump": 255
},
{
"login": "bob@free",
"valid": true,
"user_seed_hex": "316a2f8889e56e583350d02227c14a7ce0d0e9475d05fd11918fb48fdcfa6c4b",
"user_pda": "CYQTXWaTiEjBvg9eMcRuJYoRSgEY6YupCKnmqdEAoepD",
"bump": 253
},
{
"login": "a_b@shine",
"valid": true,
"user_seed_hex": "7bb903c31cd612026cf8afde3b26f8124ddb08969349c1c6f8830bf33323b51e",
"user_pda": "AJBuEQNYLYJJYn1NLV9CDe1YNyvNrYoGjrr9zzwxFUDr",
"bump": 253
},
{
"login": "a@shine",
"valid": true,
"user_seed_hex": "8ee3fb297bc57ae5669f3b9c94a4d4cc3a97a1c334ecdadd94375dd1a6848190",
"user_pda": "Aez41BW2iKLo2DNYQdF4hcx22G2xhtdrU2HnH7Fg4mZx",
"bump": 255
},
{
"login": "aaaaaaaaaaaaaaaaaaaaaaaa@shine",
"valid": true,
"user_seed_hex": "ed5c0130230c3fa9c19bfe133b88ed767bfcbd60cf37461ecb3d65676af97c9f",
"user_pda": "HXtFs2maytc7s6w62y7gprGKJvMt3aR7ErWQUqYwzE3X",
"bump": 254
},
{
"login": "aaaaaaaaaaaaaaaaaaaaaaaaa@shine",
"valid": false,
"user_seed_hex": "a0d506d1619b55f61af17454adc138bd0f60d1f667181b456b38c2716b39dd07",
"user_pda": "EwMLHtuJJ9bzCFRtu6Y2iBQXPPiN3B8Tnewp1ktjcBS4",
"bump": 255
}
],
"namespace": [
{
"name": "shine",
"type": 1,
"seed_hex": "bdb6dfbe3ba61f66e177ed92ddd85270cd653ba0b92f31d91bf94877ced616ea",
"pda": "G1QwyeTcyqBMitsTpGpbwwbCYMFqGkTiGw6trKr5baLa",
"bump": 254,
"bytes_hex": "01000103057368696e658096980000000000"
},
{
"name": "free",
"type": 2,
"seed_hex": "ceb53ebd89ee0b2663831b8a458cc7ac53a507e0a5f7b7a5766311348d829dcb",
"pda": "C4W54n5sfJfCQLwQb8bDox6JAf98YA2MMFPU2mfhefJh",
"bump": 255,
"bytes_hex": "010002030466726565404b4c0000000000174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd50f726567697374726172407368696e65"
}
],
"certificate": {
"login": "bob@free",
"inner_message_hex": "5348694e455f465245455f5245475f563100010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d",
"inner_signature_hex": "e2edfcd8b1b7a1823f56b827ddfa8a3682793e036141b526467ae346e220d08757d0a878a2f722562e6d3132ef9df04b1ab9e2f65d72bb0f48c17b7ada3e5a0a",
"payload_hex": "010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559de2edfcd8b1b7a1823f56b827ddfa8a3682793e036141b526467ae346e220d08757d0a878a2f722562e6d3132ef9df04b1ab9e2f65d72bb0f48c17b7ada3e5a0acbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956",
"identity_fields_hex": "010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d",
"dataitem_sha256_id_hex": "45ef42eda7c7e76d222ecce8a7678edb923ae63f8419ea0899701551c2466770",
"dataitem_hex": "0200a9de19b3551ace117973b80d632503bf2a55f0aa2490deb1474a280b675fa01bb2ccb5890faadcb213d3882fb21a7af13702526a569f7807b1c8b6963c0be402174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd500000300000000000000390000000000000006064170701074657374353539310274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d563100010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559de2edfcd8b1b7a1823f56b827ddfa8a3682793e036141b526467ae346e220d08757d0a878a2f722562e6d3132ef9df04b1ab9e2f65d72bb0f48c17b7ada3e5a0acbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956",
"dataitem_deep_hash_hex": "45d96dbd7e4e81420f06fb591be56c80f9b5da3df647c460d1ecea37b26e6c2b0fbaaf7531cb9ed5be10d8fe224091c6",
"tags": [
[
"App",
"test5591"
],
[
"t",
"reg"
],
[
"Protocol",
"SHiNE-Free-Registration-V1"
]
]
}
}
@@ -0,0 +1,32 @@
program_id=SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6
email_hash_hex=cbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956
inner_message_hex=5348694e455f465245455f5245475f563100010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d
inner_signature_hex=e2edfcd8b1b7a1823f56b827ddfa8a3682793e036141b526467ae346e220d08757d0a878a2f722562e6d3132ef9df04b1ab9e2f65d72bb0f48c17b7ada3e5a0a
registrar_pubkey_hex=174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd5
ans104_id_hex=45ef42eda7c7e76d222ecce8a7678edb923ae63f8419ea0899701551c2466770
user_alice_shine_seed=b82963883026329da3289e9f103a3c8883ed8ecfc4c31d9c3118a2650a00342a
user_alice_shine_pda=Fj61xHrbqCeWq5LiX3PnUgyuwemVNx1ydo5c7oy99Tzo
user_alice_shine_bump=255
user_bob_free_seed=316a2f8889e56e583350d02227c14a7ce0d0e9475d05fd11918fb48fdcfa6c4b
user_bob_free_pda=CYQTXWaTiEjBvg9eMcRuJYoRSgEY6YupCKnmqdEAoepD
user_bob_free_bump=253
user_a_underscore_b_shine_seed=7bb903c31cd612026cf8afde3b26f8124ddb08969349c1c6f8830bf33323b51e
user_a_underscore_b_shine_pda=AJBuEQNYLYJJYn1NLV9CDe1YNyvNrYoGjrr9zzwxFUDr
user_a_underscore_b_shine_bump=253
user_a_shine_seed=8ee3fb297bc57ae5669f3b9c94a4d4cc3a97a1c334ecdadd94375dd1a6848190
user_a_shine_pda=Aez41BW2iKLo2DNYQdF4hcx22G2xhtdrU2HnH7Fg4mZx
user_a_shine_bump=255
user_aaaaaaaaaaaaaaaaaaaaaaaa_shine_seed=ed5c0130230c3fa9c19bfe133b88ed767bfcbd60cf37461ecb3d65676af97c9f
user_aaaaaaaaaaaaaaaaaaaaaaaa_shine_pda=HXtFs2maytc7s6w62y7gprGKJvMt3aR7ErWQUqYwzE3X
user_aaaaaaaaaaaaaaaaaaaaaaaa_shine_bump=254
user_aaaaaaaaaaaaaaaaaaaaaaaaa_shine_seed=a0d506d1619b55f61af17454adc138bd0f60d1f667181b456b38c2716b39dd07
user_aaaaaaaaaaaaaaaaaaaaaaaaa_shine_pda=EwMLHtuJJ9bzCFRtu6Y2iBQXPPiN3B8Tnewp1ktjcBS4
user_aaaaaaaaaaaaaaaaaaaaaaaaa_shine_bump=255
namespace_shine_seed=bdb6dfbe3ba61f66e177ed92ddd85270cd653ba0b92f31d91bf94877ced616ea
namespace_shine_pda=G1QwyeTcyqBMitsTpGpbwwbCYMFqGkTiGw6trKr5baLa
namespace_shine_bump=254
namespace_shine_bytes_hex=01000103057368696e658096980000000000
namespace_free_seed=ceb53ebd89ee0b2663831b8a458cc7ac53a507e0a5f7b7a5766311348d829dcb
namespace_free_pda=C4W54n5sfJfCQLwQb8bDox6JAf98YA2MMFPU2mfhefJh
namespace_free_bump=255
namespace_free_bytes_hex=010002030466726565404b4c0000000000174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd50f726567697374726172407368696e65
@@ -0,0 +1,75 @@
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.*;
import java.security.spec.*;
import java.util.*;
/** Автономная проверка Rust/Java/JS фикстур; не зависит от Solana SDK и сетевого RPC. */
public final class RegistrationV2VectorsCheck {
private static final BigInteger P=BigInteger.ONE.shiftLeft(255).subtract(BigInteger.valueOf(19));
private static final BigInteger D=BigInteger.valueOf(-121665).multiply(BigInteger.valueOf(121666).modInverse(P)).mod(P);
private static final String B58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
private static byte[] utf8(String s){return s.getBytes(StandardCharsets.UTF_8);}
private static byte[] sha(byte[] b){try{return MessageDigest.getInstance("SHA-256").digest(b);}catch(Exception e){throw new IllegalStateException(e);}}
private static byte[] join(byte[]... array){int n=0;for(var a:array)n+=a.length;byte[] out=new byte[n];int i=0;for(var a:array){System.arraycopy(a,0,out,i,a.length);i+=a.length;}return out;}
private static String hex(byte[] b){return HexFormat.of().formatHex(b);}
private static byte[] fromHex(String s){return HexFormat.of().parseHex(s);}
private static byte[] base58decode(String text){
BigInteger n=BigInteger.ZERO, b=BigInteger.valueOf(58);
for(char c:text.toCharArray()) {int digit=B58.indexOf(c);if(digit<0)throw new IllegalArgumentException();n=n.multiply(b).add(BigInteger.valueOf(digit));}
byte[] raw=n.equals(BigInteger.ZERO)?new byte[0]:n.toByteArray();if(raw.length>0 && raw[0]==0)raw=Arrays.copyOfRange(raw,1,raw.length);
int zero=0;while(zero<text.length() && text.charAt(zero)=='1')zero++;
return join(new byte[zero],raw);
}
private static String base58encode(byte[] raw){
BigInteger n=new BigInteger(1,raw), b=BigInteger.valueOf(58);StringBuilder result=new StringBuilder();
while(n.signum()>0){BigInteger[] div=n.divideAndRemainder(b);result.append(B58.charAt(div[1].intValue()));n=div[0];}
int zero=0;while(zero<raw.length && raw[zero]==0)zero++;for(int i=0;i<zero;i++)result.append('1');
return result.reverse().toString();
}
private static boolean onCurve(byte[] raw){
byte[] ybytes=Arrays.copyOf(raw,32);int sign=(ybytes[31]&0xff)>>7;ybytes[31]&=127;
for(int i=0;i<16;i++){byte x=ybytes[i];ybytes[i]=ybytes[31-i];ybytes[31-i]=x;}
BigInteger y=new BigInteger(1,ybytes);if(y.compareTo(P)>=0)return false;
BigInteger yy=y.multiply(y).mod(P);
BigInteger xx=yy.subtract(BigInteger.ONE).multiply(D.multiply(yy).add(BigInteger.ONE).mod(P).modInverse(P)).mod(P);
if(xx.equals(BigInteger.ZERO))return sign==0;
return xx.modPow(P.subtract(BigInteger.ONE).shiftRight(1),P).equals(BigInteger.ONE);
}
private static String[] pda(byte[] seed,byte[] program){
for(int bump=255;bump>=0;bump--){byte[] bytes=sha(join(seed,new byte[]{(byte)bump},program,utf8("ProgramDerivedAddress")));
if(!onCurve(bytes))return new String[]{base58encode(bytes),Integer.toString(bump)};}
throw new IllegalStateException("PDA unavailable");
}
private static void check(boolean condition,String text){if(!condition)throw new AssertionError(text);}
public static void main(String[] argv)throws Exception{
Path path=argv.length>0?Path.of(argv[0]):Path.of("tests/fixtures/registration-v2.properties");
Properties props=new Properties();try(var reader=Files.newBufferedReader(path)){props.load(reader);}
byte[] program=base58decode(props.getProperty("program_id"));check(program.length==32,"program id");
for(String name:List.of("alice@shine","bob@free","a_b@shine","a@shine","aaaaaaaaaaaaaaaaaaaaaaaa@shine","aaaaaaaaaaaaaaaaaaaaaaaaa@shine")){
String key=name.replace("a_b","a_underscore_b").replace('@','_');
byte[] seed=sha(utf8("user_login="+name));check(hex(seed).equals(props.getProperty("user_"+key+"_seed")),"seed " + name);
String[] result=pda(seed,program);
check(result[0].equals(props.getProperty("user_"+key+"_pda")),"user pda " + name);
check(result[1].equals(props.getProperty("user_"+key+"_bump")),"user bump " + name);
}
for(String name:List.of("shine","free")){
byte[] seed=sha(utf8("namespace="+name));
check(hex(seed).equals(props.getProperty("namespace_"+name+"_seed")),"namespace seed");
String[] result=pda(seed,program);
check(result[0].equals(props.getProperty("namespace_"+name+"_pda")),"namespace pda");
check(result[1].equals(props.getProperty("namespace_"+name+"_bump")),"namespace bump");
}
byte[] raw=fromHex(props.getProperty("registrar_pubkey_hex"));
byte[] der=join(fromHex("302a300506032b6570032100"),raw);
PublicKey signer=KeyFactory.getInstance("Ed25519").generatePublic(new X509EncodedKeySpec(der));
byte[] msg=fromHex(props.getProperty("inner_message_hex")),signature=fromHex(props.getProperty("inner_signature_hex"));
Signature verifier=Signature.getInstance("Ed25519");verifier.initVerify(signer);verifier.update(msg);
check(verifier.verify(signature),"inner signature");
byte[] bad=msg.clone();bad[bad.length-1]^=1;
verifier.initVerify(signer);verifier.update(bad);check(!verifier.verify(signature),"tamper should fail");
check(hex(sha(utf8("alice.example+tag@example.com"))).equals(props.getProperty("email_hash_hex")),"email hash");
System.out.println("OK: SHA-256 + user/namespace PDA + Ed25519 + email vector");
}
}
@@ -0,0 +1,32 @@
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 vec=JSON.parse(readFileSync(new URL('./fixtures/registration-v2.json',import.meta.url)));
function throws(data,msg){assert.throws(()=>decodeNamespace(data),msg);}
test('Декодирование paid/free namespaces',()=>{
const shine=decodeNamespace(Buffer.from(vec.namespace[0].bytes_hex,'hex'));
const free=decodeNamespace(Buffer.from(vec.namespace[1].bytes_hex,'hex'));
assert.equal(shine.registrarPubkeyHex,null);
assert.equal(shine.serverLogin,null);
assert.equal(shine.registrationFeeLamports,'10000000');
assert.equal(free.serverLogin,'registrar@shine');
assert.equal(free.minLocalLen,3);
});
test('Некорректный namespace не пройдет строгий декодер',()=>{
const canonical=Buffer.from(vec.namespace[1].bytes_hex,'hex');
for(const index of [0,1,2,3,4]){
const bad=Buffer.from(canonical);bad[index]=index===1?1:0;
throws(bad);
}
throws(canonical.subarray(0,-1));
throws(Buffer.concat([canonical,Buffer.from([0])]));
const bad=Buffer.from(canonical);
bad[5]='F'.charCodeAt(0);
throws(bad);
});
test('Некорректный server login отвергается',()=>{
const canonical=Buffer.from(vec.namespace[1].bytes_hex,'hex');
const bad=Buffer.from(canonical);bad[bad.length-1]='@'.charCodeAt(0);
throws(bad);
});
@@ -0,0 +1,110 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { createHash, createPublicKey, verify } from 'node:crypto';
// Полностью автономные тесты: не требуют RPC, приватных ключей и npm install.
const vectors = JSON.parse(readFileSync(new URL('./fixtures/registration-v2.json', import.meta.url), 'utf8'));
const hash = data => createHash('sha256').update(data).digest();
const hash384 = data => createHash('sha384').update(data).digest();
const pubkeyFromRaw = hex => createPublicKey({key: Buffer.concat([Buffer.from('302a300506032b6570032100','hex'),Buffer.from(hex,'hex')]),format:'der',type:'spki'});
const b58abc = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
function decode58(text) {
let v=0n;
for (const char of text) { const n=b58abc.indexOf(char);assert.ok(n>=0);v=v*58n+BigInt(n); }
let b=[];
while(v>0n){b.unshift(Number(v%256n));v/=256n;}
return Buffer.concat([Buffer.alloc((text.match(/^1*/)?.[0]||'').length),Buffer.from(b)]);
}
function encode58(bytes) {
let value=BigInt('0x'+bytes.toString('hex'));let result='';
while(value>0n){result=b58abc[Number(value%58n)]+result;value/=58n;}
return '1'.repeat(bytes.findIndex(byte=>byte!==0)<0?bytes.length:bytes.findIndex(byte=>byte!==0))+result;
}
const p=(1n<<255n)-19n;
function mod(a){return (a%p+p)%p;}
function pow(a,n){let result=1n;while(n>0n){if(n&1n)result=mod(result*a);a=mod(a*a);n>>=1n;}return result;}
const d=mod(-121665n*pow(121666n,p-2n));
function onCurve(bytes) {
const copy=Buffer.from(bytes),sign=copy[31]>>7;copy[31]&=127;
let y=0n;for(let i=31;i>=0;i--)y=y*256n+BigInt(copy[i]);
if(y>=p)return false;
const yy=mod(y*y), xx=mod((yy-1n)*pow(d*yy+1n,p-2n));
return xx===0n ? sign===0 : pow(xx,(p-1n)/2n)===1n;
}
function address(prefix, name) {
const seed=hash(Buffer.from(prefix+name));
const program=decode58(vectors.program_id);
assert.equal(program.length,32);
for(let bump=255;bump>=0;bump--){
const a=hash(Buffer.concat([seed,Buffer.from([bump]),program,Buffer.from('ProgramDerivedAddress')]));
if(!onCurve(a))return {seed:seed.toString('hex'),pda:encode58(a),bump};
}
throw Error('PDA was not found');
}
function deepHash(item){
if(Buffer.isBuffer(item))return hash384(Buffer.concat([hash384(Buffer.from('blob'+item.length)),hash384(item)]));
let acc=hash384(Buffer.from('list'+item.length));
for(const child of item)acc=hash384(Buffer.concat([acc,deepHash(child)]));
return acc;
}
test('Одинаковые SHA-256 и PDA для всех пользователей',()=>{
for(const u of vectors.users){
const actual=address('user_login=',u.login);
assert.deepEqual(actual,{seed:u.user_seed_hex,pda:u.user_pda,bump:u.bump});
assert.equal(u.valid,u.login.length<=30);
}
});
test('Два PDA namespace отличаются от пользовательских',()=>{
for(const ns of vectors.namespace){
assert.deepEqual(address('namespace=',ns.name),{seed:ns.seed_hex,pda:ns.pda,bump:ns.bump});
assert.notEqual(ns.pda,address('user_login=',ns.name).pda);
}
});
test('namespace-PDA строгая раскладка и округления нет',()=>{
for(const ns of vectors.namespace){
const b=Buffer.from(ns.bytes_hex,'hex'),name=b.subarray(5,5+b[4]).toString();
assert.equal(b[0],1);assert.equal(b[1],0);assert.equal(b[2],ns.type);assert.equal(name,ns.name);
const offset=5+b[4],fee=b.readBigUInt64LE(offset);
assert.equal(fee,BigInt(ns.type===1?10_000_000:5_000_000));
if(ns.type===2){assert.equal(b.subarray(offset+8,offset+40).toString('hex'),vectors.public_keys_hex.registrar);}
assert.equal(b.length,ns.type===1?5+ns.name.length+8:5+ns.name.length+8+32+1+'registrar@shine'.length);
}
});
test('Внутренняя подпись защищает имя и все три публичных ключа',()=>{
const c=vectors.certificate,msg=Buffer.from(c.inner_message_hex,'hex'),sign=Buffer.from(c.inner_signature_hex,'hex');
const key=pubkeyFromRaw(vectors.public_keys_hex.registrar);
assert.ok(verify(null,msg,key,sign));
assert.equal(msg.subarray(0,18).toString('hex'),Buffer.from('SHiNE_FREE_REG_V1\0').toString('hex'));
for(const idx of [18,21,21+c.login.length,21+c.login.length+32,21+c.login.length+64]){
const bad=Buffer.from(msg);bad[idx]^=1;
assert.equal(verify(null,bad,key,sign),false);
}
});
test('Email-хеш стоит после внутренней подписи',()=>{
const c=vectors.certificate,payload=Buffer.from(c.payload_hex,'hex');
assert.equal(hash(Buffer.from(vectors.normalized_email)).toString('hex'),vectors.email_sha256_hex);
assert.equal(payload.subarray(-32).toString('hex'),vectors.email_sha256_hex);
assert.equal(payload.subarray(0,-96).toString('hex'),c.identity_fields_hex);
assert.equal(payload.subarray(-96,-32).toString('hex'),c.inner_signature_hex);
});
test('ANS-104 подпись защищает email и теги, ID фиксирован',()=>{
const item=Buffer.from(vectors.certificate.dataitem_hex,'hex'),key=pubkeyFromRaw(vectors.public_keys_hex.registrar);
assert.equal(item.readUInt16LE(0),2);
const sign=item.subarray(2,66),owner=item.subarray(66,98);
assert.equal(owner.toString('hex'),vectors.public_keys_hex.registrar);
assert.equal(item[98],0);assert.equal(item[99],0);
const count=Number(item.readBigUInt64LE(100)),size=Number(item.readBigUInt64LE(108));
assert.equal(count,3);
const tags=item.subarray(116,116+size),data=item.subarray(116+size);
assert.equal(data.toString('hex'),vectors.certificate.payload_hex);
const msg=deepHash([Buffer.from('dataitem'),Buffer.from('1'),Buffer.from('2'),owner,Buffer.alloc(0),Buffer.alloc(0),tags,data]);
assert.equal(msg.toString('hex'),vectors.certificate.dataitem_deep_hash_hex);
assert.equal(hash(sign).toString('hex'),vectors.certificate.dataitem_sha256_id_hex);
assert.ok(verify(null,msg,key,sign));
let changed=Buffer.from(data);changed[changed.length-1]^=1;
assert.equal(verify(null,deepHash([Buffer.from('dataitem'),Buffer.from('1'),Buffer.from('2'),owner,Buffer.alloc(0),Buffer.alloc(0),tags,changed]),key,sign),false);
changed=Buffer.from(tags);changed[0]^=1;
assert.equal(verify(null,deepHash([Buffer.from('dataitem'),Buffer.from('1'),Buffer.from('2'),owner,Buffer.alloc(0),Buffer.alloc(0),changed,data]),key,sign),false);
});
@@ -0,0 +1,59 @@
//! Общие зафиксированные Rust/Java/JS фикстуры. Запуск: cargo test --test registration_v2_vectors.
use std::str::FromStr;
use solana_program::{hash::hash, pubkey::Pubkey};
use shine_users::{certificate_inner_message, find_namespace_pda, find_user_pda, serialize_namespace, user_pda_seed, NamespaceState};
fn fixture(key: &str) -> String {
include_str!("fixtures/registration-v2.properties").lines()
.find_map(|line| line.split_once('=').filter(|(name,_)| *name==key).map(|(_,value)| value.to_string()))
.expect("ключ тест-вектора")
}
fn decode_hex(text: &str) -> Vec<u8> {
assert_eq!(text.len()%2,0);
(0..text.len()).step_by(2).map(|i| u8::from_str_radix(&text[i..i+2],16).unwrap()).collect()
}
fn encode_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{:02x}",b)).collect()
}
#[test]
fn user_pdas_match_portable_vectors() {
let program=Pubkey::from_str(&fixture("program_id")).unwrap();
for (login,key) in [
("alice@shine","alice_shine"), ("bob@free","bob_free"),
("a_b@shine","a_underscore_b_shine"), ("a@shine","a_shine"),
("aaaaaaaaaaaaaaaaaaaaaaaa@shine","aaaaaaaaaaaaaaaaaaaaaaaa_shine"),
("aaaaaaaaaaaaaaaaaaaaaaaaa@shine","aaaaaaaaaaaaaaaaaaaaaaaaa_shine")
] {
assert_eq!(encode_hex(&user_pda_seed(login)),fixture(&format!("user_{key}_seed")));
let (pda,bump)=find_user_pda(&program,login);
assert_eq!(pda.to_string(),fixture(&format!("user_{key}_pda")));
assert_eq!(bump.to_string(),fixture(&format!("user_{key}_bump")));
}
}
#[test]
fn namespace_pdas_and_binaries_match_vectors() {
let program=Pubkey::from_str(&fixture("program_id")).unwrap();
for (name,typ,fee) in [("shine",1,10_000_000), ("free",2,5_000_000)] {
let (pda,bump)=find_namespace_pda(&program,name);
assert_eq!(pda.to_string(),fixture(&format!("namespace_{name}_pda")));
assert_eq!(bump.to_string(),fixture(&format!("namespace_{name}_bump")));
assert_eq!(encode_hex(hash(format!("namespace={name}").as_bytes()).as_ref()),fixture(&format!("namespace_{name}_seed")));
let registrar=if typ==2 {Some(Pubkey::new_from_array(decode_hex(&fixture("registrar_pubkey_hex")).try_into().unwrap()))}else{None};
let state=NamespaceState {namespace_type:typ,min_localpart_len:3,namespace:name.to_string(),registration_fee:fee,registrar_pubkey:registrar,server_login:if typ==2{Some("registrar@shine".to_string())}else{None}};
assert_eq!(encode_hex(&serialize_namespace(&state)),fixture(&format!("namespace_{name}_bytes_hex")));
}
}
#[test]
fn free_certificate_inner_message_matches_vector() {
let msg=decode_hex(&fixture("inner_message_hex"));
assert!(msg.starts_with(b"SHiNE_FREE_REG_V1\0"));
assert_eq!(msg[18],1);
assert_eq!(msg[19],0);
assert_eq!(msg[20],8);
assert_eq!(&msg[21..29],b"bob@free");
let message=certificate_inner_message("bob@free",
&Pubkey::new_from_array(msg[29..61].try_into().unwrap()),
&Pubkey::new_from_array(msg[61..93].try_into().unwrap()),
&Pubkey::new_from_array(msg[93..125].try_into().unwrap())).unwrap();
assert_eq!(message,msg);
}