1use super::protocol_structures::{
2 block_header::BlockHeader,
3 encrypted_header::EncryptedHeader,
4 routing_header::{EncryptionType, RoutingHeader, SignatureType},
5};
6use crate::{
7 channel::mpsc::UnboundedReceiver,
8 global::protocol_structures::{
9 block_header::BlockType, routing_header::Receivers,
10 },
11 utils::buffers::write_u16,
12 values::core_values::endpoint::Endpoint,
13};
14use binrw::{
15 BinRead, BinWrite,
16 io::{Cursor, Read},
17};
18use core::{fmt::Display, result::Result, unimplemented};
19use strum::Display;
20use thiserror::Error;
21
22use crate::{prelude::*, utils::maybe_async::MaybeAsync};
23
24#[derive(Debug, Display, Error)]
25pub enum HeaderParsingError {
26 InsufficientLength,
27 InvalidMagicNumber,
28}
29
30#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Default)]
35pub struct DXBBlock {
36 pub routing_header: RoutingHeader,
37 pub block_header: BlockHeader,
38 pub signature: Option<Vec<u8>>,
39 pub encrypted_header: EncryptedHeader,
40 pub body: Vec<u8>,
41
42 #[serde(skip)]
43 pub raw_bytes: Option<Vec<u8>>,
44}
45
46impl PartialEq for DXBBlock {
47 fn eq(&self, other: &Self) -> bool {
48 self.routing_header == other.routing_header
49 && self.block_header == other.block_header
50 && self.encrypted_header == other.encrypted_header
51 && self.body == other.body
52 }
53}
54
55const SIZE_BYTE_POSITION: usize = 3; const SIZE_BYTES: usize = 2;
57
58pub type IncomingContextId = u32;
59pub type IncomingSectionIndex = u16;
60pub type IncomingBlockNumber = u16;
61pub type OutgoingContextId = u32;
62pub type OutgoingSectionIndex = u16;
63pub type OutgoingBlockNumber = u16;
64
65#[allow(clippy::large_enum_variant)]
66#[derive(Debug)]
67pub enum IncomingSection {
68 SingleBlock((Option<DXBBlock>, IncomingEndpointContextSectionId)),
70 BlockStream(
73 (
74 Option<UnboundedReceiver<DXBBlock>>,
75 IncomingEndpointContextSectionId,
76 ),
77 ),
78}
79
80impl IncomingSection {
81 pub async fn next(&mut self) -> Option<DXBBlock> {
82 match self {
83 IncomingSection::SingleBlock((block, _)) => block.take(),
84 IncomingSection::BlockStream((blocks, _)) => {
85 if let Some(receiver) = blocks {
86 receiver.next().await
87 } else {
88 None }
90 }
91 }
92 }
93
94 pub async fn drain(&mut self) -> Vec<DXBBlock> {
95 let mut blocks = Vec::new();
96 while let Some(block) = self.next().await {
97 blocks.push(block);
98 }
99 blocks
100 }
101}
102
103impl IncomingSection {
104 pub fn get_section_index(&self) -> IncomingSectionIndex {
105 self.get_section_context_id().section_index
106 }
107
108 pub fn get_sender(&self) -> Endpoint {
109 self.get_section_context_id()
110 .endpoint_context_id
111 .sender
112 .clone()
113 }
114
115 pub fn get_section_context_id(&self) -> &IncomingEndpointContextSectionId {
116 match self {
117 IncomingSection::SingleBlock((_, section_context_id))
118 | IncomingSection::BlockStream((_, section_context_id)) => {
119 section_context_id
120 }
121 }
122 }
123}
124
125#[derive(Debug, Clone, PartialEq, Eq, Hash)]
126pub struct IncomingEndpointContextId {
127 pub sender: Endpoint,
128 pub context_id: IncomingContextId,
129}
130
131#[derive(Debug, Clone, PartialEq, Eq, Hash)]
132pub struct IncomingEndpointContextSectionId {
133 pub endpoint_context_id: IncomingEndpointContextId,
134 pub section_index: IncomingSectionIndex,
135}
136
137impl IncomingEndpointContextSectionId {
138 pub fn new(
139 endpoint_context_id: IncomingEndpointContextId,
140 section_index: IncomingSectionIndex,
141 ) -> Self {
142 IncomingEndpointContextSectionId {
143 endpoint_context_id,
144 section_index,
145 }
146 }
147}
148
149#[derive(Debug, Clone, PartialEq, Eq, Hash)]
151pub struct BlockId {
152 pub endpoint_context_id: IncomingEndpointContextId,
153 pub timestamp: u64,
154 pub current_section_index: IncomingSectionIndex,
155 pub current_block_number: IncomingBlockNumber,
156}
157
158#[derive(Debug)]
159pub enum DXBBlockParseError {
160 IOError(String),
161 ParseError(binrw::Error),
162 IllegalState,
163}
164
165#[derive(Debug)]
166pub enum SignatureValidationError {
167 MissingSignature,
169 SignatureParseError,
171 InvalidSignature,
173}
174
175impl From<binrw::Error> for DXBBlockParseError {
176 fn from(err: binrw::Error) -> Self {
177 DXBBlockParseError::ParseError(err)
178 }
179}
180
181impl From<String> for DXBBlockParseError {
182 fn from(err: String) -> Self {
183 DXBBlockParseError::IOError(err)
184 }
185}
186
187impl DXBBlock {
188 pub fn new_with_body(body: &[u8]) -> DXBBlock {
189 let mut block = DXBBlock {
190 body: body.to_vec(),
191 ..DXBBlock::default()
192 };
193 block.recalculate_struct();
194 block
195 }
196 pub fn new(
197 routing_header: RoutingHeader,
198 block_header: BlockHeader,
199 encrypted_header: EncryptedHeader,
200 body: Vec<u8>,
201 ) -> DXBBlock {
202 let mut block = DXBBlock {
203 routing_header,
204 block_header,
205 signature: None,
206 encrypted_header,
207 body,
208 raw_bytes: None,
209 };
210 block.recalculate_struct();
211 block
212 }
213
214 pub fn to_bytes(&self) -> Vec<u8> {
216 let mut writer = Cursor::new(Vec::new());
217 self.routing_header.write(&mut writer).unwrap();
218 self.signature.write(&mut writer).unwrap();
219 self.block_header.write(&mut writer).unwrap();
220 self.encrypted_header.write(&mut writer).unwrap();
221 let mut bytes = writer.into_inner();
222 bytes.extend_from_slice(&self.body);
223 DXBBlock::adjust_block_length(bytes)
224 }
225 pub fn recalculate_struct(&mut self) -> &mut Self {
226 let bytes = self.to_bytes();
227 let size = bytes.len() as u16;
228 self.routing_header.block_size = size;
229 self
230 }
231
232 fn adjust_block_length(mut bytes: Vec<u8>) -> Vec<u8> {
233 let size = bytes.len() as u32;
234 write_u16(&mut bytes, &mut SIZE_BYTE_POSITION.clone(), size as u16);
235 bytes
236 }
237
238 pub fn has_dxb_magic_number(dxb: &[u8]) -> bool {
239 dxb.len() >= 2 && dxb[0] == 0x01 && dxb[1] == 0x64
240 }
241
242 pub fn extract_dxb_block_length(
243 dxb: &[u8],
244 ) -> Result<u16, HeaderParsingError> {
245 if dxb.len() < SIZE_BYTE_POSITION + SIZE_BYTES {
246 return Err(HeaderParsingError::InsufficientLength);
247 }
248
249 if !DXBBlock::has_dxb_magic_number(dxb) {
251 return Err(HeaderParsingError::InvalidMagicNumber);
252 }
253
254 let block_size_bytes =
256 &dxb[SIZE_BYTE_POSITION..SIZE_BYTE_POSITION + SIZE_BYTES];
257 Ok(u16::from_le_bytes(block_size_bytes.try_into().unwrap()))
258 }
259
260 pub fn from_bytes(bytes: &[u8]) -> Result<DXBBlock, DXBBlockParseError> {
261 let mut reader = Cursor::new(bytes);
262 let routing_header = RoutingHeader::read(&mut reader)?;
263
264 let signature = match routing_header.flags.signature_type() {
265 SignatureType::Encrypted => {
266 let mut signature = Vec::from([0u8; 108]);
268 reader.read_exact(&mut signature).map_err(|e| {
269 DXBBlockParseError::IOError(format!(
270 "Failed to read encrypted signature: {}",
271 e
272 ))
273 })?;
274
275 Some(signature)
277 }
278 SignatureType::Unencrypted => {
279 let mut signature = Vec::from([0u8; 108]);
281 reader.read_exact(&mut signature).map_err(|e| {
282 DXBBlockParseError::IOError(format!(
283 "Failed to read unencrypted signature: {}",
284 e
285 ))
286 })?;
287 Some(signature)
288 }
289 SignatureType::None => None,
290 };
291
292 let decrypted_bytes = match routing_header.flags.encryption_type() {
293 EncryptionType::Encrypted => {
294 let mut decrypted_bytes = Vec::from([0u8; 255]);
296 reader.read_exact(&mut decrypted_bytes).map_err(|e| {
297 DXBBlockParseError::IOError(format!(
298 "Failed to read encrypted body: {}",
299 e
300 ))
301 })?;
302 decrypted_bytes
303 }
304 EncryptionType::None => {
305 let mut bytes = Vec::new();
306 reader.read_to_end(&mut bytes).map_err(|e| e.to_string())?;
307 bytes
308 }
309 };
310
311 let mut reader = Cursor::new(decrypted_bytes);
312 let block_header = BlockHeader::read(&mut reader)?;
313
314 if signature.is_some()
316 && matches!(
317 block_header.flags_and_timestamp.block_type(),
318 BlockType::Trace | BlockType::TraceBack
319 )
320 {
321 return Err(DXBBlockParseError::IllegalState);
322 }
323
324 let encrypted_header = EncryptedHeader::read(&mut reader)?;
325
326 let mut body = Vec::new();
327 reader.read_to_end(&mut body).map_err(|e| e.to_string())?;
328
329 let block = DXBBlock {
330 routing_header,
331 block_header,
332 signature,
333 encrypted_header,
334 body,
335 raw_bytes: Some(bytes.to_vec()),
336 };
337
338 Ok(block)
339 }
340
341 pub fn validate_signature(
344 self,
345 ) -> MaybeAsync<
346 Result<DXBBlock, SignatureValidationError>,
347 impl Future<Output = Result<DXBBlock, SignatureValidationError>>,
348 > {
349 cfg_select! {
350 all(
352 not(feature = "crypto_enabled"),
353 feature = "allow_unsigned_blocks"
354 ) => {
355 log::info!(
356 "Crypto and signature validation are disabled, allowing block without signature validation"
357 );
358 MaybeAsync::<
359 Result<DXBBlock, SignatureValidationError>,
360 core::future::Ready<
361 Result<DXBBlock, SignatureValidationError>,
362 >,
363 >::Sync(Ok(self))
364 }
365
366 _ => {
368 use crate::crypto::CryptoImpl;
369 use datex_crypto_facade::crypto::Crypto;
370
371 match self.routing_header.flags.signature_type() {
373 signature_type @ (SignatureType::Encrypted
377 | SignatureType::Unencrypted) => {
378 MaybeAsync::Async(async move {
379 let is_valid = match signature_type {
380 SignatureType::Encrypted => {
381 let raw_sign = self.signature.as_ref().ok_or(
382 SignatureValidationError::MissingSignature,
383 )?;
384 let (enc_sign, pub_key) =
385 raw_sign.split_at(64);
386 let hash = CryptoImpl::hkdf_sha256(pub_key, &[0u8; 16])
387 .await
388 .map_err(|_| {
389 SignatureValidationError::SignatureParseError
390 })?;
391 let signature = CryptoImpl::aes_ctr_decrypt(
392 &hash, &[0u8; 16], enc_sign,
393 )
394 .await
395 .map_err(|_| {
396 SignatureValidationError::SignatureParseError
397 })?;
398
399 let raw_signed =
400 [pub_key, &self.body.clone()].concat();
401 let hashed_signed = CryptoImpl::hash_sha256(
402 &raw_signed,
403 )
404 .await
405 .map_err(|_| {
406 SignatureValidationError::SignatureParseError
407 })?;
408
409 CryptoImpl::ver_ed25519(
410 pub_key,
411 &signature,
412 &hashed_signed,
413 )
414 .await
415 .map_err(|_| {
416 SignatureValidationError::InvalidSignature
417 })?
418 }
419
420 SignatureType::Unencrypted => {
421 let raw_sign = self.signature.as_ref().ok_or(
422 SignatureValidationError::MissingSignature,
423 )?;
424 let (signature, pub_key) =
425 raw_sign.split_at(64);
426
427 let raw_signed =
428 [pub_key, &self.body.clone()].concat();
429 let hashed_signed = CryptoImpl::hash_sha256(
430 &raw_signed,
431 )
432 .await
433 .map_err(|_| {
434 SignatureValidationError::SignatureParseError
435 })?;
436
437 CryptoImpl::ver_ed25519(
438 pub_key,
439 signature,
440 &hashed_signed,
441 )
442 .await
443 .map_err(|_| {
444 SignatureValidationError::InvalidSignature
445 })?
446 }
447 _ => unreachable!(),
448 };
449
450 match is_valid {
451 true => Ok(self),
452 false => Err(
453 SignatureValidationError::InvalidSignature,
454 ),
455 }
456 })
457 }
458
459 SignatureType::None => {
460 let is_valid = {
461 cfg_if::cfg_if! {
462 if #[cfg(feature = "allow_unsigned_blocks")] {
464 log::info!("Signature validation is disabled, allowing block without signature validation");
465 true
466 }
467 else {
470 match self.block_type() {
471 BlockType::Trace | BlockType::TraceBack => true,
472 _ => return MaybeAsync::Sync(Err(SignatureValidationError::MissingSignature))
474 }
475 }
476 }
477 };
478
479 MaybeAsync::Sync(match is_valid {
480 true => Ok(self),
481 false => {
482 Err(SignatureValidationError::InvalidSignature)
483 }
484 })
485 }
486 }
487 }
488 }
489 }
490
491 pub fn receiver_endpoints(&self) -> Vec<Endpoint> {
493 match self.routing_header.receivers() {
494 Receivers::Endpoints(endpoints) => endpoints,
495 Receivers::EndpointsWithKeys(endpoints_with_keys) => {
496 endpoints_with_keys.into_iter().map(|(e, _)| e).collect()
497 }
498 Receivers::PointerId(_) => unimplemented!(),
499 _ => Vec::new(),
500 }
501 }
502 pub fn receivers(&self) -> Receivers {
503 self.routing_header.receivers()
504 }
505
506 pub fn set_receivers<T>(&mut self, endpoints: T)
508 where
509 T: Into<Receivers>,
510 {
511 self.routing_header.set_receivers(endpoints.into());
512 }
513
514 pub fn set_bounce_back(&mut self, bounce_back: bool) {
515 self.routing_header.flags.set_is_bounce_back(bounce_back);
516 }
517
518 pub fn is_bounce_back(&self) -> bool {
519 self.routing_header.flags.is_bounce_back()
520 }
521
522 pub fn sender(&self) -> &Endpoint {
523 &self.routing_header.sender
524 }
525
526 pub fn block_type(&self) -> BlockType {
527 self.block_header.flags_and_timestamp.block_type()
528 }
529
530 pub fn get_endpoint_context_id(&self) -> IncomingEndpointContextId {
531 IncomingEndpointContextId {
532 sender: self.routing_header.sender.clone(),
533 context_id: self.block_header.context_id,
534 }
535 }
536
537 pub fn get_block_id(&self) -> BlockId {
538 BlockId {
539 endpoint_context_id: self.get_endpoint_context_id(),
540 timestamp: self
541 .block_header
542 .flags_and_timestamp
543 .creation_timestamp(),
544 current_section_index: self.block_header.section_index,
545 current_block_number: self.block_header.block_number,
546 }
547 }
548
549 pub fn has_exact_receiver_count(&self) -> bool {
552 !self
553 .receiver_endpoints()
554 .iter()
555 .any(|e| e.instance_is_broadcast() || e.is_any())
556 }
557
558 pub fn clone_with_new_receivers<T>(&self, new_receivers: T) -> DXBBlock
559 where
560 T: Into<Receivers>,
561 {
562 let mut new_block = self.clone();
563 new_block.set_receivers(new_receivers.into());
564 new_block
565 }
566}
567
568impl Display for DXBBlock {
569 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
570 let block_type = self.block_header.flags_and_timestamp.block_type();
571 let sender = &self.routing_header.sender;
572 let receivers = self.receivers();
573 core::write!(f, "[{block_type}] {sender} -> {receivers}")?;
574
575 Ok(())
576 }
577}
578
579#[cfg(test)]
580mod tests {
581 use core::str::FromStr;
582 #[cfg(feature = "std")]
584 use crate::{
585 crypto::CryptoImpl, global::dxb_block::SignatureValidationError,
586 };
587
588 #[cfg(feature = "std")]
589 use datex_crypto_facade::crypto::Crypto;
590
591 use crate::{
592 global::{
593 dxb_block::{DXBBlock, DXBBlockParseError},
594 protocol_structures::{
595 block_header::BlockType,
596 encrypted_header::{self, EncryptedHeader},
597 routing_header::{RoutingHeader, SignatureType},
598 },
599 },
600 prelude::*,
601 values::core_values::endpoint::Endpoint,
602 };
603 use core::assert_matches;
604
605 #[test]
606 pub fn recalculate() {
607 let mut routing_header = RoutingHeader::default()
608 .with_sender(Endpoint::from_str("@test").unwrap())
609 .to_owned();
610 routing_header.flags.set_signature_type(SignatureType::None);
611 routing_header.set_size(420);
612 let mut block = DXBBlock {
613 body: vec![0x01, 0x02, 0x03],
614 encrypted_header: EncryptedHeader {
615 flags: encrypted_header::Flags::default()
616 .with_user_agent(encrypted_header::UserAgent::Unused11),
617 ..Default::default()
618 },
619 routing_header,
620 ..DXBBlock::default()
621 };
622
623 {
624 let block_bytes = block.to_bytes();
626 let block2: DXBBlock = DXBBlock::from_bytes(&block_bytes).unwrap();
627 assert_ne!(block, block2);
628 }
629
630 {
631 block.recalculate_struct();
633 let block_bytes = block.to_bytes();
634 let block3: DXBBlock = DXBBlock::from_bytes(&block_bytes).unwrap();
635 assert_eq!(block, block3);
636 }
637 }
638
639 #[tokio::test]
640 #[cfg(feature = "std")]
641 pub async fn signature_to_and_from_bytes() {
642 let mut routing_header = RoutingHeader::default()
644 .with_sender(Endpoint::from_str("@test").unwrap())
645 .to_owned();
646 routing_header.set_size(157);
647 let mut block = DXBBlock {
648 body: vec![0x01, 0x02, 0x03],
649 encrypted_header: EncryptedHeader {
650 ..Default::default()
651 },
652 routing_header,
653 ..DXBBlock::default()
654 };
655
656 block
658 .routing_header
659 .flags
660 .set_signature_type(SignatureType::Unencrypted);
661
662 let (pub_key, pri_key) = CryptoImpl::gen_ed25519().await.unwrap();
663 let raw_signed = [pub_key.clone(), block.body.clone()].concat();
664 let hashed_signed = CryptoImpl::hash_sha256(&raw_signed).await.unwrap();
665
666 let signature = CryptoImpl::sig_ed25519(&pri_key, &hashed_signed)
667 .await
668 .unwrap();
669 block.signature = Some([signature.to_vec(), pub_key.clone()].concat());
671
672 let block_bytes = block.to_bytes();
673 let block2: DXBBlock = DXBBlock::from_bytes(&block_bytes).unwrap();
674 assert_eq!(block, block2);
675 assert_eq!(block.signature, block2.signature);
676
677 let mut other_sig = signature;
679 if other_sig[42] != 42u8 {
680 other_sig[42] = 42u8;
681 } else {
682 other_sig[42] = 43u8;
683 }
684 block.signature = Some([other_sig.to_vec(), pub_key].concat());
685 let block_bytes2 = block.to_bytes();
686 let signature_validation = DXBBlock::from_bytes(&block_bytes2)
687 .unwrap()
688 .validate_signature()
689 .into_future()
690 .await;
691 assert!(signature_validation.is_err());
692 assert_matches!(
693 signature_validation.unwrap_err(),
694 SignatureValidationError::InvalidSignature
695 )
696 }
697
698 #[test]
699 fn illegal_signed_trace_block() {
700 let mut block = DXBBlock::new_with_body(&[0x01, 0x02, 0x03]);
701 block
702 .block_header
703 .flags_and_timestamp
704 .set_block_type(BlockType::Trace);
705 block
706 .routing_header
707 .flags
708 .set_signature_type(SignatureType::Unencrypted);
709 block.signature = Some(vec![0u8; 108]);
710
711 let block_bytes = block.to_bytes();
712 let parse_result = DXBBlock::from_bytes(&block_bytes);
713 assert!(parse_result.is_err());
714 assert_matches!(
715 parse_result.unwrap_err(),
716 DXBBlockParseError::IllegalState
717 );
718 }
719}