Validate hash literals at compile time #405
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What is the purpose of this pull request?
bhashWhich crates are being modified?
Description
I have created the
bhashmacro, short for block hash, that enforces a compile time check on the literal (must be 64 hex digits).It uses the pattern
const _: () = ...;, where the right side is evaluated at compile time. All thebhash!(literals)will be checked at compile time, even if they are not accessed at runtime (see https://doc.rust-lang.org/reference/items/constant-items.html#evaluation).In other words, code that contains invalid literals won't compile (while currently it would compile and the program would panic at runtime only if the value is used). Also an IDE with cargo check lints will now display the error immediately.
Notes to the reviewers
You can verify that this works, you can try to mess with any hash values and then try to compile: it won't.
error[E0080]: evaluation of constant value failed --> crates/floresta-chain/src/pruned_utreexo/chain_state.rs:1495:13 | 1495 | ... bhash!("572ac401b94915dde6c4957b706abdb13b5824b000cad7f6065ebd9aea6dad1... | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at 'Hash literal is not exactly 64 hex digits', crates/floresta-chain/src/pruned_utreexo/chain_state.rs:1495:13 | = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `bhash`