This commit is contained in:
Hardhat Chad
2024-02-14 17:01:30 +00:00
parent f917e49b3f
commit bbc1d835ea
21 changed files with 248 additions and 171 deletions

26
src/error.rs Normal file
View File

@@ -0,0 +1,26 @@
use num_enum::IntoPrimitive;
use solana_program::program_error::ProgramError;
use thiserror::Error;
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq, IntoPrimitive)]
#[repr(u32)]
pub enum OreError {
#[error("The epoch is still active and cannot be reset")]
EpochActive = 0,
#[error("The epoch has expired and needs reset")]
EpochExpired = 1,
#[error("The provided hash was invalid")]
InvalidHash = 2,
#[error("The provided hash does not satisfy the difficulty requirement")]
InsufficientHashDifficulty = 3,
#[error("The bus has insufficient rewards to mine at this time")]
InsufficientBusRewards = 4,
#[error("The claim amount cannot be larger than the claimable rewards")]
InvalidClaimAmount = 5,
}
impl From<OreError> for ProgramError {
fn from(e: OreError) -> Self {
ProgramError::Custom(e as u32)
}
}

View File

@@ -3,7 +3,7 @@ use num_enum::TryFromPrimitive;
use shank::ShankInstruction;
use solana_program::pubkey::Pubkey;
use crate::state::Hash;
use crate::{impl_to_bytes, state::Hash};
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, ShankInstruction, TryFromPrimitive)]
@@ -23,13 +23,13 @@ pub enum OreInstruction {
#[account(11, name = "treasury", desc = "Ore treasury account", writable)]
#[account(12, name = "treasury_tokens", desc = "Ore treasury token account", writable)]
#[account(13, name = "token_program", desc = "SPL token program")]
Epoch = 0,
Reset = 0,
#[account(0, name = "ore_program", desc = "Ore program")]
#[account(1, name = "signer", desc = "Signer", signer)]
#[account(2, name = "proof", desc = "Ore miner proof account", writable)]
#[account(3, name = "system_program", desc = "Solana system program")]
Proof = 1,
CreateProof = 1,
#[account(0, name = "ore_program", desc = "Ore program")]
#[account(1, name = "signer", desc = "Signer", signer)]
@@ -98,24 +98,12 @@ pub struct InitializeArgs {
pub treasury_bump: u8,
}
impl InitializeArgs {
pub fn to_bytes(&self) -> &[u8] {
bytemuck::bytes_of(self)
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct ProofArgs {
pub struct CreateProofArgs {
pub bump: u8,
}
impl ProofArgs {
pub fn to_bytes(&self) -> &[u8] {
bytemuck::bytes_of(self)
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct MineArgs {
@@ -123,44 +111,27 @@ pub struct MineArgs {
pub nonce: [u8; 8],
}
impl MineArgs {
pub fn to_bytes(&self) -> &[u8] {
bytemuck::bytes_of(self)
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct ClaimArgs {
pub amount: u64,
}
impl ClaimArgs {
pub fn to_bytes(&self) -> &[u8] {
bytemuck::bytes_of(self)
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct UpdateAdminArgs {
pub new_admin: Pubkey,
}
impl UpdateAdminArgs {
pub fn to_bytes(&self) -> &[u8] {
bytemuck::bytes_of(self)
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct UpdateDifficultyArgs {
pub new_difficulty: Hash,
}
impl UpdateDifficultyArgs {
pub fn to_bytes(&self) -> &[u8] {
bytemuck::bytes_of(self)
}
}
impl_to_bytes!(InitializeArgs);
impl_to_bytes!(CreateProofArgs);
impl_to_bytes!(MineArgs);
impl_to_bytes!(ClaimArgs);
impl_to_bytes!(UpdateAdminArgs);
impl_to_bytes!(UpdateDifficultyArgs);

View File

@@ -1,3 +1,4 @@
pub mod error;
pub mod instruction;
mod loaders;
mod processor;
@@ -109,8 +110,8 @@ pub fn process_instruction(
let ix = OreInstruction::try_from(*tag).or(Err(ProgramError::InvalidInstructionData))?;
match ix {
OreInstruction::Epoch => process_epoch(program_id, accounts, data)?,
OreInstruction::Proof => process_proof(program_id, accounts, data)?,
OreInstruction::Reset => process_reset(program_id, accounts, data)?,
OreInstruction::CreateProof => process_create_proof(program_id, accounts, data)?,
OreInstruction::Mine => process_mine(program_id, accounts, data)?,
OreInstruction::Claim => process_claim(program_id, accounts, data)?,
OreInstruction::Initialize => process_initialize(program_id, accounts, data)?,

View File

@@ -1,6 +1,6 @@
use solana_program::{
account_info::AccountInfo, program_error::ProgramError, program_memory::sol_memcmp,
program_pack::Pack, pubkey::Pubkey, system_program,
account_info::AccountInfo, program_error::ProgramError, program_pack::Pack, pubkey::Pubkey,
system_program,
};
use spl_token::state::Mint;
@@ -16,8 +16,11 @@ pub fn load_signer<'a, 'info>(info: &'a AccountInfo<'info>) -> Result<(), Progra
Ok(())
}
pub fn load_bus<'a, 'info>(info: &'a AccountInfo<'info>) -> Result<(), ProgramError> {
if !info.owner.eq(&crate::id()) {
pub fn load_bus<'a, 'info>(
info: &'a AccountInfo<'info>,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.owner.ne(&crate::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.data_is_empty() {
@@ -31,14 +34,19 @@ pub fn load_bus<'a, 'info>(info: &'a AccountInfo<'info>) -> Result<(), ProgramEr
return Err(ProgramError::InvalidAccountData);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
pub fn load_proof<'a, 'info>(
info: &'a AccountInfo<'info>,
signer: &Pubkey,
authority: &Pubkey,
is_writable: bool,
) -> Result<(), ProgramError> {
if !info.owner.eq(&crate::id()) {
if info.owner.ne(&crate::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.data_is_empty() {
@@ -48,31 +56,44 @@ pub fn load_proof<'a, 'info>(
let proof_data = info.data.borrow();
let proof = bytemuck::try_from_bytes::<Proof>(&proof_data).unwrap();
// if !proof.authority.eq(&signer) {
if sol_memcmp(proof.authority.as_ref(), signer.as_ref(), 32) != 0 {
if proof.authority.ne(&authority) {
return Err(ProgramError::InvalidAccountData);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
pub fn load_treasury<'a, 'info>(info: &'a AccountInfo<'info>) -> Result<(), ProgramError> {
if !info.owner.eq(&crate::id()) {
pub fn load_treasury<'a, 'info>(
info: &'a AccountInfo<'info>,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.owner.ne(&crate::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.data_is_empty() {
return Err(ProgramError::UninitializedAccount);
}
if sol_memcmp(info.key.as_ref(), TREASURY_ADDRESS.as_ref(), 32) != 0 {
if info.key.ne(&TREASURY_ADDRESS) {
return Err(ProgramError::InvalidSeeds);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
pub fn load_mint<'a, 'info>(info: &'a AccountInfo<'info>) -> Result<(), ProgramError> {
if !info.owner.eq(&spl_token::id()) {
pub fn load_mint<'a, 'info>(
info: &'a AccountInfo<'info>,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.owner.ne(&spl_token::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.data_is_empty() {
@@ -84,7 +105,11 @@ pub fn load_mint<'a, 'info>(info: &'a AccountInfo<'info>) -> Result<(), ProgramE
return Err(ProgramError::InvalidAccountData);
}
if sol_memcmp(info.key.as_ref(), MINT_ADDRESS.as_ref(), 32) != 0 {
if info.key.ne(&MINT_ADDRESS) {
return Err(ProgramError::InvalidAccountData);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
@@ -95,8 +120,9 @@ pub fn load_token_account<'a, 'info>(
info: &'a AccountInfo<'info>,
owner: Option<&Pubkey>,
mint: &Pubkey,
is_writable: bool,
) -> Result<(), ProgramError> {
if !info.owner.eq(&spl_token::id()) {
if info.owner.ne(&spl_token::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.data_is_empty() {
@@ -107,15 +133,19 @@ pub fn load_token_account<'a, 'info>(
let account = spl_token::state::Account::unpack_unchecked(&account_data)
.or(Err(ProgramError::InvalidAccountData))?;
if !account.mint.eq(&mint) {
if account.mint.ne(&mint) {
return Err(ProgramError::InvalidAccountData);
}
if let Some(owner) = owner {
if sol_memcmp(account.owner.as_ref(), owner.as_ref(), 32) != 0 {
if account.owner.ne(owner) {
return Err(ProgramError::InvalidAccountData);
}
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
@@ -124,7 +154,7 @@ pub fn load_uninitialized_pda<'a, 'info>(
seeds: &[&[u8]],
) -> Result<(), ProgramError> {
let key = Pubkey::create_program_address(seeds, &crate::id())?;
if !info.key.eq(&key) {
if info.key.ne(&key) {
return Err(ProgramError::InvalidSeeds);
}
load_uninitialized_account(info)
@@ -133,7 +163,7 @@ pub fn load_uninitialized_pda<'a, 'info>(
pub fn load_uninitialized_account<'a, 'info>(
info: &'a AccountInfo<'info>,
) -> Result<(), ProgramError> {
if !info.owner.eq(&system_program::id()) {
if info.owner.ne(&system_program::id()) {
return Err(ProgramError::AccountAlreadyInitialized);
}
if !info.data_is_empty() {
@@ -145,11 +175,35 @@ pub fn load_uninitialized_account<'a, 'info>(
Ok(())
}
pub fn load_account<'a, 'info>(
pub fn load_sysvar<'a, 'info>(
info: &'a AccountInfo<'info>,
key: Pubkey,
) -> Result<(), ProgramError> {
if !info.key.eq(&key) {
load_account(info, key, false)
}
pub fn load_account<'a, 'info>(
info: &'a AccountInfo<'info>,
key: Pubkey,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.key.ne(&key) {
return Err(ProgramError::InvalidAccountData);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
pub fn load_program<'a, 'info>(
info: &'a AccountInfo<'info>,
key: Pubkey,
) -> Result<(), ProgramError> {
if info.key.ne(&key) {
return Err(ProgramError::InvalidAccountData);
}
if !info.executable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())

View File

@@ -4,6 +4,7 @@ use solana_program::{
};
use crate::{
error::OreError,
instruction::ClaimArgs,
loaders::*,
state::{Proof, Treasury},
@@ -24,17 +25,22 @@ pub fn process_claim<'a, 'info>(
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_token_account(beneficiary_info, None, mint_info.key)?;
load_mint(mint_info)?;
load_treasury(treasury_info)?;
load_token_account(treasury_tokens_info, Some(treasury_info.key), mint_info.key)?;
load_account(token_program, spl_token::id())?;
load_token_account(beneficiary_info, None, mint_info.key, true)?;
load_mint(mint_info, true)?;
load_treasury(treasury_info, true)?;
load_token_account(
treasury_tokens_info,
Some(treasury_info.key),
mint_info.key,
true,
)?;
load_program(token_program, spl_token::id())?;
// Validate claim amout
let mut proof_data = proof_info.data.borrow_mut();
let mut proof = bytemuck::try_from_bytes_mut::<Proof>(&mut proof_data).unwrap();
if proof.claimable_rewards.lt(&args.amount) {
return Err(ProgramError::Custom(1));
return Err(OreError::InvalidClaimAmount.into());
}
// Update claimable amount

View File

@@ -5,15 +5,15 @@ use solana_program::{
program_error::ProgramError, pubkey::Pubkey, system_program,
};
use crate::{instruction::ProofArgs, loaders::*, state::Proof, utils::create_pda, PROOF};
use crate::{instruction::CreateProofArgs, loaders::*, state::Proof, utils::create_pda, PROOF};
pub fn process_proof<'a, 'info>(
pub fn process_create_proof<'a, 'info>(
_program_id: &Pubkey,
accounts: &'a [AccountInfo<'info>],
data: &[u8],
) -> ProgramResult {
// Parse args
let args = bytemuck::try_from_bytes::<ProofArgs>(data)
let args = bytemuck::try_from_bytes::<CreateProofArgs>(data)
.or(Err(ProgramError::InvalidInstructionData))?;
// Validate accounts
@@ -22,7 +22,7 @@ pub fn process_proof<'a, 'info>(
};
load_signer(signer)?;
load_uninitialized_pda(proof_info, &[PROOF, signer.key.as_ref(), &[args.bump]])?;
load_account(system_program, system_program::id())?;
load_program(system_program, system_program::id())?;
// Initialize proof
create_pda(

View File

@@ -47,10 +47,10 @@ pub fn process_initialize<'a, 'info>(
return Err(ProgramError::InvalidSeeds);
}
load_uninitialized_account(treasury_tokens_info)?;
load_account(system_program, system_program::id())?;
load_account(token_program, spl_token::id())?;
load_account(associated_token_program, spl_associated_token_account::id())?;
load_account(rent_sysvar, sysvar::rent::id())?;
load_program(system_program, system_program::id())?;
load_program(token_program, spl_token::id())?;
load_program(associated_token_program, spl_associated_token_account::id())?;
load_sysvar(rent_sysvar, sysvar::rent::id())?;
// Initialize bus accounts
let bus_infos = [

View File

@@ -6,12 +6,14 @@ use solana_program::{
entrypoint::ProgramResult,
keccak::{hashv, Hash as KeccakHash},
program_error::ProgramError,
program_memory::sol_memcmp,
pubkey::Pubkey,
slot_hashes::SlotHash,
sysvar::{self, Sysvar},
};
use crate::{
error::OreError,
instruction::MineArgs,
loaders::*,
state::{Bus, Proof, Treasury},
@@ -32,18 +34,18 @@ pub fn process_mine<'a, 'info>(
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_bus(bus_info)?;
load_proof(proof_info, signer.key)?;
load_treasury(treasury_info)?;
load_account(slot_hashes_info, sysvar::slot_hashes::id())?;
load_bus(bus_info, true)?;
load_proof(proof_info, signer.key, true)?;
load_treasury(treasury_info, false)?;
load_sysvar(slot_hashes_info, sysvar::slot_hashes::id())?;
// Validate epoch is active
let clock = Clock::get().unwrap();
let treasury_data = treasury_info.data.borrow();
let treasury = bytemuck::try_from_bytes::<Treasury>(&treasury_data).unwrap();
let epoch_end_at = treasury.epoch_start_at.saturating_add(EPOCH_DURATION);
if !clock.unix_timestamp.lt(&epoch_end_at) {
return Err(ProgramError::Custom(1));
if clock.unix_timestamp.ge(&epoch_end_at) {
return Err(OreError::EpochExpired.into());
}
// Validate provided hash
@@ -61,7 +63,7 @@ pub fn process_mine<'a, 'info>(
let mut bus_data = bus_info.data.borrow_mut();
let mut bus = bytemuck::try_from_bytes_mut::<Bus>(&mut bus_data).unwrap();
if bus.available_rewards.lt(&treasury.reward_rate) {
return Err(ProgramError::Custom(1));
return Err(OreError::InsufficientBusRewards.into());
}
bus.available_rewards = bus.available_rewards.saturating_sub(treasury.reward_rate);
proof.claimable_rewards = proof.claimable_rewards.saturating_add(treasury.reward_rate);
@@ -86,19 +88,19 @@ pub(crate) fn validate_hash(
nonce: u64,
difficulty: KeccakHash,
) -> Result<(), ProgramError> {
// Validate hash correctness.
// Validate hash correctness
let hash_ = hashv(&[
current_hash.as_ref(),
signer.as_ref(),
nonce.to_be_bytes().as_slice(),
]);
if !hash.eq(&hash_) {
return Err(ProgramError::Custom(1));
if sol_memcmp(hash.as_ref(), hash_.as_ref(), 32) != 0 {
return Err(OreError::InvalidHash.into());
}
// Validate hash difficulty.
if !hash.le(&difficulty) {
return Err(ProgramError::Custom(1));
// Validate hash difficulty
if hash.gt(&difficulty) {
return Err(OreError::InsufficientHashDifficulty.into());
}
Ok(())

View File

@@ -1,15 +1,15 @@
mod claim;
mod epoch;
mod create_proof;
mod initialize;
mod mine;
mod proof;
mod reset;
mod update_admin;
mod update_difficulty;
pub use claim::*;
pub use epoch::*;
pub use create_proof::*;
pub use initialize::*;
pub use mine::*;
pub use proof::*;
pub use reset::*;
pub use update_admin::*;
pub use update_difficulty::*;

View File

@@ -4,13 +4,14 @@ use solana_program::{
};
use crate::{
error::OreError,
loaders::*,
state::{Bus, Treasury},
BUS_COUNT, BUS_EPOCH_REWARDS, EPOCH_DURATION, MAX_EPOCH_REWARDS, SMOOTHING_FACTOR,
TARGET_EPOCH_REWARDS, TREASURY,
};
pub fn process_epoch<'a, 'info>(
pub fn process_reset<'a, 'info>(
_program_id: &Pubkey,
accounts: &'a [AccountInfo<'info>],
_data: &[u8],
@@ -20,18 +21,23 @@ pub fn process_epoch<'a, 'info>(
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_bus(bus_0_info)?;
load_bus(bus_1_info)?;
load_bus(bus_2_info)?;
load_bus(bus_3_info)?;
load_bus(bus_4_info)?;
load_bus(bus_5_info)?;
load_bus(bus_6_info)?;
load_bus(bus_7_info)?;
load_mint(mint_info)?;
load_treasury(treasury_info)?;
load_token_account(treasury_tokens_info, Some(treasury_info.key), mint_info.key)?;
load_account(token_program, spl_token::id())?;
load_bus(bus_0_info, true)?;
load_bus(bus_1_info, true)?;
load_bus(bus_2_info, true)?;
load_bus(bus_3_info, true)?;
load_bus(bus_4_info, true)?;
load_bus(bus_5_info, true)?;
load_bus(bus_6_info, true)?;
load_bus(bus_7_info, true)?;
load_mint(mint_info, true)?;
load_treasury(treasury_info, true)?;
load_token_account(
treasury_tokens_info,
Some(treasury_info.key),
mint_info.key,
true,
)?;
load_sysvar(token_program, spl_token::id())?;
let busses: [&AccountInfo; 8] = [
bus_0_info, bus_1_info, bus_2_info, bus_3_info, bus_4_info, bus_5_info, bus_6_info,
bus_7_info,
@@ -42,8 +48,8 @@ pub fn process_epoch<'a, 'info>(
let mut treasury_data = treasury_info.data.borrow_mut();
let mut treasury = bytemuck::try_from_bytes_mut::<Treasury>(&mut treasury_data).unwrap();
let epoch_end_at = treasury.epoch_start_at.saturating_add(EPOCH_DURATION);
if !clock.unix_timestamp.ge(&epoch_end_at) {
return Err(ProgramError::Custom(1));
if clock.unix_timestamp.lt(&epoch_end_at) {
return Err(OreError::EpochActive.into());
}
// Reset busses

View File

@@ -19,7 +19,7 @@ pub fn process_update_admin<'a, 'info>(
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_treasury(treasury_info)?;
load_treasury(treasury_info, true)?;
// Validate admin signer
let mut treasury_data = treasury_info.data.borrow_mut();

View File

@@ -19,7 +19,7 @@ pub fn process_update_difficulty<'a, 'info>(
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_treasury(treasury_info)?;
load_treasury(treasury_info, true)?;
// Validate admin signer
let mut treasury_data = treasury_info.data.borrow_mut();

View File

@@ -1,5 +1,7 @@
use bytemuck::{Pod, Zeroable};
use crate::impl_to_bytes;
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct Bus {
@@ -13,8 +15,4 @@ pub struct Bus {
pub available_rewards: u64,
}
impl Bus {
pub fn to_bytes(&self) -> &[u8] {
bytemuck::bytes_of(self)
}
}
impl_to_bytes!(Bus);

View File

@@ -3,6 +3,8 @@ use std::mem::transmute;
use bytemuck::{Pod, Zeroable};
use solana_program::keccak::{Hash as KeccakHash, HASH_BYTES};
use crate::impl_to_bytes;
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct Hash(pub [u8; HASH_BYTES]);
@@ -20,3 +22,5 @@ impl From<Hash> for KeccakHash {
unsafe { transmute(value) }
}
}
impl_to_bytes!(Hash);

View File

@@ -1,6 +1,8 @@
use bytemuck::{Pod, Zeroable};
use solana_program::pubkey::Pubkey;
use crate::impl_to_bytes;
use super::Hash;
#[repr(C)]
@@ -25,8 +27,4 @@ pub struct Proof {
pub total_rewards: u64,
}
impl Proof {
pub fn to_bytes(&self) -> &[u8] {
bytemuck::bytes_of(self)
}
}
impl_to_bytes!(Proof);

View File

@@ -1,6 +1,8 @@
use bytemuck::{Pod, Zeroable};
use solana_program::pubkey::Pubkey;
use crate::impl_to_bytes;
use super::Hash;
#[repr(C)]
@@ -25,8 +27,4 @@ pub struct Treasury {
pub total_claimed_rewards: u64,
}
impl Treasury {
pub fn to_bytes(&self) -> &[u8] {
bytemuck::bytes_of(self)
}
}
impl_to_bytes!(Treasury);

View File

@@ -31,3 +31,14 @@ pub fn create_pda<'a, 'info>(
)?;
Ok(())
}
#[macro_export]
macro_rules! impl_to_bytes {
($struct_name:ident) => {
impl $struct_name {
pub fn to_bytes(&self) -> &[u8] {
bytemuck::bytes_of(self)
}
}
};
}