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

Improve the algorithm for calculating the next bitcoin target. #15

Open
yangby-cryptape opened this issue Apr 7, 2024 · 0 comments
Open
Labels

Comments

@yangby-cryptape
Copy link
Contributor

Issue

Causes "arithmetic operation overflow" on Bitcoin dev chain.

Reason

In the following code:

https://github.com/ckb-cell/ckb-bitcoin-spv/blob/a3c43fd5fb70044ad438f703212b255af5024476/verifier/src/utilities/bitcoin.rs#L29-L35

when prev-target (x) is too large, y = x * U256::from(actual) will overflow.

A Proposed Solution

Pseudocode as following:

let x = U512::from_little_endian(&prev_target_le_bytes); 
let y = x * U512::from(actual); 
let z_tmp = y / U512::from(expected); 
if z_tmp > U512::from(U256::MAX) {
    panic!();
}
let z = z_tmp as U256;

Affected Scope

Bitcoin mainnet and Bitcoin testnet don't have such large target.
So, we can ignore it temporary.

But I strongly suggest fixing it when upgrade the production contract next time.

How to Reproduce

Modify this unit test, to calculate the next bitcoin target for following headers, directly.

Header 2016:

0000002088e6d6b787292d12516840a1b970464d4d3e942b5d3d23a337fdbf68762ddf603e6c81d61074df79939b5483aed21e52576ba6a5d723e33b821dc1796d21272c993c1266ffff7f2000000000

Header 4031:

00000020e86a51dbe721a9c266d639427c010c5117518b2da95eea191911f57a7eb994327b0faee0e012aff149c85178ef930559e6c04554a8ff34883aad0c93e4af846742461266ffff7f2001000000

These data could be added to as a unit test after fixing it.

References

@Flouse Flouse added the P-Low label Apr 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants