mirror of
https://github.com/d0zingcat/ore.git
synced 2026-06-06 23:26:46 +00:00
mine v2
This commit is contained in:
1252
Cargo.lock
generated
1252
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -21,6 +21,7 @@ default = []
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
bs58 = "0.5.0"
|
bs58 = "0.5.0"
|
||||||
bytemuck = "1.14.3"
|
bytemuck = "1.14.3"
|
||||||
|
drillx = { git = "https://github.com/hardhatchad/drillx", branch = "master" }
|
||||||
mpl-token-metadata = "4.1.2"
|
mpl-token-metadata = "4.1.2"
|
||||||
num_enum = "0.7.2"
|
num_enum = "0.7.2"
|
||||||
shank = "0.3.0"
|
shank = "0.3.0"
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
use solana_program::{keccak::Hash, pubkey, pubkey::Pubkey};
|
use solana_program::{keccak::Hash, pubkey, pubkey::Pubkey};
|
||||||
|
|
||||||
/// The unix timestamp after which mining can begin.
|
|
||||||
pub const START_AT: i64 = 1712070600;
|
|
||||||
|
|
||||||
/// The reward rate to intialize the program with.
|
/// The reward rate to intialize the program with.
|
||||||
pub const INITIAL_REWARD_RATE: u64 = 10u64.pow(3u32);
|
pub const INITIAL_REWARD_RATE: u64 = 10u64.pow(3u32);
|
||||||
|
|
||||||
@@ -40,6 +37,9 @@ pub const BUS_COUNT: usize = 8;
|
|||||||
/// than a factor of this constant from one epoch to the next.
|
/// than a factor of this constant from one epoch to the next.
|
||||||
pub const SMOOTHING_FACTOR: u64 = 2;
|
pub const SMOOTHING_FACTOR: u64 = 2;
|
||||||
|
|
||||||
|
/// The range of difficulties miners can target above the minimum.
|
||||||
|
pub const DIFFICULTY_RANGE: usize = 32;
|
||||||
|
|
||||||
// Assert MAX_EPOCH_REWARDS is evenly divisible by BUS_COUNT.
|
// Assert MAX_EPOCH_REWARDS is evenly divisible by BUS_COUNT.
|
||||||
static_assertions::const_assert!(
|
static_assertions::const_assert!(
|
||||||
(MAX_EPOCH_REWARDS / BUS_COUNT as u64) * BUS_COUNT as u64 == MAX_EPOCH_REWARDS
|
(MAX_EPOCH_REWARDS / BUS_COUNT as u64) * BUS_COUNT as u64 == MAX_EPOCH_REWARDS
|
||||||
@@ -96,6 +96,9 @@ pub const CONFIG_ADDRESS: Pubkey = pubkey!("FTap9fv2GPpWGqrLj3o4c9nHH7p36ih7NbSW
|
|||||||
/// The address of the mint metadata account.
|
/// The address of the mint metadata account.
|
||||||
pub const METADATA_ADDRESS: Pubkey = pubkey!("2nXZSxfjELuRatcoY64yHdFLZFi3mtesxobHmsoU3Dag");
|
pub const METADATA_ADDRESS: Pubkey = pubkey!("2nXZSxfjELuRatcoY64yHdFLZFi3mtesxobHmsoU3Dag");
|
||||||
|
|
||||||
|
/// The address of the mint metadata account.
|
||||||
|
pub const NOISE_ADDRESS: Pubkey = pubkey!("2nXZSxfjELuRatcoY64yHdFLZFi3mtesxobHmsoU3Dag");
|
||||||
|
|
||||||
/// The address of the mint account.
|
/// The address of the mint account.
|
||||||
pub const MINT_ADDRESS: Pubkey = pubkey!("oreoN2tQbHXVaZsr3pf66A48miqcBXCDJozganhEJgz");
|
pub const MINT_ADDRESS: Pubkey = pubkey!("oreoN2tQbHXVaZsr3pf66A48miqcBXCDJozganhEJgz");
|
||||||
|
|
||||||
|
|||||||
10
src/error.rs
10
src/error.rs
@@ -5,18 +5,20 @@ use thiserror::Error;
|
|||||||
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq, IntoPrimitive)]
|
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq, IntoPrimitive)]
|
||||||
#[repr(u32)]
|
#[repr(u32)]
|
||||||
pub enum OreError {
|
pub enum OreError {
|
||||||
#[error("The starting time has not passed yet")]
|
#[error("Mining is paused")]
|
||||||
NotStarted = 0,
|
IsPaused = 0,
|
||||||
#[error("The epoch has ended and needs reset")]
|
#[error("The epoch has ended and needs reset")]
|
||||||
NeedsReset = 1,
|
NeedsReset = 1,
|
||||||
#[error("The epoch is active and cannot be reset at this time")]
|
#[error("The epoch is active and cannot be reset at this time")]
|
||||||
ResetTooEarly = 2,
|
ResetTooEarly = 2,
|
||||||
#[error("The provided hash was invalid")]
|
#[error("The provided hash did not satisfy the minimum required difficulty")]
|
||||||
HashInvalid = 3,
|
DifficultyInsufficient = 3,
|
||||||
#[error("The bus does not have enough rewards to issue at this time")]
|
#[error("The bus does not have enough rewards to issue at this time")]
|
||||||
BusRewardsInsufficient = 4,
|
BusRewardsInsufficient = 4,
|
||||||
#[error("The claim amount cannot be greater than the claimable rewards")]
|
#[error("The claim amount cannot be greater than the claimable rewards")]
|
||||||
ClaimTooLarge = 5,
|
ClaimTooLarge = 5,
|
||||||
|
#[error("The clock time is invalid")]
|
||||||
|
ClockInvalid = 6,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<OreError> for ProgramError {
|
impl From<OreError> for ProgramError {
|
||||||
|
|||||||
@@ -8,19 +8,10 @@ use solana_program::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
impl_instruction_from_bytes, impl_to_bytes, state::Hash, BUS, CONFIG, CONFIG_ADDRESS, METADATA,
|
impl_instruction_from_bytes, impl_to_bytes, BUS, CONFIG, CONFIG_ADDRESS, METADATA, MINT,
|
||||||
MINT, MINT_ADDRESS, MINT_NOISE, PROOF, TREASURY, TREASURY_ADDRESS,
|
MINT_ADDRESS, MINT_NOISE, PROOF, TREASURY, TREASURY_ADDRESS,
|
||||||
};
|
};
|
||||||
|
|
||||||
// TODO Stake
|
|
||||||
// TODO Unstake
|
|
||||||
|
|
||||||
// TODO Upgrade (v1 to v2 token)
|
|
||||||
// TODO Downgrade (v2 to v1 token)
|
|
||||||
|
|
||||||
// TODO Personalized difficulty
|
|
||||||
// TODO Payout rewards based on multiplier and difficulty setting
|
|
||||||
|
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, ShankInstruction, TryFromPrimitive)]
|
#[derive(Clone, Copy, Debug, Eq, PartialEq, ShankInstruction, TryFromPrimitive)]
|
||||||
#[rustfmt::skip]
|
#[rustfmt::skip]
|
||||||
@@ -138,12 +129,6 @@ pub struct UpdateAdminArgs {
|
|||||||
pub new_admin: Pubkey,
|
pub new_admin: Pubkey,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
|
|
||||||
pub struct UpdateDifficultyArgs {
|
|
||||||
pub new_difficulty: Hash,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl_to_bytes!(InitializeArgs);
|
impl_to_bytes!(InitializeArgs);
|
||||||
impl_to_bytes!(RegisterArgs);
|
impl_to_bytes!(RegisterArgs);
|
||||||
impl_to_bytes!(MineArgs);
|
impl_to_bytes!(MineArgs);
|
||||||
|
|||||||
@@ -14,6 +14,12 @@ use solana_program::{
|
|||||||
program_error::ProgramError, pubkey::Pubkey,
|
program_error::ProgramError, pubkey::Pubkey,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// TODO Stake
|
||||||
|
// TODO Claim
|
||||||
|
|
||||||
|
// TODO Upgrade (v1 to v2 token)
|
||||||
|
// TODO Downgrade (v2 to v1 token)
|
||||||
|
|
||||||
declare_id!("mineRHF5r6S7HyD9SppBfVMXMavDkJsxwGesEvxZr2A");
|
declare_id!("mineRHF5r6S7HyD9SppBfVMXMavDkJsxwGesEvxZr2A");
|
||||||
|
|
||||||
#[cfg(not(feature = "no-entrypoint"))]
|
#[cfg(not(feature = "no-entrypoint"))]
|
||||||
|
|||||||
@@ -7,9 +7,11 @@ use spl_token::state::Mint;
|
|||||||
use crate::{
|
use crate::{
|
||||||
state::{Bus, Config, Proof, Treasury},
|
state::{Bus, Config, Proof, Treasury},
|
||||||
utils::AccountDeserialize,
|
utils::AccountDeserialize,
|
||||||
BUS_ADDRESSES, BUS_COUNT, CONFIG_ADDRESS, MINT_ADDRESS, TREASURY_ADDRESS,
|
BUS_ADDRESSES, BUS_COUNT, CONFIG_ADDRESS, MINT_ADDRESS, NOISE_ADDRESS, TREASURY_ADDRESS,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// TODO Account checks don't need to deserialize the whole byte array. They can just check the type byte
|
||||||
|
|
||||||
/// Errors if:
|
/// Errors if:
|
||||||
/// - Account is not a signer.
|
/// - Account is not a signer.
|
||||||
pub fn load_signer<'a, 'info>(info: &'a AccountInfo<'info>) -> Result<(), ProgramError> {
|
pub fn load_signer<'a, 'info>(info: &'a AccountInfo<'info>) -> Result<(), ProgramError> {
|
||||||
@@ -127,6 +129,30 @@ pub fn load_config<'a, 'info>(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// asdf
|
||||||
|
pub fn load_noise<'a, 'info>(
|
||||||
|
info: &'a AccountInfo<'info>,
|
||||||
|
is_writable: bool,
|
||||||
|
) -> Result<(), ProgramError> {
|
||||||
|
if info.owner.ne(&crate::id()) {
|
||||||
|
return Err(ProgramError::InvalidAccountOwner);
|
||||||
|
}
|
||||||
|
|
||||||
|
if info.key.ne(&NOISE_ADDRESS) {
|
||||||
|
return Err(ProgramError::InvalidSeeds);
|
||||||
|
}
|
||||||
|
|
||||||
|
if info.data_is_empty() {
|
||||||
|
return Err(ProgramError::UninitializedAccount);
|
||||||
|
}
|
||||||
|
|
||||||
|
if is_writable && !info.is_writable {
|
||||||
|
return Err(ProgramError::InvalidAccountData);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Errors if:
|
/// Errors if:
|
||||||
/// - Owner is not Ore program.
|
/// - Owner is not Ore program.
|
||||||
/// - Data is empty.
|
/// - Data is empty.
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ use crate::{
|
|||||||
utils::create_pda,
|
utils::create_pda,
|
||||||
utils::AccountDeserialize,
|
utils::AccountDeserialize,
|
||||||
utils::Discriminator,
|
utils::Discriminator,
|
||||||
BUS, BUS_COUNT, CONFIG, INITIAL_DIFFICULTY, INITIAL_REWARD_RATE, METADATA, METADATA_NAME,
|
BUS, BUS_COUNT, CONFIG, METADATA, METADATA_NAME, METADATA_SYMBOL, METADATA_URI, MINT,
|
||||||
METADATA_SYMBOL, METADATA_URI, MINT, MINT_ADDRESS, MINT_NOISE, TOKEN_DECIMALS, TREASURY,
|
MINT_ADDRESS, MINT_NOISE, TOKEN_DECIMALS, TREASURY,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Initialize sets up the Ore program. Its responsibilities include:
|
/// Initialize sets up the Ore program. Its responsibilities include:
|
||||||
@@ -131,7 +131,7 @@ pub fn process_initialize<'a, 'info>(
|
|||||||
config_data[0] = Config::discriminator() as u8;
|
config_data[0] = Config::discriminator() as u8;
|
||||||
let config = Config::try_from_bytes_mut(&mut config_data)?;
|
let config = Config::try_from_bytes_mut(&mut config_data)?;
|
||||||
config.admin = *signer.key;
|
config.admin = *signer.key;
|
||||||
config.difficulty = INITIAL_DIFFICULTY.into();
|
// config.difficulty = INITIAL_DIFFICULTY.into();
|
||||||
|
|
||||||
// Initialize treasury
|
// Initialize treasury
|
||||||
create_pda(
|
create_pda(
|
||||||
@@ -146,8 +146,8 @@ pub fn process_initialize<'a, 'info>(
|
|||||||
treasury_data[0] = Treasury::discriminator() as u8;
|
treasury_data[0] = Treasury::discriminator() as u8;
|
||||||
let treasury = Treasury::try_from_bytes_mut(&mut treasury_data)?;
|
let treasury = Treasury::try_from_bytes_mut(&mut treasury_data)?;
|
||||||
treasury.bump = args.treasury_bump as u64;
|
treasury.bump = args.treasury_bump as u64;
|
||||||
treasury.last_reset_at = 0;
|
// treasury.last_reset_at = 0;
|
||||||
treasury.reward_rate = INITIAL_REWARD_RATE;
|
// treasury.reward_rate = INITIAL_REWARD_RATE;
|
||||||
treasury.total_claimed_rewards = 0;
|
treasury.total_claimed_rewards = 0;
|
||||||
drop(treasury_data);
|
drop(treasury_data);
|
||||||
|
|
||||||
|
|||||||
@@ -4,8 +4,7 @@ use solana_program::{
|
|||||||
account_info::AccountInfo,
|
account_info::AccountInfo,
|
||||||
clock::Clock,
|
clock::Clock,
|
||||||
entrypoint::ProgramResult,
|
entrypoint::ProgramResult,
|
||||||
keccak::{hashv, Hash as KeccakHash},
|
keccak::hashv,
|
||||||
program::set_return_data,
|
|
||||||
program_error::ProgramError,
|
program_error::ProgramError,
|
||||||
pubkey::Pubkey,
|
pubkey::Pubkey,
|
||||||
slot_hashes::SlotHash,
|
slot_hashes::SlotHash,
|
||||||
@@ -16,24 +15,26 @@ use crate::{
|
|||||||
error::OreError,
|
error::OreError,
|
||||||
instruction::MineArgs,
|
instruction::MineArgs,
|
||||||
loaders::*,
|
loaders::*,
|
||||||
state::{Bus, Proof, Treasury},
|
state::{Bus, Config, Proof},
|
||||||
utils::AccountDeserialize,
|
utils::AccountDeserialize,
|
||||||
EPOCH_DURATION, START_AT,
|
DIFFICULTY_RANGE, EPOCH_DURATION,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// TODO Look into tx introspection to require 1 hash per tx
|
||||||
|
|
||||||
/// Mine is the primary workhorse instruction of the Ore program. Its responsibilities include:
|
/// Mine is the primary workhorse instruction of the Ore program. Its responsibilities include:
|
||||||
/// 1. Verify the provided hash is valid.
|
/// 1. Calculate the hash from the provided nonce.
|
||||||
/// 2. Increment the user's claimable rewards counter.
|
/// 2. Payout rewards based on difficulty, staking multiplier, and liveness penalty.
|
||||||
/// 3. Generate a new challenge for the miner.
|
/// 3. Generate a new challenge for the miner.
|
||||||
/// 4. Update the miner's lifetime stats.
|
/// 4. Update the miner's lifetime stats.
|
||||||
///
|
///
|
||||||
/// Safety requirements:
|
/// Safety requirements:
|
||||||
/// - Mine is a permissionless instruction and can be called by any signer.
|
/// - Mine is a permissionless instruction and can be called by any signer.
|
||||||
/// - Can only succeed if START_AT has passed.
|
/// - Can only succeed if mining is not paused.
|
||||||
/// - Can only succeed if the last reset was less than 60 seconds ago.
|
/// - Can only succeed if the last reset was less than 60 seconds ago.
|
||||||
/// - Can only succeed if the provided SHA3 hash and nonce are valid and satisfy the difficulty.
|
/// - Can only succeed if the provided hash satisfies the minimum difficulty requirement.
|
||||||
/// - The the provided proof account must be associated with the signer.
|
/// - The the provided proof account must be associated with the signer.
|
||||||
/// - The provided bus, treasury, and slot hash sysvar must be valid.
|
/// - The provided bus, config, noise, stake, and slot hash sysvar must be valid.
|
||||||
pub fn process_mine<'a, 'info>(
|
pub fn process_mine<'a, 'info>(
|
||||||
_program_id: &Pubkey,
|
_program_id: &Pubkey,
|
||||||
accounts: &'a [AccountInfo<'info>],
|
accounts: &'a [AccountInfo<'info>],
|
||||||
@@ -43,115 +44,118 @@ pub fn process_mine<'a, 'info>(
|
|||||||
let args = MineArgs::try_from_bytes(data)?;
|
let args = MineArgs::try_from_bytes(data)?;
|
||||||
|
|
||||||
// Load accounts
|
// Load accounts
|
||||||
let [signer, bus_info, proof_info, treasury_info, slot_hashes_info] = accounts else {
|
let [signer, bus_info, config_info, noise_info, proof_info, slot_hashes_info] = accounts else {
|
||||||
return Err(ProgramError::NotEnoughAccountKeys);
|
return Err(ProgramError::NotEnoughAccountKeys);
|
||||||
};
|
};
|
||||||
load_signer(signer)?;
|
load_signer(signer)?;
|
||||||
load_any_bus(bus_info, true)?;
|
load_any_bus(bus_info, true)?;
|
||||||
|
load_config(config_info, false)?;
|
||||||
|
load_noise(noise_info, false)?;
|
||||||
load_proof(proof_info, signer.key, true)?;
|
load_proof(proof_info, signer.key, true)?;
|
||||||
load_treasury(treasury_info, false)?;
|
|
||||||
load_sysvar(slot_hashes_info, sysvar::slot_hashes::id())?;
|
load_sysvar(slot_hashes_info, sysvar::slot_hashes::id())?;
|
||||||
|
|
||||||
// Validate mining has starting
|
// Validate mining is allowed
|
||||||
|
let config_data = config_info.data.borrow();
|
||||||
|
let config = Config::try_from_bytes(&config_data)?;
|
||||||
|
if config.paused.ne(&0) {
|
||||||
|
return Err(OreError::IsPaused.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate the clock state
|
||||||
let clock = Clock::get().or(Err(ProgramError::InvalidAccountData))?;
|
let clock = Clock::get().or(Err(ProgramError::InvalidAccountData))?;
|
||||||
if clock.unix_timestamp.lt(&START_AT) {
|
let mut proof_data = proof_info.data.borrow_mut();
|
||||||
return Err(OreError::NotStarted.into());
|
let proof = Proof::try_from_bytes_mut(&mut proof_data)?;
|
||||||
|
if clock.unix_timestamp.lt(&proof.last_hash_at) {
|
||||||
|
return Err(OreError::ClockInvalid.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate epoch is active
|
// Validate epoch is active
|
||||||
let treasury_data = treasury_info.data.borrow();
|
// let treasury_data = treasury_info.data.borrow();
|
||||||
let treasury = Treasury::try_from_bytes(&treasury_data)?;
|
// let treasury = Treasury::try_from_bytes(&treasury_data)?;
|
||||||
let threshold = treasury.last_reset_at.saturating_add(EPOCH_DURATION);
|
// let threshold = treasury.last_reset_at.saturating_add(EPOCH_DURATION);
|
||||||
if clock.unix_timestamp.ge(&threshold) {
|
// if clock.unix_timestamp.ge(&threshold) {
|
||||||
return Err(OreError::NeedsReset.into());
|
// return Err(OreError::NeedsReset.into());
|
||||||
|
// }
|
||||||
|
|
||||||
|
// Calculate the hash from the provided nonce
|
||||||
|
let noise_data = noise_info.data.borrow();
|
||||||
|
let hx = drillx::hash(&proof.hash, &args.nonce, &noise_data);
|
||||||
|
drop(noise_data);
|
||||||
|
|
||||||
|
// Validate hash satisfies the minimnum difficulty
|
||||||
|
let difficulty = drillx::difficulty(hx);
|
||||||
|
if difficulty.le(&config.min_difficulty) {
|
||||||
|
return Err(OreError::DifficultyInsufficient.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate provided hash
|
// Calculate base reward rate
|
||||||
let mut proof_data = proof_info.data.borrow_mut();
|
let difficulty = difficulty
|
||||||
let proof = Proof::try_from_bytes_mut(&mut proof_data)?;
|
.saturating_sub(config.min_difficulty)
|
||||||
// let hash = validate_hash(
|
.min(DIFFICULTY_RANGE as u32);
|
||||||
// proof.hash.into(),
|
let mut reward = config
|
||||||
// *signer.key,
|
.base_reward_rate
|
||||||
// u64::from_le_bytes(args.nonce),
|
.saturating_mul(2u64.saturating_pow(difficulty));
|
||||||
// proof.difficulty.into(),
|
|
||||||
// )?;
|
|
||||||
|
|
||||||
// TODO Calculate reward based on difficulty
|
// Apply staking multiplier
|
||||||
// TODO Calculate rewards multiplier
|
if clock.slot.gt(&proof.last_deposit_slot) {
|
||||||
// TODO Calculate reward payout amount
|
// Only apply if last deposit was at least 1 block ago to prevent flash loan attacks.
|
||||||
|
// TODO Cleanup math with a const here (unnecessary cus)
|
||||||
|
// TODO Maybe move const into config!?
|
||||||
|
let max_stake = reward
|
||||||
|
.saturating_mul(60) // min/hour
|
||||||
|
.saturating_mul(24) // hour/day
|
||||||
|
.saturating_mul(365) // day/year
|
||||||
|
.saturating_mul(2); // year
|
||||||
|
let staking_reward = proof
|
||||||
|
.balance
|
||||||
|
.min(max_stake)
|
||||||
|
.saturating_mul(reward)
|
||||||
|
.saturating_div(max_stake);
|
||||||
|
reward = reward.saturating_add(staking_reward);
|
||||||
|
}
|
||||||
|
|
||||||
// Update claimable rewards
|
// Apply liveness penalty
|
||||||
|
// TODO Should penalty be symmetric?
|
||||||
|
// TODO Or should the curve be steeper on the <1 min side?
|
||||||
|
// TODO Eg anything more frequent than 40 seconds should get 0
|
||||||
|
// TODO Anything longer than 2 minutes should be 0
|
||||||
|
let tolerance = 5i64; // TODO Get from config
|
||||||
|
let target_time = proof.last_hash_at.saturating_add(EPOCH_DURATION);
|
||||||
|
if clock
|
||||||
|
.unix_timestamp
|
||||||
|
.saturating_sub(target_time)
|
||||||
|
.abs()
|
||||||
|
.gt(&tolerance)
|
||||||
|
{
|
||||||
|
// TODO Apply
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update balances
|
||||||
let mut bus_data = bus_info.data.borrow_mut();
|
let mut bus_data = bus_info.data.borrow_mut();
|
||||||
let bus = Bus::try_from_bytes_mut(&mut bus_data)?;
|
let bus = Bus::try_from_bytes_mut(&mut bus_data)?;
|
||||||
bus.rewards = bus
|
bus.rewards = bus
|
||||||
.rewards
|
.rewards
|
||||||
.checked_sub(treasury.reward_rate)
|
.checked_sub(reward)
|
||||||
.ok_or(OreError::BusRewardsInsufficient)?;
|
.ok_or(OreError::BusRewardsInsufficient)?;
|
||||||
proof.balance = proof.balance.saturating_add(treasury.reward_rate);
|
proof.balance = proof.balance.saturating_add(reward);
|
||||||
|
|
||||||
// Hash recent slot hash into the next challenge to prevent pre-mining attacks
|
// Hash recent slot hash into the next challenge to prevent pre-mining attacks
|
||||||
proof.hash = hashv(&[
|
proof.hash = hashv(&[
|
||||||
// TODO
|
hx.as_slice(),
|
||||||
// hash.as_ref(),
|
|
||||||
&slot_hashes_info.data.borrow()[0..size_of::<SlotHash>()],
|
&slot_hashes_info.data.borrow()[0..size_of::<SlotHash>()],
|
||||||
])
|
])
|
||||||
.into();
|
.0;
|
||||||
|
|
||||||
|
// Update time trackers
|
||||||
|
proof.last_deposit_slot = clock.slot;
|
||||||
|
proof.last_hash_at = clock.unix_timestamp;
|
||||||
|
|
||||||
// Update lifetime stats
|
// Update lifetime stats
|
||||||
proof.total_hashes = proof.total_hashes.saturating_add(1);
|
proof.total_hashes = proof.total_hashes.saturating_add(1);
|
||||||
proof.total_rewards = proof.total_rewards.saturating_add(treasury.reward_rate);
|
proof.total_rewards = proof.total_rewards.saturating_add(reward);
|
||||||
|
|
||||||
// Log the mined rewards
|
// Log the mined rewards
|
||||||
set_return_data(treasury.reward_rate.to_le_bytes().as_slice());
|
// set_return_data(reward.to_le_bytes().as_slice());
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Validates the provided hash, ensursing it is equal to SHA3(current_hash, singer, nonce).
|
|
||||||
/// Fails if the provided hash is valid but does not satisfy the required difficulty.
|
|
||||||
pub(crate) fn validate_hash(
|
|
||||||
current_hash: KeccakHash,
|
|
||||||
signer: Pubkey,
|
|
||||||
nonce: u64,
|
|
||||||
difficulty: KeccakHash,
|
|
||||||
) -> Result<KeccakHash, ProgramError> {
|
|
||||||
let hash = hashv(&[
|
|
||||||
nonce.to_le_bytes().as_slice(),
|
|
||||||
current_hash.as_ref(),
|
|
||||||
signer.as_ref(),
|
|
||||||
]);
|
|
||||||
if hash.gt(&difficulty) {
|
|
||||||
return Err(OreError::HashInvalid.into());
|
|
||||||
}
|
|
||||||
Ok(hash)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use solana_program::{
|
|
||||||
keccak::{Hash, HASH_BYTES},
|
|
||||||
pubkey::Pubkey,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::validate_hash;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_validate_hash_pass() {
|
|
||||||
let h1 = Hash::new_from_array([1; HASH_BYTES]);
|
|
||||||
let signer = Pubkey::new_unique();
|
|
||||||
let nonce = 10u64;
|
|
||||||
let difficulty = Hash::new_from_array([255; HASH_BYTES]);
|
|
||||||
let res = validate_hash(h1, signer, nonce, difficulty);
|
|
||||||
assert!(res.is_ok());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_validate_hash_fail() {
|
|
||||||
let h1 = Hash::new_from_array([1; HASH_BYTES]);
|
|
||||||
let signer = Pubkey::new_unique();
|
|
||||||
let nonce = 10u64;
|
|
||||||
let difficulty = Hash::new_from_array([0; HASH_BYTES]);
|
|
||||||
let res = validate_hash(h1, signer, nonce, difficulty);
|
|
||||||
assert!(res.is_err());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -14,7 +14,9 @@ use crate::{
|
|||||||
PROOF,
|
PROOF,
|
||||||
};
|
};
|
||||||
|
|
||||||
// TODO Create a stake account
|
// TODO Create a stake account (token account)
|
||||||
|
// TODO Need to keep claimable balance (from treasury) separate from staking balance (from stake account)
|
||||||
|
// TODO Multiplier calculations should account for both
|
||||||
|
|
||||||
/// Register generates a new hash chain for a prospective miner. Its responsibilities include:
|
/// Register generates a new hash chain for a prospective miner. Its responsibilities include:
|
||||||
/// 1. Initialize a new proof account.
|
/// 1. Initialize a new proof account.
|
||||||
@@ -65,9 +67,8 @@ pub fn process_register<'a, 'info>(
|
|||||||
signer.key.as_ref(),
|
signer.key.as_ref(),
|
||||||
&slot_hashes_info.data.borrow()[0..size_of::<SlotHash>()],
|
&slot_hashes_info.data.borrow()[0..size_of::<SlotHash>()],
|
||||||
])
|
])
|
||||||
.into();
|
.0;
|
||||||
proof.last_hash_at = 0;
|
proof.last_hash_at = 0;
|
||||||
proof.multiplier = 1; // TODO
|
|
||||||
proof.total_hashes = 0;
|
proof.total_hashes = 0;
|
||||||
proof.total_rewards = 0;
|
proof.total_rewards = 0;
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,6 @@
|
|||||||
use solana_program::{
|
use solana_program::{account_info::AccountInfo, entrypoint::ProgramResult, pubkey::Pubkey};
|
||||||
account_info::AccountInfo, clock::Clock, entrypoint::ProgramResult,
|
|
||||||
program_error::ProgramError, pubkey::Pubkey, sysvar::Sysvar,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{BUS_EPOCH_REWARDS, SMOOTHING_FACTOR, TARGET_EPOCH_REWARDS};
|
||||||
error::OreError,
|
|
||||||
loaders::*,
|
|
||||||
state::{Bus, Treasury},
|
|
||||||
utils::AccountDeserialize,
|
|
||||||
BUS_COUNT, BUS_EPOCH_REWARDS, EPOCH_DURATION, MAX_EPOCH_REWARDS, SMOOTHING_FACTOR, START_AT,
|
|
||||||
TARGET_EPOCH_REWARDS, TREASURY,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Reset sets up the Ore program for the next epoch. Its responsibilities include:
|
/// Reset sets up the Ore program for the next epoch. Its responsibilities include:
|
||||||
/// 1. Reset bus account rewards counters.
|
/// 1. Reset bus account rewards counters.
|
||||||
@@ -33,85 +23,85 @@ pub fn process_reset<'a, 'info>(
|
|||||||
accounts: &'a [AccountInfo<'info>],
|
accounts: &'a [AccountInfo<'info>],
|
||||||
_data: &[u8],
|
_data: &[u8],
|
||||||
) -> ProgramResult {
|
) -> ProgramResult {
|
||||||
// Load accounts
|
// // Load accounts
|
||||||
let [signer, bus_0_info, bus_1_info, bus_2_info, bus_3_info, bus_4_info, bus_5_info, bus_6_info, bus_7_info, mint_info, treasury_info, treasury_tokens_info, token_program] =
|
// let [signer, bus_0_info, bus_1_info, bus_2_info, bus_3_info, bus_4_info, bus_5_info, bus_6_info, bus_7_info, mint_info, treasury_info, treasury_tokens_info, token_program] =
|
||||||
accounts
|
// accounts
|
||||||
else {
|
// else {
|
||||||
return Err(ProgramError::NotEnoughAccountKeys);
|
// return Err(ProgramError::NotEnoughAccountKeys);
|
||||||
};
|
// };
|
||||||
load_signer(signer)?;
|
// load_signer(signer)?;
|
||||||
load_bus(bus_0_info, 0, true)?;
|
// load_bus(bus_0_info, 0, true)?;
|
||||||
load_bus(bus_1_info, 1, true)?;
|
// load_bus(bus_1_info, 1, true)?;
|
||||||
load_bus(bus_2_info, 2, true)?;
|
// load_bus(bus_2_info, 2, true)?;
|
||||||
load_bus(bus_3_info, 3, true)?;
|
// load_bus(bus_3_info, 3, true)?;
|
||||||
load_bus(bus_4_info, 4, true)?;
|
// load_bus(bus_4_info, 4, true)?;
|
||||||
load_bus(bus_5_info, 5, true)?;
|
// load_bus(bus_5_info, 5, true)?;
|
||||||
load_bus(bus_6_info, 6, true)?;
|
// load_bus(bus_6_info, 6, true)?;
|
||||||
load_bus(bus_7_info, 7, true)?;
|
// load_bus(bus_7_info, 7, true)?;
|
||||||
load_mint(mint_info, true)?;
|
// load_mint(mint_info, true)?;
|
||||||
load_treasury(treasury_info, true)?;
|
// load_treasury(treasury_info, true)?;
|
||||||
load_token_account(
|
// load_token_account(
|
||||||
treasury_tokens_info,
|
// treasury_tokens_info,
|
||||||
Some(treasury_info.key),
|
// Some(treasury_info.key),
|
||||||
mint_info.key,
|
// mint_info.key,
|
||||||
true,
|
// true,
|
||||||
)?;
|
// )?;
|
||||||
load_program(token_program, spl_token::id())?;
|
// load_program(token_program, spl_token::id())?;
|
||||||
let busses: [&AccountInfo; BUS_COUNT] = [
|
// let busses: [&AccountInfo; BUS_COUNT] = [
|
||||||
bus_0_info, bus_1_info, bus_2_info, bus_3_info, bus_4_info, bus_5_info, bus_6_info,
|
// bus_0_info, bus_1_info, bus_2_info, bus_3_info, bus_4_info, bus_5_info, bus_6_info,
|
||||||
bus_7_info,
|
// bus_7_info,
|
||||||
];
|
// ];
|
||||||
|
|
||||||
// Validate mining has starting
|
// // Validate mining has starting
|
||||||
let clock = Clock::get().or(Err(ProgramError::InvalidAccountData))?;
|
// let clock = Clock::get().or(Err(ProgramError::InvalidAccountData))?;
|
||||||
if clock.unix_timestamp.lt(&START_AT) {
|
// if clock.unix_timestamp.lt(&START_AT) {
|
||||||
return Err(OreError::NotStarted.into());
|
// return Err(OreError::NotStarted.into());
|
||||||
}
|
// }
|
||||||
|
|
||||||
// Validate at least 60 seconds have passed since last reset
|
// // Validate at least 60 seconds have passed since last reset
|
||||||
let mut treasury_data = treasury_info.data.borrow_mut();
|
// let mut treasury_data = treasury_info.data.borrow_mut();
|
||||||
let treasury = Treasury::try_from_bytes_mut(&mut treasury_data)?;
|
// let treasury = Treasury::try_from_bytes_mut(&mut treasury_data)?;
|
||||||
let threshold = treasury.last_reset_at.saturating_add(EPOCH_DURATION);
|
// let threshold = treasury.last_reset_at.saturating_add(EPOCH_DURATION);
|
||||||
if clock.unix_timestamp.lt(&threshold) {
|
// if clock.unix_timestamp.lt(&threshold) {
|
||||||
return Err(OreError::ResetTooEarly.into());
|
// return Err(OreError::ResetTooEarly.into());
|
||||||
}
|
// }
|
||||||
|
|
||||||
// Record current timestamp
|
// // Record current timestamp
|
||||||
treasury.last_reset_at = clock.unix_timestamp;
|
// treasury.last_reset_at = clock.unix_timestamp;
|
||||||
|
|
||||||
// Reset bus accounts and calculate actual rewards mined since last reset
|
// // Reset bus accounts and calculate actual rewards mined since last reset
|
||||||
let mut total_remaining_rewards = 0u64;
|
// let mut total_remaining_rewards = 0u64;
|
||||||
for i in 0..BUS_COUNT {
|
// for i in 0..BUS_COUNT {
|
||||||
let mut bus_data = busses[i].data.borrow_mut();
|
// let mut bus_data = busses[i].data.borrow_mut();
|
||||||
let bus = Bus::try_from_bytes_mut(&mut bus_data)?;
|
// let bus = Bus::try_from_bytes_mut(&mut bus_data)?;
|
||||||
total_remaining_rewards = total_remaining_rewards.saturating_add(bus.rewards);
|
// total_remaining_rewards = total_remaining_rewards.saturating_add(bus.rewards);
|
||||||
bus.rewards = BUS_EPOCH_REWARDS;
|
// bus.rewards = BUS_EPOCH_REWARDS;
|
||||||
}
|
// }
|
||||||
let total_epoch_rewards = MAX_EPOCH_REWARDS.saturating_sub(total_remaining_rewards);
|
// let total_epoch_rewards = MAX_EPOCH_REWARDS.saturating_sub(total_remaining_rewards);
|
||||||
|
|
||||||
// Update reward rate for next epoch
|
// // Update reward rate for next epoch
|
||||||
treasury.reward_rate = calculate_new_reward_rate(treasury.reward_rate, total_epoch_rewards);
|
// treasury.reward_rate = calculate_new_reward_rate(treasury.reward_rate, total_epoch_rewards);
|
||||||
|
|
||||||
// Fund treasury token account
|
// // Fund treasury token account
|
||||||
let treasury_bump = treasury.bump as u8;
|
// let treasury_bump = treasury.bump as u8;
|
||||||
drop(treasury_data);
|
// drop(treasury_data);
|
||||||
solana_program::program::invoke_signed(
|
// solana_program::program::invoke_signed(
|
||||||
&spl_token::instruction::mint_to(
|
// &spl_token::instruction::mint_to(
|
||||||
&spl_token::id(),
|
// &spl_token::id(),
|
||||||
mint_info.key,
|
// mint_info.key,
|
||||||
treasury_tokens_info.key,
|
// treasury_tokens_info.key,
|
||||||
treasury_info.key,
|
// treasury_info.key,
|
||||||
&[treasury_info.key],
|
// &[treasury_info.key],
|
||||||
total_epoch_rewards,
|
// total_epoch_rewards,
|
||||||
)?,
|
// )?,
|
||||||
&[
|
// &[
|
||||||
token_program.clone(),
|
// token_program.clone(),
|
||||||
mint_info.clone(),
|
// mint_info.clone(),
|
||||||
treasury_tokens_info.clone(),
|
// treasury_tokens_info.clone(),
|
||||||
treasury_info.clone(),
|
// treasury_info.clone(),
|
||||||
],
|
// ],
|
||||||
&[&[TREASURY, &[treasury_bump]]],
|
// &[&[TREASURY, &[treasury_bump]]],
|
||||||
)?;
|
// )?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
1
src/processor/stake.rs
Normal file
1
src/processor/stake.rs
Normal file
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
@@ -17,12 +17,6 @@ pub struct Bus {
|
|||||||
|
|
||||||
/// The quantity of rewards this bus can issue in the current epoch epoch.
|
/// The quantity of rewards this bus can issue in the current epoch epoch.
|
||||||
pub rewards: u64,
|
pub rewards: u64,
|
||||||
|
|
||||||
/// Histogram of hash count per difficulty
|
|
||||||
pub hash_hist: [u64; 32],
|
|
||||||
|
|
||||||
/// Cumulative sum of applied multipliers per difficulty
|
|
||||||
pub multiplier_hist: [u64; 32],
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Discriminator for Bus {
|
impl Discriminator for Bus {
|
||||||
|
|||||||
@@ -2,9 +2,10 @@ use bytemuck::{Pod, Zeroable};
|
|||||||
use shank::ShankAccount;
|
use shank::ShankAccount;
|
||||||
use solana_program::pubkey::Pubkey;
|
use solana_program::pubkey::Pubkey;
|
||||||
|
|
||||||
|
// TODO next_min_difficulty: Option<u8>, update on reset
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
impl_account_from_bytes, impl_to_bytes,
|
impl_account_from_bytes, impl_to_bytes,
|
||||||
state::Hash,
|
|
||||||
utils::{AccountDiscriminator, Discriminator},
|
utils::{AccountDiscriminator, Discriminator},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -15,8 +16,14 @@ pub struct Config {
|
|||||||
/// The admin authority with permission to update the difficulty.
|
/// The admin authority with permission to update the difficulty.
|
||||||
pub admin: Pubkey,
|
pub admin: Pubkey,
|
||||||
|
|
||||||
/// The hash difficulty.
|
/// The base reward rate paid out for a hash of minimum difficulty.
|
||||||
pub difficulty: Hash,
|
pub base_reward_rate: u64,
|
||||||
|
|
||||||
|
/// The minimum accepted difficulty.
|
||||||
|
pub min_difficulty: u32,
|
||||||
|
|
||||||
|
/// Is mining paused.
|
||||||
|
pub paused: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Discriminator for Config {
|
impl Discriminator for Config {
|
||||||
|
|||||||
@@ -30,4 +30,18 @@ impl fmt::Display for Hash {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Hash {
|
||||||
|
pub fn difficulty(&self) -> u32 {
|
||||||
|
let mut count = 0;
|
||||||
|
for &byte in &self.0 {
|
||||||
|
let lz = byte.leading_zeros();
|
||||||
|
count += lz;
|
||||||
|
if lz < 8 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
count
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl_to_bytes!(Hash);
|
impl_to_bytes!(Hash);
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
mod bus;
|
mod bus;
|
||||||
mod config;
|
mod config;
|
||||||
mod hash;
|
// mod hash;
|
||||||
mod proof;
|
mod proof;
|
||||||
mod treasury;
|
mod treasury;
|
||||||
|
|
||||||
pub use bus::*;
|
pub use bus::*;
|
||||||
pub use config::*;
|
pub use config::*;
|
||||||
pub use hash::*;
|
// pub use hash::*;
|
||||||
pub use proof::*;
|
pub use proof::*;
|
||||||
pub use treasury::*;
|
pub use treasury::*;
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ use solana_program::pubkey::Pubkey;
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
impl_account_from_bytes, impl_to_bytes,
|
impl_account_from_bytes, impl_to_bytes,
|
||||||
state::Hash,
|
|
||||||
utils::{AccountDiscriminator, Discriminator},
|
utils::{AccountDiscriminator, Discriminator},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -16,18 +15,17 @@ pub struct Proof {
|
|||||||
/// The signer authorized to use this proof.
|
/// The signer authorized to use this proof.
|
||||||
pub authority: Pubkey,
|
pub authority: Pubkey,
|
||||||
|
|
||||||
/// The quantity of tokens this miner may claim from the treasury.
|
/// The quantity of tokens this miner has staked or earned.
|
||||||
pub balance: u64,
|
pub balance: u64,
|
||||||
|
|
||||||
/// The proof's current hash.
|
/// The proof's current hash.
|
||||||
pub hash: Hash,
|
pub hash: [u8; 32],
|
||||||
|
|
||||||
|
/// The last slot ore was deposited into this account.
|
||||||
|
pub last_deposit_slot: u64,
|
||||||
|
|
||||||
/// The last time this account provided a hash.
|
/// The last time this account provided a hash.
|
||||||
pub last_hash_at: u64,
|
pub last_hash_at: i64,
|
||||||
|
|
||||||
// TODO Figure out multiplier representation
|
|
||||||
/// The rewards multiplier for this account.
|
|
||||||
pub multiplier: u64,
|
|
||||||
|
|
||||||
/// The total lifetime hashes provided by this miner.
|
/// The total lifetime hashes provided by this miner.
|
||||||
pub total_hashes: u64,
|
pub total_hashes: u64,
|
||||||
|
|||||||
@@ -14,12 +14,6 @@ pub struct Treasury {
|
|||||||
/// The bump of the treasury account PDA, for signing CPIs.
|
/// The bump of the treasury account PDA, for signing CPIs.
|
||||||
pub bump: u64,
|
pub bump: u64,
|
||||||
|
|
||||||
/// The timestamp of the reset invocation.
|
|
||||||
pub last_reset_at: i64,
|
|
||||||
|
|
||||||
/// The reward rate to payout to miners for submiting valid hashes.
|
|
||||||
pub reward_rate: u64,
|
|
||||||
|
|
||||||
/// The total lifetime claimed rewards of the program.
|
/// The total lifetime claimed rewards of the program.
|
||||||
pub total_claimed_rewards: u64,
|
pub total_claimed_rewards: u64,
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user