logo
  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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
// Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
// https://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
// modified, or distributed except according to those terms. Please review the Licences for the
// specific language governing permissions and limitations relating to use of the SAFE Network
// Software.

use super::{ChunkAddress, XorName};
use bytes::Bytes;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Maximum allowed size for a serialised Chunk to grow to.
pub const MAX_CHUNK_SIZE_IN_BYTES: usize = 1024 * 1024 + 10 * 1024;

/// Chunk, an immutable chunk of data
#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Clone, custom_debug::Debug)]
pub struct Chunk {
    /// Network address. Omitted when serialising and
    /// calculated from the `value` when deserialising.
    address: ChunkAddress,
    /// Contained data.
    #[debug(skip)]
    value: Bytes,
}

impl Chunk {
    /// Creates a new instance of `Chunk`.
    pub fn new(value: Bytes) -> Self {
        Self {
            address: ChunkAddress(XorName::from_content(value.as_ref())),
            value,
        }
    }

    /// Returns the value.
    pub fn value(&self) -> &Bytes {
        &self.value
    }

    /// Returns the address.
    pub fn address(&self) -> &ChunkAddress {
        &self.address
    }

    /// Returns the name.
    pub fn name(&self) -> &XorName {
        self.address.name()
    }

    /// Returns size of contained value.
    pub fn payload_size(&self) -> usize {
        self.value.len()
    }

    /// Returns size of this chunk after serialisation.
    pub fn serialised_size(&self) -> usize {
        self.value.len()
    }

    /// Returns `true` if the size is valid.
    pub fn validate_size(&self) -> bool {
        self.serialised_size() <= MAX_CHUNK_SIZE_IN_BYTES
    }
}

impl Serialize for Chunk {
    fn serialize<S: Serializer>(&self, serialiser: S) -> Result<S::Ok, S::Error> {
        // Address is omitted since it's derived from value
        self.value.serialize(serialiser)
    }
}

impl<'de> Deserialize<'de> for Chunk {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = Deserialize::deserialize(deserializer)?;
        Ok(Self::new(value))
    }
}

#[cfg(test)]
mod tests {
    use crate::types::{utils, Chunk, Error, Result};
    use bytes::Bytes;
    use hex::encode;
    use rand::{self, Rng, SeedableRng};
    use rand_xorshift::XorShiftRng;
    use std::{env, iter, thread};

    #[test]
    fn deterministic_name() {
        let bytes1 = Bytes::from(b"Hello".to_vec());
        let bytes2 = Bytes::from(b"Goodbye".to_vec());

        let chunk1 = Chunk::new(bytes1.clone());
        let chunk2 = Chunk::new(bytes2.clone());
        let chunk3 = Chunk::new(bytes1);
        let chunk4 = Chunk::new(bytes2);

        assert_eq!(chunk1.name(), chunk3.name());
        assert_eq!(chunk2.name(), chunk4.name());

        assert_ne!(chunk1.name(), chunk2.name());
        assert_ne!(chunk3.name(), chunk4.name());
    }

    #[test]
    fn deterministic_address() -> Result<()> {
        let bytes1 = Bytes::from(b"Hello".to_vec());
        let bytes2 = Bytes::from(b"Goodbye".to_vec());

        let chunk1 = Chunk::new(bytes1.clone());
        let chunk2 = Chunk::new(bytes2.clone());
        let chunk3 = Chunk::new(bytes1);
        let chunk4 = Chunk::new(bytes2);

        assert_eq!(chunk1.address(), chunk3.address());
        assert_eq!(chunk2.address(), chunk4.address());

        assert_ne!(chunk1.address(), chunk2.address());
        assert_ne!(chunk3.address(), chunk4.address());

        assert_ne!(
            bincode::serialize(chunk1.address()).map_err(|_| Error::Serialisation(
                "Test address serialisation failed".to_string()
            ))?,
            bincode::serialize(chunk2.address()).map_err(|_| Error::Serialisation(
                "Test address serialisation failed".to_string()
            ))?
        );

        Ok(())
    }

    #[test]
    fn deterministic_test() {
        let value = Bytes::from(b"immutable chunk value".to_vec());
        let chunk = Chunk::new(value);
        let chunk_name = encode(chunk.name().0.as_ref());
        let expected_name = "920f9a03bc90af3a7bfaf50c03abd5ff5b1579bd4006ba28eebcf240d4922519";

        assert_eq!(&expected_name, &chunk_name);
    }

    #[test]
    fn serialisation() -> Result<()> {
        let mut rng = get_rng();
        let len = rng.gen_range(1, 10_000);
        let value = iter::repeat_with(|| rng.gen()).take(len).collect();
        let chunk = Chunk::new(value);
        let serialised = utils::serialise(&chunk)?;
        let parsed = utils::deserialise(&serialised)?;
        assert_eq!(chunk, parsed);
        Ok(())
    }

    fn get_rng() -> XorShiftRng {
        let env_var_name = "RANDOM_SEED";
        let seed = env::var(env_var_name)
            .map(|res| res.parse::<u64>().unwrap_or_else(|_| rand::random()))
            .unwrap_or_else(|_| rand::random());
        println!(
            "To replay this '{}', set env var {}={}",
            thread::current().name().unwrap_or(""),
            env_var_name,
            seed
        );
        XorShiftRng::seed_from_u64(seed)
    }
}