Initial Commit

This commit is contained in:
2024-07-11 20:34:07 +01:00
commit bc50e0e088
4 changed files with 362 additions and 0 deletions

62
src/lib.rs Normal file
View File

@@ -0,0 +1,62 @@
use chrono::prelude::*;
// TODO review whether a genesis block has a block height of 1 or 0
type BlockHeight = i64;
pub struct BlockchainBlockInfo {
block_period: u64, // in seconds maybe?
latest_block_height: BlockHeight,
latest_block_time: DateTime<Utc>,
}
pub fn time_to_blockheight(time: DateTime<Utc>, blockchain: BlockchainBlockInfo) -> BlockHeight {
let time_difference = (time - blockchain.latest_block_time).num_seconds();
let num_blocks = time_difference / blockchain.block_period as i64;
num_blocks + blockchain.latest_block_height
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_block_time_away() {
let latest_block_time = Utc.with_ymd_and_hms(2024, 10, 10, 10, 10, 0).unwrap();
let wanted_future_block_time = Utc.with_ymd_and_hms(2024, 10, 10, 10, 20, 1).unwrap();
let blockchain_info = BlockchainBlockInfo {
block_period: 60 * 10, // 10 minutes
latest_block_height: 1000,
latest_block_time,
};
let result = time_to_blockheight(wanted_future_block_time, blockchain_info);
assert_eq!(result, 1001);
}
#[test]
fn one_block_time_previous() {
let latest_block_time = Utc.with_ymd_and_hms(2024, 10, 10, 10, 20, 1).unwrap();
let wanted_future_block_time = Utc.with_ymd_and_hms(2024, 10, 10, 10, 10, 0).unwrap();
let blockchain_info = BlockchainBlockInfo {
block_period: 60 * 10, // 10 minutes
latest_block_height: 1000,
latest_block_time,
};
let result = time_to_blockheight(wanted_future_block_time, blockchain_info);
assert_eq!(result, 999);
}
#[test]
fn negative_block_time() {
let latest_block_time = Utc.with_ymd_and_hms(2024, 10, 10, 10, 30, 0).unwrap();
let wanted_negative_block_time = Utc.with_ymd_and_hms(2024, 10, 10, 10, 10, 0).unwrap();
let blockchain_info = BlockchainBlockInfo {
block_period: 60 * 10, // 10 minutes
latest_block_height: 1,
latest_block_time,
};
let result = time_to_blockheight(wanted_negative_block_time, blockchain_info);
assert_eq!(result, -1);
}
}