Skip to content

Commit

Permalink
add convenience method for hashing a program
Browse files Browse the repository at this point in the history
  • Loading branch information
jan-ferdinand committed Jul 5, 2023
1 parent 12f87de commit b0555e2
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion triton-opcodes/src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use serde_derive::Deserialize;
use serde_derive::Serialize;
use twenty_first::shared_math::b_field_element::BFieldElement;
use twenty_first::shared_math::bfield_codec::BFieldCodec;
use twenty_first::shared_math::digest::Digest;
use twenty_first::util_types::algebraic_hasher::AlgebraicHasher;

use crate::instruction::convert_labels;
use crate::instruction::Instruction;
Expand Down Expand Up @@ -172,13 +174,20 @@ impl Program {
pub fn is_empty(&self) -> bool {
self.instructions.is_empty()
}

/// Hash the program using the given `AlgebraicHasher`.
pub fn hash<H: AlgebraicHasher>(&self) -> Digest {
H::hash_varlen(&self.to_bwords())
}
}

#[cfg(test)]
mod test {
use crate::parser::parser_tests::program_gen;
use rand::thread_rng;
use rand::Rng;
use twenty_first::shared_math::tip5::Tip5;

use crate::parser::parser_tests::program_gen;

use super::*;

Expand Down Expand Up @@ -234,4 +243,28 @@ mod test {
let err = Program::decode(&encoded).err().unwrap();
assert_eq!("Sequence to decode must not be empty.", err.to_string(),);
}

#[test]
fn hash_simple_program() {
let program = Program::from_code("halt").unwrap();
let digest = program.hash::<Tip5>();

let expected_digest = [
4843866011885844809,
16618866032559590857,
18247689143239181392,
7637465675240023996,
9104890367162237026,
]
.map(BFieldElement::new);
let expected_digest = Digest::new(expected_digest);

assert_eq!(expected_digest, digest);
}

#[test]
fn empty_program_is_empty() {
let program = Program::from_code("").unwrap();
assert!(program.is_empty());
}
}

0 comments on commit b0555e2

Please sign in to comment.