Added getting and updating BSV time

This commit is contained in:
2024-07-13 20:28:33 +01:00
parent c9a2fe6c71
commit bdc027aa16
3 changed files with 1140 additions and 11 deletions

1097
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -8,3 +8,5 @@ edition = "2021"
[dependencies]
chrono = "0.4.38"
lazy_static = "1.5.0"
reqwest = { version = "0.12.5", features = ["json", "blocking"] }
serde_json = "1.0.120"

View File

@@ -2,6 +2,9 @@ use chrono::prelude::*;
use lazy_static::lazy_static;
use std::convert::Into;
use std::sync::RwLock;
use reqwest;
use serde_json;
use std::collections::HashMap;
// TODO review whether a genesis block has a block height of 1 or 0
@@ -9,12 +12,13 @@ pub enum BlockchainSupported {
BTC,
BSV,
XMR,
ETH,
ETH
}
type BlockHeight = i64;
#[derive(Clone, Copy)]
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct BlockchainInfo {
block_period: u64, // In seconds
latest_block_height: BlockHeight,
@@ -69,11 +73,55 @@ pub fn time_to_blockheight(time: DateTime<Utc>, bi: BlockchainInfo) -> BlockHeig
num_blocks + bi.latest_block_height
}
pub fn update_bsv_blockheight() {
let whatsonchain_url = "https://api.whatsonchain.com/v1/bsv/main/block/headers";
match reqwest::blocking::get(whatsonchain_url) {
Ok(resp) => {
let json = resp.json::<Vec<HashMap<String, serde_json::Value>>>();
match json {
Ok(json) => {
let height = json[0].get("height").unwrap().as_i64().unwrap();
// I am presuming that "time" is when WhatsOnChain saw the block rather than the
// timestamp in the block. I could be very wrong about that though... As I understand
// the timestamp in the block has no garuntee of anything other than maybe it's more
// than the last one.
let unixtime = json[0].get("time").unwrap().as_i64().unwrap();
let datetime = Utc.timestamp_opt(unixtime, 0).unwrap();
{
let mut bi = BSV_BI.write().unwrap();
bi.latest_block_height = height;
bi.latest_block_time = datetime;
}
}
Err(err) => {
println!("Err: {}", err);
}
}
}
Err(err) => {
println!("Err: {}", err);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Duration;
#[test]
#[ignore]
fn get_latest_bsv_blockinfo() {
let bi_a = *BSV_BI.read().unwrap();
update_bsv_blockheight();
let bi_b = *BSV_BI.read().unwrap();
assert_ne!(bi_a, bi_b);
assert!(bi_a.latest_block_height < bi_b.latest_block_height);
assert!(bi_a.latest_block_time < bi_b.latest_block_time);
}
#[test]
fn one_block_time_away() {
let latest_block_time = Utc.with_ymd_and_hms(2024, 10, 10, 10, 10, 0).unwrap();