ant_protocol/messages/
chunk_proof.rs

1// Copyright 2024 MaidSafe.net limited.
2//
3// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
4// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
5// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
6// KIND, either express or implied. Please review the Licences for the specific language governing
7// permissions and limitations relating to use of the SAFE Network Software.
8
9use serde::{Deserialize, Serialize};
10use std::fmt;
11
12/// The nonce provided by the verifier
13pub type Nonce = u64;
14
15/// The hash(record_value + nonce) that is used to prove the existence of a chunk
16#[derive(Clone, Serialize, Deserialize, Eq, PartialEq)]
17pub struct ChunkProof([u8; 32]);
18
19impl ChunkProof {
20    pub fn new(record_value: &[u8], nonce: Nonce) -> Self {
21        let nonce_bytes = nonce.to_be_bytes();
22        let combined = [record_value, &nonce_bytes].concat();
23        let hash = sha3_256(&combined);
24        ChunkProof(hash)
25    }
26
27    pub fn verify(&self, other_proof: &ChunkProof) -> bool {
28        self.0 == other_proof.0
29    }
30
31    /// Serialize this `ChunkProof` instance to a hex string.
32    fn to_hex(&self) -> String {
33        hex::encode(self.0)
34    }
35}
36
37fn sha3_256(input: &[u8]) -> [u8; 32] {
38    use tiny_keccak::{Hasher, Sha3};
39
40    let mut sha3 = Sha3::v256();
41    let mut output = [0; 32];
42    sha3.update(input);
43    sha3.finalize(&mut output);
44    output
45}
46
47impl fmt::Debug for ChunkProof {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        f.debug_tuple("ChunkProof").field(&self.to_hex()).finish()
50    }
51}