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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use std::{borrow::Borrow, convert::TryFrom};
use anyhow::{anyhow, Context};
use crate::{
certificate::Certificate,
message::{
buffer::{header_length, MessageBuffer},
traits::{FromBytes, ToBytes},
DecodeError,
},
CoordinatorPublicKey,
ParticipantPublicKey,
};
#[derive(Copy, Debug, Clone, Eq, PartialEq)]
pub enum Tag {
Sum,
Update,
Sum2,
}
impl TryFrom<u8> for Tag {
type Error = DecodeError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
Ok(match value {
1 => Tag::Sum,
2 => Tag::Update,
3 => Tag::Sum2,
_ => return Err(anyhow!("invalid tag {}", value)),
})
}
}
impl Into<u8> for Tag {
fn into(self) -> u8 {
match self {
Tag::Sum => 1,
Tag::Update => 2,
Tag::Sum2 => 3,
}
}
}
const CERTIFICATE_FLAG: u8 = 0;
bitflags::bitflags! {
pub struct Flags: u8 {
const CERTIFICATE = 1 << CERTIFICATE_FLAG;
}
}
#[derive(Debug, Eq, PartialEq)]
#[cfg_attr(test, derive(Clone))]
pub struct Header<C> {
pub tag: Tag,
pub coordinator_pk: CoordinatorPublicKey,
pub participant_pk: ParticipantPublicKey,
pub certificate: Option<C>,
}
impl<C> ToBytes for Header<C>
where
C: Borrow<Certificate>,
{
fn buffer_length(&self) -> usize {
let cert_length = self
.certificate
.as_ref()
.map(|cert| cert.borrow().buffer_length())
.unwrap_or(0);
header_length(cert_length)
}
fn to_bytes<T: AsMut<[u8]>>(&self, buffer: &mut T) {
let mut writer = MessageBuffer::new(buffer.as_mut()).unwrap();
writer.set_tag(self.tag.into());
if self.certificate.is_some() {
writer.set_flags(Flags::CERTIFICATE);
} else {
writer.set_flags(Flags::empty());
}
self.coordinator_pk
.to_bytes(&mut writer.coordinator_pk_mut());
self.participant_pk
.to_bytes(&mut writer.participant_pk_mut());
}
}
pub type HeaderOwned = Header<Certificate>;
impl FromBytes for HeaderOwned {
fn from_bytes<T: AsRef<[u8]>>(buffer: &T) -> Result<Self, DecodeError> {
let reader = MessageBuffer::new(buffer.as_ref())?;
let certificate = if let Some(bytes) = reader.certificate() {
Some(Certificate::from_bytes(&bytes.value())?)
} else {
None
};
Ok(Self {
tag: Tag::try_from(reader.tag())?,
coordinator_pk: CoordinatorPublicKey::from_bytes(&reader.coordinator_pk())
.context("invalid coordinator public key")?,
participant_pk: ParticipantPublicKey::from_bytes(&reader.participant_pk())
.context("invalid participant public key")?,
certificate,
})
}
}