ate_crypto/spec/
chain_key.rs

1#[allow(unused_imports)]
2use tracing::{debug, error, info, instrument, span, trace, warn, Level};
3
4use crate::crypto::AteHash;
5use super::PrimaryKey;
6use serde::{Deserialize, Serialize};
7
8/// Unique key that represents this chain-of-trust. The design must
9/// partition their data space into seperate chains to improve scalability
10/// and performance as a single chain will reside on a single node within
11/// the cluster.
12#[derive(Serialize, Deserialize, Debug, Clone, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
13pub struct ChainKey {
14    pub name: String,
15    #[serde(skip)]
16    pub hash: Option<AteHash>,
17}
18
19impl std::fmt::Display for ChainKey {
20    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
21        write!(f, "{}", self.name)
22    }
23}
24
25impl ChainKey {
26    pub fn new(mut val: String) -> ChainKey {
27        while val.starts_with("/") == true {
28            val = val[1..].to_string();
29        }
30
31        ChainKey {
32            hash: Some(AteHash::from_bytes(val.as_bytes())),
33            name: val,
34        }
35    }
36
37    pub const ROOT: ChainKey = ChainKey {
38        name: String::new(),
39        hash: None,
40    };
41
42    pub fn with_name(&self, val: String) -> ChainKey {
43        let mut ret = self.clone();
44        ret.name = val;
45        ret
46    }
47
48    pub fn with_temp_name(&self, val: String) -> ChainKey {
49        let mut ret = self.clone();
50        ret.name = format!("{}_{}", val, PrimaryKey::generate().as_hex_string());
51        ret
52    }
53
54    pub fn hash(&self) -> AteHash {
55        match &self.hash {
56            Some(a) => a.clone(),
57            None => AteHash::from_bytes(self.name.as_bytes()),
58        }
59    }
60
61    pub fn hash64(&self) -> u64 {
62        match &self.hash {
63            Some(a) => a.to_u64(),
64            None => AteHash::from_bytes(self.name.as_bytes()).to_u64(),
65        }
66    }
67
68    pub fn to_string(&self) -> String {
69        self.name.clone()
70    }
71}
72
73impl From<String> for ChainKey {
74    fn from(val: String) -> ChainKey {
75        ChainKey::new(val)
76    }
77}
78
79impl From<&'static str> for ChainKey {
80    fn from(val: &'static str) -> ChainKey {
81        ChainKey::new(val.to_string())
82    }
83}
84
85impl From<u64> for ChainKey {
86    fn from(val: u64) -> ChainKey {
87        ChainKey::new(val.to_string())
88    }
89}