simple_crypto/
structs.rs

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
use super::Error;

use schemars::schema::{Schema, SchemaObject, StringValidation};
use schemars::gen::SchemaGenerator;
use schemars::JsonSchema;

use bitcoin_hashes::sha256t::Hash as HashT;

use bitcoin_hashes::Hash as _;
use bitcoin_hashes::sha256::Midstate;
use bitcoin_hashes::sha256::HashEngine;
use bitcoin_hashes::sha256t::Tag as TagTrait;

const MIDSTATE: Midstate = Midstate::hash_tag(b"SIMPLE_CRYPTO");

pub struct Tag {}
impl TagTrait for Tag {
    fn engine() -> HashEngine {HashEngine::from_midstate(MIDSTATE, 0)}
}

pub type BHash = HashT<Tag>;


#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[derive(serde_with::SerializeDisplay)]
#[derive(serde_with::DeserializeFromStr)]
pub struct Hash {
    inner: BHash
}

impl Hash {
    pub fn to_arr(self) -> [u8; 32] {*self.inner.as_ref()}
    pub fn all_zeros() -> Self {Hash{inner: BHash::all_zeros()}}
    pub fn new(inner: BHash) -> Self {Hash{inner}}
    pub fn to_vec(&self) -> Vec<u8> {
        self.inner.as_byte_array().to_vec()
    }
    pub fn as_bytes(&self) -> &[u8] {self.inner.as_byte_array()}
    pub fn from_slice(slice: &[u8]) -> Result<Self, Error> {
        Ok(Hash{inner: BHash::from_slice(slice)?})
    }
}

impl std::fmt::Display for Hash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", hex::encode(self.to_vec()))
    }
}

impl std::fmt::Debug for Hash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", hex::encode(self.to_vec()))
    }
}

impl std::str::FromStr for Hash {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Hash::from_slice(&hex::decode(s)?)
    }
}

impl JsonSchema for Hash {
    fn schema_name() -> String {"Hash".to_string()}
    fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
        Schemas::regex("^(0x|0X)?[a-fA-F0-9]{64}$".to_string())
    }
}

pub struct Schemas {}
impl Schemas {
    pub fn regex(regex: String) -> Schema {
        Schema::Object(SchemaObject{
            string: Some(Box::new(StringValidation {
                max_length: None,
                min_length: None,
                pattern: Some(regex)
            })),
            ..Default::default()
        })
    }
}