1use heika_core::hash::Hash256;
12
13use crate::DecodeError;
14
15pub const COSIGNATURE_SIZE: usize = 8 + 32 + 64;
17pub const DETACHED_COSIGNATURE_SIZE: usize = COSIGNATURE_SIZE + 32;
19
20const TRANSACTION_PRESENT: u64 = 0x8000;
22
23pub fn split_detached_cosignatures(
25 body: &[u8],
26) -> Result<Vec<&[u8; DETACHED_COSIGNATURE_SIZE]>, DecodeError> {
27 let (chunks, rest) = body.as_chunks::<DETACHED_COSIGNATURE_SIZE>();
28 if chunks.is_empty() || !rest.is_empty() {
29 return Err(DecodeError::BodySize {
30 expected: chunks.len().max(1) * DETACHED_COSIGNATURE_SIZE,
31 actual: body.len(),
32 });
33 }
34 Ok(chunks.iter().collect())
35}
36
37#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
40pub struct ShortHashPair {
41 pub transaction: u32,
42 pub cosignatures: u32,
43}
44
45pub fn pull_partial_request(min_deadline: u64, known: &[ShortHashPair]) -> Vec<u8> {
47 let mut request = Vec::with_capacity(8 + 8 * known.len());
48 request.extend_from_slice(&min_deadline.to_le_bytes());
49 for pair in known {
50 request.extend_from_slice(&pair.transaction.to_le_bytes());
51 request.extend_from_slice(&pair.cosignatures.to_le_bytes());
52 }
53 request
54}
55
56pub fn read_pull_partial_request(body: &[u8]) -> Result<(u64, Vec<ShortHashPair>), DecodeError> {
58 let Some((deadline, pairs)) = body.split_at_checked(8) else {
59 return Err(DecodeError::Truncated {
60 needed: 8,
61 remaining: body.len(),
62 });
63 };
64 let (chunks, rest) = pairs.as_chunks::<8>();
65 if !rest.is_empty() {
66 return Err(DecodeError::BodySize {
67 expected: 8 + chunks.len() * 8,
68 actual: body.len(),
69 });
70 }
71 let known = chunks
72 .iter()
73 .map(|pair| ShortHashPair {
74 transaction: u32::from_le_bytes(pair[..4].try_into().expect("4 bytes")),
75 cosignatures: u32::from_le_bytes(pair[4..].try_into().expect("4 bytes")),
76 })
77 .collect();
78 Ok((
79 u64::from_le_bytes(deadline.try_into().expect("8 bytes")),
80 known,
81 ))
82}
83
84#[derive(Clone, Copy, PartialEq, Eq, Debug)]
86pub enum PartialInfo<'a> {
87 Transaction(&'a [u8]),
89 Hash(Hash256),
91}
92
93#[derive(Clone, PartialEq, Eq, Debug)]
95pub struct CosignedInfo<'a> {
96 pub info: PartialInfo<'a>,
97 pub cosignatures: Vec<&'a [u8; COSIGNATURE_SIZE]>,
98}
99
100fn padding(size: usize) -> usize {
102 (8 - size % 8) % 8
103}
104
105pub fn write_partial_infos(infos: &[CosignedInfo<'_>]) -> Vec<u8> {
108 let mut body = Vec::new();
109 for info in infos {
110 let count = info.cosignatures.len() as u64 & 0x7FFF;
111 match info.info {
112 PartialInfo::Transaction(transaction) => {
113 body.extend_from_slice(&(TRANSACTION_PRESENT | count).to_le_bytes());
114 body.extend_from_slice(transaction);
115 body.resize(body.len() + padding(transaction.len()), 0);
116 }
117 PartialInfo::Hash(hash) => {
118 body.extend_from_slice(&count.to_le_bytes());
119 body.extend_from_slice(&hash.0);
120 }
121 }
122 for cosignature in &info.cosignatures {
123 body.extend_from_slice(&cosignature[..]);
124 }
125 }
126 body
127}
128
129struct Reader<'a>(&'a [u8]);
131
132impl<'a> Reader<'a> {
133 fn take(&mut self, size: usize) -> Result<&'a [u8], DecodeError> {
134 let (head, rest) = self
135 .0
136 .split_at_checked(size)
137 .ok_or(DecodeError::Truncated {
138 needed: size,
139 remaining: self.0.len(),
140 })?;
141 self.0 = rest;
142 Ok(head)
143 }
144
145 fn zeros(&mut self, size: usize) -> Result<(), DecodeError> {
147 if self.take(size)?.iter().any(|&byte| byte != 0) {
148 return Err(DecodeError::NonZeroPadding);
149 }
150 Ok(())
151 }
152}
153
154pub fn read_partial_infos(body: &[u8]) -> Result<Vec<CosignedInfo<'_>>, DecodeError> {
156 let mut reader = Reader(body);
157 let mut infos = Vec::new();
158 while !reader.0.is_empty() {
159 let tag = reader.take(2)?;
160 let tag = u16::from_le_bytes([tag[0], tag[1]]);
161 reader.zeros(6)?;
162 let info = if u64::from(tag) & TRANSACTION_PRESENT != 0 {
163 let size = reader
165 .0
166 .get(..4)
167 .map(|bytes| u32::from_le_bytes(bytes.try_into().expect("4 bytes")) as usize)
168 .ok_or(DecodeError::Truncated {
169 needed: 4,
170 remaining: reader.0.len(),
171 })?;
172 if size < 4 {
173 return Err(DecodeError::EntityTooSmall { size, minimum: 4 });
174 }
175 let transaction = reader.take(size)?;
176 reader.zeros(padding(size))?;
177 PartialInfo::Transaction(transaction)
178 } else {
179 PartialInfo::Hash(Hash256(reader.take(32)?.try_into().expect("32 bytes")))
180 };
181 let cosignatures = (0..tag & 0x7FFF)
182 .map(|_| {
183 reader
184 .take(COSIGNATURE_SIZE)
185 .map(|bytes| bytes.try_into().expect("cosignature size"))
186 })
187 .collect::<Result<_, _>>()?;
188 infos.push(CosignedInfo { info, cosignatures });
189 }
190 Ok(infos)
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 fn transaction(size: u32, fill: u8) -> Vec<u8> {
199 let mut bytes = vec![fill; size as usize];
200 bytes[..4].copy_from_slice(&size.to_le_bytes());
201 bytes
202 }
203
204 #[test]
205 fn splits_detached_cosignatures() {
206 let body = [
207 [1u8; DETACHED_COSIGNATURE_SIZE],
208 [2; DETACHED_COSIGNATURE_SIZE],
209 ]
210 .concat();
211 let split = split_detached_cosignatures(&body).unwrap();
212 assert_eq!(split.len(), 2);
213 assert_eq!(split[1][0], 2);
214 assert!(split_detached_cosignatures(&[]).is_err());
215 assert!(split_detached_cosignatures(&body[1..]).is_err());
216 }
217
218 #[test]
219 fn round_trips_a_pull_request() {
220 let known = [
221 ShortHashPair {
222 transaction: 0x0102_0304,
223 cosignatures: 0x0506_0708,
224 },
225 ShortHashPair {
226 transaction: 9,
227 cosignatures: 10,
228 },
229 ];
230 let request = pull_partial_request(0x1122_3344_5566_7788, &known);
231 assert_eq!(request.len(), 24);
232 assert_eq!(&request[..8], &0x1122_3344_5566_7788u64.to_le_bytes());
233 assert_eq!(&request[8..12], &0x0102_0304u32.to_le_bytes());
234 assert_eq!(
235 read_pull_partial_request(&request),
236 Ok((0x1122_3344_5566_7788, known.to_vec()))
237 );
238 assert_eq!(
239 read_pull_partial_request(&request[..8]),
240 Ok((0x1122_3344_5566_7788, Vec::new()))
241 );
242 assert!(read_pull_partial_request(&request[..7]).is_err());
243 assert!(read_pull_partial_request(&request[..20]).is_err());
244 }
245
246 #[test]
247 fn writes_and_reads_cosigned_infos_like_catapult() {
248 let unknown = transaction(13, 0xAA);
250 let cosignature = [0x55u8; COSIGNATURE_SIZE];
251 let infos = [
252 CosignedInfo {
253 info: PartialInfo::Transaction(&unknown),
254 cosignatures: vec![&cosignature],
255 },
256 CosignedInfo {
257 info: PartialInfo::Hash(Hash256([7; 32])),
258 cosignatures: vec![&cosignature, &cosignature],
259 },
260 ];
261 let body = write_partial_infos(&infos);
262 let mut expected = (0x8000u64 | 1).to_le_bytes().to_vec();
263 expected.extend_from_slice(&unknown);
264 expected.extend_from_slice(&[0; 3]);
265 expected.extend_from_slice(&cosignature);
266 expected.extend_from_slice(&2u64.to_le_bytes());
267 expected.extend_from_slice(&[7; 32]);
268 expected.extend_from_slice(&cosignature);
269 expected.extend_from_slice(&cosignature);
270 assert_eq!(body, expected);
271 assert_eq!(read_partial_infos(&body).unwrap(), infos);
272 assert_eq!(read_partial_infos(&[]).unwrap(), Vec::new());
273 }
274
275 #[test]
276 fn refuses_broken_infos() {
277 let unknown = transaction(13, 0xAA);
278 let body = write_partial_infos(&[CosignedInfo {
279 info: PartialInfo::Transaction(&unknown),
280 cosignatures: Vec::new(),
281 }]);
282 for index in [2, 8 + 13] {
284 let mut broken = body.clone();
285 broken[index] = 1;
286 assert_eq!(
287 read_partial_infos(&broken),
288 Err(DecodeError::NonZeroPadding)
289 );
290 }
291 assert!(read_partial_infos(&body[..body.len() - 1]).is_err());
293 let mut short = 3u64.to_le_bytes().to_vec();
294 short.extend_from_slice(&[0; 32]);
295 short.extend_from_slice(&[0; COSIGNATURE_SIZE]);
296 assert!(read_partial_infos(&short).is_err());
297 }
298}