From 7b3a9ddb5045c76794327e50d0cc5fa0c910b546 Mon Sep 17 00:00:00 2001 From: Marcos Pernambuco Motta <1091485+mpernambuco@users.noreply.github.commits> Date: Sun, 5 Nov 2023 16:50:53 -0300 Subject: [PATCH] chore: Replace dup code with get_merkle_tree_hash --- src/i-hasher.h | 33 +++++++++++++++++++++++++++ src/uarch-record-step-state-access.h | 21 +---------------- src/uarch-replay-reset-state-access.h | 25 +++++--------------- src/uarch-replay-step-state-access.h | 22 +----------------- 4 files changed, 41 insertions(+), 60 deletions(-) diff --git a/src/i-hasher.h b/src/i-hasher.h index 0b7f1793d..d261efba2 100644 --- a/src/i-hasher.h +++ b/src/i-hasher.h @@ -23,6 +23,7 @@ #include #include #include +#include #include "meta.h" @@ -100,6 +101,38 @@ inline static typename H::hash_type get_concat_hash(H &h, const typename H::hash return result; } +/// \brief Computes a merkle tree hash of a data buffer +/// \tparam H Hasher class +/// \param h Hasher object +/// \param data Data to be hashed +/// \param data_length Length of data +/// \param word_length Length of each word +/// \param result Receives the resulting merkle tree hash +template +inline static void get_merkle_tree_hash(H &h, const unsigned char *data, uint64_t data_length, uint64_t word_length, + typename H::hash_type &result) { + if (data_length > word_length) { + if (data_length & 1) { + throw std::invalid_argument("data_length must be a power of 2 multiple of word_length"); + } + data_length = data_length / 2; + typename H::hash_type left; + get_merkle_tree_hash(h, data, data_length, word_length, left); + get_merkle_tree_hash(h, data + data_length, data_length, word_length, result); + h.begin(); + h.add_data(left.data(), left.size()); + h.add_data(result.data(), result.size()); + h.end(result); + } else { + if (data_length != word_length) { + throw std::invalid_argument("data_length must be a power of 2 multiple of word_length"); + } + h.begin(); + h.add_data(data, data_length); + h.end(result); + } +} + } // namespace cartesi #endif diff --git a/src/uarch-record-step-state-access.h b/src/uarch-record-step-state-access.h index d535be9b6..54c31fdbf 100644 --- a/src/uarch-record-step-state-access.h +++ b/src/uarch-record-step-state-access.h @@ -65,28 +65,9 @@ class uarch_record_step_state_access : public i_uarch_step_state_access