1#![allow(clippy::integer_arithmetic)]
101use bytes::Bytes;
102use hex::FromHex;
103use more_asserts::{debug_assert_ge, debug_assert_lt};
104use once_cell::sync::{Lazy, OnceCell};
105#[cfg(any(test, feature = "fuzzing"))]
106use proptest_derive::Arbitrary;
107use rand::{rngs::OsRng, Rng};
108use serde::{de, ser, Deserialize, Serialize};
109use std::{
110 self,
111 convert::{AsRef, TryFrom},
112 fmt,
113 str::FromStr,
114};
115use tiny_keccak::{Hasher, Sha3};
116
117pub(crate) const HASH_PREFIX: &[u8] = b"APTOS::";
121
122#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
124#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))]
125pub struct HashValue {
126 hash: [u8; HashValue::LENGTH],
127}
128
129impl HashValue {
130 pub const LENGTH: usize = 32;
132 pub const LENGTH_IN_BITS: usize = Self::LENGTH * 8;
134
135 pub fn new(hash: [u8; HashValue::LENGTH]) -> Self {
137 HashValue { hash }
138 }
139
140 pub fn from_slice<T: AsRef<[u8]>>(bytes: T) -> Result<Self, HashValueParseError> {
142 <[u8; Self::LENGTH]>::try_from(bytes.as_ref())
143 .map_err(|_| HashValueParseError)
144 .map(Self::new)
145 }
146
147 pub fn to_vec(&self) -> Vec<u8> {
149 self.hash.to_vec()
150 }
151
152 pub const fn zero() -> Self {
154 HashValue {
155 hash: [0; HashValue::LENGTH],
156 }
157 }
158
159 pub fn random() -> Self {
161 let mut rng = OsRng;
162 let hash: [u8; HashValue::LENGTH] = rng.gen();
163 HashValue { hash }
164 }
165
166 pub fn random_with_rng<R: Rng>(rng: &mut R) -> Self {
168 let hash: [u8; HashValue::LENGTH] = rng.gen();
169 HashValue { hash }
170 }
171
172 pub fn sha3_256_of(buffer: &[u8]) -> Self {
179 let mut sha3 = Sha3::v256();
180 sha3.update(buffer);
181 HashValue::from_keccak(sha3)
182 }
183
184 #[cfg(test)]
185 pub fn from_iter_sha3<'a, I>(buffers: I) -> Self
186 where
187 I: IntoIterator<Item = &'a [u8]>,
188 {
189 let mut sha3 = Sha3::v256();
190 for buffer in buffers {
191 sha3.update(buffer);
192 }
193 HashValue::from_keccak(sha3)
194 }
195
196 fn as_ref_mut(&mut self) -> &mut [u8] {
197 &mut self.hash[..]
198 }
199
200 fn from_keccak(state: Sha3) -> Self {
201 let mut hash = Self::zero();
202 state.finalize(hash.as_ref_mut());
203 hash
204 }
205
206 pub fn bit(&self, index: usize) -> bool {
208 debug_assert!(index < Self::LENGTH_IN_BITS); let pos = index / 8;
210 let bit = 7 - index % 8;
211 (self.hash[pos] >> bit) & 1 != 0
212 }
213
214 pub fn nibble(&self, index: usize) -> u8 {
216 debug_assert!(index < Self::LENGTH * 2); let pos = index / 2;
218 let shift = if index % 2 == 0 { 4 } else { 0 };
219 (self.hash[pos] >> shift) & 0x0f
220 }
221
222 pub fn iter_bits(&self) -> HashValueBitIterator<'_> {
224 HashValueBitIterator::new(self)
225 }
226
227 pub fn from_bit_iter(
229 iter: impl ExactSizeIterator<Item = bool>,
230 ) -> Result<Self, HashValueParseError> {
231 if iter.len() != Self::LENGTH_IN_BITS {
232 return Err(HashValueParseError);
233 }
234
235 let mut buf = [0; Self::LENGTH];
236 for (i, bit) in iter.enumerate() {
237 if bit {
238 buf[i / 8] |= 1 << (7 - i % 8);
239 }
240 }
241 Ok(Self::new(buf))
242 }
243
244 pub fn common_prefix_bits_len(&self, other: HashValue) -> usize {
246 self.iter_bits()
247 .zip(other.iter_bits())
248 .take_while(|(x, y)| x == y)
249 .count()
250 }
251
252 pub fn to_hex(&self) -> String {
254 format!("{:x}", self)
255 }
256
257 pub fn to_hex_literal(&self) -> String {
259 format!("{:#x}", self)
260 }
261
262 pub fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, HashValueParseError> {
264 <[u8; Self::LENGTH]>::from_hex(hex)
265 .map_err(|_| HashValueParseError)
266 .map(Self::new)
267 }
268
269 #[cfg(any(test, feature = "fuzzing"))]
274 pub fn from_u64(v: u64) -> Self {
275 let mut hash = [0u8; Self::LENGTH];
276 let bytes = v.to_be_bytes();
277 hash[Self::LENGTH - bytes.len()..].copy_from_slice(&bytes[..]);
278 Self::new(hash)
279 }
280}
281
282impl ser::Serialize for HashValue {
283 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
284 where
285 S: ser::Serializer,
286 {
287 if serializer.is_human_readable() {
288 serializer.serialize_str(&self.to_hex())
289 } else {
290 #[derive(Serialize)]
294 #[serde(rename = "HashValue")]
295 struct Value<'a> {
296 hash: &'a [u8; HashValue::LENGTH],
297 }
298 Value { hash: &self.hash }.serialize(serializer)
299 }
300 }
301}
302
303impl<'de> de::Deserialize<'de> for HashValue {
304 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
305 where
306 D: de::Deserializer<'de>,
307 {
308 if deserializer.is_human_readable() {
309 let encoded_hash = <String>::deserialize(deserializer)?;
310 HashValue::from_hex(encoded_hash.as_str())
311 .map_err(<D::Error as ::serde::de::Error>::custom)
312 } else {
313 #[derive(Deserialize)]
315 #[serde(rename = "HashValue")]
316 struct Value {
317 hash: [u8; HashValue::LENGTH],
318 }
319
320 let value = Value::deserialize(deserializer)
321 .map_err(<D::Error as ::serde::de::Error>::custom)?;
322 Ok(Self::new(value.hash))
323 }
324 }
325}
326
327impl Default for HashValue {
328 fn default() -> Self {
329 HashValue::zero()
330 }
331}
332
333impl AsRef<[u8; HashValue::LENGTH]> for HashValue {
334 fn as_ref(&self) -> &[u8; HashValue::LENGTH] {
335 &self.hash
336 }
337}
338
339impl std::ops::Deref for HashValue {
340 type Target = [u8; Self::LENGTH];
341
342 fn deref(&self) -> &Self::Target {
343 &self.hash
344 }
345}
346
347impl std::ops::Index<usize> for HashValue {
348 type Output = u8;
349
350 fn index(&self, s: usize) -> &u8 {
351 self.hash.index(s)
352 }
353}
354
355impl fmt::Binary for HashValue {
356 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357 for byte in &self.hash {
358 write!(f, "{:08b}", byte)?;
359 }
360 Ok(())
361 }
362}
363
364impl fmt::LowerHex for HashValue {
365 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366 if f.alternate() {
367 write!(f, "0x")?;
368 }
369 for byte in &self.hash {
370 write!(f, "{:02x}", byte)?;
371 }
372 Ok(())
373 }
374}
375
376impl fmt::Debug for HashValue {
377 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
378 write!(f, "HashValue(")?;
379 <Self as fmt::LowerHex>::fmt(self, f)?;
380 write!(f, ")")?;
381 Ok(())
382 }
383}
384
385impl fmt::Display for HashValue {
387 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
388 for byte in self.hash.iter().take(4) {
389 write!(f, "{:02x}", byte)?;
390 }
391 Ok(())
392 }
393}
394
395impl From<HashValue> for Bytes {
396 fn from(value: HashValue) -> Bytes {
397 Bytes::copy_from_slice(value.hash.as_ref())
398 }
399}
400
401impl FromStr for HashValue {
402 type Err = HashValueParseError;
403
404 fn from_str(s: &str) -> Result<Self, HashValueParseError> {
405 HashValue::from_hex(s)
406 }
407}
408
409#[derive(Clone, Copy, Debug)]
411pub struct HashValueParseError;
412
413impl fmt::Display for HashValueParseError {
414 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
415 write!(f, "unable to parse HashValue")
416 }
417}
418
419impl std::error::Error for HashValueParseError {}
420
421pub struct HashValueBitIterator<'a> {
423 hash_bytes: &'a [u8],
425 pos: std::ops::Range<usize>,
426 }
429
430impl<'a> HashValueBitIterator<'a> {
431 fn new(hash_value: &'a HashValue) -> Self {
433 HashValueBitIterator {
434 hash_bytes: hash_value.as_ref(),
435 pos: (0..HashValue::LENGTH_IN_BITS),
436 }
437 }
438
439 fn get_bit(&self, index: usize) -> bool {
441 debug_assert_eq!(self.hash_bytes.len(), HashValue::LENGTH); debug_assert_lt!(index, self.hash_bytes.len() * 8); debug_assert_ge!(index, 0); let pos = index / 8;
445 let bit = 7 - index % 8;
446 (self.hash_bytes[pos] >> bit) & 1 != 0
447 }
448}
449
450impl<'a> std::iter::Iterator for HashValueBitIterator<'a> {
451 type Item = bool;
452
453 fn next(&mut self) -> Option<Self::Item> {
454 self.pos.next().map(|x| self.get_bit(x))
455 }
456
457 fn size_hint(&self) -> (usize, Option<usize>) {
458 self.pos.size_hint()
459 }
460}
461
462impl<'a> std::iter::DoubleEndedIterator for HashValueBitIterator<'a> {
463 fn next_back(&mut self) -> Option<Self::Item> {
464 self.pos.next_back().map(|x| self.get_bit(x))
465 }
466}
467
468impl<'a> std::iter::ExactSizeIterator for HashValueBitIterator<'a> {}
469
470pub trait CryptoHash {
475 type Hasher: CryptoHasher;
477
478 fn hash(&self) -> HashValue;
480}
481
482pub trait CryptoHasher: Default + std::io::Write {
484 fn seed() -> &'static [u8; 32];
486
487 fn update(&mut self, bytes: &[u8]);
489
490 fn finish(self) -> HashValue;
492
493 fn hash_all(bytes: &[u8]) -> HashValue {
495 let mut hasher = Self::default();
496 hasher.update(bytes);
497 hasher.finish()
498 }
499}
500
501#[doc(hidden)]
503#[derive(Clone)]
504pub struct DefaultHasher {
505 state: Sha3,
506}
507
508impl DefaultHasher {
509 #[doc(hidden)]
510 pub fn prefixed_hash(buffer: &[u8]) -> [u8; HashValue::LENGTH] {
514 let salt: Vec<u8> = [HASH_PREFIX, buffer].concat();
517 HashValue::sha3_256_of(&salt[..]).hash
520 }
521
522 #[doc(hidden)]
523 pub fn new(typename: &[u8]) -> Self {
524 let mut state = Sha3::v256();
525 if !typename.is_empty() {
526 state.update(&Self::prefixed_hash(typename));
527 }
528 DefaultHasher { state }
529 }
530
531 #[doc(hidden)]
532 pub fn update(&mut self, bytes: &[u8]) {
533 self.state.update(bytes);
534 }
535
536 #[doc(hidden)]
537 pub fn finish(self) -> HashValue {
538 let mut hasher = HashValue::default();
539 self.state.finalize(hasher.as_ref_mut());
540 hasher
541 }
542}
543
544impl fmt::Debug for DefaultHasher {
545 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
546 write!(f, "DefaultHasher: state = Sha3")
547 }
548}
549
550macro_rules! define_hasher {
551 (
552 $(#[$attr:meta])*
553 ($hasher_type: ident, $hasher_name: ident, $seed_name: ident, $salt: expr)
554 ) => {
555
556 #[derive(Clone, Debug)]
557 $(#[$attr])*
558 pub struct $hasher_type(DefaultHasher);
559
560 impl $hasher_type {
561 fn new() -> Self {
562 $hasher_type(DefaultHasher::new($salt))
563 }
564 }
565
566 static $hasher_name: Lazy<$hasher_type> = Lazy::new(|| { $hasher_type::new() });
567 static $seed_name: OnceCell<[u8; 32]> = OnceCell::new();
568
569 impl Default for $hasher_type {
570 fn default() -> Self {
571 $hasher_name.clone()
572 }
573 }
574
575 impl CryptoHasher for $hasher_type {
576 fn seed() -> &'static [u8;32] {
577 $seed_name.get_or_init(|| {
578 DefaultHasher::prefixed_hash($salt)
579 })
580 }
581
582 fn update(&mut self, bytes: &[u8]) {
583 self.0.update(bytes);
584 }
585
586 fn finish(self) -> HashValue {
587 self.0.finish()
588 }
589 }
590
591 impl std::io::Write for $hasher_type {
592 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
593 self.0.update(bytes);
594 Ok(bytes.len())
595 }
596 fn flush(&mut self) -> std::io::Result<()> {
597 Ok(())
598 }
599 }
600 };
601}
602
603define_hasher! {
604 (
606 TransactionAccumulatorHasher,
607 TRANSACTION_ACCUMULATOR_HASHER,
608 TRANSACTION_ACCUMULATOR_SEED,
609 b"TransactionAccumulator"
610 )
611}
612
613define_hasher! {
614 (
616 EventAccumulatorHasher,
617 EVENT_ACCUMULATOR_HASHER,
618 EVENT_ACCUMULATOR_SEED,
619 b"EventAccumulator"
620 )
621}
622
623define_hasher! {
624 (
626 SparseMerkleInternalHasher,
627 SPARSE_MERKLE_INTERNAL_HASHER,
628 SPARSE_MERKLE_INTERNAL_SEED,
629 b"SparseMerkleInternal"
630 )
631}
632
633define_hasher! {
634 (TestOnlyHasher, TEST_ONLY_HASHER, TEST_ONLY_SEED, b"")
636}
637
638fn create_literal_hash(word: &str) -> HashValue {
639 let mut s = word.as_bytes().to_vec();
640 assert!(s.len() <= HashValue::LENGTH);
641 s.resize(HashValue::LENGTH, 0);
642 HashValue::from_slice(&s).expect("Cannot fail")
643}
644
645pub static ACCUMULATOR_PLACEHOLDER_HASH: Lazy<HashValue> =
647 Lazy::new(|| create_literal_hash("ACCUMULATOR_PLACEHOLDER_HASH"));
648
649pub static SPARSE_MERKLE_PLACEHOLDER_HASH: Lazy<HashValue> =
651 Lazy::new(|| create_literal_hash("SPARSE_MERKLE_PLACEHOLDER_HASH"));
652
653pub static PRE_GENESIS_BLOCK_ID: Lazy<HashValue> =
655 Lazy::new(|| create_literal_hash("PRE_GENESIS_BLOCK_ID"));
656
657pub static GENESIS_BLOCK_ID: Lazy<HashValue> = Lazy::new(|| {
659 HashValue::new([
662 0x5e, 0x10, 0xba, 0xd4, 0x5b, 0x35, 0xed, 0x92, 0x9c, 0xd6, 0xd2, 0xc7, 0x09, 0x8b, 0x13,
663 0x5d, 0x02, 0xdd, 0x25, 0x9a, 0xe8, 0x8a, 0x8d, 0x09, 0xf4, 0xeb, 0x5f, 0xba, 0xe9, 0xa6,
664 0xf6, 0xe4,
665 ])
666});
667
668pub trait TestOnlyHash {
678 fn test_only_hash(&self) -> HashValue;
680}
681
682impl<T: ser::Serialize + ?Sized> TestOnlyHash for T {
683 fn test_only_hash(&self) -> HashValue {
684 let bytes = bcs::to_bytes(self).expect("serialize failed during hash.");
685 let mut hasher = TestOnlyHasher::default();
686 hasher.update(&bytes);
687 hasher.finish()
688 }
689}