comments and cleanup

This commit is contained in:
Hardhat Chad
2024-07-31 21:03:15 +00:00
parent 213a068fb0
commit 73016f3a23
6 changed files with 60 additions and 19 deletions

View File

@@ -434,3 +434,16 @@ pub fn load_program<'a, 'info>(
Ok(()) Ok(())
} }
/// Errors if:
/// - Account is not writable.
pub fn load_any<'a, 'info>(
info: &'a AccountInfo<'info>,
is_writable: bool,
) -> Result<(), ProgramError> {
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}

View File

@@ -105,6 +105,8 @@ pub fn process_initialize<'a, 'info>(
let bus = Bus::try_from_bytes_mut(&mut bus_data)?; let bus = Bus::try_from_bytes_mut(&mut bus_data)?;
bus.id = i as u64; bus.id = i as u64;
bus.rewards = 0; bus.rewards = 0;
bus.theoretical_rewards = 0;
bus.top_balance = 0;
} }
// Initialize config. // Initialize config.

View File

@@ -45,6 +45,9 @@ pub fn process_mine<'a, 'info>(accounts: &'a [AccountInfo<'info>], data: &[u8])
load_sysvar(slot_hashes_sysvar, sysvar::slot_hashes::id())?; load_sysvar(slot_hashes_sysvar, sysvar::slot_hashes::id())?;
// Authenticate the proof account. // Authenticate the proof account.
//
// Only one proof account can be used for any given transaction. All `mine` instructions
// in the transaction must use the same proof account.
authenticate(&instructions_sysvar.data.borrow(), proof_info.key)?; authenticate(&instructions_sysvar.data.borrow(), proof_info.key)?;
// Validate epoch is active. // Validate epoch is active.
@@ -60,6 +63,9 @@ pub fn process_mine<'a, 'info>(accounts: &'a [AccountInfo<'info>], data: &[u8])
} }
// Validate the hash digest. // Validate the hash digest.
//
// Here we use drillx to validate the provided solution is a valid hash of the challenge.
// If invalid, we return an error.
let mut proof_data = proof_info.data.borrow_mut(); let mut proof_data = proof_info.data.borrow_mut();
let proof = Proof::try_from_bytes_mut(&mut proof_data)?; let proof = Proof::try_from_bytes_mut(&mut proof_data)?;
let solution = Solution::new(args.digest, args.nonce); let solution = Solution::new(args.digest, args.nonce);
@@ -68,6 +74,9 @@ pub fn process_mine<'a, 'info>(accounts: &'a [AccountInfo<'info>], data: &[u8])
} }
// Reject spam transactions. // Reject spam transactions.
//
// If a miner attempts to submit solutions too frequently, we reject with an error. In general,
// miners are limited to 1 hash per epoch on average.
let t: i64 = clock.unix_timestamp; let t: i64 = clock.unix_timestamp;
let t_target = proof.last_hash_at.saturating_add(ONE_MINUTE); let t_target = proof.last_hash_at.saturating_add(ONE_MINUTE);
let t_spam = t_target.saturating_sub(TOLERANCE); let t_spam = t_target.saturating_sub(TOLERANCE);
@@ -76,15 +85,18 @@ pub fn process_mine<'a, 'info>(accounts: &'a [AccountInfo<'info>], data: &[u8])
} }
// Validate the hash satisfies the minimum difficulty. // Validate the hash satisfies the minimum difficulty.
//
// We use drillx to get the difficulty (leading zeros) of the hash. If the hash does not have the
// minimum required difficulty, we reject it with an error.
let hash = solution.to_hash(); let hash = solution.to_hash();
let difficulty = hash.difficulty(); let difficulty = hash.difficulty();
if difficulty.lt(&(config.min_difficulty as u32)) { if difficulty.lt(&(config.min_difficulty as u32)) {
return Err(OreError::HashTooEasy.into()); return Err(OreError::HashTooEasy.into());
} }
// Normalize difficulty and calculate reward rate. // Normalize the difficulty and calculate the reward amount.
// //
// The reward double for every bit of difficulty (leading zero) on the hash. We use the normalized // The reward doubles for every bit of difficulty (leading zeros) on the hash. We use the normalized
// difficulty so the minimum accepted difficulty pays out at the base reward rate. // difficulty so the minimum accepted difficulty pays out at the base reward rate.
let normalized_difficulty = difficulty let normalized_difficulty = difficulty
.checked_sub(config.min_difficulty as u32) .checked_sub(config.min_difficulty as u32)
@@ -102,7 +114,7 @@ pub fn process_mine<'a, 'info>(accounts: &'a [AccountInfo<'info>], data: &[u8])
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)?;
if proof.balance.gt(&0) && proof.last_stake_at.saturating_add(ONE_MINUTE).lt(&t) { if proof.balance.gt(&0) && proof.last_stake_at.saturating_add(ONE_MINUTE).lt(&t) {
// Update staking reward // Calculate staking reward.
if config.top_balance.gt(&0) { if config.top_balance.gt(&0) {
let staking_reward = (reward as u128) let staking_reward = (reward as u128)
.checked_mul(proof.balance.min(config.top_balance) as u128) .checked_mul(proof.balance.min(config.top_balance) as u128)
@@ -112,7 +124,7 @@ pub fn process_mine<'a, 'info>(accounts: &'a [AccountInfo<'info>], data: &[u8])
reward = reward.checked_add(staking_reward).unwrap(); reward = reward.checked_add(staking_reward).unwrap();
} }
// Update bus stake tracker if stake is active // Update bus stake tracker.
if proof.balance.gt(&bus.top_balance) { if proof.balance.gt(&bus.top_balance) {
bus.top_balance = proof.balance; bus.top_balance = proof.balance;
} }
@@ -124,7 +136,7 @@ pub fn process_mine<'a, 'info>(accounts: &'a [AccountInfo<'info>], data: &[u8])
// should not be possible to spend ~1 hour on a given challenge and submit a hash with a large // should not be possible to spend ~1 hour on a given challenge and submit a hash with a large
// difficulty value to earn an outsized reward. // difficulty value to earn an outsized reward.
// //
// This penalty works by halving the reward amount for every minute late the solution has been submitted. // The penalty works by halving the reward amount for every minute late the solution has been submitted.
// This ultimately drives the reward to zero given enough time (10-20 minutes). // This ultimately drives the reward to zero given enough time (10-20 minutes).
let t_liveness = t_target.saturating_add(TOLERANCE); let t_liveness = t_target.saturating_add(TOLERANCE);
if t.gt(&t_liveness) { if t.gt(&t_liveness) {
@@ -135,7 +147,7 @@ pub fn process_mine<'a, 'info>(accounts: &'a [AccountInfo<'info>], data: &[u8])
reward = reward.saturating_div(2u64.saturating_pow(halvings as u32)); reward = reward.saturating_div(2u64.saturating_pow(halvings as u32));
} }
// Linear decay between minutes // Linear decay with remainder seconds.
let remainder_secs = tardiness.saturating_sub(halvings.saturating_mul(ONE_MINUTE as u64)); let remainder_secs = tardiness.saturating_sub(halvings.saturating_mul(ONE_MINUTE as u64));
if remainder_secs.gt(&0) && reward.gt(&0) { if remainder_secs.gt(&0) && reward.gt(&0) {
let penalty = reward let penalty = reward
@@ -148,17 +160,22 @@ pub fn process_mine<'a, 'info>(accounts: &'a [AccountInfo<'info>], data: &[u8])
// Limit payout amount to whatever is left in the bus. // Limit payout amount to whatever is left in the bus.
// //
// Busses are limited 1 ORE per epoch. This is the maximum amount a miner can earn for any one hash. // Busses are limited to distributing 1 ORE per epoch. This is the maximum amount a miner can earn
// We still track the theoretical rewards that would have been paid out ignoring the bus limit, so the // for any given hash.
// base reward rate will be updated to account for the real hashpower on the network.
let reward_actual = reward.min(bus.rewards); let reward_actual = reward.min(bus.rewards);
// Update balances. // Update balances.
//
// We track the theoretical rewards that would have been paid out ignoring the bus limit, so the
// base reward rate will be updated to account for the real hashpower on the network.
bus.theoretical_rewards = bus.theoretical_rewards.checked_add(reward).unwrap(); bus.theoretical_rewards = bus.theoretical_rewards.checked_add(reward).unwrap();
bus.rewards = bus.rewards.checked_sub(reward_actual).unwrap(); bus.rewards = bus.rewards.checked_sub(reward_actual).unwrap();
proof.balance = proof.balance.checked_add(reward_actual).unwrap(); proof.balance = proof.balance.checked_add(reward_actual).unwrap();
// Hash recent slot hash into the next challenge to prevent pre-mining attacks. // Hash a recent slot hash into the next challenge to prevent pre-mining attacks.
//
// The slot hashes are unpredictable values. By seeding the next challenge with the most recent slot hash,
// miners are forced to submit their current solution before they can begin mining for the next.
proof.last_hash = hash.h; proof.last_hash = hash.h;
proof.challenge = hashv(&[ proof.challenge = hashv(&[
hash.h.as_slice(), hash.h.as_slice(),
@@ -174,6 +191,8 @@ pub fn process_mine<'a, 'info>(accounts: &'a [AccountInfo<'info>], data: &[u8])
proof.total_rewards = proof.total_rewards.saturating_add(reward); proof.total_rewards = proof.total_rewards.saturating_add(reward);
// Log the mined rewards. // Log the mined rewards.
//
// This data can be used by off-chain indexers to display mining stats.
set_return_data( set_return_data(
MineEvent { MineEvent {
difficulty: difficulty as u64, difficulty: difficulty as u64,

View File

@@ -25,7 +25,7 @@ pub fn process_open<'a, 'info>(accounts: &'a [AccountInfo<'info>], data: &[u8])
return Err(ProgramError::NotEnoughAccountKeys); return Err(ProgramError::NotEnoughAccountKeys);
}; };
load_signer(signer)?; load_signer(signer)?;
load_system_account(miner_info, false)?; load_any(miner_info, false)?;
load_signer(payer_info)?; load_signer(payer_info)?;
load_uninitialized_pda( load_uninitialized_pda(
proof_info, proof_info,

View File

@@ -12,7 +12,7 @@ use spl_token::state::Mint;
use crate::utils::AccountDeserialize; use crate::utils::AccountDeserialize;
/// Reset tops up the busses, updates the base reward rate, and sets up the ORE program for the next epoch. /// Reset tops up the bus balances, updates the base reward rate, and sets up the ORE program for the next epoch.
pub fn process_reset<'a, 'info>(accounts: &'a [AccountInfo<'info>], _data: &[u8]) -> ProgramResult { pub fn process_reset<'a, 'info>(accounts: &'a [AccountInfo<'info>], _data: &[u8]) -> 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, config_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, config_info, mint_info, treasury_info, treasury_tokens_info, token_program] =
@@ -39,7 +39,7 @@ pub fn process_reset<'a, 'info>(accounts: &'a [AccountInfo<'info>], _data: &[u8]
bus_7_info, bus_7_info,
]; ];
// Validate enough time has passed since last reset. // Validate enough time has passed since the last reset.
let mut config_data = config_info.data.borrow_mut(); let mut config_data = config_info.data.borrow_mut();
let config = Config::try_from_bytes_mut(&mut config_data)?; let config = Config::try_from_bytes_mut(&mut config_data)?;
let clock = Clock::get().or(Err(ProgramError::InvalidAccountData))?; let clock = Clock::get().or(Err(ProgramError::InvalidAccountData))?;
@@ -51,7 +51,7 @@ pub fn process_reset<'a, 'info>(accounts: &'a [AccountInfo<'info>], _data: &[u8]
return Ok(()); return Ok(());
} }
// Update reset timestamp. // Update timestamp.
config.last_reset_at = clock.unix_timestamp; config.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.
@@ -59,34 +59,41 @@ pub fn process_reset<'a, 'info>(accounts: &'a [AccountInfo<'info>], _data: &[u8]
let mut total_theoretical_rewards = 0u64; let mut total_theoretical_rewards = 0u64;
let mut top_balance = 0u64; let mut top_balance = 0u64;
for i in 0..BUS_COUNT { for i in 0..BUS_COUNT {
// Parse bus account.
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)?;
// Track top balance.
if bus.top_balance.gt(&top_balance) { if bus.top_balance.gt(&top_balance) {
top_balance = bus.top_balance; top_balance = bus.top_balance;
} }
// Track accumulators.
total_remaining_rewards = total_remaining_rewards.saturating_add(bus.rewards); total_remaining_rewards = total_remaining_rewards.saturating_add(bus.rewards);
total_theoretical_rewards = total_theoretical_rewards =
total_theoretical_rewards.saturating_add(bus.theoretical_rewards); total_theoretical_rewards.saturating_add(bus.theoretical_rewards);
// Reset bus account for new epoch.
bus.rewards = BUS_EPOCH_REWARDS; bus.rewards = BUS_EPOCH_REWARDS;
bus.theoretical_rewards = 0; bus.theoretical_rewards = 0;
bus.top_balance = 0; bus.top_balance = 0;
} }
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 the top balance. // Update global top balance.
config.top_balance = top_balance; config.top_balance = top_balance;
// Update base reward rate for next epoch. // Update base reward rate for next epoch.
config.base_reward_rate = config.base_reward_rate =
calculate_new_reward_rate(config.base_reward_rate, total_theoretical_rewards); calculate_new_reward_rate(config.base_reward_rate, total_theoretical_rewards);
// If base_reward_rate is too low, then increment difficulty by 1 and double base reward rate. // If base reward rate is too low, increment min difficulty by 1 and double base reward rate.
if config.base_reward_rate.le(&BASE_REWARD_RATE_MIN_THRESHOLD) { if config.base_reward_rate.le(&BASE_REWARD_RATE_MIN_THRESHOLD) {
config.min_difficulty = config.min_difficulty.checked_add(1).unwrap(); config.min_difficulty = config.min_difficulty.checked_add(1).unwrap();
config.base_reward_rate = config.base_reward_rate.checked_mul(2).unwrap(); config.base_reward_rate = config.base_reward_rate.checked_mul(2).unwrap();
} }
// If base reward rate is too high, then decrement difficulty by 1 and halve base reward rate. // If base reward rate is too high, decrement min difficulty by 1 and halve base reward rate.
if config.base_reward_rate.ge(&BASE_REWARD_RATE_MAX_THRESHOLD) && config.min_difficulty.gt(&1) { if config.base_reward_rate.ge(&BASE_REWARD_RATE_MAX_THRESHOLD) && config.min_difficulty.gt(&1) {
config.min_difficulty = config.min_difficulty.checked_sub(1).unwrap(); config.min_difficulty = config.min_difficulty.checked_sub(1).unwrap();
config.base_reward_rate = config.base_reward_rate.checked_div(2).unwrap(); config.base_reward_rate = config.base_reward_rate.checked_div(2).unwrap();
@@ -98,7 +105,7 @@ pub fn process_reset<'a, 'info>(accounts: &'a [AccountInfo<'info>], _data: &[u8]
return Err(OreError::MaxSupply.into()); return Err(OreError::MaxSupply.into());
} }
// Fund treasury token account. // Fund the treasury token account.
let amount = MAX_SUPPLY let amount = MAX_SUPPLY
.saturating_sub(mint.supply) .saturating_sub(mint.supply)
.min(total_epoch_rewards); .min(total_epoch_rewards);

View File

@@ -15,7 +15,7 @@ pub fn process_update<'a, 'info>(
return Err(ProgramError::NotEnoughAccountKeys); return Err(ProgramError::NotEnoughAccountKeys);
}; };
load_signer(signer)?; load_signer(signer)?;
load_system_account(miner_info, false)?; load_any(miner_info, false)?;
load_proof(proof_info, signer.key, true)?; load_proof(proof_info, signer.key, true)?;
// Update the proof's miner authority. // Update the proof's miner authority.