Skip to content
This repository was archived by the owner on Oct 13, 2025. It is now read-only.

Latest commit

 

History

History
127 lines (70 loc) · 4.79 KB

File metadata and controls

127 lines (70 loc) · 4.79 KB

Module (bitcoin_spv=0x0)::block_header

use (bitcoin_parser=0x0)::crypto;
use (bitcoin_parser=0x0)::encoding;
use (bitcoin_parser=0x0)::header;
use (bitcoin_parser=0x0)::reader;
use (bitcoin_spv=0x0)::btc_math;
use std::ascii;
use std::hash;
use std::option;
use std::string;
use std::u256;
use std::vector;

Constants

#[error]
const EPoW: vector<u8> = b"The block hash does not meet the target difficulty (Proof-of-Work check failed)";

Function target

public fun target(header: &(bitcoin_parser=0x0)::header::BlockHeader): u256
Implementation
public fun target(header: &BlockHeader): u256 {
    bits_to_target(header.bits())
}

Function calc_work

public fun calc_work(header: &(bitcoin_parser=0x0)::header::BlockHeader): u256
Implementation
public fun calc_work(header: &BlockHeader): u256 {
    // We compute the total expected hashes or expected "calc_work".
    //    calc_work of header = 2**256 / (target+1).
    // This is a very clever way to compute this value from bitcoin core. Comments from the bitcoin core:
    // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
    // as it's too large for an arith_uint256. However, as 2**256 is at least as large
    // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
    // or ~bnTarget / (bnTarget+1) + 1.
    // More information: https://github.com/bitcoin/bitcoin/blob/28.x/src/chain.cpp#L139.
    // we have bitwise_not is ~ operation in move
    let target = target(header);
    (target.bitwise_not() / (target + 1)) + 1
}

Function pow_check

checks if the block headers meet PoW target requirements. Panics otherewise.

public fun pow_check(header: &(bitcoin_parser=0x0)::header::BlockHeader)
Implementation
public fun pow_check(header: &BlockHeader) {
    let work = header.block_hash();
    let target = target(header);
    assert!(target >= to_u256(work), EPoW);
}