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
use core::{
ops::Deref,
fmt::Display,
};
use ed25519_dalek::SIGNATURE_LENGTH;
use encdec::{Encode, Decode};
use crate::error::ManifestError;
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
pub struct Signature(pub(crate) [u8; SIGNATURE_LENGTH]);
impl Signature {
pub fn empty() -> Self {
Self([0u8; SIGNATURE_LENGTH])
}
}
impl From<ed25519_dalek::Signature> for Signature {
fn from(value: ed25519_dalek::Signature) -> Self {
Signature(value.to_bytes())
}
}
impl TryFrom<&Signature> for ed25519_dalek::Signature {
type Error = ManifestError;
fn try_from(value: &Signature) -> Result<Self, Self::Error> {
ed25519_dalek::Signature::from_bytes(&value.0)
.map_err(|_e| ManifestError::InvalidSignature)
}
}
impl Deref for Signature {
type Target = [u8; SIGNATURE_LENGTH];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Display for Signature {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for b in self.0 {
write!(f, "{:02x}", b)?;
}
Ok(())
}
}
#[cfg(test)]
mod test {
use ed25519_dalek::SIGNATURE_LENGTH;
use encdec::{Encode, Decode};
use super::Signature;
#[test]
fn encode_decode() {
let mut data = [0u8; 64];
for d in &mut data {
*d = rand::random();
}
let v = Signature(data);
let mut buff = [0u8; 256];
let n = v.encode(&mut buff).unwrap();
assert_eq!(n, SIGNATURE_LENGTH);
assert_eq!(&buff[..SIGNATURE_LENGTH], &v[..SIGNATURE_LENGTH]);
let (v1, n1) = Signature::decode(&buff[..n]).unwrap();
assert_eq!(n1, SIGNATURE_LENGTH);
assert_eq!(v1, v);
}
}