Skip to content

Commit

Permalink
Merge pull request #25 from Jeanmichel7/main
Browse files Browse the repository at this point in the history
add validate_target
  • Loading branch information
maciejka authored Aug 3, 2024
2 parents 2bb04d0 + 4832a8e commit 1221865
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 3 deletions.
3 changes: 3 additions & 0 deletions Scarb.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@ version = "0.1.0"
edition = "2023_11"

[dependencies]

[dev-dependencies]
cairo_test = "2.7.0"
2 changes: 1 addition & 1 deletion src/state.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub struct Block {
/// Block header
/// https://developer.bitcoin.org/reference/block_chain.html#block-headers
#[derive(Drop, Copy)]
struct Header {
pub struct Header {
/// The version of the block.
pub version: u32,
/// The hash of the previous block in the blockchain.
Expand Down
47 changes: 45 additions & 2 deletions src/validation.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,11 @@ fn validate_proof_of_work(self: @ChainState, block: @Block) -> Result<(), ByteAr
}

fn validate_target(self: @ChainState, block: @Block) -> Result<(), ByteArray> {
// TODO: implement
Result::Ok(())
if self.current_target == block.header.bits {
Result::Ok(())
} else {
Result::Err("Target is {block.header.bits}. Expected {self.current_target}")
}
}

fn validate_timestamp(self: @ChainState, block: @Block) -> Result<(), ByteArray> {
Expand All @@ -63,3 +66,43 @@ fn validate_merkle_root(self: @ChainState, block: @Block) -> Result<(), ByteArra
// TODO: implement
Result::Ok(())
}

#[cfg(test)]
mod tests {
use core::result::ResultTrait;
use super::validate_target;
use super::{Block, ChainState};
use super::super::state::{Header, Transaction, TxIn, TxOut};
use core::array::{Span};

#[test]
fn test_validate_target() {
let mut chain_state = ChainState {
block_height: 1,
total_work: 1,
best_block_hash: 1,
current_target: 1,
epoch_start_time: 1,
prev_timestamps: array![1, 2, 3, 4, 5].span(),
};
let mut block = Block {
header: Header {
version: 1, prev_block_hash: 1, merkle_root_hash: 1, time: 1, bits: 1, nonce: 1,
},
txs: ArrayTrait::new().span(),
};

let result = validate_target(@chain_state, @block);
assert(result.is_ok(), 'Expected target to be valid');

chain_state.current_target = 2;
block.header.bits = 1;
let result = validate_target(@chain_state, @block);
assert(result.is_err(), 'Expected target to be invalid');

chain_state.current_target = 1;
block.header.bits = 2;
let result = validate_target(@chain_state, @block);
assert(result.is_err(), 'Expected target to be invalid');
}
}

0 comments on commit 1221865

Please sign in to comment.