1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

use super::{ByteDigest, ElementHasher, Hasher};
use core::{convert::TryInto, fmt::Debug, marker::PhantomData};
use math::{FieldElement, StarkField};
use utils::ByteWriter;

#[cfg(test)]
mod tests;

// BLAKE3 256-BIT OUTPUT
// ================================================================================================

/// Implementation of the [Hasher](super::Hasher) trait for BLAKE3 hash function with 256-bit
/// output.
#[derive(Debug, PartialEq, Eq)]
pub struct Blake3_256<B: StarkField>(PhantomData<B>);

impl<B: StarkField> Hasher for Blake3_256<B> {
    type Digest = ByteDigest<32>;

    fn hash(bytes: &[u8]) -> Self::Digest {
        ByteDigest(*blake3::hash(bytes).as_bytes())
    }

    fn merge(values: &[Self::Digest; 2]) -> Self::Digest {
        ByteDigest(blake3::hash(ByteDigest::digests_as_bytes(values)).into())
    }

    fn merge_with_int(seed: Self::Digest, value: u64) -> Self::Digest {
        let mut data = [0; 40];
        data[..32].copy_from_slice(&seed.0);
        data[32..].copy_from_slice(&value.to_le_bytes());
        ByteDigest(*blake3::hash(&data).as_bytes())
    }
}

impl<B: StarkField> ElementHasher for Blake3_256<B> {
    type BaseField = B;

    fn hash_elements<E: FieldElement<BaseField = Self::BaseField>>(elements: &[E]) -> Self::Digest {
        if B::IS_CANONICAL {
            // when element's internal and canonical representations are the same, we can hash
            // element bytes directly
            let bytes = E::elements_as_bytes(elements);
            ByteDigest(*blake3::hash(bytes).as_bytes())
        } else {
            // when elements' internal and canonical representations differ, we need to serialize
            // them before hashing
            let mut hasher = BlakeHasher::new();
            hasher.write(elements);
            ByteDigest(hasher.finalize())
        }
    }
}

// BLAKE3 192-BIT OUTPUT
// ================================================================================================

/// Implementation of the [Hasher](super::Hasher) trait for BLAKE3 hash function with 192-bit
/// output.
#[derive(Debug, PartialEq, Eq)]
pub struct Blake3_192<B: StarkField>(PhantomData<B>);

impl<B: StarkField> Hasher for Blake3_192<B> {
    type Digest = ByteDigest<24>;

    fn hash(bytes: &[u8]) -> Self::Digest {
        let result = blake3::hash(bytes);
        ByteDigest(result.as_bytes()[..24].try_into().unwrap())
    }

    fn merge(values: &[Self::Digest; 2]) -> Self::Digest {
        let result = blake3::hash(ByteDigest::digests_as_bytes(values));
        ByteDigest(result.as_bytes()[..24].try_into().unwrap())
    }

    fn merge_with_int(seed: Self::Digest, value: u64) -> Self::Digest {
        let mut data = [0; 32];
        data[..24].copy_from_slice(&seed.0);
        data[24..].copy_from_slice(&value.to_le_bytes());

        let result = blake3::hash(&data);
        ByteDigest(result.as_bytes()[..24].try_into().unwrap())
    }
}

impl<B: StarkField> ElementHasher for Blake3_192<B> {
    type BaseField = B;

    fn hash_elements<E: FieldElement<BaseField = Self::BaseField>>(elements: &[E]) -> Self::Digest {
        if B::IS_CANONICAL {
            // when element's internal and canonical representations are the same, we can hash
            // element bytes directly
            let bytes = E::elements_as_bytes(elements);
            let result = blake3::hash(bytes);
            ByteDigest(result.as_bytes()[..24].try_into().unwrap())
        } else {
            // when elements' internal and canonical representations differ, we need to serialize
            // them before hashing
            let mut hasher = BlakeHasher::new();
            hasher.write(elements);
            let result = hasher.finalize();
            ByteDigest(result[..24].try_into().unwrap())
        }
    }
}

// BLAKE HASHER
// ================================================================================================

/// Wrapper around BLAKE3 hasher to implement [ByteWriter] trait for it.
struct BlakeHasher(blake3::Hasher);

impl BlakeHasher {
    pub fn new() -> Self {
        Self(blake3::Hasher::new())
    }

    pub fn finalize(&self) -> [u8; 32] {
        *self.0.finalize().as_bytes()
    }
}

impl ByteWriter for BlakeHasher {
    fn write_u8(&mut self, value: u8) {
        self.0.update(&[value]);
    }

    fn write_u8_slice(&mut self, values: &[u8]) {
        self.0.update(values);
    }
}