Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bitcoin Headerchain verification #259

Merged
merged 4 commits into from
Aug 30, 2024

Conversation

prajwolrg
Copy link
Contributor

Description

Implements code for block header verification.

The chain of block headers provides everything a light client needs to validate the proof of work and the correct arrangement of blocks in the chain. When receiving a block header the light client checks it against Bitcoin's consensus rules:

  1. The block hash has to be below the current target - a number that represents a hash with a certain amount of leading zeros. Closely related to the block's difficulty.
  2. The encoded previous block hash of the current block is indeed the previous block's hash.
  3. The block's timestamp is not below the median of the preceding eleven blocks' timestamps and not above the network time plus two hours.
    4.The correct target is encoded in the block. In case a retarget happened the new target was correctly derived from the epoch timestamps.

While rules 1 and 2 directly enforce the correct formation and mining of the chain, rules 3 and 4 are required so that no one can adjust the target to their own will. Otherwise, they were able to mine new blocks at a faster rate than honest nodes by increasing the target (which can be done by decreasing the epoch's timestamp delta) or they could decrease the target to make it artificially harder to mine blocks.

Copied from: https://geometry.xyz/notebook/A-light-introduction-to-ZeroSync

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature/Enhancement (non-breaking change which adds functionality or enhances an existing one)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactor

Checklist

  • I have performed a self-review of my code.
  • I have commented my code where necessary.
  • I have updated the documentation if needed.
  • My changes do not introduce new warnings.
  • I have added tests that prove my changes are effective or that my feature works.
  • New and existing tests pass with my changes.

Related Issues

@prajwolrg prajwolrg requested review from storopoli and MdTeach August 29, 2024 06:15
Copy link

codecov bot commented Aug 29, 2024

Codecov Report

Attention: Patch coverage is 97.24138% with 4 lines in your changes missing coverage. Please review.

Project coverage is 59.10%. Comparing base (6f75f6f) to head (88bc45a).
Report is 27 commits behind head on master.

Files with missing lines Patch % Lines
crates/prover/btc-headerchain/src/lib.rs 98.11% 2 Missing ⚠️
crates/test-utils/src/bitcoin.rs 94.11% 2 Missing ⚠️
@@            Coverage Diff             @@
##           master     #259      +/-   ##
==========================================
+ Coverage   58.47%   59.10%   +0.63%     
==========================================
  Files         123      124       +1     
  Lines       13618    13546      -72     
==========================================
+ Hits         7963     8007      +44     
+ Misses       5655     5539     -116     
Files with missing lines Coverage Δ
crates/prover/bitcoin-blockspace/src/block.rs 92.15% <100.00%> (ø)
crates/prover/btc-headerchain/src/lib.rs 98.11% <98.11%> (ø)
crates/test-utils/src/bitcoin.rs 96.72% <94.11%> (-3.28%) ⬇️

... and 21 files with indirect coverage changes

@prajwolrg prajwolrg force-pushed the EXP-213-bitcoin-headerchain-verification branch from 57fa303 to 1b876da Compare August 29, 2024 06:33
crates/prover/btc-headerchain/src/lib.rs Outdated Show resolved Hide resolved
crates/prover/btc-headerchain/src/lib.rs Show resolved Hide resolved
crates/prover/btc-headerchain/src/lib.rs Outdated Show resolved Hide resolved
@prajwolrg prajwolrg changed the title Bitcoin Headerchain erification Bitcoin Headerchain verification Aug 30, 2024
@prajwolrg prajwolrg requested a review from MdTeach August 30, 2024 07:06
@prajwolrg prajwolrg merged commit 9c3179b into master Aug 30, 2024
15 checks passed
@storopoli storopoli deleted the EXP-213-bitcoin-headerchain-verification branch August 30, 2024 12:43
Copy link
Contributor

@delbonis delbonis left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A bit scared by seemingly reimplementing Bitcoin validation logic here, would like it if we looked into being able to reuse the logic from the bitcoin-pow crate or another one. There was another crate that I saw that had no-std versions of all of these, but I don't remember the name now.

Also the inconsistency between the names of the bitcoin-blockspace and btc-headerchain crate names is a bit weird, was there a logic to this?

Comment on lines +5 to +15
/// Difficulty recalculation interval.
/// On [MAINNET](bitcoin::consensus::params::MAINNET), it is around 2 weeks
const POW_TARGET_TIMESPAN: u32 = 14 * 24 * 60 * 60;

/// Expected amount of time to mine one block.
/// On [MAINNET](bitcoin::consensus::params::MAINNET), it is around 10 minutes
const POW_TARGET_SPACING: u32 = 10 * 60;

/// No of blocks after which the difficulty is adjusted.
/// [bitcoin::consensus::params::Params::difficulty_adjustment_interval].
const DIFFICULTY_ADJUSTMENT_INTERVAL: u32 = POW_TARGET_TIMESPAN / POW_TARGET_SPACING;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These should all be configurable for whichever Bitcoin chain we're using, perhaps again with env!.


/// Total accumulated [difficulty](bitcoin::pow::Target::difficulty_float)
/// TODO: check if using [this](bitcoin::pow::Target::difficulty) makes more sense
pub total_accumulated_pow: f64,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚩

Do the other Rust Bitcoin crates used f64? We so want to avoid using floats if possible, this isn't natively supported in the riscv arch that r0 or sp1 supports so this would be a huge prover cost to use if it's being emulated by the codegen. Plus floats are screwy in general.

It looks like this isn't being used, what's it for?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

total_accumulated_pow is used as:

L148: self.total_accumulated_pow += header.difficulty_float();

This will later used in the Challenge-Response game to determine the right fork of the bitcoin. The chain with highest accumulated PoW is considered valid.

f64 was used because rust-bitcoin already had a function internally to convert difficulty to f64 and this seems to be how the difficulty was displayed in the UI.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add a prefix to this like the other one so it's clear what it's for. Was this extracted with a tool? If it's something bespoke then add it to a new contrib directory.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure I'll attach the prefix! I wrote a simple binary to fetch the block headers.

@prajwolrg
Copy link
Contributor Author

prajwolrg commented Sep 4, 2024

I looked into rust-bitcoin, which seems to have the logic but is was not yet released. I didn't look into other crates for this. Will checkout bitcoin-pow.

Edit: bitcoin-pow impl requires BlockIndex which has a lot of redundant fields.

Thanks for pointing the inconsistency out.

@prajwolrg
Copy link
Contributor Author

I will try to resolve all the comments here in PR #268

@prajwolrg prajwolrg mentioned this pull request Sep 4, 2024
12 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants