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
use crate::bases::b58::{bytes_to_str_base58, ToBase58};
use crate::bases::*;
#[cfg(feature = "rand")]
use crate::rand::UnspecifiedRandError;
#[cfg(feature = "ser")]
use serde::{Deserialize, Serialize};
use std::fmt::{self, Debug, Display, Formatter};
use zeroize::Zeroize;
pub const SEED_32_SIZE_IN_BYTES: usize = 32;
#[cfg_attr(feature = "ser", derive(Deserialize, Serialize))]
#[derive(Clone, Default, PartialEq, Eq, Hash, Zeroize)]
#[zeroize(drop)]
pub struct Seed32([u8; SEED_32_SIZE_IN_BYTES]);
impl AsRef<[u8]> for Seed32 {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl ToBase58 for Seed32 {
fn to_base58(&self) -> String {
bytes_to_str_base58(&self.0[..], 0)
}
}
impl Debug for Seed32 {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "Seed32 {{ {} }}", self)
}
}
impl Display for Seed32 {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.to_base58())
}
}
impl Seed32 {
#[inline]
pub fn new(seed_bytes: [u8; SEED_32_SIZE_IN_BYTES]) -> Seed32 {
Seed32(seed_bytes)
}
#[inline]
pub fn from_base58(base58_str: &str) -> Result<Self, BaseConvertionError> {
Ok(Seed32::new(b58::str_base58_to_32bytes(base58_str)?.0))
}
#[cfg(feature = "rand")]
#[inline]
pub fn random() -> Result<Seed32, UnspecifiedRandError> {
let random_bytes = crate::rand::gen_32_bytes().map_err(|_| UnspecifiedRandError)?;
Ok(Seed32::new(random_bytes))
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "rand")]
use super::*;
#[cfg(feature = "rand")]
#[test]
fn test_gen_random_seed() {
assert_ne!(Seed32::random(), Seed32::random());
}
}