use solana_program::{ account_info::{next_account_info, AccountInfo}, clock::Clock, entrypoint, entrypoint::ProgramResult, hash::{hash, hashv}, bpf_loader_upgradeable, program::{invoke, invoke_signed}, program_error::ProgramError, program_memory::sol_memcmp, pubkey::Pubkey, rent::Rent, system_instruction, system_program, sysvar::{instructions::{load_current_index_checked, load_instruction_at_checked}, Sysvar}, }; use std::{convert::TryFrom, str::FromStr}; use anchor_lang::AccountDeserialize; use pyth_solana_receiver_sdk::price_update::{get_feed_id_from_hex, PriceUpdateV2}; pub mod settings; solana_program::declare_id!("SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6"); entrypoint!(process_instruction); const MAGIC: &[u8; 5] = b"SHiNE"; const FORMAT_MAJOR: u8 = 1; const FORMAT_MINOR: u8 = 3; const PREVIOUS_FORMAT_MINOR: u8 = 2; const LEGACY_FORMAT_MINOR: u8 = 0; const MAX_AUTO_REALLOC_INCREASE: usize = 10_000; const ZERO_HASH: [u8; 32] = [0; 32]; const BLOCK_TYPE_ROOT_KEY: u8 = 1; const BLOCK_TYPE_CLIENT_KEY: u8 = 2; const BLOCK_TYPE_BLOCKCHAIN_REGISTRY: u8 = 3; const BLOCK_TYPE_SERVER_PROFILE: u8 = 30; const BLOCK_TYPE_ACCESS_SERVERS: u8 = 40; const BLOCK_VERSION_0: u8 = 0; const AUTH_MODE_ROOT: u8 = 1; const DAY_MS: u64 = 86_400_000; const FORK_COOLDOWN_MS: u64 = 3 * DAY_MS; const MAX_CLIENT_CLOCK_SKEW_MS: u64 = 5 * 60 * 1000; 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_CLOSE_LEGACY_USER_PDA: u8 = 6; const IX_CREATE_NAMESPACE: u8 = 7; const IX_UPDATE_NAMESPACE_PRICE: u8 = 8; const IX_SUPPORT_USER: u8 = 9; const IX_SUPPORT_DAO: u8 = 10; const SUPPORT_STATS_VERSION: u8 = 2; // ONLY Stars cents, old SOL stats rejected const SUPPORT_STATS_LEN: usize = 25; const SUPPORT_TARGET_USER: u8 = 0; const SUPPORT_TARGET_CHANNEL: u8 = 1; const SUPPORT_TARGET_MESSAGE: u8 = 2; const NAMESPACE_CURRENCY_SOL: u8 = 1; // 2 зарезервировано под USDT, пока запрещено const CERTIFICATE_DOMAIN: &[u8] = b"SHiNE_FREE_REG_V1\0"; #[repr(u32)] #[derive(Clone, Copy, Debug)] enum ShineUsersError { InvalidInstruction = 1, InvalidSigner = 2, InvalidPdaAddress = 3, UserAlreadyExists = 4, EmptyPdaData = 5, InvalidRecordData = 6, InvalidRecordMagic = 7, InvalidRecordFormat = 8, InvalidRecordLength = 9, InvalidLogin = 10, InvalidLimitIncrement = 11, InvalidFeeReceiver = 12, InvalidLoginGuardResponse = 13, PremiumLogin = 14, TrademarkLoginRequiresReview = 15, InvalidVersion = 16, InvalidPrevHash = 17, ImmutableFieldChanged = 18, BalanceDecrease = 19, InvalidSignature = 20, RecordTooLarge = 21, MathOverflow = 22, SystemAlreadyInitialized = 23, MissingRequiredSignature = 24, InvalidSystemProgram = 25, InvalidAccountOwner = 26, InvalidAccountData = 27, InvalidPromoCode = 28, PromoSellerNotFound = 29, PromoSalesExhausted = 30, PromoLoginTooShort = 31, InvalidPromoSellerState = 32, PromoSignatureMismatch = 33, ForkCooldown = 34, DuplicateBlockchainKey = 35, PaidLimitTooLarge = 36, CannotCloseCurrentFormat = 37, RootChangeRequiresRoot = 38, AmbiguousAuthorityRotation = 39, RootModeRequiresFullRotation = 40, InvalidNamespace = 41, InvalidUpgradeAuthority = 42, NamespaceAlreadyExists = 43, CertificateRequired = 44, RegistrationFeeBelowRent = 45, UnsupportedNamespaceCurrency = 46, InvalidSupport = 47, UnsupportedSupportStats = 48, InvalidStars = 49, InvalidOracle = 50, StaleOracle = 51, StarRateMismatch = 52, } impl From for ProgramError { fn from(value: ShineUsersError) -> Self { ProgramError::Custom(value as u32) } } macro_rules! require { ($cond:expr, $err:expr) => { if !($cond) { return Err(ProgramError::from($err)); } }; } macro_rules! require_keys_eq { ($left:expr, $right:expr, $err:expr) => { if $left != $right { return Err(ProgramError::from($err)); } }; } #[derive(Clone, Debug, PartialEq, Eq)] pub struct ForkRecordV12 { pub blockchain_key: Pubkey, pub created_at_ms: u64, pub paid_limit_bytes: u32, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct ServerAddressRecordV12 { pub address_format_type: u8, pub address_format_version: u8, pub address: String, } #[derive(Clone, Debug)] pub struct UserRecordV12 { pub created_at_ms: u64, pub updated_at_ms: u64, pub record_number: u32, pub prev_record_hash: [u8; 32], pub login: String, pub root_key: Pubkey, pub client_key: Pubkey, pub forks: Vec, pub server_addresses: Vec, pub access_servers: Vec, pub signature: [u8; 64], } /// Блок располагается сразу после подписанной записи и не входит в record_len. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct SupportStats { pub support_sent: u64, pub support_received: u64, pub dao_direct: u64, } #[derive(Clone, Debug)] struct SupportUserArgs { sender_login: String, recipient_login: String, amount_lamports: u64, amount_star_cents: u64, target_type: u8, channel_block_number: Option, channel_block_hash: Option<[u8; 32]>, message_block_number: Option, message_block_hash: Option<[u8; 32]>, } #[derive(Clone, Debug)] struct SupportDaoArgs { sender_login: String, amount_lamports: u64, amount_star_cents: u64 } impl UserRecordV12 { fn active_fork(&self) -> Result<&ForkRecordV12, ProgramError> { self.forks.last().ok_or(ProgramError::from(ShineUsersError::InvalidRecordData)) } } #[derive(Clone, Debug)] pub struct CreateUserPdaArgs { pub login: String, pub root_key: Pubkey, pub created_at_ms: u64, pub client_key: Pubkey, pub blockchain_key: Pubkey, pub server_addresses: Vec, pub access_servers: Vec, pub signature: [u8; 64], pub registrar_signature: Option<[u8; 64]>, } #[derive(Clone, Debug)] pub struct UpdateUserPdaArgs { pub login: String, pub root_key: Pubkey, pub updated_at_ms: u64, pub client_key: Pubkey, pub auth_mode: u8, pub new_blockchain_key: Option, pub server_addresses: Vec, pub access_servers: Vec, pub signature: [u8; 64], } #[derive(Clone, Debug)] pub struct CloseLegacyUserPdaArgs { pub login: String, } #[derive(Clone, Debug)] pub struct UpdateUsersEconomyConfigArgs { pub update_fee_lamports: u64, } #[derive(Clone, Debug)] pub struct UsersEconomyConfigState { pub version: u8, pub update_fee_lamports: u64, } #[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 currency_code: u8, pub registrar_pubkey: Option, pub server_login: Option, } struct Reader<'a> { data: &'a [u8], cursor: usize, } impl<'a> Reader<'a> { fn new(data: &'a [u8]) -> Self { Self { data, cursor: 0 } } fn read_u8(&mut self) -> Result { let v = *self.data.get(self.cursor).ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?; self.cursor += 1; Ok(v) } fn read_u16(&mut self) -> Result { let end = self.cursor.checked_add(2).ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?; let s = self.data.get(self.cursor..end).ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?; self.cursor = end; Ok(u16::from_le_bytes([s[0], s[1]])) } fn read_u32(&mut self) -> Result { let end = self.cursor.checked_add(4).ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?; let s = self.data.get(self.cursor..end).ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?; self.cursor = end; Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]])) } fn read_u64(&mut self) -> Result { let end = self.cursor.checked_add(8).ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?; let s = self.data.get(self.cursor..end).ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?; self.cursor = end; Ok(u64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]])) } fn read_fixed_32(&mut self) -> Result<[u8; 32], ProgramError> { let end = self.cursor.checked_add(32).ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?; let s = self.data.get(self.cursor..end).ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?; self.cursor = end; <[u8; 32]>::try_from(s).map_err(|_| ProgramError::from(ShineUsersError::InvalidInstruction)) } fn read_fixed_64(&mut self) -> Result<[u8; 64], ProgramError> { let end = self.cursor.checked_add(64).ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?; let s = self.data.get(self.cursor..end).ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?; self.cursor = end; <[u8; 64]>::try_from(s).map_err(|_| ProgramError::from(ShineUsersError::InvalidInstruction)) } fn read_pubkey(&mut self) -> Result { Ok(Pubkey::new_from_array(self.read_fixed_32()?)) } fn read_string_u8(&mut self) -> Result { let len = self.read_u8()? as usize; let end = self.cursor.checked_add(len).ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?; let s = self.data.get(self.cursor..end).ok_or(ProgramError::from(ShineUsersError::InvalidInstruction))?; self.cursor = end; std::str::from_utf8(s).map(|v| v.to_string()).map_err(|_| ProgramError::from(ShineUsersError::InvalidInstruction)) } fn remaining(&self) -> usize { self.data.len().saturating_sub(self.cursor) } fn finish(self) -> Result<(), ProgramError> { require!(self.cursor == self.data.len(), ShineUsersError::InvalidInstruction); Ok(()) } } fn process_instruction<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'a>], instruction_data: &[u8]) -> ProgramResult { let mut r = Reader::new(instruction_data); let tag = r.read_u8()?; match tag { IX_INIT_USERS_ECONOMY_CONFIG => { r.finish()?; process_init_users_economy_config(program_id, accounts) } IX_UPDATE_USERS_ECONOMY_CONFIG => { let args = UpdateUsersEconomyConfigArgs { update_fee_lamports: r.read_u64()?, }; r.finish()?; process_update_users_economy_config(program_id, accounts, args) } 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_SUPPORT_USER => dispatch_support_user(program_id, accounts, r), IX_SUPPORT_DAO => dispatch_support_dao(program_id, accounts, r), IX_CREATE_NAMESPACE => { let args = parse_namespace_args(&mut r)?; r.finish()?; process_create_namespace(program_id, accounts, args) }, IX_UPDATE_NAMESPACE_PRICE => { let namespace_name = r.read_string_u8()?; let currency_code = r.read_u8()?; let registration_fee = r.read_u64()?; r.finish()?; process_update_namespace_price(program_id, accounts, &namespace_name, currency_code, registration_fee) }, IX_CLOSE_LEGACY_USER_PDA => dispatch_close_legacy_user_pda(program_id, accounts, r), _ => Err(ProgramError::from(ShineUsersError::InvalidInstruction)), } } fn dispatch_support_user(program_id: &Pubkey, accounts: &[AccountInfo], mut r: Reader<'_>) -> ProgramResult { let sender_login = r.read_string_u8()?; let recipient_login = r.read_string_u8()?; let amount_lamports = r.read_u64()?; let amount_star_cents = r.read_u64()?; let target_type = r.read_u8()?; let (channel_block_number, channel_block_hash, message_block_number, message_block_hash) = match target_type { SUPPORT_TARGET_USER => (None, None, None, None), SUPPORT_TARGET_CHANNEL => (Some(r.read_u64()?), Some(r.read_fixed_32()?), None, None), SUPPORT_TARGET_MESSAGE => (Some(r.read_u64()?), Some(r.read_fixed_32()?), Some(r.read_u64()?), Some(r.read_fixed_32()?)), _ => return Err(ShineUsersError::InvalidSupport.into()), }; r.finish()?; process_support_user(program_id, accounts, SupportUserArgs { sender_login, recipient_login, amount_lamports, amount_star_cents, target_type, channel_block_number, channel_block_hash, message_block_number, message_block_hash }) } fn dispatch_support_dao(program_id: &Pubkey, accounts: &[AccountInfo], mut r: Reader<'_>) -> ProgramResult { let args = SupportDaoArgs { sender_login: r.read_string_u8()?, amount_lamports: r.read_u64()?, amount_star_cents: r.read_u64()? }; r.finish()?; process_support_dao(program_id, accounts, args) } fn dispatch_create_user_pda<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'a>], mut r: Reader<'_>) -> ProgramResult { let args = Box::new(parse_create_args(&mut r)?); r.finish()?; process_create_user_pda(program_id, accounts, args) } fn dispatch_update_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], mut r: Reader<'_>) -> ProgramResult { let args = Box::new(parse_update_args(&mut r)?); r.finish()?; process_update_user_pda(program_id, accounts, args) } fn parse_namespace_args(r: &mut Reader<'_>) -> Result { 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()), }; let state = NamespaceState { namespace_type, min_localpart_len, namespace, registration_fee, currency_code: NAMESPACE_CURRENCY_SOL, registrar_pubkey, server_login }; validate_namespace_state(&state)?; Ok(state) } fn parse_server_addresses(r: &mut Reader<'_>) -> Result, ProgramError> { let count = r.read_u8()? as usize; let mut addresses = Vec::with_capacity(count); for _ in 0..count { addresses.push(ServerAddressRecordV12 { address_format_type: r.read_u8()?, address_format_version: r.read_u8()?, address: r.read_string_u8()?, }); } Ok(addresses) } fn parse_access_servers(r: &mut Reader<'_>) -> Result, ProgramError> { let count = r.read_u8()? as usize; let mut servers = Vec::with_capacity(count); for _ in 0..count { servers.push(r.read_string_u8()?); } Ok(servers) } fn parse_create_args(r: &mut Reader<'_>) -> Result { Ok(CreateUserPdaArgs { login: r.read_string_u8()?, root_key: r.read_pubkey()?, created_at_ms: r.read_u64()?, client_key: r.read_pubkey()?, blockchain_key: r.read_pubkey()?, server_addresses: parse_server_addresses(r)?, access_servers: parse_access_servers(r)?, signature: r.read_fixed_64()?, registrar_signature: match r.read_u8()? { 0 => None, 1 => Some(r.read_fixed_64()?), _ => return Err(ShineUsersError::InvalidInstruction.into()), }, }) } fn parse_update_args(r: &mut Reader<'_>) -> Result { let login = r.read_string_u8()?; let root_key = r.read_pubkey()?; let updated_at_ms = r.read_u64()?; let client_key = r.read_pubkey()?; let auth_mode = r.read_u8()?; let new_blockchain_key = match r.read_u8()? { 0 => None, 1 => Some(r.read_pubkey()?), _ => return Err(ProgramError::from(ShineUsersError::InvalidInstruction)), }; let server_addresses = parse_server_addresses(r)?; let access_servers = parse_access_servers(r)?; let signature = r.read_fixed_64()?; Ok(UpdateUserPdaArgs { login, root_key, updated_at_ms, client_key, auth_mode, new_blockchain_key, server_addresses, access_servers, signature, }) } fn dispatch_close_legacy_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], mut r: Reader<'_>) -> ProgramResult { let args = CloseLegacyUserPdaArgs { login: r.read_string_u8()? }; r.finish()?; process_close_legacy_user_pda(program_id, accounts, args) } fn process_init_users_economy_config(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult { let mut it = accounts.iter(); let signer = next_account_info(&mut it)?; let users_economy_config_pda = next_account_info(&mut it)?; let system_program_ai = 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); let (expected_pda, bump) = 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 == &system_program::id(), ShineUsersError::SystemAlreadyInitialized); require!(users_economy_config_pda.data_is_empty(), ShineUsersError::SystemAlreadyInitialized); let state = UsersEconomyConfigState { version: 2, update_fee_lamports: settings::UPDATE_FEE_LAMPORTS, }; let data = serialize_users_economy_config(&state); create_pda_account( signer, users_economy_config_pda, system_program_ai, program_id, &[settings::USERS_ECONOMY_CONFIG_SEED, &[bump]], data.len(), )?; write_pda_exact(users_economy_config_pda, &data)?; Ok(()) } fn process_update_users_economy_config(program_id: &Pubkey, accounts: &[AccountInfo], args: UpdateUsersEconomyConfigArgs) -> ProgramResult { 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); 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); let mut state = read_users_economy_config(users_economy_config_pda)?; state.version = 2; state.update_fee_lamports = args.update_fee_lamports; write_pda_exact(users_economy_config_pda, &serialize_users_economy_config(&state))?; Ok(()) } 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 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_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) } /// Обновление цены namespace; единственный разрешённый администратор — текущая upgrade authority. /// Мета economy PDA нужна для истории синхронизации; аккаунт только для чтения. fn process_update_namespace_price(program_id: &Pubkey, accounts: &[AccountInfo], name: &str, currency_code: u8, registration_fee: u64) -> ProgramResult { let mut it = accounts.iter(); let signer = 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)?; require!(it.next().is_none(), ShineUsersError::InvalidInstruction); require!(signer.is_signer && signer.is_writable, ShineUsersError::InvalidSigner); require!(namespace_pda.is_writable, ShineUsersError::InvalidAccountData); require_keys_eq!(*system_program_ai.key, system_program::id(), ShineUsersError::InvalidSystemProgram); validate_upgrade_authority(program_id, signer, program_ai, programdata_ai)?; validate_users_economy_config_pda(program_id, economy_pda)?; read_users_economy_config(economy_pda)?; require!(!economy_pda.is_writable, ShineUsersError::InvalidAccountData); validate_namespace_name(name)?; let mut state = read_namespace(program_id, namespace_pda, name)?; state.currency_code = currency_code; state.registration_fee = registration_fee; validate_namespace_state(&state)?; let encoded = serialize_namespace(&state); // v1.0 аккаунт создан без места под currency_code. При первом update расширяем на 1 байт. ensure_pda_size_and_rent(namespace_pda, signer, system_program_ai, encoded.len())?; write_pda_exact(namespace_pda, &encoded) } /// Проверяем не просто подписанта, а актуальную authority ProgramData ИМЕННО этой программы. /// Bincode layout UpgradeableLoaderState: Program = [2:u32LE, programdata:32], /// ProgramData = [3:u32LE, slot:u64LE, Option: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(()) } fn process_create_user_pda<'a>(program_id: &Pubkey, accounts: &'a [AccountInfo<'a>], args: Box) -> ProgramResult { let mut it = accounts.iter(); let signer = next_account_info(&mut it)?; let user_pda = next_account_info(&mut it)?; let system_program_ai = next_account_info(&mut it)?; 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 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); 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)?; validate_users_economy_config_pda(program_id, users_economy_config_pda)?; require!(!users_economy_config_pda.is_writable, ShineUsersError::InvalidAccountData); read_users_economy_config(users_economy_config_pda)?; 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, -2, ®istrar, signature, &message)?; }, _ => return Err(ShineUsersError::InvalidNamespace.into()), } let now_ms = current_time_ms()?; validate_client_time_ms(args.created_at_ms, now_ms)?; let fork_created_at_ms = args.created_at_ms; let mut record = UserRecordV12 { created_at_ms: args.created_at_ms, updated_at_ms: args.created_at_ms, record_number: 0, prev_record_hash: ZERO_HASH, login: args.login, root_key: args.root_key, client_key: args.client_key, forks: vec![ForkRecordV12 { blockchain_key: args.blockchain_key, created_at_ms: fork_created_at_ms, paid_limit_bytes: 0, }], server_addresses: args.server_addresses, access_servers: args.access_servers, signature: [0; 64], }; let unsigned = serialize_unsigned_record_v12(&record)?; let unsigned_hash = hashv(&[&signed_bytes_without_limits(&unsigned)?]); // PDA 1.3: only root signs the on-chain identity record. The blockchain // key signs content blocks but cannot authorize changes to this PDA. // For free namespaces registrar certificate is the previous ed25519 ix (-2). record.signature = verify_record_signature_hash_at(instructions_sysvar, -1, &record.root_key, &args.signature, unsigned_hash.as_ref())?; let serialized = serialize_record_with_stats(&record, SupportStats::default())?; let serialized = pad_to_fixed_size(serialized, settings::USER_PDA_SPACE)?; // Цена namespace включает депозит PDA: пользователь оплачивает rent из своей // фиксированной суммы, а в inflow_vault поступает лишь её остаток. // Для заранее пополненного system-owned адреса учитываем только фактический top-up. let required_rent = Rent::get()?.minimum_balance(settings::USER_PDA_SPACE); // Недорогие namespace блокируются независимо от внешнего пополнения PDA: // в любой момент цена должна покрывать rent записи фиксированного размера. require!(namespace.registration_fee >= required_rent, ShineUsersError::RegistrationFeeBelowRent); let rent_paid_by_signer = required_rent.saturating_sub(user_pda.lamports()); let namespace_remainder = namespace.registration_fee .checked_sub(rent_paid_by_signer) .ok_or(ProgramError::from(ShineUsersError::RegistrationFeeBelowRent))?; let vault_fee = namespace_remainder; create_pda_account( signer, user_pda, system_program_ai, program_id, &[&user_pda_seed(&record.login), &[bump]], settings::USER_PDA_SPACE, )?; write_pda_exact(user_pda, &serialized)?; transfer_lamports(signer, inflow_vault, system_program_ai, vault_fee)?; Ok(()) } fn process_update_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args: Box) -> ProgramResult { let mut it = accounts.iter(); let signer = next_account_info(&mut it)?; let user_pda = next_account_info(&mut it)?; let system_program_ai = next_account_info(&mut it)?; 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)?; 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); // Старые аккаунты без 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)?; validate_users_economy_config_pda(program_id, users_economy_config_pda)?; let economy = read_users_economy_config(users_economy_config_pda)?; 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)?; require!(matches!(record_format_minor(&raw)?, FORMAT_MINOR | PREVIOUS_FORMAT_MINOR), ShineUsersError::InvalidRecordFormat); let old_record = deserialize_record_v12_from_pda(&raw)?; require!(old_record.login == args.login, ShineUsersError::ImmutableFieldChanged); require!(args.updated_at_ms >= old_record.updated_at_ms, ShineUsersError::InvalidRecordData); let now_ms = current_time_ms()?; validate_client_time_ms(args.updated_at_ms, now_ms)?; require!(args.auth_mode == AUTH_MODE_ROOT, ShineUsersError::InvalidInstruction); let root_changed = args.root_key != old_record.root_key; let client_changed = args.client_key != old_record.client_key; let full_key_rotation = root_changed && client_changed && args.new_blockchain_key.is_some(); // Rotating root/client remains atomic with appending a fresh blockchain key. if root_changed || client_changed { require!(full_key_rotation, ShineUsersError::AmbiguousAuthorityRotation); } let old_authority = old_record.root_key; let mut forks = old_record.forks.clone(); if let Some(new_key) = args.new_blockchain_key { for fork in &forks { require!(fork.blockchain_key != new_key, ShineUsersError::DuplicateBlockchainKey); } if !full_key_rotation { enforce_fork_cooldown(old_record.active_fork()?.created_at_ms, args.updated_at_ms)?; } // Each new fork starts with its own unlimited quota (0). // Historical forks retain their existing system-owned limits. forks.push(ForkRecordV12 { blockchain_key: new_key, created_at_ms: args.updated_at_ms, paid_limit_bytes: 0 }); } let old_record_len = u16::from_le_bytes([raw[7], raw[8]]) as usize; let old_unsigned = &raw[..old_record_len - 64]; // Existing v1.2 links were hashed including limits. The first migration // link commits to the exact old bytes; v1.3 links omit quota bytes. let prev_hash = if raw[6] == PREVIOUS_FORMAT_MINOR { hash(old_unsigned).to_bytes() } else { hash(&signed_bytes_without_limits(old_unsigned)?).to_bytes() }; let mut new_record = UserRecordV12 { created_at_ms: old_record.created_at_ms, updated_at_ms: args.updated_at_ms, record_number: old_record.record_number.checked_add(1).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?, prev_record_hash: prev_hash, login: old_record.login.clone(), root_key: args.root_key, client_key: args.client_key, forks, server_addresses: args.server_addresses.clone(), access_servers: args.access_servers.clone(), signature: [0; 64], }; let unsigned = serialize_unsigned_record_v12(&new_record)?; let unsigned_hash = hashv(&[&signed_bytes_without_limits(&unsigned)?]); // Normal update: one root signature. Root rotation: both old and new root // authorize the same canonical hash (old at -2, new at -1). if root_changed { verify_ed25519_instruction_pubkey_message(instructions_sysvar, -2, &old_authority, unsigned_hash.as_ref())?; } new_record.signature = verify_record_signature_hash_at(instructions_sysvar, -1, &new_record.root_key, &args.signature, unsigned_hash.as_ref())?; let stats = read_support_stats(&raw)?; let serialized = serialize_record_with_stats(&new_record, stats)?; ensure_pda_size_and_rent(user_pda, signer, system_program_ai, serialized.len())?; write_pda_exact(user_pda, &serialized)?; transfer_lamports(signer, inflow_vault, system_program_ai, economy.update_fee_lamports)?; Ok(()) } /// Accounts: signer(sender wallet), sender PDA, recipient wallet, recipient PDA, /// inflow vault, economy config (readonly), system program. Экономический PDA /// намеренно присутствует в каждой операции для индексирования истории. // SHiNE Stars v1: 1 Star = 1 USDT reference unit. Both prices are full-verification // Pyth price-update accounts. No client-provided price is trusted. const PYTH_SOL_FEED: &str = "0xef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d"; const PYTH_USDT_FEED: &str = "0x2b89b9dc8fdf9f34709a5b106b472f0f39bb6ca9ce04b0fd7f2e971688e2e53b"; // Devnet допускает более редкие обновления Pyth; production-лимит должен быть строже. const ORACLE_MAX_AGE_SECONDS: u64 = 3_600; const ORACLE_CONFIDENCE_MAX_PPM: u128 = 10_000; // 1%, reject weak feeds fn verified_pyth_price(account: &AccountInfo, feed: &str) -> Result { require_keys_eq!(*account.owner, pyth_solana_receiver_sdk::ID, ShineUsersError::InvalidOracle); let raw = account.try_borrow_data()?; let mut bytes: &[u8] = &raw; let update = PriceUpdateV2::try_deserialize(&mut bytes) .map_err(|_| ProgramError::from(ShineUsersError::InvalidOracle))?; let feed_id = get_feed_id_from_hex(feed).map_err(|_| ProgramError::from(ShineUsersError::InvalidOracle))?; let price = update.get_price_no_older_than(&Clock::get()?, ORACLE_MAX_AGE_SECONDS, &feed_id) .map_err(|_| ProgramError::from(ShineUsersError::StaleOracle))?; require!(price.price > 0, ShineUsersError::InvalidOracle); let p = price.price as u128; require!((price.conf as u128).checked_mul(1_000_000).ok_or(ShineUsersError::MathOverflow)? <= p.checked_mul(ORACLE_CONFIDENCE_MAX_PPM).ok_or(ShineUsersError::MathOverflow)?, ShineUsersError::InvalidOracle); // Normalize to price * 10^8 without floating point. let power = i64::from(price.exponent) + 8; require!((-18..=18).contains(&power), ShineUsersError::InvalidOracle); let normalized = if power >= 0 { p.checked_mul(10u128.pow(power as u32)) } else { Some(p / 10u128.pow((-power) as u32)) }.ok_or(ShineUsersError::MathOverflow)?; require!(normalized > 0, ShineUsersError::InvalidOracle); Ok(normalized) } fn verify_stars_quote(lamports: u64, star_cents: u64, sol_oracle: &AccountInfo, usdt_oracle: &AccountInfo) -> ProgramResult { require!(star_cents >= 10 && lamports > 0, ShineUsersError::InvalidStars); let sol_usd = verified_pyth_price(sol_oracle, PYTH_SOL_FEED)?; let usdt_usd = verified_pyth_price(usdt_oracle, PYTH_USDT_FEED)?; let actual_num = (lamports as u128).checked_mul(sol_usd).and_then(|v| v.checked_mul(100)) .ok_or(ShineUsersError::MathOverflow)?; let den = 1_000_000_000u128.checked_mul(usdt_usd).ok_or(ShineUsersError::MathOverflow)?; let declared_num = (star_cents as u128).checked_mul(den).ok_or(ShineUsersError::MathOverflow)?; let difference = actual_num.abs_diff(declared_num); // |actual - declared| / declared <= 0.005. Avoid intermediate overflow. require!(difference.checked_mul(200).ok_or(ShineUsersError::MathOverflow)? <= declared_num, ShineUsersError::StarRateMismatch); Ok(()) } fn process_support_user(program_id: &Pubkey, accounts: &[AccountInfo], args: SupportUserArgs) -> ProgramResult { let mut it = accounts.iter(); let sender = next_account_info(&mut it)?; let sender_pda = next_account_info(&mut it)?; let recipient = next_account_info(&mut it)?; let recipient_pda = next_account_info(&mut it)?; let inflow_vault = next_account_info(&mut it)?; let economy_config = next_account_info(&mut it)?; let system_program_ai = next_account_info(&mut it)?; let sol_oracle = next_account_info(&mut it)?; let usdt_oracle = next_account_info(&mut it)?; require!(it.next().is_none(), ShineUsersError::InvalidInstruction); require!(sender.is_signer && sender.is_writable && recipient.is_writable && sender_pda.is_writable && recipient_pda.is_writable, ShineUsersError::InvalidSigner); require_keys_eq!(*system_program_ai.key, system_program::id(), ShineUsersError::InvalidSystemProgram); validate_full_login(&args.sender_login)?; validate_full_login(&args.recipient_login)?; require!(args.sender_login != args.recipient_login && args.amount_lamports > 0 && args.amount_star_cents >= 10, ShineUsersError::InvalidSupport); verify_stars_quote(args.amount_lamports, args.amount_star_cents, sol_oracle, usdt_oracle)?; validate_inflow_vault(inflow_vault)?; validate_users_economy_config_pda(program_id, economy_config)?; require!(!economy_config.is_writable, ShineUsersError::InvalidAccountData); require_keys_eq!(find_user_pda(program_id, &args.sender_login).0, *sender_pda.key, ShineUsersError::InvalidPdaAddress); require_keys_eq!(find_user_pda(program_id, &args.recipient_login).0, *recipient_pda.key, ShineUsersError::InvalidPdaAddress); require!(sender_pda.owner == program_id && recipient_pda.owner == program_id, ShineUsersError::InvalidAccountOwner); let sender_raw = read_pda_all(sender_pda)?; let recipient_raw = read_pda_all(recipient_pda)?; require!(matches!(record_format_minor(&sender_raw)?, FORMAT_MINOR | PREVIOUS_FORMAT_MINOR) && matches!(record_format_minor(&recipient_raw)?, FORMAT_MINOR | PREVIOUS_FORMAT_MINOR), ShineUsersError::InvalidRecordFormat); let sender_record = deserialize_record_v12_from_pda(&sender_raw)?; let recipient_record = deserialize_record_v12_from_pda(&recipient_raw)?; require!(sender_record.login == args.sender_login && recipient_record.login == args.recipient_login, ShineUsersError::InvalidRecordData); let sender_key = sender_record.active_fork()?.blockchain_key; let recipient_key = recipient_record.active_fork()?.blockchain_key; require_keys_eq!(sender_key, *sender.key, ShineUsersError::InvalidSigner); require_keys_eq!(recipient_key, *recipient.key, ShineUsersError::InvalidSupport); require!(sender_key != recipient_key, ShineUsersError::InvalidSupport); let inflow_amount = args.amount_lamports / 10 + u64::from(args.amount_lamports % 10 != 0); let recipient_amount = args.amount_lamports - inflow_amount; let dao_star_cents = args.amount_star_cents / 10 + u64::from(args.amount_star_cents % 10 != 0); let author_star_cents = args.amount_star_cents - dao_star_cents; let mut sender_stats = read_support_stats(&sender_raw)?; let mut recipient_stats = read_support_stats(&recipient_raw)?; sender_stats.support_sent = sender_stats.support_sent.checked_add(args.amount_star_cents).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?; recipient_stats.support_received = recipient_stats.support_received.checked_add(author_star_cents).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?; let sender_data = append_stats_to_existing_signed_record(&sender_raw, sender_stats)?; let recipient_data = append_stats_to_existing_signed_record(&recipient_raw, recipient_stats)?; ensure_pda_size_and_rent(sender_pda, sender, system_program_ai, sender_data.len())?; ensure_pda_size_and_rent(recipient_pda, sender, system_program_ai, recipient_data.len())?; transfer_lamports(sender, recipient, system_program_ai, recipient_amount)?; transfer_lamports(sender, inflow_vault, system_program_ai, inflow_amount)?; write_pda_exact(sender_pda, &sender_data)?; write_pda_exact(recipient_pda, &recipient_data)?; solana_program::msg!("SHINE_STARS_V1|USER|{}|{}|{}|{}|{}|{}", args.sender_login, args.recipient_login, args.amount_lamports, args.amount_star_cents, author_star_cents, dao_star_cents); Ok(()) } /// Accounts: signer, sender PDA, inflow vault, economy config (readonly), system. fn process_support_dao(program_id: &Pubkey, accounts: &[AccountInfo], args: SupportDaoArgs) -> ProgramResult { let mut it = accounts.iter(); let sender = next_account_info(&mut it)?; let sender_pda = next_account_info(&mut it)?; let inflow_vault = next_account_info(&mut it)?; let economy_config = next_account_info(&mut it)?; let system_program_ai = next_account_info(&mut it)?; let sol_oracle = next_account_info(&mut it)?; let usdt_oracle = next_account_info(&mut it)?; require!(it.next().is_none(), ShineUsersError::InvalidInstruction); require!(sender.is_signer && sender.is_writable && sender_pda.is_writable, ShineUsersError::InvalidSigner); require_keys_eq!(*system_program_ai.key, system_program::id(), ShineUsersError::InvalidSystemProgram); validate_full_login(&args.sender_login)?; require!(args.amount_lamports > 0 && args.amount_star_cents >= 10, ShineUsersError::InvalidSupport); verify_stars_quote(args.amount_lamports, args.amount_star_cents, sol_oracle, usdt_oracle)?; validate_inflow_vault(inflow_vault)?; validate_users_economy_config_pda(program_id, economy_config)?; require!(!economy_config.is_writable, ShineUsersError::InvalidAccountData); require_keys_eq!(find_user_pda(program_id, &args.sender_login).0, *sender_pda.key, ShineUsersError::InvalidPdaAddress); require!(sender_pda.owner == program_id, ShineUsersError::InvalidAccountOwner); let raw = read_pda_all(sender_pda)?; require!(matches!(record_format_minor(&raw)?, FORMAT_MINOR | PREVIOUS_FORMAT_MINOR), ShineUsersError::InvalidRecordFormat); let record = deserialize_record_v12_from_pda(&raw)?; require!(record.login == args.sender_login, ShineUsersError::InvalidRecordData); require_keys_eq!(record.active_fork()?.blockchain_key, *sender.key, ShineUsersError::InvalidSigner); let mut stats = read_support_stats(&raw)?; stats.dao_direct = stats.dao_direct.checked_add(args.amount_star_cents).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?; let data = append_stats_to_existing_signed_record(&raw, stats)?; ensure_pda_size_and_rent(sender_pda, sender, system_program_ai, data.len())?; transfer_lamports(sender, inflow_vault, system_program_ai, args.amount_lamports)?; write_pda_exact(sender_pda, &data)?; solana_program::msg!("SHINE_STARS_V1|DAO|{}|-|{}|{}|0|{}", args.sender_login, args.amount_lamports, args.amount_star_cents, args.amount_star_cents); Ok(()) } fn process_close_legacy_user_pda(program_id: &Pubkey, accounts: &[AccountInfo], args: CloseLegacyUserPdaArgs) -> ProgramResult { let mut it = accounts.iter(); let caller = next_account_info(&mut it)?; let user_pda = next_account_info(&mut it)?; require!(it.next().is_none(), ShineUsersError::InvalidInstruction); require!(caller.is_signer, ShineUsersError::InvalidSigner); require!(caller.is_writable, ShineUsersError::InvalidAccountData); require!(user_pda.is_writable, ShineUsersError::InvalidAccountData); 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)?; require!(record_format_minor(&raw)? == LEGACY_FORMAT_MINOR, ShineUsersError::CannotCloseCurrentFormat); let lamports = user_pda.lamports(); { let mut caller_lamports = caller.try_borrow_mut_lamports().map_err(|_| ProgramError::from(ShineUsersError::InvalidAccountData))?; **caller_lamports = (**caller_lamports).checked_add(lamports).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?; } { let mut pda_lamports = user_pda.try_borrow_mut_lamports().map_err(|_| ProgramError::from(ShineUsersError::InvalidAccountData))?; **pda_lamports = 0; } user_pda.realloc(0, false)?; Ok(()) } fn serialize_users_economy_config(state: &UsersEconomyConfigState) -> Vec { let mut out = Vec::with_capacity(1 + 8); out.push(state.version); out.extend_from_slice(&state.update_fee_lamports.to_le_bytes()); 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); require!(pda.owner == program_id, ShineUsersError::InvalidPdaAddress); Ok(()) } fn read_users_economy_config(pda: &AccountInfo) -> Result { let raw = read_pda_all(pda)?; require!(!raw.is_empty(), ShineUsersError::EmptyPdaData); // Existing v1 config remains readable until an authority-signed update to v2. // Its update fee was previously hardcoded; do not reinterpret v1 bytes as fee. match raw[0] { 1 if raw.len() >= 25 => Ok(UsersEconomyConfigState { version: 1, update_fee_lamports: settings::UPDATE_FEE_LAMPORTS }), 2 if raw.len() >= 9 => Ok(UsersEconomyConfigState { version: 2, update_fee_lamports: u64::from_le_bytes(raw[1..9].try_into().unwrap()), }), _ => Err(ShineUsersError::InvalidAccountData.into()), } } fn record_format_minor(raw: &[u8]) -> Result { require!(raw.len() >= 9, ShineUsersError::InvalidRecordData); require!(sol_memcmp(&raw[0..5], MAGIC, 5) == 0, ShineUsersError::InvalidRecordMagic); require!(raw[5] == FORMAT_MAJOR, ShineUsersError::InvalidRecordFormat); Ok(raw[6]) } fn deserialize_record_v12_from_pda(raw: &[u8]) -> Result { require!(raw.len() >= 9, ShineUsersError::InvalidRecordData); require!(sol_memcmp(&raw[0..5], MAGIC, 5) == 0, ShineUsersError::InvalidRecordMagic); require!(raw[5] == FORMAT_MAJOR && matches!(raw[6], FORMAT_MINOR | PREVIOUS_FORMAT_MINOR), ShineUsersError::InvalidRecordFormat); let record_len = u16::from_le_bytes([raw[7], raw[8]]) as usize; require!(record_len >= 9 + 64, ShineUsersError::InvalidRecordLength); require!(record_len <= raw.len(), ShineUsersError::InvalidRecordLength); let useful = &raw[..record_len]; let mut cursor = 9usize; let created_at_ms = read_u64_from(useful, &mut cursor)?; let updated_at_ms = read_u64_from(useful, &mut cursor)?; let record_number = read_u32_from(useful, &mut cursor)?; let prev_record_hash = read_fixed_32_from(useful, &mut cursor)?; let login = read_len_prefixed_string_from(useful, &mut cursor)?; let blocks_count = read_u8_from(useful, &mut cursor)? as usize; let mut root_key = None; let mut client_key = None; let mut forks: Option> = None; let mut server_addresses = Vec::new(); let mut access_servers = Vec::new(); for _ in 0..blocks_count { let block_type = read_u8_from(useful, &mut cursor)?; let block_version = read_u8_from(useful, &mut cursor)?; match block_type { BLOCK_TYPE_ROOT_KEY => { require!(block_version == BLOCK_VERSION_0 && root_key.is_none(), ShineUsersError::InvalidRecordFormat); root_key = Some(Pubkey::new_from_array(read_fixed_32_from(useful, &mut cursor)?)); } BLOCK_TYPE_CLIENT_KEY => { require!(block_version == BLOCK_VERSION_0 && client_key.is_none(), ShineUsersError::InvalidRecordFormat); client_key = Some(Pubkey::new_from_array(read_fixed_32_from(useful, &mut cursor)?)); } _ => { let payload_len = read_u16_from(useful, &mut cursor)? as usize; let payload_end = cursor.checked_add(payload_len).ok_or(ProgramError::from(ShineUsersError::InvalidRecordLength))?; require!(payload_end <= useful.len().saturating_sub(64), ShineUsersError::InvalidRecordLength); if block_version == BLOCK_VERSION_0 { match block_type { BLOCK_TYPE_BLOCKCHAIN_REGISTRY => { require!(forks.is_none(), ShineUsersError::InvalidRecordData); let mut p = cursor; let count = read_u16_from(useful, &mut p)? as usize; require!(count > 0, ShineUsersError::InvalidRecordData); let mut list = Vec::with_capacity(count); for _ in 0..count { list.push(ForkRecordV12 { blockchain_key: Pubkey::new_from_array(read_fixed_32_from(useful, &mut p)?), created_at_ms: read_u64_from(useful, &mut p)?, paid_limit_bytes: read_u32_from(useful, &mut p)?, }); } for pair in list.windows(2) { require!(pair[0].created_at_ms <= pair[1].created_at_ms, ShineUsersError::InvalidRecordData); } require!(p == payload_end, ShineUsersError::InvalidRecordLength); forks = Some(list); } BLOCK_TYPE_SERVER_PROFILE => { require!(server_addresses.is_empty(), ShineUsersError::InvalidRecordData); let mut p = cursor; let count = read_u8_from(useful, &mut p)? as usize; for _ in 0..count { server_addresses.push(ServerAddressRecordV12 { address_format_type: read_u8_from(useful, &mut p)?, address_format_version: read_u8_from(useful, &mut p)?, address: read_len_prefixed_string_from(useful, &mut p)?, }); } require!(p == payload_end, ShineUsersError::InvalidRecordLength); } BLOCK_TYPE_ACCESS_SERVERS => { require!(access_servers.is_empty(), ShineUsersError::InvalidRecordData); let mut p = cursor; let count = read_u8_from(useful, &mut p)? as usize; for _ in 0..count { access_servers.push(read_len_prefixed_string_from(useful, &mut p)?); } require!(p == payload_end, ShineUsersError::InvalidRecordLength); } _ => { // Неизвестный variable block 1.2 можно безопасно пропустить по payload_len. } } } cursor = payload_end; } } } let signature = read_fixed_64_from(useful, &mut cursor)?; require!(cursor == useful.len(), ShineUsersError::InvalidRecordLength); let record = UserRecordV12 { created_at_ms, updated_at_ms, record_number, prev_record_hash, login, root_key: root_key.ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?, client_key: client_key.ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?, forks: forks.ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?, server_addresses, access_servers, signature, }; validate_server_addresses(&record.server_addresses)?; validate_access_servers(&record.access_servers)?; Ok(record) } fn serialize_unsigned_record_v12(record: &UserRecordV12) -> Result, ProgramError> { let login_bytes = record.login.as_bytes(); require!(login_bytes.len() <= u8::MAX as usize, ShineUsersError::InvalidLogin); require!(!record.forks.is_empty() && record.forks.len() <= u16::MAX as usize, ShineUsersError::InvalidRecordData); validate_server_addresses(&record.server_addresses)?; validate_access_servers(&record.access_servers)?; let mut out = Vec::new(); out.extend_from_slice(MAGIC); out.push(FORMAT_MAJOR); out.push(FORMAT_MINOR); out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(&record.created_at_ms.to_le_bytes()); out.extend_from_slice(&record.updated_at_ms.to_le_bytes()); out.extend_from_slice(&record.record_number.to_le_bytes()); out.extend_from_slice(&record.prev_record_hash); out.push(login_bytes.len() as u8); out.extend_from_slice(login_bytes); let mut blocks_count = 3usize; if !record.server_addresses.is_empty() { blocks_count += 1; } if !record.access_servers.is_empty() { blocks_count += 1; } require!(blocks_count <= u8::MAX as usize, ShineUsersError::RecordTooLarge); out.push(blocks_count as u8); // Fixed-size core blocks intentionally omit payload_len. out.push(BLOCK_TYPE_ROOT_KEY); out.push(BLOCK_VERSION_0); out.extend_from_slice(record.root_key.as_ref()); out.push(BLOCK_TYPE_CLIENT_KEY); out.push(BLOCK_VERSION_0); out.extend_from_slice(record.client_key.as_ref()); write_variable_block(&mut out, BLOCK_TYPE_BLOCKCHAIN_REGISTRY, BLOCK_VERSION_0, |payload| { payload.extend_from_slice(&(record.forks.len() as u16).to_le_bytes()); for fork in &record.forks { payload.extend_from_slice(fork.blockchain_key.as_ref()); payload.extend_from_slice(&fork.created_at_ms.to_le_bytes()); payload.extend_from_slice(&fork.paid_limit_bytes.to_le_bytes()); } Ok(()) })?; if !record.server_addresses.is_empty() { write_variable_block(&mut out, BLOCK_TYPE_SERVER_PROFILE, BLOCK_VERSION_0, |payload| { require!(record.server_addresses.len() <= u8::MAX as usize, ShineUsersError::InvalidRecordData); payload.push(record.server_addresses.len() as u8); for address in &record.server_addresses { payload.push(address.address_format_type); payload.push(address.address_format_version); write_len_prefixed_string(payload, &address.address)?; } Ok(()) })?; } if !record.access_servers.is_empty() { write_variable_block(&mut out, BLOCK_TYPE_ACCESS_SERVERS, BLOCK_VERSION_0, |payload| { require!(record.access_servers.len() <= u8::MAX as usize, ShineUsersError::InvalidRecordData); payload.push(record.access_servers.len() as u8); for login in &record.access_servers { write_len_prefixed_string(payload, login)?; } Ok(()) })?; } let record_len = out.len().checked_add(64).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?; require!(record_len <= u16::MAX as usize, ShineUsersError::RecordTooLarge); let len_bytes = (record_len as u16).to_le_bytes(); out[7] = len_bytes[0]; out[8] = len_bytes[1]; Ok(out) } /// Canonical signing bytes of a physical PDA 1.3 unsigned record: /// all original headers, lengths and blocks, EXCEPT four limit bytes per fork. /// Works over raw bytes to preserve unknown future variable blocks verbatim. fn signed_bytes_without_limits(unsigned: &[u8]) -> Result, ProgramError> { require!(unsigned.len() >= 9 + 8 + 8 + 4 + 32 + 1 + 1, ShineUsersError::InvalidRecordLength); require!(&unsigned[..5] == MAGIC && unsigned[5] == FORMAT_MAJOR && unsigned[6] == FORMAT_MINOR, ShineUsersError::InvalidRecordFormat); let expected = u16::from_le_bytes([unsigned[7], unsigned[8]]) as usize; require!(expected == unsigned.len() + 64, ShineUsersError::InvalidRecordLength); let mut c = 9 + 8 + 8 + 4 + 32; let login_len = *unsigned.get(c).ok_or(ShineUsersError::InvalidRecordLength)? as usize; c = c.checked_add(1 + login_len).ok_or(ShineUsersError::MathOverflow)?; let blocks = *unsigned.get(c).ok_or(ShineUsersError::InvalidRecordLength)? as usize; c += 1; let mut out = Vec::with_capacity(unsigned.len()); out.extend_from_slice(&unsigned[..c]); let mut found_registry = false; for _ in 0..blocks { let start = c; let ty = *unsigned.get(c).ok_or(ShineUsersError::InvalidRecordLength)?; let ver = *unsigned.get(c + 1).ok_or(ShineUsersError::InvalidRecordLength)?; c += 2; if ty == BLOCK_TYPE_ROOT_KEY || ty == BLOCK_TYPE_CLIENT_KEY { c = c.checked_add(32).ok_or(ShineUsersError::MathOverflow)?; require!(c <= unsigned.len(), ShineUsersError::InvalidRecordLength); out.extend_from_slice(&unsigned[start..c]); continue; } let len_slice = unsigned.get(c..c + 2).ok_or(ShineUsersError::InvalidRecordLength)?; let len = u16::from_le_bytes([len_slice[0], len_slice[1]]) as usize; c += 2; let end = c.checked_add(len).ok_or(ShineUsersError::MathOverflow)?; require!(end <= unsigned.len(), ShineUsersError::InvalidRecordLength); if ty == BLOCK_TYPE_BLOCKCHAIN_REGISTRY && ver == BLOCK_VERSION_0 { require!(!found_registry, ShineUsersError::InvalidRecordData); found_registry = true; let count_slice = unsigned.get(c..c + 2).ok_or(ShineUsersError::InvalidRecordLength)?; let count = u16::from_le_bytes([count_slice[0], count_slice[1]]) as usize; require!(count > 0 && len == 2 + count * 44, ShineUsersError::InvalidRecordLength); out.extend_from_slice(&unsigned[start..c + 2]); c += 2; for _ in 0..count { out.extend_from_slice(&unsigned[c..c + 40]); c += 44; } require!(c == end, ShineUsersError::InvalidRecordLength); } else { out.extend_from_slice(&unsigned[start..end]); } c = end; } require!(found_registry && c == unsigned.len(), ShineUsersError::InvalidRecordLength); Ok(out) } fn serialize_full_record_v12(record: &UserRecordV12) -> Result, ProgramError> { let mut out = serialize_unsigned_record_v12(record)?; out.extend_from_slice(&record.signature); Ok(out) } fn read_support_stats(raw: &[u8]) -> Result { require!(raw.len() >= 9, ShineUsersError::InvalidRecordData); let record_len = u16::from_le_bytes([raw[7], raw[8]]) as usize; if record_len >= raw.len() || raw[record_len] == 0 { return Ok(SupportStats::default()); } // Тестовый переход: прежние lamports-счётчики v1 намеренно забываются. // При следующей записи PDA они заменяются нулевыми Stars v2. if raw[record_len] == 1 { return Ok(SupportStats::default()); } require!(raw[record_len] == SUPPORT_STATS_VERSION, ShineUsersError::UnsupportedSupportStats); let end = record_len.checked_add(SUPPORT_STATS_LEN).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?; require!(end <= raw.len(), ShineUsersError::InvalidRecordLength); let mut cursor = record_len + 1; Ok(SupportStats { support_sent: read_u64_from(raw, &mut cursor)?, support_received: read_u64_from(raw, &mut cursor)?, dao_direct: read_u64_from(raw, &mut cursor)?, }) } fn serialize_record_with_stats(record: &UserRecordV12, stats: SupportStats) -> Result, ProgramError> { let mut out = serialize_full_record_v12(record)?; out.push(SUPPORT_STATS_VERSION); out.extend_from_slice(&stats.support_sent.to_le_bytes()); out.extend_from_slice(&stats.support_received.to_le_bytes()); out.extend_from_slice(&stats.dao_direct.to_le_bytes()); Ok(out) } /// Update only the program-owned Stars stats tail; never alter the signed /// PDA record (particularly v1.2 signatures during transition to 1.3). fn append_stats_to_existing_signed_record(raw: &[u8], stats: SupportStats) -> Result, ProgramError> { require!(raw.len() >= 9, ShineUsersError::InvalidRecordLength); let signed_len = u16::from_le_bytes([raw[7], raw[8]]) as usize; require!(signed_len >= 9 + 64 && signed_len <= raw.len(), ShineUsersError::InvalidRecordLength); let mut out = Vec::with_capacity(signed_len + SUPPORT_STATS_LEN); out.extend_from_slice(&raw[..signed_len]); out.push(SUPPORT_STATS_VERSION); out.extend_from_slice(&stats.support_sent.to_le_bytes()); out.extend_from_slice(&stats.support_received.to_le_bytes()); out.extend_from_slice(&stats.dao_direct.to_le_bytes()); Ok(out) } fn write_variable_block(out: &mut Vec, block_type: u8, block_version: u8, writer: F) -> Result<(), ProgramError> where F: FnOnce(&mut Vec) -> Result<(), ProgramError>, { out.push(block_type); out.push(block_version); let len_pos = out.len(); out.extend_from_slice(&0u16.to_le_bytes()); let payload_start = out.len(); writer(out)?; let payload_len = out.len().checked_sub(payload_start).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?; require!(payload_len <= u16::MAX as usize, ShineUsersError::RecordTooLarge); let len = (payload_len as u16).to_le_bytes(); out[len_pos] = len[0]; out[len_pos + 1] = len[1]; Ok(()) } fn write_len_prefixed_string(out: &mut Vec, value: &str) -> Result<(), ProgramError> { let bytes = value.as_bytes(); require!(bytes.len() <= u8::MAX as usize, ShineUsersError::InvalidRecordData); out.push(bytes.len() as u8); out.extend_from_slice(bytes); Ok(()) } fn verify_record_signature_hash_at(instructions_sysvar: &AccountInfo, index_relative_to_current: i64, key: &Pubkey, signature: &[u8; 64], message_hash: &[u8]) -> Result<[u8; 64], ProgramError> { verify_ed25519_signature_instruction(instructions_sysvar, index_relative_to_current, key, signature, message_hash)?; Ok(*signature) } struct ParsedEd25519Data { pubkey: Pubkey, signature: [u8; 64], message: Vec, } fn verify_ed25519_signature_instruction(instructions_sysvar: &AccountInfo, index_relative_to_current: i64, expected_pubkey: &Pubkey, expected_signature: &[u8; 64], expected_message: &[u8]) -> ProgramResult { let parsed = load_parsed_ed25519_instruction(instructions_sysvar, index_relative_to_current)?; require!(parsed.pubkey == *expected_pubkey, ShineUsersError::InvalidSignature); require!(parsed.signature == *expected_signature, ShineUsersError::InvalidSignature); require!(parsed.message == expected_message, ShineUsersError::InvalidSignature); Ok(()) } fn verify_ed25519_instruction_pubkey_message(instructions_sysvar: &AccountInfo, index_relative_to_current: i64, expected_pubkey: &Pubkey, expected_message: &[u8]) -> ProgramResult { let parsed = load_parsed_ed25519_instruction(instructions_sysvar, index_relative_to_current)?; require!(parsed.pubkey == *expected_pubkey, ShineUsersError::InvalidSignature); require!(parsed.message == expected_message, ShineUsersError::InvalidSignature); Ok(()) } fn load_parsed_ed25519_instruction(instructions_sysvar: &AccountInfo, index_relative_to_current: i64) -> Result { require_keys_eq!(*instructions_sysvar.key, solana_program::sysvar::instructions::id(), ShineUsersError::InvalidSignature); let current_index = load_current_index_checked(instructions_sysvar).map_err(|_| ProgramError::from(ShineUsersError::InvalidSignature))? as i64; let target_index = current_index.checked_add(index_relative_to_current).ok_or(ProgramError::from(ShineUsersError::InvalidSignature))?; require!(target_index >= 0, ShineUsersError::InvalidSignature); let ed_ix = load_instruction_at_checked(target_index as usize, instructions_sysvar).map_err(|_| ProgramError::from(ShineUsersError::InvalidSignature))?; require_keys_eq!(ed_ix.program_id, solana_program::ed25519_program::id(), ShineUsersError::InvalidSignature); parse_ed25519_ix(ed_ix.data.as_slice()) } fn parse_ed25519_ix(data: &[u8]) -> Result { require!(data.len() >= 16, ShineUsersError::InvalidSignature); require!(data[0] == 1, ShineUsersError::InvalidSignature); let signature_offset = le_u16(data, 2)? as usize; let signature_ix_index = le_u16(data, 4)?; let pubkey_offset = le_u16(data, 6)? as usize; let pubkey_ix_index = le_u16(data, 8)?; let message_offset = le_u16(data, 10)? as usize; let message_size = le_u16(data, 12)? as usize; let message_ix_index = le_u16(data, 14)?; require!(signature_ix_index == u16::MAX, ShineUsersError::InvalidSignature); require!(pubkey_ix_index == u16::MAX, ShineUsersError::InvalidSignature); require!(message_ix_index == u16::MAX, ShineUsersError::InvalidSignature); let signature_end = signature_offset.checked_add(64).ok_or(ProgramError::from(ShineUsersError::InvalidSignature))?; let pubkey_end = pubkey_offset.checked_add(32).ok_or(ProgramError::from(ShineUsersError::InvalidSignature))?; let message_end = message_offset.checked_add(message_size).ok_or(ProgramError::from(ShineUsersError::InvalidSignature))?; let signature_slice = data.get(signature_offset..signature_end).ok_or(ProgramError::from(ShineUsersError::InvalidSignature))?; let pubkey_slice = data.get(pubkey_offset..pubkey_end).ok_or(ProgramError::from(ShineUsersError::InvalidSignature))?; let message = data.get(message_offset..message_end).ok_or(ProgramError::from(ShineUsersError::InvalidSignature))?; let mut signature = [0u8; 64]; signature.copy_from_slice(signature_slice); let pubkey = Pubkey::new_from_array(<[u8; 32]>::try_from(pubkey_slice).map_err(|_| ProgramError::from(ShineUsersError::InvalidSignature))?); Ok(ParsedEd25519Data { pubkey, signature, message: message.to_vec() }) } fn le_u16(data: &[u8], offset: usize) -> Result { let end = offset.checked_add(2).ok_or(ProgramError::from(ShineUsersError::InvalidSignature))?; let s = data.get(offset..end).ok_or(ProgramError::from(ShineUsersError::InvalidSignature))?; Ok(u16::from_le_bytes([s[0], s[1]])) } 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 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_alphanumeric() || b == b'_'), ShineUsersError::InvalidLogin); Ok(namespace) } pub fn validate_namespace_state(state: &NamespaceState) -> ProgramResult { require!(state.currency_code == NAMESPACE_CURRENCY_SOL, ShineUsersError::UnsupportedNamespaceCurrency); 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 { let mut out = vec![1, 1, 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()); out.push(state.currency_code); 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 { 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, ShineUsersError::InvalidNamespace); let minor = r.read_u8()?; require!(minor == 0 || minor == 1, 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 currency_code = if minor == 1 { r.read_u8()? } else { NAMESPACE_CURRENCY_SOL }; 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, currency_code, 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, 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.to_ascii_lowercase()).as_bytes()).to_bytes() } fn validate_server_addresses(addresses: &[ServerAddressRecordV12]) -> ProgramResult { require!(addresses.len() <= 1, ShineUsersError::InvalidRecordData); for address in addresses { let bytes = address.address.as_bytes(); require!(!bytes.is_empty() && bytes.len() <= u8::MAX as usize, ShineUsersError::InvalidRecordData); } Ok(()) } fn validate_access_servers(servers: &[String]) -> ProgramResult { require!(servers.len() <= 1, ShineUsersError::InvalidRecordData); for login in servers { if login.contains('@') { validate_full_login(login)?; } else { validate_legacy_login(login)?; } } Ok(()) } fn current_time_ms() -> Result { let seconds = Clock::get()?.unix_timestamp; require!(seconds >= 0, ShineUsersError::InvalidRecordData); (seconds as u64).checked_mul(1000).ok_or(ProgramError::from(ShineUsersError::MathOverflow)) } fn validate_client_time_ms(value_ms: u64, now_ms: u64) -> ProgramResult { let delta = if value_ms >= now_ms { value_ms - now_ms } else { now_ms - value_ms }; require!(delta <= MAX_CLIENT_CLOCK_SKEW_MS, ShineUsersError::InvalidRecordData); Ok(()) } fn enforce_fork_cooldown(last_fork_ms: u64, now_ms: u64) -> ProgramResult { require!(now_ms >= last_fork_ms, ShineUsersError::InvalidRecordData); require!(now_ms.saturating_sub(last_fork_ms) >= FORK_COOLDOWN_MS, ShineUsersError::ForkCooldown); Ok(()) } fn validate_inflow_vault(inflow_vault: &AccountInfo) -> ProgramResult { let payments_program_id = Pubkey::from_str(settings::SHINE_PAYMENTS_PROGRAM_ID).map_err(|_| ProgramError::from(ShineUsersError::InvalidFeeReceiver))?; let (expected, _) = Pubkey::find_program_address(&[settings::SHINE_PAYMENTS_INFLOW_VAULT_SEED], &payments_program_id); require_keys_eq!(expected, *inflow_vault.key, ShineUsersError::InvalidFeeReceiver); Ok(()) } fn transfer_lamports<'a>(payer: &AccountInfo<'a>, recipient: &AccountInfo<'a>, system_program_ai: &AccountInfo<'a>, lamports: u64) -> ProgramResult { if lamports == 0 { return Ok(()); } let ix = system_instruction::transfer(payer.key, recipient.key, lamports); invoke(&ix, &[payer.clone(), recipient.clone(), system_program_ai.clone()]) } // Создание PDA, устойчивое к «минированию» детерминированного адреса. // Адрес будущей записи логина выводится из самого логина, поэтому злоумышленник // может заранее вычислить адрес и перевести на него немного лампортов обычным // system-переводом. Тогда обычный system_instruction::create_account упал бы // («account already in use») и заблокировал бы регистрацию этого логина навсегда. // Чтобы это исключить, при уже существующих на адресе лампортах создаём аккаунт // «поверх предзаполненного»: доводим ренту переводом, затем allocate + assign // под подписью PDA. Подсев чужих лампортов больше ничего не ломает. fn create_pda_account<'a>(payer: &AccountInfo<'a>, pda: &AccountInfo<'a>, system_program_ai: &AccountInfo<'a>, owner: &Pubkey, seeds: &[&[u8]], space: usize) -> ProgramResult { let rent = Rent::get()?; let required_lamports = rent.minimum_balance(space); let current_lamports = pda.lamports(); if current_lamports == 0 { // Быстрый путь: адрес пуст — обычное создание аккаунта одной инструкцией. let ix = system_instruction::create_account(payer.key, pda.key, required_lamports, space as u64, owner); return invoke_signed(&ix, &[payer.clone(), pda.clone(), system_program_ai.clone()], &[seeds]); } // На адресе уже лежат лампорты (вероятно, «подсев» атакующим). Доводим баланс // до рент-экземпта, выделяем место и назначаем владельцем нашу программу. let top_up = required_lamports.saturating_sub(current_lamports); transfer_lamports(payer, pda, system_program_ai, top_up)?; let allocate_ix = system_instruction::allocate(pda.key, space as u64); invoke_signed(&allocate_ix, &[pda.clone(), system_program_ai.clone()], &[seeds])?; let assign_ix = system_instruction::assign(pda.key, owner); invoke_signed(&assign_ix, &[pda.clone(), system_program_ai.clone()], &[seeds]) } fn ensure_pda_size_and_rent<'a>(pda: &AccountInfo<'a>, payer: &AccountInfo<'a>, system_program_ai: &AccountInfo<'a>, required_len: usize) -> ProgramResult { let current_len = pda.data_len(); if required_len <= current_len { return Ok(()); } let increase = required_len.checked_sub(current_len).ok_or(ProgramError::from(ShineUsersError::MathOverflow))?; require!(increase <= MAX_AUTO_REALLOC_INCREASE, ShineUsersError::RecordTooLarge); let rent = Rent::get()?; let required_lamports = rent.minimum_balance(required_len); let current_lamports = pda.lamports(); let top_up = required_lamports.saturating_sub(current_lamports); if top_up > 0 { transfer_lamports(payer, pda, system_program_ai, top_up)?; } pda.realloc(required_len, false) } 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 pad_to_fixed_size(mut bytes: Vec, target_size: usize) -> Result, ProgramError> { require!(bytes.len() <= target_size, ShineUsersError::RecordTooLarge); bytes.resize(target_size, 0); Ok(bytes) } fn read_pda_all(pda: &AccountInfo) -> Result, ProgramError> { Ok(pda.try_borrow_data().map_err(|_| ProgramError::from(ShineUsersError::InvalidAccountData))?.to_vec()) } /// Запись пользовательского PDA всегда идёт вместе со статистикой. Хвост очищается /// только после уже записанного статистического блока, поэтому смена длины записи /// не может уничтожить SupportStats. fn write_pda_exact(pda: &AccountInfo, data: &[u8]) -> ProgramResult { let mut dst = pda.try_borrow_mut_data().map_err(|_| ProgramError::from(ShineUsersError::InvalidAccountData))?; require!(data.len() <= dst.len(), ShineUsersError::RecordTooLarge); dst[..data.len()].copy_from_slice(data); for b in &mut dst[data.len()..] { *b = 0; } Ok(()) } fn write_pda_prefix(pda: &AccountInfo, data: &[u8]) -> ProgramResult { let mut dst = pda.try_borrow_mut_data().map_err(|_| ProgramError::from(ShineUsersError::InvalidAccountData))?; require!(data.len() <= dst.len(), ShineUsersError::RecordTooLarge); dst[..data.len()].copy_from_slice(data); Ok(()) } fn read_u8_from(data: &[u8], cursor: &mut usize) -> Result { let v = *data.get(*cursor).ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?; *cursor += 1; Ok(v) } fn read_u16_from(data: &[u8], cursor: &mut usize) -> Result { let end = cursor.checked_add(2).ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?; let s = data.get(*cursor..end).ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?; *cursor = end; Ok(u16::from_le_bytes([s[0], s[1]])) } fn read_u32_from(data: &[u8], cursor: &mut usize) -> Result { let end = cursor.checked_add(4).ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?; let s = data.get(*cursor..end).ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?; *cursor = end; Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]])) } fn read_u64_from(data: &[u8], cursor: &mut usize) -> Result { let end = cursor.checked_add(8).ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?; let s = data.get(*cursor..end).ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?; *cursor = end; Ok(u64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]])) } fn read_fixed_32_from(data: &[u8], cursor: &mut usize) -> Result<[u8; 32], ProgramError> { let end = cursor.checked_add(32).ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?; let s = data.get(*cursor..end).ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?; *cursor = end; <[u8; 32]>::try_from(s).map_err(|_| ProgramError::from(ShineUsersError::InvalidRecordData)) } fn read_fixed_64_from(data: &[u8], cursor: &mut usize) -> Result<[u8; 64], ProgramError> { let end = cursor.checked_add(64).ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?; let s = data.get(*cursor..end).ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?; *cursor = end; <[u8; 64]>::try_from(s).map_err(|_| ProgramError::from(ShineUsersError::InvalidRecordData)) } fn read_len_prefixed_string_from(data: &[u8], cursor: &mut usize) -> Result { let len = read_u8_from(data, cursor)? as usize; let end = cursor.checked_add(len).ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?; let s = data.get(*cursor..end).ok_or(ProgramError::from(ShineUsersError::InvalidRecordData))?; *cursor = end; std::str::from_utf8(s).map(|v| v.to_string()).map_err(|_| ProgramError::from(ShineUsersError::InvalidRecordData)) } #[cfg(test)] mod support_stats_tests { use super::*; #[test] fn legacy_support_stats_are_reset_and_v2_is_supported() { let mut v0 = vec![0u8; 100]; v0[7..9].copy_from_slice(&80u16.to_le_bytes()); assert_eq!(read_support_stats(&v0).unwrap(), SupportStats::default()); let mut v1 = v0; v1[80] = 1; v1[81..89].copy_from_slice(&100u64.to_le_bytes()); v1[89..97].copy_from_slice(&90u64.to_le_bytes()); // Статистика v1 игнорируется: это lamports, не Stars. assert_eq!(read_support_stats(&v1).unwrap(), SupportStats::default()); v1.resize(105, 0); v1[97..105].copy_from_slice(&7u64.to_le_bytes()); assert_eq!(read_support_stats(&v1).unwrap(), SupportStats::default()); v1[80] = 2; assert_eq!(read_support_stats(&v1).unwrap(), SupportStats { support_sent: 100, support_received: 90, dao_direct: 7 }); } }