1use std::io::{self, Read, Write};
8
9use dusk_core::transfer::Transaction as ProtocolTransaction;
10
11use crate::bls::PublicKeyBytes;
12use crate::ledger::{
13 Attestation, Block, Fault, Header, IterationsInfo, Label, Signature,
14 SpentTransaction, StepVotes, Transaction,
15};
16use crate::message::payload::{
17 QuorumType, Ratification, RatificationResult, ValidationQuorum,
18 ValidationResult, Vote,
19};
20use crate::message::{
21 ConsensusHeader, SignInfo, MESSAGE_MAX_FAILED_ITERATIONS,
22};
23use crate::Serializable;
24
25impl Serializable for Block {
26 fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
27 self.header().write(w)?;
28
29 let txs_len = self.txs().len() as u32;
30 w.write_all(&txs_len.to_le_bytes())?;
31
32 for t in self.txs().iter() {
33 t.write(w)?;
34 }
35
36 let faults_len = self.faults().len() as u32;
37 w.write_all(&faults_len.to_le_bytes())?;
38
39 for f in self.faults().iter() {
40 f.write(w)?;
41 }
42 Ok(())
43 }
44
45 fn read<R: Read>(r: &mut R) -> io::Result<Self>
46 where
47 Self: Sized,
48 {
49 let header = Header::read(r)?;
50
51 let tx_len = Self::read_u32_le(r)?;
53
54 let txs = (0..tx_len)
55 .map(|_| Transaction::read(r))
56 .collect::<Result<Vec<_>, _>>()?;
57
58 let faults_len = Self::read_u32_le(r)?;
60
61 let faults = (0..faults_len)
62 .map(|_| Fault::read(r))
63 .collect::<Result<Vec<_>, _>>()?;
64
65 Block::new(header, txs, faults)
66 }
67}
68
69impl Serializable for Transaction {
70 fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
71 w.write_all(&self.version.to_le_bytes())?;
73
74 w.write_all(&self.r#type.to_le_bytes())?;
76
77 let data = self.inner.to_var_bytes();
78
79 Self::write_var_le_bytes32(w, &data)?;
81
82 Ok(())
83 }
84
85 fn read<R: Read>(r: &mut R) -> io::Result<Self>
86 where
87 Self: Sized,
88 {
89 let version = Self::read_u32_le(r)?;
90 let tx_type = Self::read_u32_le(r)?;
91
92 let protocol_tx = Self::read_var_le_bytes32(r)?;
93 let tx_size = protocol_tx.len();
94 let inner = ProtocolTransaction::from_slice(&protocol_tx[..])
95 .map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?;
96
97 Ok(Self {
98 inner,
99 version,
100 r#type: tx_type,
101 size: Some(tx_size),
102 })
103 }
104}
105
106impl Serializable for SpentTransaction {
107 fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
108 self.inner.write(w)?;
109 w.write_all(&self.block_height.to_le_bytes())?;
110 w.write_all(&self.gas_spent.to_le_bytes())?;
111
112 match &self.err {
113 Some(e) => {
114 let b = e.as_bytes();
115 w.write_all(&(b.len() as u32).to_le_bytes())?;
116 w.write_all(b)?;
117 }
118 None => {
119 w.write_all(&0_u64.to_le_bytes())?;
120 }
121 }
122
123 Ok(())
124 }
125
126 fn read<R: Read>(r: &mut R) -> io::Result<Self>
127 where
128 Self: Sized,
129 {
130 let inner = Transaction::read(r)?;
131
132 let block_height = Self::read_u64_le(r)?;
133 let gas_spent = Self::read_u64_le(r)?;
134 let error_len = Self::read_u32_le(r)?;
135
136 let err = if error_len > 0 {
137 let mut buf = vec![0u8; error_len as usize];
138 r.read_exact(&mut buf[..])?;
139
140 Some(String::from_utf8(buf).expect("Cannot from_utf8"))
141 } else {
142 None
143 };
144
145 Ok(Self {
146 inner,
147 block_height,
148 gas_spent,
149 err,
150 })
151 }
152}
153
154impl Serializable for Header {
155 fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
156 self.marshal_hashable(w)?;
157 self.att.write(w)?;
158 w.write_all(&self.hash)?;
159 w.write_all(self.signature.inner())?;
160
161 Ok(())
162 }
163
164 fn read<R: Read>(r: &mut R) -> io::Result<Self>
165 where
166 Self: Sized,
167 {
168 let mut header = Self::unmarshal_hashable(r)?;
169 header.att = Attestation::read(r)?;
170 header.hash = Self::read_bytes(r)?;
171 header.signature = Signature::from(Self::read_bytes(r)?);
172 Ok(header)
173 }
174}
175
176impl Serializable for Attestation {
177 fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
178 self.result.write(w)?;
179 self.validation.write(w)?;
180 self.ratification.write(w)?;
181
182 Ok(())
183 }
184
185 fn read<R: Read>(r: &mut R) -> io::Result<Self>
186 where
187 Self: Sized,
188 {
189 let result = RatificationResult::read(r)?;
190 let validation = StepVotes::read(r)?;
191 let ratification = StepVotes::read(r)?;
192
193 Ok(Attestation {
194 result,
195 validation,
196 ratification,
197 })
198 }
199}
200
201impl Serializable for StepVotes {
202 fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
203 w.write_all(&self.bitset.to_le_bytes())?;
204 w.write_all(self.aggregate_signature.inner())?;
205
206 Ok(())
207 }
208
209 fn read<R: Read>(r: &mut R) -> io::Result<Self>
210 where
211 Self: Sized,
212 {
213 let bitset = Self::read_u64_le(r)?;
214 let aggregate_signature = Self::read_bytes(r)?;
215
216 Ok(StepVotes {
217 bitset,
218 aggregate_signature: aggregate_signature.into(),
219 })
220 }
221}
222
223impl Serializable for RatificationResult {
224 fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
225 match self {
226 RatificationResult::Fail(v) => {
227 w.write_all(&[0])?;
228 v.write(w)?;
229 }
230
231 RatificationResult::Success(v) => {
232 w.write_all(&[1])?;
233 v.write(w)?;
234 }
235 }
236
237 Ok(())
238 }
239
240 fn read<R: Read>(r: &mut R) -> io::Result<Self>
241 where
242 Self: Sized,
243 {
244 let result = match Self::read_u8(r)? {
245 0 => {
246 let vote = Vote::read(r)?;
247 Self::Fail(vote)
248 }
249 1 => {
250 let vote = Vote::read(r)?;
251 Self::Success(vote)
252 }
253 _ => Err(io::Error::new(
254 io::ErrorKind::InvalidData,
255 "Invalid RatificationResult",
256 ))?,
257 };
258 Ok(result)
259 }
260}
261
262impl Serializable for IterationsInfo {
263 fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
264 let count = self.att_list.len() as u8;
265 w.write_all(&count.to_le_bytes())?;
266
267 for iter in &self.att_list {
268 match iter {
269 Some((att, pk)) => {
270 w.write_all(&[1])?;
271 att.write(w)?;
272 w.write_all(pk.inner())?;
273 }
274 None => w.write_all(&[0])?,
275 }
276 }
277
278 Ok(())
279 }
280
281 fn read<R: Read>(r: &mut R) -> io::Result<Self>
282 where
283 Self: Sized,
284 {
285 let mut att_list = vec![];
286
287 let count = Self::read_u8(r)?;
288
289 if count > MESSAGE_MAX_FAILED_ITERATIONS {
291 return Err(io::Error::new(
292 io::ErrorKind::InvalidData,
293 format!("Invalid iterations_info count {count})"),
294 ));
295 }
296
297 for _ in 0..count {
298 let opt = Self::read_u8(r)?;
299
300 let att = match opt {
301 0 => None,
302 1 => {
303 let att = Attestation::read(r)?;
304 let pk = Self::read_bytes(r)?;
305 Some((att, PublicKeyBytes(pk)))
306 }
307 _ => {
308 return Err(io::Error::new(
309 io::ErrorKind::InvalidData,
310 "Invalid option",
311 ))
312 }
313 };
314 att_list.push(att)
315 }
316
317 Ok(IterationsInfo { att_list })
318 }
319}
320
321impl Serializable for Label {
322 fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
323 match self {
324 Label::Accepted(v) => {
325 w.write_all(&0u8.to_le_bytes())?;
326 w.write_all(&v.to_le_bytes())?;
327 }
328 Label::Attested(v) => {
329 w.write_all(&1u8.to_le_bytes())?;
330 w.write_all(&v.to_le_bytes())?;
331 }
332 Label::Confirmed(v) => {
333 w.write_all(&2u8.to_le_bytes())?;
334 w.write_all(&v.to_le_bytes())?;
335 }
336 Label::Final(v) => {
337 w.write_all(&3u8.to_le_bytes())?;
338 w.write_all(&v.to_le_bytes())?;
339 }
340 }
341
342 Ok(())
343 }
344
345 fn read<R: Read>(r: &mut R) -> io::Result<Self>
346 where
347 Self: Sized,
348 {
349 let label = Self::read_u8(r)?;
350 let label = match label {
351 0 => Label::Accepted(Self::read_u64_le(r)?),
352 1 => Label::Attested(Self::read_u64_le(r)?),
353 2 => Label::Confirmed(Self::read_u64_le(r)?),
354 3 => Label::Final(Self::read_u64_le(r)?),
355 _ => Err(io::Error::new(
356 io::ErrorKind::InvalidData,
357 "Invalid label",
358 ))?,
359 };
360
361 Ok(label)
362 }
363}
364
365impl Serializable for Ratification {
366 fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
367 self.header.write(w)?;
368 self.vote.write(w)?;
369 w.write_all(&self.timestamp.to_le_bytes())?;
370 self.validation_result.write(w)?;
371 self.sign_info.write(w)?;
373
374 Ok(())
375 }
376
377 fn read<R: Read>(r: &mut R) -> io::Result<Self>
378 where
379 Self: Sized,
380 {
381 let header = ConsensusHeader::read(r)?;
382 let vote = Vote::read(r)?;
383 let timestamp = Self::read_u64_le(r)?;
384 let validation_result = ValidationResult::read(r)?;
385 let sign_info = SignInfo::read(r)?;
386
387 Ok(Ratification {
388 header,
389 vote,
390 sign_info,
391 timestamp,
392 validation_result,
393 })
394 }
395}
396
397impl Serializable for ValidationResult {
398 fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
399 self.step_votes.write(w)?;
400 self.vote.write(w)?;
401 self.quorum.write(w)?;
402
403 Ok(())
404 }
405
406 fn read<R: Read>(r: &mut R) -> io::Result<Self>
407 where
408 Self: Sized,
409 {
410 let step_votes: StepVotes = StepVotes::read(r)?;
411 let vote = Vote::read(r)?;
412 let quorum = QuorumType::read(r)?;
413
414 Ok(ValidationResult::new(step_votes, vote, quorum))
415 }
416}
417
418impl Serializable for ValidationQuorum {
419 fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
420 self.header.write(w)?;
421 self.result.write(w)?;
422
423 Ok(())
424 }
425
426 fn read<R: Read>(r: &mut R) -> io::Result<Self>
427 where
428 Self: Sized,
429 {
430 let header = ConsensusHeader::read(r)?;
431 let result = ValidationResult::read(r)?;
432
433 Ok(ValidationQuorum { header, result })
434 }
435}
436
437impl Serializable for QuorumType {
438 fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
439 let val: u8 = *self as u8;
440 w.write_all(&val.to_le_bytes())
441 }
442
443 fn read<R: Read>(r: &mut R) -> io::Result<Self>
444 where
445 Self: Sized,
446 {
447 Ok(Self::read_u8(r)?.into())
448 }
449}
450
451#[cfg(test)]
452mod tests {
453 use fake::{Dummy, Fake, Faker};
454
455 use super::*;
456 use crate::message::payload::{Candidate, Validation};
457
458 fn assert_serializable<S: Dummy<Faker> + Eq + Serializable>() {
460 let obj: S = Faker.fake();
461 let mut buf = vec![];
462 obj.write(&mut buf).expect("should be writable");
463
464 assert!(obj.eq(&S::read(&mut &buf[..]).expect("should be readable")));
465 }
466
467 #[test]
468 fn test_encoding_iterations_info() {
469 assert_serializable::<IterationsInfo>();
470 }
471
472 #[test]
473 fn test_encoding_ratification() {
474 assert_serializable::<Ratification>();
475 }
476
477 #[test]
478 fn test_encoding_validation() {
479 assert_serializable::<Validation>();
480 }
481
482 #[test]
483 fn test_encoding_candidate() {
484 assert_serializable::<Candidate>();
485 }
486
487 #[test]
488 fn test_encoding_att() {
489 assert_serializable::<Attestation>();
490 }
491
492 #[test]
493 fn test_encoding_transaction() {
494 assert_serializable::<Transaction>();
495 }
496
497 #[test]
498 fn test_encoding_spent_transaction() {
499 assert_serializable::<SpentTransaction>();
500 }
501
502 #[test]
503 fn test_encoding_header() {
504 assert_serializable::<ConsensusHeader>();
505 }
506
507 #[test]
508 fn test_encoding_block() {
509 assert_serializable::<Block>();
510 }
511
512 #[test]
513 fn test_encoding_ratification_result() {
514 assert_serializable::<RatificationResult>();
515 }
516
517 #[test]
518 fn test_encoding_fault() {
519 assert_serializable::<Fault>();
520 }
521}