ccp_shared/types/
local_nonce.rs

1/*
2 * Copyright 2024 Fluence DAO
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use std::str::FromStr;
18
19use hex::FromHex;
20use hex::ToHex;
21use serde_with::DeserializeFromStr;
22use serde_with::SerializeDisplay;
23
24pub type LocalNonceInner = [u8; 32];
25
26#[derive(Copy, Clone, Hash, PartialEq, Eq, SerializeDisplay, DeserializeFromStr)]
27#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
28#[repr(transparent)]
29pub struct LocalNonce(LocalNonceInner);
30
31impl LocalNonce {
32    pub const fn new(inner: LocalNonceInner) -> Self {
33        Self(inner)
34    }
35
36    /// Creates a new random nonce.
37    /// It uses random generator to be sure that in the next start with the same parameters,
38    /// CCP won't do the same job twice.
39    pub fn random() -> Self {
40        use rand::RngCore;
41
42        let mut rng = rand::rng();
43        let mut nonce_inner = LocalNonceInner::default();
44
45        rng.fill_bytes(&mut nonce_inner);
46
47        LocalNonce::new(nonce_inner)
48    }
49}
50
51impl AsRef<LocalNonceInner> for LocalNonce {
52    fn as_ref(&self) -> &LocalNonceInner {
53        &self.0
54    }
55}
56
57impl AsMut<LocalNonceInner> for LocalNonce {
58    fn as_mut(&mut self) -> &mut LocalNonceInner {
59        &mut self.0
60    }
61}
62
63impl FromHex for LocalNonce {
64    type Error = <LocalNonceInner as FromHex>::Error;
65
66    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
67        LocalNonceInner::from_hex(hex).map(Self)
68    }
69}
70
71impl ToHex for LocalNonce {
72    fn encode_hex<T: std::iter::FromIterator<char>>(&self) -> T {
73        ToHex::encode_hex(&self.0)
74    }
75
76    fn encode_hex_upper<T: std::iter::FromIterator<char>>(&self) -> T {
77        ToHex::encode_hex_upper(&self.0)
78    }
79}
80
81impl FromStr for LocalNonce {
82    type Err = hex::FromHexError;
83
84    fn from_str(s: &str) -> Result<Self, Self::Err> {
85        FromHex::from_hex(s)
86    }
87}
88
89use std::fmt;
90
91impl std::fmt::Display for LocalNonce {
92    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93        f.write_str(&self.encode_hex::<String>())
94    }
95}
96
97impl fmt::Debug for LocalNonce {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.debug_tuple("LocalNonce")
100            .field(&self.to_string())
101            .finish()
102    }
103}