src/transactions/types.rs
pub const TARGET_BLOCK_TIME: u32 = 15;
impl Block {
pub fn adjust_difficulty(previous_timestamp: u32, current_timestamp: u32, current_difficulty: u32) -> u32 {
// calculate the time between the previous block and the current block
let time_since_parent = current_timestamp - previous_timestamp;
// set an acceptable time frame for difficulty to have met
let max_time = TARGET_BLOCK_TIME + 5;
let min_time = TARGET_BLOCK_TIME - 5;
// empty new difficulty and balancer
let mut new_difficulty: u32;
let balancer: f32;
// if time passed is greater than acceptable difficulty
// timeframe adjust the difficulty by making it easier.
if time_since_parent > max_time {
// this results in an offset of how much extra
// time passed that was unacceptable
let offset = (time_since_parent - max_time) as f32;
// a balancing offset is created by taking the offset
// and dividing by the minimum acceptable time.
balancer = offset / min_time as f32;
// new difficulty is current difficulty plus max time
// times balancer times offset
new_difficulty = (current_difficulty as f32 + ((max_time as f32 * balancer) * offset))as u32;
// if time passed is less than acceptable difficulty
// timeframe adjust the difficulty by making it harder.
} else if time_since_parent < min_time {
// this results in an offset of how many more seconds
// were required to reach an acceptable offset
let offset = (min_time - time_since_parent) as f32;
// a balancing offset is created by taking the offset
// and dividing by the maximum acceptable time.
balancer = offset / max_time as f32;
// new difficulty is current difficulty minux min time
// times balancer times offset
new_difficulty = (current_difficulty as f32 - ((min_time as f32 * balancer) * offset)) as u32;
// if the time passed was within the target keep the
// difficulty the same
} else {
new_difficulty = current_difficulty as u32;
}
// if the new difficulty is greater than 5000
// plus the current difficulty set the max to current
// difficulty plus 5000 to prevent wild swings
// in the event of flukes
if new_difficulty > (current_difficulty + 5000) as u32 {
new_difficulty = (current_difficulty + 5000) as u32
}
// if the new difficulty is less than 5000
// taken from the current difficulty set the
// min at a max of current diffoculty minus
// 5000 to prevent wild swings in the event
// of flukes
if new_difficulty < (current_difficulty - 5000) as u32 {
new_difficulty = (current_difficulty - 5000) as u32
}
new_difficulty
}
}