keep-starknet-strange / raito

Bitcoin ZK client written in Cairo.
https://raito.wtf
MIT License
46 stars 37 forks source link

[feat] optimize bits_to_target #277

Closed Th0rgal closed 1 month ago

Th0rgal commented 1 month ago

Context

The function bits_to_target is called for every block to verify the block digest is smaller than the target threshold. It uses a special decoding algorithm to extract the bits value in an exponent and a mantissa.

Documentation: https://developer.bitcoin.org/reference/block_chain.html#target-nbits

It was already optimized by replacing a right shift by a faster function. A naive optimization would be to do the same with the left shift. I think I can leverage Cairo Field arithmetic to do something faster (same code for all exponents).

References

1) According to Bitcoin Core, if the most significant bit is set, the target threshold should be zero (instead of being negative). Currently it produces an error "Target cannot have most significant bit set", this is not expected.

2)

target = mantissa * 256 ^ (exponent - 3)
target = mantissa * 2 ^ ( 8 *(exponent-3) )